title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
CardView in Android With Example
08 Jun, 2022 CardView is a new widget in Android that can be used to display any sort of data by providing a rounded corner layout along with a specific elevation. CardView is the view that can display views on top of each other. The main usage of CardView is that it helps to give a rich feel and look to the UI design. This widget can be easily seen in many different Android Apps. CardView can be used for creating items in listview or inside Recycler View. The best part about CardView is that it extends Framelayout and it can be displayed on all platforms of Android. Now we will see the simple example of CardView implementation. Implementation: CardView Step 1: Create a new Android Studio Project. For creating a new Android Studio Project. Click on File>New>New Project. Make sure to keep your language as JAVA and select Empty Activity. Step 2: Add material dependency in build.gradle file. Navigate to Gradle Scripts then to build.gradle(app) and then add below dependency to it. implementation 'com.google.android.material:material:1.2.1' After adding this dependency you will get to see a popup option at top right corner which displays sync now. Click on that option to sync your project. Step 3: Add google repository in the build.gradle file of the application project if by default it is not there buildscript { repositories { google() mavenCentral() } All Jetpack components are available in the Google Maven repository, include them in the build.gradle file allprojects { repositories { google() mavenCentral() } } Step 4: Now we will create a simple CardView. Navigate to app>res>layout>activity_main.xml then create new CardView widget to it. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context=".MainActivity"> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" app:cardElevation="10dp" app:cardCornerRadius="20dp" android:layout_margin="10dp" app:cardBackgroundColor="@color/white" app:cardMaxElevation="12dp" app:cardPreventCornerOverlap="true" app:cardUseCompatPadding="true" > <!-- In the above cardview widget cardelevation property will give elevation to your card view card corner radius will provide radius to your card view card background color will give background color to your card view card max elevation will give the cardview maximum elevation card prevent corner overlap will add padding to CardView on v20 and before to prevent intersections between the Card content and rounded corners. card use compact padding will add padding in API v21+ as well to have the same measurements with previous versions. below are the two widgets imageview and text view we are displaying inside our card view. --> <ImageView android:layout_width="200dp" android:layout_height="200dp" android:layout_gravity="center" android:src="@drawable/gfgimage" android:layout_margin="10dp" android:id="@+id/img" android:contentDescription="@string/app_name" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/app_name" android:layout_gravity="bottom|center_horizontal" android:layout_marginTop="20dp" android:layout_marginBottom="20dp" android:textSize="20sp" android:textStyle="bold" /> </androidx.cardview.widget.CardView> </RelativeLayout> Step 5: Now run your app on your emulator or device you will get to see the output. Output: hemantjain99 Android-View Picked Technical Scripter 2020 Android Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Android RecyclerView in Kotlin Android Project folder Structure Broadcast Receiver in Android With Example Flutter - Custom Bottom Navigation Bar How to Update Gradle in Android Studio? Navigation Drawer in Android Retrofit with Kotlin Coroutine in Android Android Projects - From Basic to Advanced Level How to Create and Add Data to SQLite Database in Android?
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jun, 2022" }, { "code": null, "e": 678, "s": 53, "text": "CardView is a new widget in Android that can be used to display any sort of data by providing a rounded corner layout along with a specific elevation. CardView is the view that can display views on top of each other. The main usage of CardView is that it helps to give a rich feel and look to the UI design. This widget can be easily seen in many different Android Apps. CardView can be used for creating items in listview or inside Recycler View. The best part about CardView is that it extends Framelayout and it can be displayed on all platforms of Android. Now we will see the simple example of CardView implementation. " }, { "code": null, "e": 703, "s": 678, "text": "Implementation: CardView" }, { "code": null, "e": 749, "s": 703, "text": "Step 1: Create a new Android Studio Project. " }, { "code": null, "e": 890, "s": 749, "text": "For creating a new Android Studio Project. Click on File>New>New Project. Make sure to keep your language as JAVA and select Empty Activity." }, { "code": null, "e": 944, "s": 890, "text": "Step 2: Add material dependency in build.gradle file." }, { "code": null, "e": 1035, "s": 944, "text": "Navigate to Gradle Scripts then to build.gradle(app) and then add below dependency to it. " }, { "code": null, "e": 1095, "s": 1035, "text": "implementation 'com.google.android.material:material:1.2.1'" }, { "code": null, "e": 1248, "s": 1095, "text": "After adding this dependency you will get to see a popup option at top right corner which displays sync now. Click on that option to sync your project. " }, { "code": null, "e": 1360, "s": 1248, "text": "Step 3: Add google repository in the build.gradle file of the application project if by default it is not there" }, { "code": null, "e": 1374, "s": 1360, "text": "buildscript {" }, { "code": null, "e": 1389, "s": 1374, "text": "repositories {" }, { "code": null, "e": 1401, "s": 1389, "text": " google()" }, { "code": null, "e": 1419, "s": 1401, "text": " mavenCentral()" }, { "code": null, "e": 1421, "s": 1419, "text": "}" }, { "code": null, "e": 1528, "s": 1421, "text": "All Jetpack components are available in the Google Maven repository, include them in the build.gradle file" }, { "code": null, "e": 1542, "s": 1528, "text": "allprojects {" }, { "code": null, "e": 1557, "s": 1542, "text": "repositories {" }, { "code": null, "e": 1569, "s": 1557, "text": " google()" }, { "code": null, "e": 1586, "s": 1569, "text": " mavenCentral()" }, { "code": null, "e": 1588, "s": 1586, "text": "}" }, { "code": null, "e": 1590, "s": 1588, "text": "}" }, { "code": null, "e": 1637, "s": 1590, "text": "Step 4: Now we will create a simple CardView. " }, { "code": null, "e": 1722, "s": 1637, "text": "Navigate to app>res>layout>activity_main.xml then create new CardView widget to it. " }, { "code": null, "e": 1726, "s": 1722, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" tools:context=\".MainActivity\"> <androidx.cardview.widget.CardView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:cardElevation=\"10dp\" app:cardCornerRadius=\"20dp\" android:layout_margin=\"10dp\" app:cardBackgroundColor=\"@color/white\" app:cardMaxElevation=\"12dp\" app:cardPreventCornerOverlap=\"true\" app:cardUseCompatPadding=\"true\" > <!-- In the above cardview widget cardelevation property will give elevation to your card view card corner radius will provide radius to your card view card background color will give background color to your card view card max elevation will give the cardview maximum elevation card prevent corner overlap will add padding to CardView on v20 and before to prevent intersections between the Card content and rounded corners. card use compact padding will add padding in API v21+ as well to have the same measurements with previous versions. below are the two widgets imageview and text view we are displaying inside our card view. --> <ImageView android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_gravity=\"center\" android:src=\"@drawable/gfgimage\" android:layout_margin=\"10dp\" android:id=\"@+id/img\" android:contentDescription=\"@string/app_name\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"@string/app_name\" android:layout_gravity=\"bottom|center_horizontal\" android:layout_marginTop=\"20dp\" android:layout_marginBottom=\"20dp\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </androidx.cardview.widget.CardView> </RelativeLayout>", "e": 3775, "s": 1726, "text": null }, { "code": null, "e": 3860, "s": 3775, "text": "Step 5: Now run your app on your emulator or device you will get to see the output. " }, { "code": null, "e": 3869, "s": 3860, "text": "Output: " }, { "code": null, "e": 3882, "s": 3869, "text": "hemantjain99" }, { "code": null, "e": 3895, "s": 3882, "text": "Android-View" }, { "code": null, "e": 3902, "s": 3895, "text": "Picked" }, { "code": null, "e": 3926, "s": 3902, "text": "Technical Scripter 2020" }, { "code": null, "e": 3934, "s": 3926, "text": "Android" }, { "code": null, "e": 3953, "s": 3934, "text": "Technical Scripter" }, { "code": null, "e": 3961, "s": 3953, "text": "Android" }, { "code": null, "e": 4059, "s": 3961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4091, "s": 4059, "text": "Android SDK and it's Components" }, { "code": null, "e": 4122, "s": 4091, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 4155, "s": 4122, "text": "Android Project folder Structure" }, { "code": null, "e": 4198, "s": 4155, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 4237, "s": 4198, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 4277, "s": 4237, "text": "How to Update Gradle in Android Studio?" }, { "code": null, "e": 4306, "s": 4277, "text": "Navigation Drawer in Android" }, { "code": null, "e": 4348, "s": 4306, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 4396, "s": 4348, "text": "Android Projects - From Basic to Advanced Level" } ]
Reshaping a Tensor in Pytorch
01 Sep, 2021 In this article, we will discuss how to reshape a Tensor in Pytorch. Reshaping allows us to change the shape with the same data and number of elements as self but with the specified shape, which means it returns the same data as the specified array, but with different specified dimension sizes. Creating Tensor for demonstration: Python code to create a 1D Tensor and display it. Python3 # import torch moduleimport torch # create an 1 D etnsor with 8 elementsa = torch.tensor([1,2,3,4,5,6,7,8]) # display tensor shapeprint(a.shape) # display tensora Output: torch.Size([8]) tensor([1, 2, 3, 4, 5, 6, 7, 8]) This method is used to reshape the given tensor into a given shape( Change the dimensions) Syntax: tensor.reshape([row,column]) where, tensor is the input tensor row represents the number of rows in the reshaped tensor column represents the number of columns in the reshaped tensor Example 1: Python program to reshape a 1 D tensor to a two-dimensional tensor. Python3 # import torch moduleimport torch # create an 1 D etnsor with 8 elementsa = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) # display tensor shapeprint(a.shape) # display actual tensorprint(a) # reshape tensor into 4 rows and 2 columnsprint(a.reshape([4, 2])) # display shape of reshaped tensorprint(a.shape) Output: torch.Size([8]) tensor([1, 2, 3, 4, 5, 6, 7, 8]) tensor([[1, 2], [3, 4], [5, 6], [7, 8]]) torch.Size([8]) Example 2: Python code to reshape tensors into 4 rows and 2 columns Python3 # import torch moduleimport torch # create an 1 D etnsor with 8 elementsa = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) # display tensor shapeprint(a.shape) # display actual tensorprint(a) # reshape tensor into 4 rows and 2 columnsprint(a.reshape([4, 2])) # display shapeprint(a.shape) Output: torch.Size([8]) tensor([1, 2, 3, 4, 5, 6, 7, 8]) tensor([[1, 2], [3, 4], [5, 6], [7, 8]]) torch.Size([8]) Example 3: Python code to reshape tensor into 8 rows and 1 column. Python3 # import torch moduleimport torch # create an 1 D etnsor with 8 elementsa = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) # display tensor shapeprint(a.shape) # display actual tensorprint(a) # reshape tensor into 8 rows and 1 columnprint(a.reshape([8, 1])) # display shapeprint(a.shape) Output: torch.Size([8]) tensor([1, 2, 3, 4, 5, 6, 7, 8]) tensor([[1], [2], [3], [4], [5], [6], [7], [8]]) torch.Size([8]) flatten() is used to flatten an N-Dimensional tensor to a 1D Tensor. Syntax: torch.flatten(tensor) Where, tensor is the input tensor Example 1: Python code to create a tensor with 2 D elements and flatten this vector Python3 # import torch moduleimport torch # create an 2 D tensor with 8 elements eacha = torch.tensor([[1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8]]) # display actual tensorprint(a) # flatten a tensor with flatten() functionprint(torch.flatten(a)) Output: tensor([[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8]]) tensor([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]) Example 2: Python code to create a tensor with 3 D elements and flatten this vector Python3 # import torch moduleimport torch # create an 3 D tensor with 8 elements eacha = torch.tensor([[[1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8]], [[1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8]]]) # display actual tensorprint(a) # flatten a tensor with flatten() functionprint(torch.flatten(a)) Output: tensor([[[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8]], [[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8]]]) tensor([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]) view() is used to change the tensor in two-dimensional format IE rows and columns. We have to specify the number of rows and the number of columns to be viewed. Syntax: tensor.view(no_of_rows,no_of_columns) where, tensor is an input one dimensional tensor no_of_rows is the total number of the rows that the tensor is viewed no_of_columns is the total number of the columns that the tensor is viewed. Example 1: Python program to create a tensor with 12 elements and view with 3 rows and 4 columns and vice versa. Python3 # importing torch moduleimport torch # create one dimensional tensor 12 elementsa=torch.FloatTensor([24, 56, 10, 20, 30, 40, 50, 1, 2, 3, 4, 5]) # view tensor in 4 rows and 3 columnsprint(a.view(4, 3)) # view tensor in 3 rows and 4 columnsprint(a.view(3, 4)) Output: tensor([[24., 56., 10.], [20., 30., 40.], [50., 1., 2.], [ 3., 4., 5.]]) tensor([[24., 56., 10., 20.], [30., 40., 50., 1.], [ 2., 3., 4., 5.]]) Example 2: Python code to change the view of a tensor into 10 rows and one column and vice versa. Python3 # importing torch moduleimport torch # create one dimensional tensor 10 elementsa = torch.FloatTensor([24, 56, 10, 20, 30, 40, 50, 1, 2, 3]) # view tensor in 10 rows and 1 columnprint(a.view(10, 1)) # view tensor in 1 row and 10 columnsprint(a.view(1, 10)) Output: tensor([[24.], [56.], [10.], [20.], [30.], [40.], [50.], [ 1.], [ 2.], [ 3.]]) tensor([[24., 56., 10., 20., 30., 40., 50., 1., 2., 3.]]) This is used to resize the dimensions of the given tensor. Syntax: tensor.resize_(no_of_tensors,no_of_rows,no_of_columns) where: tensor is the input tensor no_of_tensors represents the total number of tensors to be generated no_of_rows represents the total number of rows in the new resized tensor no_of_columns represents the total number of columns in the new resized tensor Example 1: Python code to create an empty one D tensor and create 4 new tensors with 4 rows and 5 columns Python3 # importing torch moduleimport torch # create one dimensional tensora = torch.Tensor() # resize the tensor to 4 tensors.# each tensor with 4 rows and 5 columnsprint(a.resize_(4, 4, 5)) Output: Example 2: Create a 1 D tensor with elements and resize to 3 tensors with 2 rows and 2 columns Python3 # importing torch moduleimport torch # create one dimensionala = torch.Tensor() # resize the tensor to 2 tensors.# each tensor with 4 rows and 2 columnsprint(a.resize_(2, 4, 2)) Output: This is used to reshape a tensor by adding new dimensions at given positions. Syntax: tensor.unsqueeze(position) where, position is the dimension index which will start from 0. Example 1: Python code to create 2 D tensors and add a dimension in 0 the dimension. Python3 # importing torch moduleimport torch # create two dimensional tensora = torch.Tensor([[2,3], [1,2]]) # display shapeprint(a.shape) # add dimension at 0 positionadded = a.unsqueeze(0) print(added.shape) Output: torch.Size([2, 2]) torch.Size([1, 2, 2]) Example 2: Python code to create 1 D tensor and add dimensions Python3 # importing torch moduleimport torch # create one dimensional tensora = torch.Tensor([1, 2, 3, 4, 5]) # display shapeprint(a.shape) # add dimension at 0 positionadded = a.unsqueeze(0) print(added.shape) # add dimension at 1 positionadded = a.unsqueeze(1) print(added.shape) Output: torch.Size([5]) torch.Size([1, 5]) torch.Size([5, 1]) kapoorsagar226 Picked Python-PyTorch Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Sep, 2021" }, { "code": null, "e": 324, "s": 28, "text": "In this article, we will discuss how to reshape a Tensor in Pytorch. Reshaping allows us to change the shape with the same data and number of elements as self but with the specified shape, which means it returns the same data as the specified array, but with different specified dimension sizes." }, { "code": null, "e": 359, "s": 324, "text": "Creating Tensor for demonstration:" }, { "code": null, "e": 409, "s": 359, "text": "Python code to create a 1D Tensor and display it." }, { "code": null, "e": 417, "s": 409, "text": "Python3" }, { "code": "# import torch moduleimport torch # create an 1 D etnsor with 8 elementsa = torch.tensor([1,2,3,4,5,6,7,8]) # display tensor shapeprint(a.shape) # display tensora", "e": 580, "s": 417, "text": null }, { "code": null, "e": 588, "s": 580, "text": "Output:" }, { "code": null, "e": 637, "s": 588, "text": "torch.Size([8])\ntensor([1, 2, 3, 4, 5, 6, 7, 8])" }, { "code": null, "e": 728, "s": 637, "text": "This method is used to reshape the given tensor into a given shape( Change the dimensions)" }, { "code": null, "e": 765, "s": 728, "text": "Syntax: tensor.reshape([row,column])" }, { "code": null, "e": 772, "s": 765, "text": "where," }, { "code": null, "e": 799, "s": 772, "text": "tensor is the input tensor" }, { "code": null, "e": 856, "s": 799, "text": "row represents the number of rows in the reshaped tensor" }, { "code": null, "e": 920, "s": 856, "text": "column represents the number of columns in the reshaped tensor" }, { "code": null, "e": 999, "s": 920, "text": "Example 1: Python program to reshape a 1 D tensor to a two-dimensional tensor." }, { "code": null, "e": 1007, "s": 999, "text": "Python3" }, { "code": "# import torch moduleimport torch # create an 1 D etnsor with 8 elementsa = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) # display tensor shapeprint(a.shape) # display actual tensorprint(a) # reshape tensor into 4 rows and 2 columnsprint(a.reshape([4, 2])) # display shape of reshaped tensorprint(a.shape)", "e": 1308, "s": 1007, "text": null }, { "code": null, "e": 1316, "s": 1308, "text": "Output:" }, { "code": null, "e": 1446, "s": 1316, "text": "torch.Size([8])\ntensor([1, 2, 3, 4, 5, 6, 7, 8])\ntensor([[1, 2],\n [3, 4],\n [5, 6],\n [7, 8]])\ntorch.Size([8])" }, { "code": null, "e": 1514, "s": 1446, "text": "Example 2: Python code to reshape tensors into 4 rows and 2 columns" }, { "code": null, "e": 1522, "s": 1514, "text": "Python3" }, { "code": "# import torch moduleimport torch # create an 1 D etnsor with 8 elementsa = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) # display tensor shapeprint(a.shape) # display actual tensorprint(a) # reshape tensor into 4 rows and 2 columnsprint(a.reshape([4, 2])) # display shapeprint(a.shape)", "e": 1804, "s": 1522, "text": null }, { "code": null, "e": 1812, "s": 1804, "text": "Output:" }, { "code": null, "e": 1939, "s": 1812, "text": "torch.Size([8])\ntensor([1, 2, 3, 4, 5, 6, 7, 8])\ntensor([[1, 2],\n [3, 4],\n [5, 6],\n [7, 8]])\ntorch.Size([8])" }, { "code": null, "e": 2006, "s": 1939, "text": "Example 3: Python code to reshape tensor into 8 rows and 1 column." }, { "code": null, "e": 2014, "s": 2006, "text": "Python3" }, { "code": "# import torch moduleimport torch # create an 1 D etnsor with 8 elementsa = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) # display tensor shapeprint(a.shape) # display actual tensorprint(a) # reshape tensor into 8 rows and 1 columnprint(a.reshape([8, 1])) # display shapeprint(a.shape)", "e": 2295, "s": 2014, "text": null }, { "code": null, "e": 2303, "s": 2295, "text": "Output:" }, { "code": null, "e": 2466, "s": 2303, "text": "torch.Size([8])\ntensor([1, 2, 3, 4, 5, 6, 7, 8])\ntensor([[1],\n [2],\n [3],\n [4],\n [5],\n [6],\n [7],\n [8]])\ntorch.Size([8])" }, { "code": null, "e": 2536, "s": 2466, "text": "flatten() is used to flatten an N-Dimensional tensor to a 1D Tensor. " }, { "code": null, "e": 2566, "s": 2536, "text": "Syntax: torch.flatten(tensor)" }, { "code": null, "e": 2600, "s": 2566, "text": "Where, tensor is the input tensor" }, { "code": null, "e": 2685, "s": 2600, "text": "Example 1: Python code to create a tensor with 2 D elements and flatten this vector" }, { "code": null, "e": 2693, "s": 2685, "text": "Python3" }, { "code": "# import torch moduleimport torch # create an 2 D tensor with 8 elements eacha = torch.tensor([[1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8]]) # display actual tensorprint(a) # flatten a tensor with flatten() functionprint(torch.flatten(a))", "e": 2942, "s": 2693, "text": null }, { "code": null, "e": 2950, "s": 2942, "text": "Output:" }, { "code": null, "e": 3075, "s": 2950, "text": "tensor([[1, 2, 3, 4, 5, 6, 7, 8],\n [1, 2, 3, 4, 5, 6, 7, 8]])\ntensor([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8])" }, { "code": null, "e": 3160, "s": 3075, "text": "Example 2: Python code to create a tensor with 3 D elements and flatten this vector" }, { "code": null, "e": 3168, "s": 3160, "text": "Python3" }, { "code": "# import torch moduleimport torch # create an 3 D tensor with 8 elements eacha = torch.tensor([[[1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8]], [[1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8]]]) # display actual tensorprint(a) # flatten a tensor with flatten() functionprint(torch.flatten(a))", "e": 3489, "s": 3168, "text": null }, { "code": null, "e": 3497, "s": 3489, "text": "Output:" }, { "code": null, "e": 3532, "s": 3497, "text": "tensor([[[1, 2, 3, 4, 5, 6, 7, 8]," }, { "code": null, "e": 3567, "s": 3532, "text": " [1, 2, 3, 4, 5, 6, 7, 8]]," }, { "code": null, "e": 3601, "s": 3567, "text": " [[1, 2, 3, 4, 5, 6, 7, 8]," }, { "code": null, "e": 3637, "s": 3601, "text": " [1, 2, 3, 4, 5, 6, 7, 8]]])" }, { "code": null, "e": 3717, "s": 3637, "text": "tensor([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8," }, { "code": null, "e": 3749, "s": 3717, "text": " 1, 2, 3, 4, 5, 6, 7, 8])" }, { "code": null, "e": 3910, "s": 3749, "text": "view() is used to change the tensor in two-dimensional format IE rows and columns. We have to specify the number of rows and the number of columns to be viewed." }, { "code": null, "e": 3956, "s": 3910, "text": "Syntax: tensor.view(no_of_rows,no_of_columns)" }, { "code": null, "e": 3963, "s": 3956, "text": "where," }, { "code": null, "e": 4005, "s": 3963, "text": "tensor is an input one dimensional tensor" }, { "code": null, "e": 4074, "s": 4005, "text": "no_of_rows is the total number of the rows that the tensor is viewed" }, { "code": null, "e": 4151, "s": 4074, "text": "no_of_columns is the total number of the columns that the tensor is viewed." }, { "code": null, "e": 4264, "s": 4151, "text": "Example 1: Python program to create a tensor with 12 elements and view with 3 rows and 4 columns and vice versa." }, { "code": null, "e": 4272, "s": 4264, "text": "Python3" }, { "code": "# importing torch moduleimport torch # create one dimensional tensor 12 elementsa=torch.FloatTensor([24, 56, 10, 20, 30, 40, 50, 1, 2, 3, 4, 5]) # view tensor in 4 rows and 3 columnsprint(a.view(4, 3)) # view tensor in 3 rows and 4 columnsprint(a.view(3, 4))", "e": 4553, "s": 4272, "text": null }, { "code": null, "e": 4561, "s": 4553, "text": "Output:" }, { "code": null, "e": 4748, "s": 4561, "text": "tensor([[24., 56., 10.],\n [20., 30., 40.],\n [50., 1., 2.],\n [ 3., 4., 5.]])\ntensor([[24., 56., 10., 20.],\n [30., 40., 50., 1.],\n [ 2., 3., 4., 5.]])" }, { "code": null, "e": 4846, "s": 4748, "text": "Example 2: Python code to change the view of a tensor into 10 rows and one column and vice versa." }, { "code": null, "e": 4854, "s": 4846, "text": "Python3" }, { "code": "# importing torch moduleimport torch # create one dimensional tensor 10 elementsa = torch.FloatTensor([24, 56, 10, 20, 30, 40, 50, 1, 2, 3]) # view tensor in 10 rows and 1 columnprint(a.view(10, 1)) # view tensor in 1 row and 10 columnsprint(a.view(1, 10))", "e": 5133, "s": 4854, "text": null }, { "code": null, "e": 5141, "s": 5133, "text": "Output:" }, { "code": null, "e": 5344, "s": 5141, "text": "tensor([[24.],\n [56.],\n [10.],\n [20.],\n [30.],\n [40.],\n [50.],\n [ 1.],\n [ 2.],\n [ 3.]])\ntensor([[24., 56., 10., 20., 30., 40., 50., 1., 2., 3.]])" }, { "code": null, "e": 5403, "s": 5344, "text": "This is used to resize the dimensions of the given tensor." }, { "code": null, "e": 5466, "s": 5403, "text": "Syntax: tensor.resize_(no_of_tensors,no_of_rows,no_of_columns)" }, { "code": null, "e": 5473, "s": 5466, "text": "where:" }, { "code": null, "e": 5500, "s": 5473, "text": "tensor is the input tensor" }, { "code": null, "e": 5569, "s": 5500, "text": "no_of_tensors represents the total number of tensors to be generated" }, { "code": null, "e": 5642, "s": 5569, "text": "no_of_rows represents the total number of rows in the new resized tensor" }, { "code": null, "e": 5721, "s": 5642, "text": "no_of_columns represents the total number of columns in the new resized tensor" }, { "code": null, "e": 5827, "s": 5721, "text": "Example 1: Python code to create an empty one D tensor and create 4 new tensors with 4 rows and 5 columns" }, { "code": null, "e": 5835, "s": 5827, "text": "Python3" }, { "code": "# importing torch moduleimport torch # create one dimensional tensora = torch.Tensor() # resize the tensor to 4 tensors.# each tensor with 4 rows and 5 columnsprint(a.resize_(4, 4, 5))", "e": 6021, "s": 5835, "text": null }, { "code": null, "e": 6029, "s": 6021, "text": "Output:" }, { "code": null, "e": 6124, "s": 6029, "text": "Example 2: Create a 1 D tensor with elements and resize to 3 tensors with 2 rows and 2 columns" }, { "code": null, "e": 6132, "s": 6124, "text": "Python3" }, { "code": "# importing torch moduleimport torch # create one dimensionala = torch.Tensor() # resize the tensor to 2 tensors.# each tensor with 4 rows and 2 columnsprint(a.resize_(2, 4, 2))", "e": 6311, "s": 6132, "text": null }, { "code": null, "e": 6319, "s": 6311, "text": "Output:" }, { "code": null, "e": 6397, "s": 6319, "text": "This is used to reshape a tensor by adding new dimensions at given positions." }, { "code": null, "e": 6432, "s": 6397, "text": "Syntax: tensor.unsqueeze(position)" }, { "code": null, "e": 6496, "s": 6432, "text": "where, position is the dimension index which will start from 0." }, { "code": null, "e": 6581, "s": 6496, "text": "Example 1: Python code to create 2 D tensors and add a dimension in 0 the dimension." }, { "code": null, "e": 6589, "s": 6581, "text": "Python3" }, { "code": "# importing torch moduleimport torch # create two dimensional tensora = torch.Tensor([[2,3], [1,2]]) # display shapeprint(a.shape) # add dimension at 0 positionadded = a.unsqueeze(0) print(added.shape)", "e": 6792, "s": 6589, "text": null }, { "code": null, "e": 6800, "s": 6792, "text": "Output:" }, { "code": null, "e": 6841, "s": 6800, "text": "torch.Size([2, 2])\ntorch.Size([1, 2, 2])" }, { "code": null, "e": 6904, "s": 6841, "text": "Example 2: Python code to create 1 D tensor and add dimensions" }, { "code": null, "e": 6912, "s": 6904, "text": "Python3" }, { "code": "# importing torch moduleimport torch # create one dimensional tensora = torch.Tensor([1, 2, 3, 4, 5]) # display shapeprint(a.shape) # add dimension at 0 positionadded = a.unsqueeze(0) print(added.shape) # add dimension at 1 positionadded = a.unsqueeze(1) print(added.shape)", "e": 7187, "s": 6912, "text": null }, { "code": null, "e": 7195, "s": 7187, "text": "Output:" }, { "code": null, "e": 7249, "s": 7195, "text": "torch.Size([5])\ntorch.Size([1, 5])\ntorch.Size([5, 1])" }, { "code": null, "e": 7264, "s": 7249, "text": "kapoorsagar226" }, { "code": null, "e": 7271, "s": 7264, "text": "Picked" }, { "code": null, "e": 7286, "s": 7271, "text": "Python-PyTorch" }, { "code": null, "e": 7293, "s": 7286, "text": "Python" }, { "code": null, "e": 7391, "s": 7293, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7423, "s": 7391, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7450, "s": 7423, "text": "Python Classes and Objects" }, { "code": null, "e": 7471, "s": 7450, "text": "Python OOPs Concepts" }, { "code": null, "e": 7494, "s": 7471, "text": "Introduction To PYTHON" }, { "code": null, "e": 7525, "s": 7494, "text": "Python | os.path.join() method" }, { "code": null, "e": 7581, "s": 7525, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 7623, "s": 7581, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 7665, "s": 7623, "text": "Check if element exists in list in Python" }, { "code": null, "e": 7704, "s": 7665, "text": "Python | datetime.timedelta() function" } ]
How to remove spaces from a string using JavaScript ?
26 Nov, 2019 Method 1: Using split() and join() Method: The split() method is used to split a string into multiple sub-strings and return them in the form of an array. A separator can be specified as a parameter so that the string is split whenever that separator is found in the string. The space character (” “) is specified in this parameter to separate the string whenever a space occurs. The join() method is used to join an array of strings using a separator. This will return a new string with the joined string using the specified separator. This method is used on the returned array and no separator (“”) is used to join the strings. This will join the strings in the array and return a new string. This will remove all the spaces in the original string. Syntax: string.split(" ").join("") Example: <!DOCTYPE html><html> <head> <title> How to remove spaces from a string using JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to remove spaces from a string using JavaScript? </b> <p> Original string is: Geeks for Geeks Portal </p> <p> New String is: <span class="output"></span> </p> <button onclick="removeSpaces()"> Remove Spaces </button> <script type="text/javascript"> function removeSpaces() { originalText = "Geeks for Geeks Portal"; removedSpacesText = originalText.split(" ").join(""); document.querySelector('.output').textContent = removedSpacesText; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Using replace() method with regex: The replace() method is used to replace a specified string with another string. It takes two parameters, first is the string to be replaced and the second parameter is the string replaced with. The second string can be given as empty string so that the empty space to be replaced. The first parameter is given a regular expression with a space character (” “) along with the global property. This will select every occurrence of space in the string and it can then be removed by using an empty string in the second parameter. This will remove all the spaces in the original string. Syntax: string.replace(/ /g, "") Example: <!DOCTYPE html><html> <head> <title> How to remove spaces from a string using JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to remove spaces from a string using JavaScript? </b> <p> Original string is: Geeks for Geeks Portal </p> <p> New String is: <span class="output"></span> </p> <button onclick="removeSpaces()"> Remove Spaces </button> <script type="text/javascript"> function removeSpaces() { originalText = "Geeks for Geeks Portal"; newText = originalText.replace(/ /g, ""); document.querySelector('.output').textContent = newText; } </script></body> </html> Output: Before clicking the button: After clicking the button: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Nov, 2019" }, { "code": null, "e": 434, "s": 54, "text": "Method 1: Using split() and join() Method: The split() method is used to split a string into multiple sub-strings and return them in the form of an array. A separator can be specified as a parameter so that the string is split whenever that separator is found in the string. The space character (” “) is specified in this parameter to separate the string whenever a space occurs." }, { "code": null, "e": 805, "s": 434, "text": "The join() method is used to join an array of strings using a separator. This will return a new string with the joined string using the specified separator. This method is used on the returned array and no separator (“”) is used to join the strings. This will join the strings in the array and return a new string. This will remove all the spaces in the original string." }, { "code": null, "e": 813, "s": 805, "text": "Syntax:" }, { "code": null, "e": 840, "s": 813, "text": "string.split(\" \").join(\"\")" }, { "code": null, "e": 849, "s": 840, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to remove spaces from a string using JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to remove spaces from a string using JavaScript? </b> <p> Original string is: Geeks for Geeks Portal </p> <p> New String is: <span class=\"output\"></span> </p> <button onclick=\"removeSpaces()\"> Remove Spaces </button> <script type=\"text/javascript\"> function removeSpaces() { originalText = \"Geeks for Geeks Portal\"; removedSpacesText = originalText.split(\" \").join(\"\"); document.querySelector('.output').textContent = removedSpacesText; } </script></body> </html>", "e": 1745, "s": 849, "text": null }, { "code": null, "e": 1753, "s": 1745, "text": "Output:" }, { "code": null, "e": 1781, "s": 1753, "text": "Before clicking the button:" }, { "code": null, "e": 1808, "s": 1781, "text": "After clicking the button:" }, { "code": null, "e": 2134, "s": 1808, "text": "Method 2: Using replace() method with regex: The replace() method is used to replace a specified string with another string. It takes two parameters, first is the string to be replaced and the second parameter is the string replaced with. The second string can be given as empty string so that the empty space to be replaced." }, { "code": null, "e": 2435, "s": 2134, "text": "The first parameter is given a regular expression with a space character (” “) along with the global property. This will select every occurrence of space in the string and it can then be removed by using an empty string in the second parameter. This will remove all the spaces in the original string." }, { "code": null, "e": 2443, "s": 2435, "text": "Syntax:" }, { "code": null, "e": 2468, "s": 2443, "text": "string.replace(/ /g, \"\")" }, { "code": null, "e": 2477, "s": 2468, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to remove spaces from a string using JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to remove spaces from a string using JavaScript? </b> <p> Original string is: Geeks for Geeks Portal </p> <p> New String is: <span class=\"output\"></span> </p> <button onclick=\"removeSpaces()\"> Remove Spaces </button> <script type=\"text/javascript\"> function removeSpaces() { originalText = \"Geeks for Geeks Portal\"; newText = originalText.replace(/ /g, \"\"); document.querySelector('.output').textContent = newText; } </script></body> </html>", "e": 3351, "s": 2477, "text": null }, { "code": null, "e": 3359, "s": 3351, "text": "Output:" }, { "code": null, "e": 3387, "s": 3359, "text": "Before clicking the button:" }, { "code": null, "e": 3414, "s": 3387, "text": "After clicking the button:" }, { "code": null, "e": 3430, "s": 3414, "text": "JavaScript-Misc" }, { "code": null, "e": 3437, "s": 3430, "text": "Picked" }, { "code": null, "e": 3448, "s": 3437, "text": "JavaScript" }, { "code": null, "e": 3465, "s": 3448, "text": "Web Technologies" }, { "code": null, "e": 3492, "s": 3465, "text": "Web technologies Questions" } ]
Instance method in Python
02 Jul, 2020 A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state. Example: # Python program to demonstrate# classes class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print('Hello, my name is', self.name) p = Person('Nikhil') p.say_hi() Output: Hello, my name is Nikhil Note: For more information, refer to Python Classes and Objects Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute. For example, consider a class shapes that have many objects like circle, square, triangle, etc. having its own attributes and methods. An instance attribute refers to the properties of that particular object like edge of the triangle being 3, while the edge of the square can be 4. An instance method can access and even modify the value of attributes of an instance. It has one default parameter:- self – It is a keyword which points to the current passed instance. But it need not be passed every time while calling an instance method. Example: # Python program to demonstrate# instance methods class shape: # Calling Constructor def __init__(self, edge, color): self.edge = edge self.color = color # Instance Method def finEdges(self): return self.edge # Instance Method def modifyEdges(self, newedge): self.edge = newedge # Driver Codecircle = shape(0, 'red')square = shape(4, 'blue') # Calling Instance Methodprint("No. of edges for circle: "+ str(circle.finEdges())) # Calling Instance Methodsquare.modifyEdges(6) print("No. of edges for square: "+ str(square.finEdges())) Output No. of edges for circle: 0 No. of edges for square: 6 Akanksha_Rai Python-OOP python-oop-concepts Technical Scripter 2019 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jul, 2020" }, { "code": null, "e": 471, "s": 54, "text": "A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state." }, { "code": null, "e": 480, "s": 471, "text": "Example:" }, { "code": "# Python program to demonstrate# classes class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print('Hello, my name is', self.name) p = Person('Nikhil') p.say_hi() ", "e": 777, "s": 480, "text": null }, { "code": null, "e": 785, "s": 777, "text": "Output:" }, { "code": null, "e": 811, "s": 785, "text": "Hello, my name is Nikhil\n" }, { "code": null, "e": 875, "s": 811, "text": "Note: For more information, refer to Python Classes and Objects" }, { "code": null, "e": 1005, "s": 875, "text": "Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute." }, { "code": null, "e": 1287, "s": 1005, "text": "For example, consider a class shapes that have many objects like circle, square, triangle, etc. having its own attributes and methods. An instance attribute refers to the properties of that particular object like edge of the triangle being 3, while the edge of the square can be 4." }, { "code": null, "e": 1404, "s": 1287, "text": "An instance method can access and even modify the value of attributes of an instance. It has one default parameter:-" }, { "code": null, "e": 1543, "s": 1404, "text": "self – It is a keyword which points to the current passed instance. But it need not be passed every time while calling an instance method." }, { "code": null, "e": 1552, "s": 1543, "text": "Example:" }, { "code": "# Python program to demonstrate# instance methods class shape: # Calling Constructor def __init__(self, edge, color): self.edge = edge self.color = color # Instance Method def finEdges(self): return self.edge # Instance Method def modifyEdges(self, newedge): self.edge = newedge # Driver Codecircle = shape(0, 'red')square = shape(4, 'blue') # Calling Instance Methodprint(\"No. of edges for circle: \"+ str(circle.finEdges())) # Calling Instance Methodsquare.modifyEdges(6) print(\"No. of edges for square: \"+ str(square.finEdges()))", "e": 2171, "s": 1552, "text": null }, { "code": null, "e": 2178, "s": 2171, "text": "Output" }, { "code": null, "e": 2232, "s": 2178, "text": "No. of edges for circle: 0\nNo. of edges for square: 6" }, { "code": null, "e": 2245, "s": 2232, "text": "Akanksha_Rai" }, { "code": null, "e": 2256, "s": 2245, "text": "Python-OOP" }, { "code": null, "e": 2276, "s": 2256, "text": "python-oop-concepts" }, { "code": null, "e": 2300, "s": 2276, "text": "Technical Scripter 2019" }, { "code": null, "e": 2307, "s": 2300, "text": "Python" }, { "code": null, "e": 2326, "s": 2307, "text": "Technical Scripter" } ]
Flutter – Container Styling
09 May, 2021 In this article we will look at the most basic and simple widget in flutter Container. We will look that how can we style our container in different ways according to our need , so that we can effectively use this widget in our app . First of all we have to write some starting code for our project . Our code for the structure of our app will go like :- Dart import 'package:flutter/material.dart'; void main(){ runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: HomePage(), ); }} class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Container(), ); }} We had created a stateless widget called HomePage in our home property of Material App . So when we run our app we do not see anything created on our screen . This is because a container itself is an empty body until some constraints are provided . By constraints here we mean some height or width should be given to our container . Also assign some color to it so that it can be reflected in our app. Dart class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( height: 200.0, width: 200.0, color: Colors.blueAccent ) ) ); }} NOTE :- We have to assign color property inside BoxDecoration constructor only else it will create an error . Decoration property takes an argument of type Box Decoration . Now we can see that multiple properties can be applied to our container . 1. Border : – We will assign some border to our container using Border.all constructor. Also provide it some width ,color and style properties . Dart border: Border.all( color: Colors.black, width: 2.0, ), 2. Border Radius :- This is used when we have to structure our container other than a default rectangular one . We can provide some radius to our container so that it can have a rounded border . This property is used many times to provide some uniqueness to our UI . Dart borderRadius: BorderRadius.circular(10.0) 3. Image : – As the name suggests if we want to add some image to our container we can use it with Decoration Image constructor . Image can be added in 2 ways . One by adding into our assets and another by fetching from internet . 4. Box Shadow :- To provide some shadow to our container this can be used . Actually it accepts a list of object of type Box Shadow . We can provide some color and blur radius to it . Dart boxShadow: [ BoxShadow( color: Colors.grey , blurRadius: 2.0, offset: Offset(2.0,2.0) ) ] 5. Shape : – If for some reasons we do not want to hard code the value of radius inside Border Radius property we can use this property by assigning it circle value . (Note : – Both can not be used simultaneously.) Dart shape: BoxShape.circle 6. Gradient :- If we wish to provide some multiple or combination of colors to our container we can use this property . A gradient of type Linear Gradient is assigned to it and colors are provided in form of list . Dart gradient: LinearGradient( colors: [ Colors.indigo, Colors.blueAccent ] ), Complete code for our app : Dart import 'package:flutter/material.dart'; void main(){ runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: HomePage(), ); }} class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( height: 200.0, width: 200.0, decoration: BoxDecoration( color: Colors.blueAccent, border: Border.all( color: Colors.black, width: 2.0, ), borderRadius: BorderRadius.circular(10.0), gradient: LinearGradient( colors: [ Colors.indigo, Colors.blueAccent ] ), boxShadow: [ BoxShadow( color: Colors.grey , blurRadius: 2.0, offset: Offset(2.0,2.0) ) ] ), ), ), ); }} Output: So in this article we saw that how we can style our container in different and best ways to make some better UIs . Flutter UI-components Flutter-widgets Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 May, 2021" }, { "code": null, "e": 288, "s": 52, "text": "In this article we will look at the most basic and simple widget in flutter Container. We will look that how can we style our container in different ways according to our need , so that we can effectively use this widget in our app . " }, { "code": null, "e": 410, "s": 288, "text": "First of all we have to write some starting code for our project . Our code for the structure of our app will go like :- " }, { "code": null, "e": 415, "s": 410, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main(){ runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: HomePage(), ); }} class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Container(), ); }}", "e": 777, "s": 415, "text": null }, { "code": null, "e": 937, "s": 777, "text": "We had created a stateless widget called HomePage in our home property of Material App . So when we run our app we do not see anything created on our screen . " }, { "code": null, "e": 1180, "s": 937, "text": "This is because a container itself is an empty body until some constraints are provided . By constraints here we mean some height or width should be given to our container . Also assign some color to it so that it can be reflected in our app." }, { "code": null, "e": 1185, "s": 1180, "text": "Dart" }, { "code": "class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( height: 200.0, width: 200.0, color: Colors.blueAccent ) ) ); }}", "e": 1436, "s": 1185, "text": null }, { "code": null, "e": 1546, "s": 1436, "text": "NOTE :- We have to assign color property inside BoxDecoration constructor only else it will create an error ." }, { "code": null, "e": 1684, "s": 1546, "text": "Decoration property takes an argument of type Box Decoration . Now we can see that multiple properties can be applied to our container . " }, { "code": null, "e": 1831, "s": 1684, "text": "1. Border : – We will assign some border to our container using Border.all constructor. Also provide it some width ,color and style properties . " }, { "code": null, "e": 1836, "s": 1831, "text": "Dart" }, { "code": "border: Border.all( color: Colors.black, width: 2.0, ),", "e": 1913, "s": 1836, "text": null }, { "code": null, "e": 2181, "s": 1913, "text": "2. Border Radius :- This is used when we have to structure our container other than a default rectangular one . We can provide some radius to our container so that it can have a rounded border . This property is used many times to provide some uniqueness to our UI . " }, { "code": null, "e": 2186, "s": 2181, "text": "Dart" }, { "code": "borderRadius: BorderRadius.circular(10.0)", "e": 2228, "s": 2186, "text": null }, { "code": null, "e": 2462, "s": 2228, "text": "3. Image : – As the name suggests if we want to add some image to our container we can use it with Decoration Image constructor . Image can be added in 2 ways . One by adding into our assets and another by fetching from internet . " }, { "code": null, "e": 2647, "s": 2462, "text": "4. Box Shadow :- To provide some shadow to our container this can be used . Actually it accepts a list of object of type Box Shadow . We can provide some color and blur radius to it . " }, { "code": null, "e": 2652, "s": 2647, "text": "Dart" }, { "code": "boxShadow: [ BoxShadow( color: Colors.grey , blurRadius: 2.0, offset: Offset(2.0,2.0) ) ]", "e": 2800, "s": 2652, "text": null }, { "code": null, "e": 3016, "s": 2800, "text": "5. Shape : – If for some reasons we do not want to hard code the value of radius inside Border Radius property we can use this property by assigning it circle value . (Note : – Both can not be used simultaneously.)" }, { "code": null, "e": 3021, "s": 3016, "text": "Dart" }, { "code": "shape: BoxShape.circle", "e": 3044, "s": 3021, "text": null }, { "code": null, "e": 3260, "s": 3044, "text": "6. Gradient :- If we wish to provide some multiple or combination of colors to our container we can use this property . A gradient of type Linear Gradient is assigned to it and colors are provided in form of list . " }, { "code": null, "e": 3265, "s": 3260, "text": "Dart" }, { "code": "gradient: LinearGradient( colors: [ Colors.indigo, Colors.blueAccent ] ),", "e": 3399, "s": 3265, "text": null }, { "code": null, "e": 3427, "s": 3399, "text": "Complete code for our app :" }, { "code": null, "e": 3432, "s": 3427, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main(){ runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: HomePage(), ); }} class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( height: 200.0, width: 200.0, decoration: BoxDecoration( color: Colors.blueAccent, border: Border.all( color: Colors.black, width: 2.0, ), borderRadius: BorderRadius.circular(10.0), gradient: LinearGradient( colors: [ Colors.indigo, Colors.blueAccent ] ), boxShadow: [ BoxShadow( color: Colors.grey , blurRadius: 2.0, offset: Offset(2.0,2.0) ) ] ), ), ), ); }}", "e": 4431, "s": 3432, "text": null }, { "code": null, "e": 4439, "s": 4431, "text": "Output:" }, { "code": null, "e": 4555, "s": 4439, "text": "So in this article we saw that how we can style our container in different and best ways to make some better UIs . " }, { "code": null, "e": 4577, "s": 4555, "text": "Flutter UI-components" }, { "code": null, "e": 4593, "s": 4577, "text": "Flutter-widgets" }, { "code": null, "e": 4598, "s": 4593, "text": "Dart" }, { "code": null, "e": 4606, "s": 4598, "text": "Flutter" } ]
Python program to count words in a sentence
03 Jun, 2022 Data preprocessing is an important task in text classification. With the emergence of Python in the field of data science, it is essential to have certain shorthands to have the upper hand among others. This article discusses ways to count words in a sentence, it starts with space-separated words but also includes ways to in presence of special characters as well. Let’s discuss certain ways to perform this. Quick Ninja Methods: One line Code to find count words in a sentence with Static and Dynamic Inputs. Python3 # Quick Two Line CodescountOfWords = len("Geeksforgeeks is best Computer Science Portal".split())print("Count of Words in the given Sentence:", countOfWords) # Quick One Line Codesprint(len("Geeksforgeeks is best Computer Science Portal".split())) # Quick One Line Code with User Inputprint(len(input("Enter Input:").split())) Output: Method #1: Using split() split function is quite useful and usually quite generic method to get words out of the list, but this approach fails once we introduce special characters in the list. Python3 # Python3 code to demonstrate# to count words in string# using split() # initializing string test_string = "Geeksforgeeks is best Computer Science Portal" # printing original stringprint ("The original string is : " + test_string) # using split()# to count words in stringres = len(test_string.split()) # printing resultprint ("The number of words in string are : " + str(res)) Method #2 : Using regex(findall()) Regular expressions have to be used in case we require to handle the cases of punctuation marks or special characters in the string. This is the most elegant way in which this task can be performed. Example Python3 # Python3 code to demonstrate# to count words in string# using regex (findall())import re # initializing string test_string = "Geeksforgeeks, is best @# Computer Science Portal.!!!" # printing original stringprint ("The original string is : " + test_string) # using regex (findall())# to count words in stringres = len(re.findall(r'\w+', test_string)) # printing resultprint ("The number of words in string are : " + str(res)) Method #3 : Using sum() + strip() + split() This method performs this particular task without using regex. In this method we first check all the words consisting of all the alphabets, if so they are added to sum and then returned. Python3 # Python3 code to demonstrate# to count words in string# using sum() + strip() + split()import string # initializing string test_string = "Geeksforgeeks, is best @# Computer Science Portal.!!!" # printing original stringprint ("The original string is : " + test_string) # using sum() + strip() + split()# to count words in stringres = sum([i.strip(string.punctuation).isalpha() for i in test_string.split()]) # printing resultprint ("The number of words in string are : " + str(res)) dey0btpch57lmvgz5mqhpaiqn337p09fd8yq1lw4 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Jun, 2022" }, { "code": null, "e": 464, "s": 53, "text": "Data preprocessing is an important task in text classification. With the emergence of Python in the field of data science, it is essential to have certain shorthands to have the upper hand among others. This article discusses ways to count words in a sentence, it starts with space-separated words but also includes ways to in presence of special characters as well. Let’s discuss certain ways to perform this." }, { "code": null, "e": 565, "s": 464, "text": "Quick Ninja Methods: One line Code to find count words in a sentence with Static and Dynamic Inputs." }, { "code": null, "e": 573, "s": 565, "text": "Python3" }, { "code": "# Quick Two Line CodescountOfWords = len(\"Geeksforgeeks is best Computer Science Portal\".split())print(\"Count of Words in the given Sentence:\", countOfWords) # Quick One Line Codesprint(len(\"Geeksforgeeks is best Computer Science Portal\".split())) # Quick One Line Code with User Inputprint(len(input(\"Enter Input:\").split()))", "e": 900, "s": 573, "text": null }, { "code": null, "e": 908, "s": 900, "text": "Output:" }, { "code": null, "e": 1104, "s": 910, "text": "Method #1: Using split() split function is quite useful and usually quite generic method to get words out of the list, but this approach fails once we introduce special characters in the list. " }, { "code": null, "e": 1112, "s": 1104, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to count words in string# using split() # initializing string test_string = \"Geeksforgeeks is best Computer Science Portal\" # printing original stringprint (\"The original string is : \" + test_string) # using split()# to count words in stringres = len(test_string.split()) # printing resultprint (\"The number of words in string are : \" + str(res))", "e": 1492, "s": 1112, "text": null }, { "code": null, "e": 1727, "s": 1492, "text": "Method #2 : Using regex(findall()) Regular expressions have to be used in case we require to handle the cases of punctuation marks or special characters in the string. This is the most elegant way in which this task can be performed. " }, { "code": null, "e": 1735, "s": 1727, "text": "Example" }, { "code": null, "e": 1743, "s": 1735, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to count words in string# using regex (findall())import re # initializing string test_string = \"Geeksforgeeks, is best @# Computer Science Portal.!!!\" # printing original stringprint (\"The original string is : \" + test_string) # using regex (findall())# to count words in stringres = len(re.findall(r'\\w+', test_string)) # printing resultprint (\"The number of words in string are : \" + str(res))", "e": 2175, "s": 1743, "text": null }, { "code": null, "e": 2408, "s": 2175, "text": "Method #3 : Using sum() + strip() + split() This method performs this particular task without using regex. In this method we first check all the words consisting of all the alphabets, if so they are added to sum and then returned. " }, { "code": null, "e": 2416, "s": 2408, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to count words in string# using sum() + strip() + split()import string # initializing string test_string = \"Geeksforgeeks, is best @# Computer Science Portal.!!!\" # printing original stringprint (\"The original string is : \" + test_string) # using sum() + strip() + split()# to count words in stringres = sum([i.strip(string.punctuation).isalpha() for i in test_string.split()]) # printing resultprint (\"The number of words in string are : \" + str(res))", "e": 2905, "s": 2416, "text": null }, { "code": null, "e": 2946, "s": 2905, "text": "dey0btpch57lmvgz5mqhpaiqn337p09fd8yq1lw4" }, { "code": null, "e": 2969, "s": 2946, "text": "Python string-programs" }, { "code": null, "e": 2976, "s": 2969, "text": "Python" }, { "code": null, "e": 2992, "s": 2976, "text": "Python Programs" } ]
Kali Linux – Forensics Tools
28 Jul, 2020 Today when we are surrounded by a lot of ransomware, malware, and digital viruses to spy and invade our policy, there is a great need to learn how to prevent ourselves from them. When it comes to malicious, encrypted, secure, or any other file forensics tools helps us to analyze them and makes our path to the attacker more clear or even sometimes gives us a lot of information about the message in the file or the author of the file. These tools even allow us to encrypt our messages in images or other files to hide it from those who want to read the message because of their malicious intentions. We could analyze or even open the code of any file using the following mentioned tools. Below is the list of the Basic tools for Forensics Tools Binwalk is a great tool when we have a binary image and have to extract embedded files and executable codes out of them. It is even used to identify the files and codes which are embedded inside the firmware images. Binwalk is compatible with magic signatures for UNIX file utility as it uses libmagic library. The Official Github Repository for Binwalk is: https://github.com/ReFirmLabs/binwalk To use Binwalk Tool: Enter the following command in the terminal. binwalk -h This will display the help section of the Binwalk command. Bulk-Extractor tool which is to be used when you have to extract features like E-Mail address, URLs, Confidential Document Numbers from files. This tool is used for Intrusion investigations, malware investigations, identity investigations, or any other kind of cyber investigation. The awesome feature of working with compressed or corrupt files makes it a great tool to work with those files. IT works on disk images, files, or a directory of files and finds out the useful information. To use Bulk-Extractor: Enter the following command in the terminal. bulk_extractor p0f is a great tool when we have to analyze network captured packages. p0f is used to gather the information of the host like the IP address, Operating System, and much more from the package. This tool may prove to be a great tool when there is a firewall over the network of the captured packet. It is very highly scalable and allows the fast identification of host details. It also allows us to perform information gathering while performing vulnerability tests and to monitor the network. To use p0f: Enter the following command in the terminal. p0f -h Autopsy is a digital forensics tool that is used to gather the information form forensics. Or in other words, this tool is used to investigate files or logs to learn about what exactly was done with the system. It could even be used as a recovery software to recover files from a memory card or a pen drive. To use autopsy tool Autopsy comes pre-installed in Kali Linux Just type “autopsy” in the terminal. Now visit http://localhost:9999/autopsy in order to use the tool. 5. John the Ripper John the Ripper is a great tool for cracking passwords of files like zipped files pdf files etc. These password-protected files can be easily decrypted with john the ripper there are many attacks for the same in it like brute force attack, dictionary attack, etc. To use John the Ripper John the ripper comes pre-installed in Kali Linux. Just type “john” in the terminal to use the tool. Kali-Linux 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": "\n28 Jul, 2020" }, { "code": null, "e": 774, "s": 28, "text": "Today when we are surrounded by a lot of ransomware, malware, and digital viruses to spy and invade our policy, there is a great need to learn how to prevent ourselves from them. When it comes to malicious, encrypted, secure, or any other file forensics tools helps us to analyze them and makes our path to the attacker more clear or even sometimes gives us a lot of information about the message in the file or the author of the file. These tools even allow us to encrypt our messages in images or other files to hide it from those who want to read the message because of their malicious intentions. We could analyze or even open the code of any file using the following mentioned tools. Below is the list of the Basic tools for Forensics Tools" }, { "code": null, "e": 1085, "s": 774, "text": "Binwalk is a great tool when we have a binary image and have to extract embedded files and executable codes out of them. It is even used to identify the files and codes which are embedded inside the firmware images. Binwalk is compatible with magic signatures for UNIX file utility as it uses libmagic library." }, { "code": null, "e": 1170, "s": 1085, "text": "The Official Github Repository for Binwalk is: https://github.com/ReFirmLabs/binwalk" }, { "code": null, "e": 1238, "s": 1170, "text": "To use Binwalk Tool: Enter the following command in the terminal. " }, { "code": null, "e": 1250, "s": 1238, "text": "binwalk -h\n" }, { "code": null, "e": 1309, "s": 1250, "text": "This will display the help section of the Binwalk command." }, { "code": null, "e": 1799, "s": 1311, "text": "Bulk-Extractor tool which is to be used when you have to extract features like E-Mail address, URLs, Confidential Document Numbers from files. This tool is used for Intrusion investigations, malware investigations, identity investigations, or any other kind of cyber investigation. The awesome feature of working with compressed or corrupt files makes it a great tool to work with those files. IT works on disk images, files, or a directory of files and finds out the useful information." }, { "code": null, "e": 1869, "s": 1799, "text": "To use Bulk-Extractor: Enter the following command in the terminal. " }, { "code": null, "e": 1885, "s": 1869, "text": "bulk_extractor " }, { "code": null, "e": 2377, "s": 1885, "text": "p0f is a great tool when we have to analyze network captured packages. p0f is used to gather the information of the host like the IP address, Operating System, and much more from the package. This tool may prove to be a great tool when there is a firewall over the network of the captured packet. It is very highly scalable and allows the fast identification of host details. It also allows us to perform information gathering while performing vulnerability tests and to monitor the network." }, { "code": null, "e": 2436, "s": 2377, "text": "To use p0f: Enter the following command in the terminal. " }, { "code": null, "e": 2444, "s": 2436, "text": "p0f -h\n" }, { "code": null, "e": 2753, "s": 2444, "text": "Autopsy is a digital forensics tool that is used to gather the information form forensics. Or in other words, this tool is used to investigate files or logs to learn about what exactly was done with the system. It could even be used as a recovery software to recover files from a memory card or a pen drive. " }, { "code": null, "e": 2774, "s": 2753, "text": "To use autopsy tool " }, { "code": null, "e": 2817, "s": 2774, "text": "Autopsy comes pre-installed in Kali Linux " }, { "code": null, "e": 2856, "s": 2817, "text": "Just type “autopsy” in the terminal. " }, { "code": null, "e": 2924, "s": 2856, "text": "Now visit http://localhost:9999/autopsy in order to use the tool. " }, { "code": null, "e": 2944, "s": 2924, "text": "5. John the Ripper " }, { "code": null, "e": 3208, "s": 2944, "text": "John the Ripper is a great tool for cracking passwords of files like zipped files pdf files etc. These password-protected files can be easily decrypted with john the ripper there are many attacks for the same in it like brute force attack, dictionary attack, etc." }, { "code": null, "e": 3232, "s": 3208, "text": "To use John the Ripper " }, { "code": null, "e": 3284, "s": 3232, "text": "John the ripper comes pre-installed in Kali Linux. " }, { "code": null, "e": 3336, "s": 3284, "text": "Just type “john” in the terminal to use the tool. " }, { "code": null, "e": 3347, "s": 3336, "text": "Kali-Linux" }, { "code": null, "e": 3358, "s": 3347, "text": "Linux-Unix" } ]
GATE | GATE-CS-2014-(Set-2) | Question 65
28 Jun, 2021 SQL allows tuples in relations, and correspondingly defines the multiplicity of tuples in the result of joins. Which one of the following queries always gives the same answer as the nested query shown below: select * from R where a in (select S.a from S) (A) select R.* from R, S where R.a=S.a(D)(B) select distinct R.* from R,S where R.a=S.a(C) select R.* from R,(select distinct a from S) as S1 whereR.a=S1.a(D) select R.* from R,S where R.a=S.a and is unique RAnswer: (C)Explanation: The solution of this question lies in the data set(tuples) of Relations R and S we define. If we miss some case then we may get wrong answer.Let’s say, Relation R(BCA) with attributes B, C and A contains the following tuples. B C A --------- 7 2 1 7 2 1 8 9 5 8 9 5 And Relation S(AMN) with attributes A, M, and N contains the following tuples. A M N --------- 1 6 7 2 8 4 5 9 6 5 5 3 ———————————————————————————————————–Now ,the original Query will give result as: “select * from R where a in (select S.a from S) ” – The query asks to display every tuple of Relation R where R.a is present in the complete set S.a. B C A --------- 7 2 1 7 2 1 8 9 5 8 9 5 ———————————————————————————————————– Option A query will result in : “select R.* from R, S where R.a=S.a” B C A --------- 7 2 1 7 2 1 8 9 5 8 9 5 8 9 5 8 9 5 ———————————————————————————————————– Option B query will result in : ” select distinct R.* from R,S where R.a=S.a” B C A --------- 7 2 1 8 9 5 ———————————————————————————————————– Option C query will result in : “select R.* from R,(select distinct a from S) as S1 whereR.a=S1.a”B C A———7 2 17 2 18 9 58 9 5 ———————————————————————————————————– Option D query will result in : NULL set “select R.* from R,S where R.a=S.a and is unique R” ———————————————————————————————————-Hence option C query matches the original result set. Note : As mentioned earlier, we should take those data sets which can show us the difference in different queries. Suppose in R if you don’t put identical tuples then you will get wrong answers. (Try this yourself, this is left as an exercise for you ).Quiz of this Question GATE-CS-2014-(Set-2) GATE-GATE-CS-2014-(Set-2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 236, "s": 28, "text": "SQL allows tuples in relations, and correspondingly defines the multiplicity of tuples in the result of joins. Which one of the following queries always gives the same answer as the nested query shown below:" }, { "code": null, "e": 288, "s": 236, "text": " select * from R where a in (select S.a from S) " }, { "code": null, "e": 672, "s": 288, "text": "(A) select R.* from R, S where R.a=S.a(D)(B) select distinct R.* from R,S where R.a=S.a(C) select R.* from R,(select distinct a from S) as S1 whereR.a=S1.a(D) select R.* from R,S where R.a=S.a and is unique RAnswer: (C)Explanation: The solution of this question lies in the data set(tuples) of Relations R and S we define. If we miss some case then we may get wrong answer.Let’s say," }, { "code": null, "e": 746, "s": 672, "text": "Relation R(BCA) with attributes B, C and A contains the following tuples." }, { "code": null, "e": 786, "s": 746, "text": "B C A\n---------\n7 2 1\n7 2 1\n8 9 5\n8 9 5" }, { "code": null, "e": 865, "s": 786, "text": "And Relation S(AMN) with attributes A, M, and N contains the following tuples." }, { "code": null, "e": 905, "s": 865, "text": "A M N\n---------\n1 6 7\n2 8 4\n5 9 6\n5 5 3" }, { "code": null, "e": 986, "s": 905, "text": "———————————————————————————————————–Now ,the original Query will give result as:" }, { "code": null, "e": 1136, "s": 986, "text": "“select * from R where a in (select S.a from S) ” – The query asks to display every tuple of Relation R where R.a is present in the complete set S.a." }, { "code": null, "e": 1176, "s": 1136, "text": "B C A\n---------\n7 2 1\n7 2 1\n8 9 5\n8 9 5" }, { "code": null, "e": 1213, "s": 1176, "text": "———————————————————————————————————–" }, { "code": null, "e": 1245, "s": 1213, "text": "Option A query will result in :" }, { "code": null, "e": 1282, "s": 1245, "text": "“select R.* from R, S where R.a=S.a”" }, { "code": null, "e": 1334, "s": 1282, "text": "B C A\n---------\n7 2 1\n7 2 1\n8 9 5\n8 9 5\n8 9 5\n8 9 5" }, { "code": null, "e": 1371, "s": 1334, "text": "———————————————————————————————————–" }, { "code": null, "e": 1403, "s": 1371, "text": "Option B query will result in :" }, { "code": null, "e": 1449, "s": 1403, "text": "” select distinct R.* from R,S where R.a=S.a”" }, { "code": null, "e": 1477, "s": 1449, "text": "B C A\n---------\n7 2 1\n8 9 5" }, { "code": null, "e": 1514, "s": 1477, "text": "———————————————————————————————————–" }, { "code": null, "e": 1546, "s": 1514, "text": "Option C query will result in :" }, { "code": null, "e": 1641, "s": 1546, "text": "“select R.* from R,(select distinct a from S) as S1 whereR.a=S1.a”B C A———7 2 17 2 18 9 58 9 5" }, { "code": null, "e": 1678, "s": 1641, "text": "———————————————————————————————————–" }, { "code": null, "e": 1719, "s": 1678, "text": "Option D query will result in : NULL set" }, { "code": null, "e": 1771, "s": 1719, "text": "“select R.* from R,S where R.a=S.a and is unique R”" }, { "code": null, "e": 1861, "s": 1771, "text": "———————————————————————————————————-Hence option C query matches the original result set." }, { "code": null, "e": 2136, "s": 1861, "text": "Note : As mentioned earlier, we should take those data sets which can show us the difference in different queries. Suppose in R if you don’t put identical tuples then you will get wrong answers. (Try this yourself, this is left as an exercise for you ).Quiz of this Question" }, { "code": null, "e": 2157, "s": 2136, "text": "GATE-CS-2014-(Set-2)" }, { "code": null, "e": 2183, "s": 2157, "text": "GATE-GATE-CS-2014-(Set-2)" }, { "code": null, "e": 2188, "s": 2183, "text": "GATE" } ]
Sending an Intent to browser to open specific URL using Kotlin.
This example demonstrates how to Send an Intent to browser to open specific URL using Kotlin Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:onClick="getUrlFromIntent" android:text="Get URL from Intent" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" } fun getUrlFromIntent(view: View) { val url = "http://www.google.com" val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(url) startActivity(intent) } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your 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 the 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": 1155, "s": 1062, "text": "This example demonstrates how to Send an Intent to browser to open specific URL using Kotlin" }, { "code": null, "e": 1284, "s": 1155, "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": 1349, "s": 1284, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2269, "s": 1349, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:onClick=\"getUrlFromIntent\"\n android:text=\"Get URL from Intent\" />\n</RelativeLayout>" }, { "code": null, "e": 2324, "s": 2269, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 2885, "s": 2324, "text": "import android.content.Intent\nimport android.net.Uri\nimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.view.View\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n }\n fun getUrlFromIntent(view: View) {\n val url = \"http://www.google.com\"\n val intent = Intent(Intent.ACTION_VIEW)\n intent.data = Uri.parse(url)\n startActivity(intent)\n }\n}" }, { "code": null, "e": 2940, "s": 2885, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3673, "s": 2940, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q11\">\n <uses-permission android:name=\"android.permission.INTERNET\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\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": 4021, "s": 3673, "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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by Java (will not be executed). This example uses a single-line comment before a line of code: // This is a comment System.out.println("Hello World"); Try it Yourself » This example uses a single-line comment at the end of a line of code: System.out.println("Hello World"); // This is a comment Try it Yourself » Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored by Java. This example uses a multi-line comment (a comment block) to explain the code: /* The code below will print the words Hello World to the screen, and it is amazing */ System.out.println("Hello World"); Try it Yourself » It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer. Insert the missing part to create two types of comments. This is a single-line comment This is a multi-line comment Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 146, "s": 0, "text": "Comments can be used to explain Java code, and to make it more readable. It can also be used to \nprevent execution when testing alternative code." }, { "code": null, "e": 204, "s": 146, "text": "Single-line comments start with two forward slashes (//)." }, { "code": null, "e": 292, "s": 204, "text": "Any text between // and the end of the line \nis ignored by Java (will not be executed)." }, { "code": null, "e": 355, "s": 292, "text": "This example uses a single-line comment before a line of code:" }, { "code": null, "e": 412, "s": 355, "text": "// This is a comment\nSystem.out.println(\"Hello World\");\n" }, { "code": null, "e": 432, "s": 412, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 502, "s": 432, "text": "This example uses a single-line comment at the end of a line of code:" }, { "code": null, "e": 559, "s": 502, "text": "System.out.println(\"Hello World\"); // This is a comment\n" }, { "code": null, "e": 579, "s": 559, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 631, "s": 579, "text": "Multi-line comments start with /* and ends with */." }, { "code": null, "e": 683, "s": 631, "text": "Any text between /* and */ will be ignored by Java." }, { "code": null, "e": 761, "s": 683, "text": "This example uses a multi-line comment (a comment block) to explain the code:" }, { "code": null, "e": 884, "s": 761, "text": "/* The code below will print the words Hello World\nto the screen, and it is amazing */\nSystem.out.println(\"Hello World\");\n" }, { "code": null, "e": 904, "s": 884, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1005, "s": 904, "text": "It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer." }, { "code": null, "e": 1062, "s": 1005, "text": "Insert the missing part to create two types of comments." }, { "code": null, "e": 1125, "s": 1062, "text": " This is a single-line comment\n This is a multi-line comment \n" }, { "code": null, "e": 1144, "s": 1125, "text": "Start the Exercise" }, { "code": null, "e": 1177, "s": 1144, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1219, "s": 1177, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1326, "s": 1219, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1345, "s": 1326, "text": "[email protected]" } ]
Check if string contains another string in Swift
To check if a string contains another string in swift, we’ll need two different strings. One string that we have to check if it consists another string. Let us say the string we want to check is “point” and the whole string is “TutorialsPoint” and another string is “one two three”. Let’s check with both these string in the playground. We can do this in two ways as shown below. Let’s start by creating three different strings. var CompleteStr1 = "Tutorials point" var completeStr2 = "one two three" var stringToCheck = "point" In this method we’ll use the .contains method of Strings to check if there is a string within another string, it returns true if it exists, otherwise, it returns false. if CompleteStr1.contains(stringToCheck) { print("contains") } else { print("does not contain") } In this method we’ll check the range of a string if the range is nil, it means that the string we are checking for, does not exist. Otherwise, it means that string exists. if completeStr2.range(of: stringToCheck) != nil { print("contains") } else { print("does not contain") } When we run the above code, we get the output as shown below. Similarly, let’s try these methods with one more example. var Str1 = "12312$$33@" var Str2 = "%%" var Str3 = "$$" if Str1.contains(Str2) { print("contains") } else { print("does not contain") } if Str1.range(of: Str3) != nil { print("contains") } else { print("does not contain") } This produces the result as shown below.
[ { "code": null, "e": 1215, "s": 1062, "text": "To check if a string contains another string in swift, we’ll need two different strings. One string that we have to check if it consists another string." }, { "code": null, "e": 1399, "s": 1215, "text": "Let us say the string we want to check is “point” and the whole string is “TutorialsPoint” and another string is “one two three”. Let’s check with both these string in the playground." }, { "code": null, "e": 1491, "s": 1399, "text": "We can do this in two ways as shown below. Let’s start by creating three different strings." }, { "code": null, "e": 1591, "s": 1491, "text": "var CompleteStr1 = \"Tutorials point\"\nvar completeStr2 = \"one two three\"\nvar stringToCheck = \"point\"" }, { "code": null, "e": 1760, "s": 1591, "text": "In this method we’ll use the .contains method of Strings to check if there is a string within another string, it returns true if it exists, otherwise, it returns false." }, { "code": null, "e": 1863, "s": 1760, "text": "if CompleteStr1.contains(stringToCheck) {\n print(\"contains\")\n} else {\n print(\"does not contain\")\n}" }, { "code": null, "e": 2035, "s": 1863, "text": "In this method we’ll check the range of a string if the range is nil, it means that the string we are checking for, does not exist. Otherwise, it means that string exists." }, { "code": null, "e": 2146, "s": 2035, "text": "if completeStr2.range(of: stringToCheck) != nil {\n print(\"contains\")\n} else {\n print(\"does not contain\")\n}" }, { "code": null, "e": 2208, "s": 2146, "text": "When we run the above code, we get the output as shown below." }, { "code": null, "e": 2266, "s": 2208, "text": "Similarly, let’s try these methods with one more example." }, { "code": null, "e": 2502, "s": 2266, "text": "var Str1 = \"12312$$33@\"\nvar Str2 = \"%%\"\nvar Str3 = \"$$\"\nif Str1.contains(Str2) {\n print(\"contains\")\n} else {\n print(\"does not contain\")\n}\nif Str1.range(of: Str3) != nil {\n print(\"contains\")\n} else {\n print(\"does not contain\")\n}" }, { "code": null, "e": 2543, "s": 2502, "text": "This produces the result as shown below." } ]
Find frequency of each word in a string in Java
In order to get frequency of each in a string in Java we will take help of hash map collection of Java.First convert string to a character array so that it become easy to access each character of string. Now compare for each character that whether it is present in hash map or not in case it is not present than simply add it to hash map as key and assign one as its value.And if character is present than find its value which is count of occurrence of this character in the string (initial we put as 1 when it is not present in map) and add one to it.Again put the this character into the map with the updated value of its count. In last print the hash map which will give the each character as key and its occurrence as value. Live Demo import java.util.HashMap; public class FrequencyOfEachWord { public static void main(String[] args) { String str = "aaddrfshdsklhio"; char[] arr = str.toCharArray(); HashMap<Character,Integer> hMap = new HashMap<>(); for(int i= 0 ; i< arr.length ; i++) { if(hMap.containsKey(arr[i])) { int count = hMap.get(arr[i]); hMap.put(arr[i],count+1); } else { hMap.put(arr[i],1); } } System.out.println(hMap); } } {a=2, r=1, s=2, d=3, f=1, h=2, i=1, k=1, l=1, o=1}
[ { "code": null, "e": 1266, "s": 1062, "text": "In order to get frequency of each in a string in Java we will take help of hash map collection of Java.First convert string to a character array so that it become easy to access each character of string." }, { "code": null, "e": 1693, "s": 1266, "text": "Now compare for each character that whether it is present in hash map or not in case it is not present than simply add it to hash map as key and assign one as its value.And if character is present than find its value which is count of occurrence of this character in the string (initial we put as 1 when it is not present in map) and add one to it.Again put the this character into the map with the updated value of its count." }, { "code": null, "e": 1791, "s": 1693, "text": "In last print the hash map which will give the each character as key and its occurrence as value." }, { "code": null, "e": 1802, "s": 1791, "text": " Live Demo" }, { "code": null, "e": 2312, "s": 1802, "text": "import java.util.HashMap;\npublic class FrequencyOfEachWord {\n public static void main(String[] args) {\n String str = \"aaddrfshdsklhio\";\n char[] arr = str.toCharArray();\n HashMap<Character,Integer> hMap = new HashMap<>();\n for(int i= 0 ; i< arr.length ; i++) {\n if(hMap.containsKey(arr[i])) {\n int count = hMap.get(arr[i]);\n hMap.put(arr[i],count+1);\n } else {\n hMap.put(arr[i],1);\n }\n }\n System.out.println(hMap);\n }\n}" }, { "code": null, "e": 2363, "s": 2312, "text": "{a=2, r=1, s=2, d=3, f=1, h=2, i=1, k=1, l=1, o=1}" } ]
Generating QR Codes With Python In Less Than 10 Lines | by Bharath K | Towards Data Science
In the modern world, our objective is to always have a secure and convenient way of accessing things. Nobody wants to read and click on elongated URL links or lengthy word sequences. Also, in the world of the recent pandemic, it is usually considered best to avoid touches and achieve transactions without much physical contact. This objective is achieved with the help of bar codes and QR codes. Bar codes suffer from some spacing limitations, which are handled by the introduction of QR codes. QR Codes are typically two-dimensional pictographic codes that offer the users a large storage capacity and fast readability in the form of black modules arranged in a square pattern on a white background. QR codes are a fantastic resource for tracking information about numerous products, exchanging data, directing customers to a landing page or website, downloading apps, paying bills (at restaurants or other places), shopping, e-commerce, and so much more! In this article, we will learn how we can utilize Python programming to create QR codes for any specific purpose. We will generate some bar codes for specific purposes and also find out how we can decode these generated codes with the help of some decoding steps. Finally, we will look at some of the additional stuff that you can accomplish with the encoding and decoding of QR codes. For getting started with this project, there are a few library requirements in Python that we will ensure that we install successfully on our system to create, generate, and decode QR codes. The first library that we will install for encoding our QR codes is the QR code library. The command to get started with the installation of the qrcode library module is quite simple and can be installed with the following pip command. You can add the following line of command either in the virtual environment of your choice or directly in the command prompt (or windows shell) if you have the path of the environment variables set accordingly. pip install qrcode Ensure that you also have the Pillow library installed in the particular Python environment. This library is one of the best options for operating with images and dealing with most functions related to visual aesthetics. The alternative command shown in the below command block will install both the essential libraries together with the additional pillow library for generating the images of the QR codes that will be stored. pip install qrcode[pil] The final library that we will require for the successful completion of this project is the computer vision library, Open-CV. The following library is one of the more essential elements for most tasks related to image processing and computer vision. The purpose of this module for this project is to utilize one of its significant functions to decode the hidden information in the generated QR codes. The library is installable with the following command shown below. pip install opencv-python Computer vision is one of the most intriguing aspects of Data Science and Artificial Intelligence. The subject is on a constant boom and will continue to rise in popularity in the upcoming years. Hence, I would recommend viewers who are interested in this field check out my beginner’s mastery guide to Open-CV for getting started with all the essential concepts of computer vision from the below link. towardsdatascience.com In this section of the article, we will utilize the qrcode library to encode our information and generate a quick response code that we can access with some decoding. For generating the QR code, please follow the code snippet provided below, and you will have the image of the particular QR code with the relevant data stored in it. import qrcode# Create The variable to store the information# link = "https://bharath-k1297.medium.com/membership"data = "Hello! Welcome To World Of Programming!"# Encode The Linkimg = qrcode.make(data)print(type(img))# Save the QR Codeimg.save("test1.jpg") The first step to encode your desired code is to import the qrcode library that we previously installed. Once we import the library, we can either create a variable that stores the link to a particular website or create a variable that stores some useful information embedded in the form of a QR code. Encode the link into the form of an image and save the QR code that is now generated in a file name that you desire. When you print the type or format of the image that is generated, you should notice the following class displayed — <class 'qrcode.image.pil.PilImage'> Now that we have finished learning how to encode the data in the form of QR code images, let us explore some of the ways in which the following data is decodable. The above image representation is a representation of a QR code containing a link. If you are trying to access a QR code with a URL link, try to use a mobile app for decoding such QR codes or any other application to read the QR code. The above QR code, when read by an app, will direct you to the provided URL website. (The following link supports other authors and me if you apply for membership). For decoding URL links such as the above image, you can make use of QR code scanners. However, if you are trying to access encrypted data, you can decode the information with the help of Open-CV. The QR Code Detector function provides the user with the option of decoding the particular QR code image and retrieving the stored data in the QR code. Check out the below code snippet for a brief idea on you can perform the following action. import cv2# Create The Decoderdecoder = cv2.QRCodeDetector()# Load Your Datafile_name = "test1.jpg"image = cv2.imread(file_name)# Decode and Print the required informationlink, data_points, straight_qrcode = decoder.detectAndDecode(image)print(link) Here, we are importing the cv2 library and creating a variable that will act as the decoder for cracking the particular QR code image. We will then proceed to load the data and read it with the help of the cv2 library. We can then access the data and print the information accordingly. The below screenshot shows my output. Note that I am running the decoder code in the decode.py file in the tensors virtual environment. In this section, we will understand a couple of improvements that you can make to this Python project. Firstly, if you are developing your project for a specific purpose like a start-up or any other service or simply for fun, you can add a mini logo of the product, brand, or yourself as an integral part of the QR code to avoid confusion and have a clear representation of the item. The next improvement that we can make to our project is to control the QR code that is generated. The following code block shown below demonstrates how such a process can be carried out accordingly. The version attribute determines the matrix size of the QR code. The error correction used for the QR Code scan is analyzed with the error connection attribute. The box size is the pixel size of each box, and the border controls the thickness. I would recommend experimenting with the below code block. import qrcodeqr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4,) QR codes are extremely significant in the modern world today, where most of the transactions and useful data are conveyed with minimal physical contact in the most technical mechanism. Whether you want to exchange information, conduct transactions, or simplify specify the essential URL links to a particular website, these QR codes are a high utility resource. In this article, we understood how easy it is to generate QR codes with the help of Python programming in less than ten lines of code. With the installation of the required libraries, you can generate your own QR codes and decode them accordingly. You can embed useful URL links or important information in these QR codes and convey it to others in a simplistic, highly structured format. If you want to get notified about my articles as soon as they go up, check out the following link to subscribe for email recommendations. If you wish to support other authors and me, then subscribe to the below link. bharath-k1297.medium.com The technology of QR codes is quite revolutionary, and it will continue to exist until a better discovery replaces it. Hence, it is a great time to start exploring this topic. 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 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": 500, "s": 171, "text": "In the modern world, our objective is to always have a secure and convenient way of accessing things. Nobody wants to read and click on elongated URL links or lengthy word sequences. Also, in the world of the recent pandemic, it is usually considered best to avoid touches and achieve transactions without much physical contact." }, { "code": null, "e": 873, "s": 500, "text": "This objective is achieved with the help of bar codes and QR codes. Bar codes suffer from some spacing limitations, which are handled by the introduction of QR codes. QR Codes are typically two-dimensional pictographic codes that offer the users a large storage capacity and fast readability in the form of black modules arranged in a square pattern on a white background." }, { "code": null, "e": 1129, "s": 873, "text": "QR codes are a fantastic resource for tracking information about numerous products, exchanging data, directing customers to a landing page or website, downloading apps, paying bills (at restaurants or other places), shopping, e-commerce, and so much more!" }, { "code": null, "e": 1515, "s": 1129, "text": "In this article, we will learn how we can utilize Python programming to create QR codes for any specific purpose. We will generate some bar codes for specific purposes and also find out how we can decode these generated codes with the help of some decoding steps. Finally, we will look at some of the additional stuff that you can accomplish with the encoding and decoding of QR codes." }, { "code": null, "e": 1795, "s": 1515, "text": "For getting started with this project, there are a few library requirements in Python that we will ensure that we install successfully on our system to create, generate, and decode QR codes. The first library that we will install for encoding our QR codes is the QR code library." }, { "code": null, "e": 2153, "s": 1795, "text": "The command to get started with the installation of the qrcode library module is quite simple and can be installed with the following pip command. You can add the following line of command either in the virtual environment of your choice or directly in the command prompt (or windows shell) if you have the path of the environment variables set accordingly." }, { "code": null, "e": 2172, "s": 2153, "text": "pip install qrcode" }, { "code": null, "e": 2599, "s": 2172, "text": "Ensure that you also have the Pillow library installed in the particular Python environment. This library is one of the best options for operating with images and dealing with most functions related to visual aesthetics. The alternative command shown in the below command block will install both the essential libraries together with the additional pillow library for generating the images of the QR codes that will be stored." }, { "code": null, "e": 2623, "s": 2599, "text": "pip install qrcode[pil]" }, { "code": null, "e": 3091, "s": 2623, "text": "The final library that we will require for the successful completion of this project is the computer vision library, Open-CV. The following library is one of the more essential elements for most tasks related to image processing and computer vision. The purpose of this module for this project is to utilize one of its significant functions to decode the hidden information in the generated QR codes. The library is installable with the following command shown below." }, { "code": null, "e": 3117, "s": 3091, "text": "pip install opencv-python" }, { "code": null, "e": 3520, "s": 3117, "text": "Computer vision is one of the most intriguing aspects of Data Science and Artificial Intelligence. The subject is on a constant boom and will continue to rise in popularity in the upcoming years. Hence, I would recommend viewers who are interested in this field check out my beginner’s mastery guide to Open-CV for getting started with all the essential concepts of computer vision from the below link." }, { "code": null, "e": 3543, "s": 3520, "text": "towardsdatascience.com" }, { "code": null, "e": 3876, "s": 3543, "text": "In this section of the article, we will utilize the qrcode library to encode our information and generate a quick response code that we can access with some decoding. For generating the QR code, please follow the code snippet provided below, and you will have the image of the particular QR code with the relevant data stored in it." }, { "code": null, "e": 4133, "s": 3876, "text": "import qrcode# Create The variable to store the information# link = \"https://bharath-k1297.medium.com/membership\"data = \"Hello! Welcome To World Of Programming!\"# Encode The Linkimg = qrcode.make(data)print(type(img))# Save the QR Codeimg.save(\"test1.jpg\")" }, { "code": null, "e": 4668, "s": 4133, "text": "The first step to encode your desired code is to import the qrcode library that we previously installed. Once we import the library, we can either create a variable that stores the link to a particular website or create a variable that stores some useful information embedded in the form of a QR code. Encode the link into the form of an image and save the QR code that is now generated in a file name that you desire. When you print the type or format of the image that is generated, you should notice the following class displayed —" }, { "code": null, "e": 4704, "s": 4668, "text": "<class 'qrcode.image.pil.PilImage'>" }, { "code": null, "e": 4867, "s": 4704, "text": "Now that we have finished learning how to encode the data in the form of QR code images, let us explore some of the ways in which the following data is decodable." }, { "code": null, "e": 5267, "s": 4867, "text": "The above image representation is a representation of a QR code containing a link. If you are trying to access a QR code with a URL link, try to use a mobile app for decoding such QR codes or any other application to read the QR code. The above QR code, when read by an app, will direct you to the provided URL website. (The following link supports other authors and me if you apply for membership)." }, { "code": null, "e": 5706, "s": 5267, "text": "For decoding URL links such as the above image, you can make use of QR code scanners. However, if you are trying to access encrypted data, you can decode the information with the help of Open-CV. The QR Code Detector function provides the user with the option of decoding the particular QR code image and retrieving the stored data in the QR code. Check out the below code snippet for a brief idea on you can perform the following action." }, { "code": null, "e": 5956, "s": 5706, "text": "import cv2# Create The Decoderdecoder = cv2.QRCodeDetector()# Load Your Datafile_name = \"test1.jpg\"image = cv2.imread(file_name)# Decode and Print the required informationlink, data_points, straight_qrcode = decoder.detectAndDecode(image)print(link)" }, { "code": null, "e": 6378, "s": 5956, "text": "Here, we are importing the cv2 library and creating a variable that will act as the decoder for cracking the particular QR code image. We will then proceed to load the data and read it with the help of the cv2 library. We can then access the data and print the information accordingly. The below screenshot shows my output. Note that I am running the decoder code in the decode.py file in the tensors virtual environment." }, { "code": null, "e": 6762, "s": 6378, "text": "In this section, we will understand a couple of improvements that you can make to this Python project. Firstly, if you are developing your project for a specific purpose like a start-up or any other service or simply for fun, you can add a mini logo of the product, brand, or yourself as an integral part of the QR code to avoid confusion and have a clear representation of the item." }, { "code": null, "e": 7264, "s": 6762, "text": "The next improvement that we can make to our project is to control the QR code that is generated. The following code block shown below demonstrates how such a process can be carried out accordingly. The version attribute determines the matrix size of the QR code. The error correction used for the QR Code scan is analyzed with the error connection attribute. The box size is the pixel size of each box, and the border controls the thickness. I would recommend experimenting with the below code block." }, { "code": null, "e": 7395, "s": 7264, "text": "import qrcodeqr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4,)" }, { "code": null, "e": 7757, "s": 7395, "text": "QR codes are extremely significant in the modern world today, where most of the transactions and useful data are conveyed with minimal physical contact in the most technical mechanism. Whether you want to exchange information, conduct transactions, or simplify specify the essential URL links to a particular website, these QR codes are a high utility resource." }, { "code": null, "e": 8146, "s": 7757, "text": "In this article, we understood how easy it is to generate QR codes with the help of Python programming in less than ten lines of code. With the installation of the required libraries, you can generate your own QR codes and decode them accordingly. You can embed useful URL links or important information in these QR codes and convey it to others in a simplistic, highly structured format." }, { "code": null, "e": 8363, "s": 8146, "text": "If you want to get notified about my articles as soon as they go up, check out the following link to subscribe for email recommendations. If you wish to support other authors and me, then subscribe to the below link." }, { "code": null, "e": 8388, "s": 8363, "text": "bharath-k1297.medium.com" }, { "code": null, "e": 8762, "s": 8388, "text": "The technology of QR codes is quite revolutionary, and it will continue to exist until a better discovery replaces it. Hence, it is a great time to start exploring this topic. 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": 8828, "s": 8762, "text": "Check out some of my other articles that you might enjoy reading!" }, { "code": null, "e": 8851, "s": 8828, "text": "towardsdatascience.com" }, { "code": null, "e": 8874, "s": 8851, "text": "towardsdatascience.com" }, { "code": null, "e": 8897, "s": 8874, "text": "towardsdatascience.com" } ]
JSP - Cookies Handling
In this chapter, we will discuss Cookies Handling in JSP. Cookies are text files stored on the client computer and they are kept for various information tracking purposes. JSP transparently supports HTTP cookies using underlying servlet technology. There are three steps involved in identifying and returning users − Server script sends a set of cookies to the browser. For example, name, age, or identification number, etc. Server script sends a set of cookies to the browser. For example, name, age, or identification number, etc. Browser stores this information on the local machine for future use. Browser stores this information on the local machine for future use. When the next time the browser sends any request to the web server then it sends those cookies information to the server and server uses that information to identify the user or may be for some other purpose as well. When the next time the browser sends any request to the web server then it sends those cookies information to the server and server uses that information to identify the user or may be for some other purpose as well. This chapter will teach you how to set or reset cookies, how to access them and how to delete them using JSP programs. Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A JSP that sets a cookie might send headers that look something like this − HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; path = /; domain = tutorialspoint.com Connection: close Content-Type: text/html As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date. If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this − GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name = xyz A JSP script will then have access to the cookies through the request method request.getCookies() which returns an array of Cookie objects. Following table lists out the useful methods associated with the Cookie object which you can use while manipulating cookies in JSP − public void setDomain(String pattern) This method sets the domain to which the cookie applies; for example, tutorialspoint.com. public String getDomain() This method gets the domain to which the cookie applies; for example, tutorialspoint.com. public void setMaxAge(int expiry) This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session. public int getMaxAge() This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until the browser shutdown. public String getName() This method returns the name of the cookie. The name cannot be changed after the creation. public void setValue(String newValue) This method sets the value associated with the cookie. public String getValue() This method gets the value associated with the cookie. public void setPath(String uri) This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories. public String getPath() This method gets the path to which this cookie applies. public void setSecure(boolean flag) This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e, SSL) connections. public void setComment(String purpose) This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user. public String getComment() This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment. Setting cookies with JSP involves three steps − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings. Cookie cookie = new Cookie("key","value"); Keep in mind, neither the name nor the value should contain white space or any of the following characters − [ ] ( ) = , " / ? @ : ; You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code will set up a cookie for 24 hours. cookie.setMaxAge(60*60*24); You use response.addCookie to add cookies in the HTTP response header as follows response.addCookie(cookie); Let us modify our Form Example to set the cookies for the first and the last name. <% // Create cookies for first and last names. Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); %> <html> <head> <title>Setting Cookies</title> </head> <body> <center> <h1>Setting Cookies</h1> </center> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last_name")%> </p></li> </ul> </body> </html> Let us put the above code in main.jsp file and use it in the following HTML page − <html> <body> <form action = "main.jsp" method = "GET"> First Name: <input type = "text" name = "first_name"> <br /> Last Name: <input type = "text" name = "last_name" /> <input type = "submit" value = "Submit" /> </form> </body> </html> Keep the above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-installation-directory>/webapps/ROOT directory. When you will access http://localhost:8080/hello.jsp, here is the actual output of the above form. Try to enter the First Name and the Last Name and then click the submit button. This will display the first name and the last name on your screen and will also set two cookies firstName and lastName. These cookies will be passed back to the server when the next time you click the Submit button. In the next section, we will explain how you can access these cookies back in your web application. To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value. Let us now read cookies that were set in the previous example − <html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with the this domain cookies = request.getCookies(); if( cookies != null ) { out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } } else { out.println("<h2>No cookies founds</h2>"); } %> </body> </html> Let us now put the above code in main.jsp file and try to access it. If you set the first_name cookie as "John" and the last_name cookie as "Player" then running http://localhost:8080/main.jsp will display the following result − Found Cookies Name and Value Name : first_name, Value: John Name : last_name, Value: Player Name : first_name, Value: John Name : last_name, Value: Player To delete cookies is very simple. If you want to delete a cookie, then you simply need to follow these three steps − Read an already existing cookie and store it in Cookie object. Read an already existing cookie and store it in Cookie object. Set cookie age as zero using the setMaxAge() method to delete an existing cookie. Set cookie age as zero using the setMaxAge() method to delete an existing cookie. Add this cookie back into the response header. Add this cookie back into the response header. Following example will show you how to delete an existing cookie named "first_name" and when you run main.jsp JSP next time, it will return null value for first_name. <html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with the this domain cookies = request.getCookies(); if( cookies != null ) { out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; if((cookie.getName( )).compareTo("first_name") == 0 ) { cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie: " + cookie.getName( ) + "<br/>"); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } } else { out.println( "<h2>No cookies founds</h2>"); } %> </body> </html> Let us now put the above code in the main.jsp file and try to access it. It will display the following result − Cookies Name and Value Deleted cookie : first_name Name : first_name, Value: John Name : last_name, Value: Player Deleted cookie : first_name Name : first_name, Value: John Name : last_name, Value: Player Now run http://localhost:8080/main.jsp once again and it should display only one cookie as follows − Found Cookies Name and Value Name : last_name, Value: Player You can delete your cookies in the Internet Explorer manually. Start at the Tools menu and select the Internet Options. To delete all cookies, click the Delete Cookies button. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2488, "s": 2239, "text": "In this chapter, we will discuss Cookies Handling in JSP. Cookies are text files stored on the client computer and they are kept for various information tracking purposes. JSP transparently supports HTTP cookies using underlying servlet technology." }, { "code": null, "e": 2556, "s": 2488, "text": "There are three steps involved in identifying and returning users −" }, { "code": null, "e": 2664, "s": 2556, "text": "Server script sends a set of cookies to the browser. For example, name, age, or identification number, etc." }, { "code": null, "e": 2772, "s": 2664, "text": "Server script sends a set of cookies to the browser. For example, name, age, or identification number, etc." }, { "code": null, "e": 2841, "s": 2772, "text": "Browser stores this information on the local machine for future use." }, { "code": null, "e": 2910, "s": 2841, "text": "Browser stores this information on the local machine for future use." }, { "code": null, "e": 3127, "s": 2910, "text": "When the next time the browser sends any request to the web server then it sends those cookies information to the server and server uses that information to identify the user or may be for some other purpose as well." }, { "code": null, "e": 3344, "s": 3127, "text": "When the next time the browser sends any request to the web server then it sends those cookies information to the server and server uses that information to identify the user or may be for some other purpose as well." }, { "code": null, "e": 3463, "s": 3344, "text": "This chapter will teach you how to set or reset cookies, how to access them and how to delete them using JSP programs." }, { "code": null, "e": 3648, "s": 3463, "text": "Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A JSP that sets a cookie might send headers that look something like this −" }, { "code": null, "e": 3888, "s": 3648, "text": "HTTP/1.1 200 OK\nDate: Fri, 04 Feb 2000 21:03:38 GMT\nServer: Apache/1.3.9 (UNIX) PHP/4.0b3\nSet-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; \n path = /; domain = tutorialspoint.com\nConnection: close\nContent-Type: text/html" }, { "code": null, "e": 4132, "s": 3888, "text": "As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to \"forget\" the cookie after the given time and date." }, { "code": null, "e": 4424, "s": 4132, "text": "If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this −" }, { "code": null, "e": 4668, "s": 4424, "text": "GET / HTTP/1.0\nConnection: Keep-Alive\nUser-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)\nHost: zink.demon.co.uk:1126\n\nAccept: image/gif, */*\nAccept-Encoding: gzip\nAccept-Language: en\nAccept-Charset: iso-8859-1,*,utf-8\nCookie: name = xyz" }, { "code": null, "e": 4808, "s": 4668, "text": "A JSP script will then have access to the cookies through the request method request.getCookies() which returns an array of Cookie objects." }, { "code": null, "e": 4941, "s": 4808, "text": "Following table lists out the useful methods associated with the Cookie object which you can use while manipulating cookies in JSP −" }, { "code": null, "e": 4979, "s": 4941, "text": "public void setDomain(String pattern)" }, { "code": null, "e": 5069, "s": 4979, "text": "This method sets the domain to which the cookie applies; for example, tutorialspoint.com." }, { "code": null, "e": 5095, "s": 5069, "text": "public String getDomain()" }, { "code": null, "e": 5185, "s": 5095, "text": "This method gets the domain to which the cookie applies; for example, tutorialspoint.com." }, { "code": null, "e": 5219, "s": 5185, "text": "public void setMaxAge(int expiry)" }, { "code": null, "e": 5378, "s": 5219, "text": "This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session." }, { "code": null, "e": 5401, "s": 5378, "text": "public int getMaxAge()" }, { "code": null, "e": 5552, "s": 5401, "text": "This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until the browser shutdown." }, { "code": null, "e": 5576, "s": 5552, "text": "public String getName()" }, { "code": null, "e": 5667, "s": 5576, "text": "This method returns the name of the cookie. The name cannot be changed after the creation." }, { "code": null, "e": 5705, "s": 5667, "text": "public void setValue(String newValue)" }, { "code": null, "e": 5760, "s": 5705, "text": "This method sets the value associated with the cookie." }, { "code": null, "e": 5785, "s": 5760, "text": "public String getValue()" }, { "code": null, "e": 5840, "s": 5785, "text": "This method gets the value associated with the cookie." }, { "code": null, "e": 5872, "s": 5840, "text": "public void setPath(String uri)" }, { "code": null, "e": 6066, "s": 5872, "text": "This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories." }, { "code": null, "e": 6090, "s": 6066, "text": "public String getPath()" }, { "code": null, "e": 6146, "s": 6090, "text": "This method gets the path to which this cookie applies." }, { "code": null, "e": 6182, "s": 6146, "text": "public void setSecure(boolean flag)" }, { "code": null, "e": 6306, "s": 6182, "text": "This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e, SSL) connections." }, { "code": null, "e": 6345, "s": 6306, "text": "public void setComment(String purpose)" }, { "code": null, "e": 6482, "s": 6345, "text": "This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user." }, { "code": null, "e": 6509, "s": 6482, "text": "public String getComment()" }, { "code": null, "e": 6618, "s": 6509, "text": "This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment." }, { "code": null, "e": 6666, "s": 6618, "text": "Setting cookies with JSP involves three steps −" }, { "code": null, "e": 6764, "s": 6666, "text": "You call the Cookie constructor with a cookie name and a cookie value, both of which are strings." }, { "code": null, "e": 6808, "s": 6764, "text": "Cookie cookie = new Cookie(\"key\",\"value\");\n" }, { "code": null, "e": 6917, "s": 6808, "text": "Keep in mind, neither the name nor the value should contain white space or any of the following characters −" }, { "code": null, "e": 6942, "s": 6917, "text": "[ ] ( ) = , \" / ? @ : ;\n" }, { "code": null, "e": 7075, "s": 6942, "text": "You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code will set up a cookie for 24 hours." }, { "code": null, "e": 7105, "s": 7075, "text": "cookie.setMaxAge(60*60*24); \n" }, { "code": null, "e": 7186, "s": 7105, "text": "You use response.addCookie to add cookies in the HTTP response header as follows" }, { "code": null, "e": 7215, "s": 7186, "text": "response.addCookie(cookie);\n" }, { "code": null, "e": 7298, "s": 7215, "text": "Let us modify our Form Example to set the cookies for the first and the last name." }, { "code": null, "e": 8182, "s": 7298, "text": "<%\n // Create cookies for first and last names. \n Cookie firstName = new Cookie(\"first_name\", request.getParameter(\"first_name\"));\n Cookie lastName = new Cookie(\"last_name\", request.getParameter(\"last_name\"));\n \n // Set expiry date after 24 Hrs for both the cookies.\n firstName.setMaxAge(60*60*24); \n lastName.setMaxAge(60*60*24); \n \n // Add both the cookies in the response header.\n response.addCookie( firstName );\n response.addCookie( lastName );\n%>\n\n<html>\n <head>\n <title>Setting Cookies</title>\n </head>\n \n <body>\n <center>\n <h1>Setting Cookies</h1>\n </center>\n <ul>\n <li><p><b>First Name:</b>\n <%= request.getParameter(\"first_name\")%>\n </p></li>\n <li><p><b>Last Name:</b>\n <%= request.getParameter(\"last_name\")%>\n </p></li>\n </ul>\n \n </body>\n</html>" }, { "code": null, "e": 8265, "s": 8182, "text": "Let us put the above code in main.jsp file and use it in the following HTML page −" }, { "code": null, "e": 8571, "s": 8265, "text": "<html>\n <body>\n \n <form action = \"main.jsp\" method = \"GET\">\n First Name: <input type = \"text\" name = \"first_name\">\n <br />\n Last Name: <input type = \"text\" name = \"last_name\" />\n <input type = \"submit\" value = \"Submit\" />\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 8808, "s": 8571, "text": "Keep the above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-installation-directory>/webapps/ROOT directory. When you will access http://localhost:8080/hello.jsp, here is the actual output of the above form." }, { "code": null, "e": 9104, "s": 8808, "text": "Try to enter the First Name and the Last Name and then click the submit button. This will display the first name and the last name on your screen and will also set two cookies firstName and lastName. These cookies will be passed back to the server when the next time you click the Submit button." }, { "code": null, "e": 9204, "s": 9104, "text": "In the next section, we will explain how you can access these cookies back in your web application." }, { "code": null, "e": 9460, "s": 9204, "text": "To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value." }, { "code": null, "e": 9524, "s": 9460, "text": "Let us now read cookies that were set in the previous example −" }, { "code": null, "e": 10337, "s": 9524, "text": "<html>\n <head>\n <title>Reading Cookies</title>\n </head>\n \n <body>\n <center>\n <h1>Reading Cookies</h1>\n </center>\n <%\n Cookie cookie = null;\n Cookie[] cookies = null;\n \n // Get an array of Cookies associated with the this domain\n cookies = request.getCookies();\n \n if( cookies != null ) {\n out.println(\"<h2> Found Cookies Name and Value</h2>\");\n \n for (int i = 0; i < cookies.length; i++) {\n cookie = cookies[i];\n out.print(\"Name : \" + cookie.getName( ) + \", \");\n out.print(\"Value: \" + cookie.getValue( )+\" <br/>\");\n }\n } else {\n out.println(\"<h2>No cookies founds</h2>\");\n }\n %>\n </body>\n \n</html>" }, { "code": null, "e": 10566, "s": 10337, "text": "Let us now put the above code in main.jsp file and try to access it. If you set the first_name cookie as \"John\" and the last_name cookie as \"Player\" then running http://localhost:8080/main.jsp will display the following result −" }, { "code": null, "e": 10661, "s": 10566, "text": " Found Cookies Name and Value\nName : first_name, Value: John\nName : last_name, Value: Player\n" }, { "code": null, "e": 10692, "s": 10661, "text": "Name : first_name, Value: John" }, { "code": null, "e": 10725, "s": 10692, "text": "Name : last_name, Value: Player" }, { "code": null, "e": 10842, "s": 10725, "text": "To delete cookies is very simple. If you want to delete a cookie, then you simply need to follow these three steps −" }, { "code": null, "e": 10905, "s": 10842, "text": "Read an already existing cookie and store it in Cookie object." }, { "code": null, "e": 10968, "s": 10905, "text": "Read an already existing cookie and store it in Cookie object." }, { "code": null, "e": 11050, "s": 10968, "text": "Set cookie age as zero using the setMaxAge() method to delete an existing cookie." }, { "code": null, "e": 11132, "s": 11050, "text": "Set cookie age as zero using the setMaxAge() method to delete an existing cookie." }, { "code": null, "e": 11179, "s": 11132, "text": "Add this cookie back into the response header." }, { "code": null, "e": 11226, "s": 11179, "text": "Add this cookie back into the response header." }, { "code": null, "e": 11393, "s": 11226, "text": "Following example will show you how to delete an existing cookie named \"first_name\" and when you run main.jsp JSP next time, it will return null value for first_name." }, { "code": null, "e": 12506, "s": 11393, "text": "<html>\n <head>\n <title>Reading Cookies</title>\n </head>\n \n <body>\n <center>\n <h1>Reading Cookies</h1>\n </center>\n <%\n Cookie cookie = null;\n Cookie[] cookies = null;\n \n // Get an array of Cookies associated with the this domain\n cookies = request.getCookies();\n \n if( cookies != null ) {\n out.println(\"<h2> Found Cookies Name and Value</h2>\");\n \n for (int i = 0; i < cookies.length; i++) {\n cookie = cookies[i];\n \n if((cookie.getName( )).compareTo(\"first_name\") == 0 ) {\n cookie.setMaxAge(0);\n response.addCookie(cookie);\n out.print(\"Deleted cookie: \" + \n cookie.getName( ) + \"<br/>\");\n }\n out.print(\"Name : \" + cookie.getName( ) + \", \");\n out.print(\"Value: \" + cookie.getValue( )+\" <br/>\");\n }\n } else {\n out.println(\n \"<h2>No cookies founds</h2>\");\n }\n %>\n </body>\n \n</html>" }, { "code": null, "e": 12618, "s": 12506, "text": "Let us now put the above code in the main.jsp file and try to access it. It will display the following result −" }, { "code": null, "e": 12734, "s": 12618, "text": "Cookies Name and Value\nDeleted cookie : first_name\nName : first_name, Value: John\nName : last_name, Value: Player\n" }, { "code": null, "e": 12762, "s": 12734, "text": "Deleted cookie : first_name" }, { "code": null, "e": 12793, "s": 12762, "text": "Name : first_name, Value: John" }, { "code": null, "e": 12826, "s": 12793, "text": "Name : last_name, Value: Player" }, { "code": null, "e": 12927, "s": 12826, "text": "Now run http://localhost:8080/main.jsp once again and it should display only one cookie as follows −" }, { "code": null, "e": 12991, "s": 12927, "text": " Found Cookies Name and Value\nName : last_name, Value: Player\n" }, { "code": null, "e": 13167, "s": 12991, "text": "You can delete your cookies in the Internet Explorer manually. Start at the Tools menu and select the Internet Options. To delete all cookies, click the Delete Cookies button." }, { "code": null, "e": 13202, "s": 13167, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 13217, "s": 13202, "text": " Chaand Sheikh" }, { "code": null, "e": 13252, "s": 13217, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 13267, "s": 13252, "text": " Chaand Sheikh" }, { "code": null, "e": 13302, "s": 13267, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13316, "s": 13302, "text": " Karthikeya T" }, { "code": null, "e": 13351, "s": 13316, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 13367, "s": 13351, "text": " TELCOMA Global" }, { "code": null, "e": 13400, "s": 13367, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 13416, "s": 13400, "text": " TELCOMA Global" }, { "code": null, "e": 13450, "s": 13416, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 13458, "s": 13450, "text": " Uplatz" }, { "code": null, "e": 13465, "s": 13458, "text": " Print" }, { "code": null, "e": 13476, "s": 13465, "text": " Add Notes" } ]
Maximize the sum of array after multiplying a prefix and suffix by -1 - GeeksforGeeks
17 Jan, 2022 Given an array arr[] of length N, the task is to maximize the sum of all the elements of the array by performing the following operations at most once. Choose a prefix of the array and multiply all the elements by -1. Choose a suffix of the array and multiply all the elements by -1. Examples: Input: arr[] = {-1, -2, -3} Output: 6 Explanation: Operation 1: Prefix of array – {-1, -2, -3} can be multiplied with -1 to get the maximum sum. Array after Operation: {1, 2, 3} Sum = 1 + 2 + 3 = 6 Input: arr[] = {-4, 2, 0, 5, 0} Output: 11 Explanation: Operation 1: Prefix of array – {-4} can be multiplied with -1 to get the maximum sum. Array after operation: {4, 2, 0, 5, 0} Sum = 4 + 2 + 0 + 5 + 0 = 11 Approach: The key observation in the problem is if the chosen range of the prefix and suffix intersect, then the elements of intersection portion have same sign. Due to which it is always better to choose non-intersecting ranges of the prefix and suffix array. Below is the illustration of the steps: It is easily been observed that there will be a portion/subarray in the array whose sum is the same as the original and the sum of the other elements is reversed. So the new sum of the array will be: // X - Sum of subarray which is not in // the range of the prefix and suffix // S - Sum of the original array New Sum = X + -1*(S - X) = 2*X - S Hence, the idea is to maximize the value of X to get the maximum sum because S is the constant value which cannot be changed. This can be achieved with the help of the Kadane’s Algorithm. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// maximum sum of the array by// multiplying the prefix and suffix// of the array by -1 #include <bits/stdc++.h> using namespace std; // Kadane's algorithm to find// the maximum subarray sumint maxSubArraySum(int a[], int size){ int max_so_far = INT_MIN, max_ending_here = 0; // Loop to find the maximum subarray // array sum in the given array for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far;} // Function to find the maximum// sum of the array by multiplying// the prefix and suffix by -1int maxSum(int a[], int n){ // Total initial sum int S = 0; // Loop to find the maximum // sum of the array for (int i = 0; i < n; i++) S += a[i]; int X = maxSubArraySum(a, n); // Maximum value return 2 * X - S;} // Driver Codeint main(){ int a[] = { -1, -2, -3 }; int n = sizeof(a) / sizeof(a[0]); int max_sum = maxSum(a, n); cout << max_sum; return 0;} // Java implementation to find the// maximum sum of the array by// multiplying the prefix and suffix// of the array by -1class GFG{ // Kadane's algorithm to find // the maximum subarray sum static int maxSubArraySum(int a[], int size) { int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; // Loop to find the maximum subarray // array sum in the given array for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far; } // Function to find the maximum // sum of the array by multiplying // the prefix and suffix by -1 static int maxSum(int a[], int n) { // Total initial sum int S = 0; int i; // Loop to find the maximum // sum of the array for (i = 0; i < n; i++) S += a[i]; int X = maxSubArraySum(a, n); // Maximum value return 2 * X - S; } // Driver Code public static void main(String []args) { int a[] = { -1, -2, -3 }; int n = a.length; int max_sum = maxSum(a, n); System.out.print(max_sum); }} // This code is contributed by chitranayal # Python3 implementation to find the# maximum sum of the array by# multiplying the prefix and suffix# of the array by -1 # Kadane's algorithm to find# the maximum subarray sumdef maxSubArraySum(a, size): max_so_far = -10**9 max_ending_here = 0 # Loop to find the maximum subarray # array sum in the given array for i in range(size): max_ending_here = max_ending_here + a[i] if (max_ending_here < 0): max_ending_here = 0 if (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far # Function to find the maximum# sum of the array by multiplying# the prefix and suffix by -1def maxSum(a, n): # Total initial sum S = 0 # Loop to find the maximum # sum of the array for i in range(n): S += a[i] X = maxSubArraySum(a, n) # Maximum value return 2 * X - S # Driver Codeif __name__ == '__main__': a=[-1, -2, -3] n= len(a) max_sum = maxSum(a, n) print(max_sum) # This code is contributed by mohit kumar 29 // C# implementation to find the// maximum sum of the array by// multiplying the prefix and suffix// of the array by -1using System; class GFG{ // Kadane's algorithm to find // the maximum subarray sum static int maxSubArraySum(int []a, int size) { int max_so_far = int.MinValue, max_ending_here = 0; // Loop to find the maximum subarray // array sum in the given array for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far; } // Function to find the maximum // sum of the array by multiplying // the prefix and suffix by -1 static int maxSum(int []a, int n) { // Total initial sum int S = 0; int i; // Loop to find the maximum // sum of the array for (i = 0; i < n; i++) S += a[i]; int X = maxSubArraySum(a, n); // Maximum value return 2 * X - S; } // Driver Code public static void Main(String []args) { int []a = { -1, -2, -3 }; int n = a.Length; int max_sum = maxSum(a, n); Console.Write(max_sum); }} // This code is contributed by sapnasingh4991 <script> // Javascript implementation to find the// maximum sum of the array by// multiplying the prefix and suffix// of the array by -1 // Kadane's algorithm to find// the maximum subarray sumfunction maxSubArraySum(a, size){ var max_so_far = Number.MIN_VALUE, max_ending_here = 0; // Loop to find the maximum subarray // array sum in the given array for(i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far;} // Function to find the maximum// sum of the array by multiplying// the prefix and suffix by -1function maxSum(a, n){ // Total initial sum var S = 0; var i; // Loop to find the maximum // sum of the array for(i = 0; i < n; i++) S += a[i]; var X = maxSubArraySum(a, n); // Maximum value return 2 * X - S;} // Driver Codevar a = [ -1, -2, -3 ];var n = a.length;var max_sum = maxSum(a, n); document.write(max_sum); // This code is contributed by aashish1995 </script> 6 Time Complexity: O(N) mohit kumar 29 ukasp sapnasingh4991 aashish1995 simranarora5sos Algorithms Arrays Dynamic Programming Greedy Arrays Dynamic Programming Greedy Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms How to write a Pseudo Code? Difference between Informed and Uninformed Search in AI Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Write a program to reverse an array or string
[ { "code": null, "e": 24853, "s": 24825, "text": "\n17 Jan, 2022" }, { "code": null, "e": 25006, "s": 24853, "text": "Given an array arr[] of length N, the task is to maximize the sum of all the elements of the array by performing the following operations at most once. " }, { "code": null, "e": 25072, "s": 25006, "text": "Choose a prefix of the array and multiply all the elements by -1." }, { "code": null, "e": 25138, "s": 25072, "text": "Choose a suffix of the array and multiply all the elements by -1." }, { "code": null, "e": 25150, "s": 25138, "text": "Examples: " }, { "code": null, "e": 25348, "s": 25150, "text": "Input: arr[] = {-1, -2, -3} Output: 6 Explanation: Operation 1: Prefix of array – {-1, -2, -3} can be multiplied with -1 to get the maximum sum. Array after Operation: {1, 2, 3} Sum = 1 + 2 + 3 = 6" }, { "code": null, "e": 25559, "s": 25348, "text": "Input: arr[] = {-4, 2, 0, 5, 0} Output: 11 Explanation: Operation 1: Prefix of array – {-4} can be multiplied with -1 to get the maximum sum. Array after operation: {4, 2, 0, 5, 0} Sum = 4 + 2 + 0 + 5 + 0 = 11 " }, { "code": null, "e": 25862, "s": 25559, "text": "Approach: The key observation in the problem is if the chosen range of the prefix and suffix intersect, then the elements of intersection portion have same sign. Due to which it is always better to choose non-intersecting ranges of the prefix and suffix array. Below is the illustration of the steps: " }, { "code": null, "e": 26062, "s": 25862, "text": "It is easily been observed that there will be a portion/subarray in the array whose sum is the same as the original and the sum of the other elements is reversed. So the new sum of the array will be:" }, { "code": null, "e": 26213, "s": 26062, "text": "// X - Sum of subarray which is not in\n// the range of the prefix and suffix\n// S - Sum of the original array\n\nNew Sum = X + -1*(S - X) = 2*X - S " }, { "code": null, "e": 26401, "s": 26213, "text": "Hence, the idea is to maximize the value of X to get the maximum sum because S is the constant value which cannot be changed. This can be achieved with the help of the Kadane’s Algorithm." }, { "code": null, "e": 26453, "s": 26401, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26457, "s": 26453, "text": "C++" }, { "code": null, "e": 26462, "s": 26457, "text": "Java" }, { "code": null, "e": 26470, "s": 26462, "text": "Python3" }, { "code": null, "e": 26473, "s": 26470, "text": "C#" }, { "code": null, "e": 26484, "s": 26473, "text": "Javascript" }, { "code": "// C++ implementation to find the// maximum sum of the array by// multiplying the prefix and suffix// of the array by -1 #include <bits/stdc++.h> using namespace std; // Kadane's algorithm to find// the maximum subarray sumint maxSubArraySum(int a[], int size){ int max_so_far = INT_MIN, max_ending_here = 0; // Loop to find the maximum subarray // array sum in the given array for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far;} // Function to find the maximum// sum of the array by multiplying// the prefix and suffix by -1int maxSum(int a[], int n){ // Total initial sum int S = 0; // Loop to find the maximum // sum of the array for (int i = 0; i < n; i++) S += a[i]; int X = maxSubArraySum(a, n); // Maximum value return 2 * X - S;} // Driver Codeint main(){ int a[] = { -1, -2, -3 }; int n = sizeof(a) / sizeof(a[0]); int max_sum = maxSum(a, n); cout << max_sum; return 0;}", "e": 27666, "s": 26484, "text": null }, { "code": "// Java implementation to find the// maximum sum of the array by// multiplying the prefix and suffix// of the array by -1class GFG{ // Kadane's algorithm to find // the maximum subarray sum static int maxSubArraySum(int a[], int size) { int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; // Loop to find the maximum subarray // array sum in the given array for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far; } // Function to find the maximum // sum of the array by multiplying // the prefix and suffix by -1 static int maxSum(int a[], int n) { // Total initial sum int S = 0; int i; // Loop to find the maximum // sum of the array for (i = 0; i < n; i++) S += a[i]; int X = maxSubArraySum(a, n); // Maximum value return 2 * X - S; } // Driver Code public static void main(String []args) { int a[] = { -1, -2, -3 }; int n = a.length; int max_sum = maxSum(a, n); System.out.print(max_sum); }} // This code is contributed by chitranayal", "e": 29090, "s": 27666, "text": null }, { "code": "# Python3 implementation to find the# maximum sum of the array by# multiplying the prefix and suffix# of the array by -1 # Kadane's algorithm to find# the maximum subarray sumdef maxSubArraySum(a, size): max_so_far = -10**9 max_ending_here = 0 # Loop to find the maximum subarray # array sum in the given array for i in range(size): max_ending_here = max_ending_here + a[i] if (max_ending_here < 0): max_ending_here = 0 if (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far # Function to find the maximum# sum of the array by multiplying# the prefix and suffix by -1def maxSum(a, n): # Total initial sum S = 0 # Loop to find the maximum # sum of the array for i in range(n): S += a[i] X = maxSubArraySum(a, n) # Maximum value return 2 * X - S # Driver Codeif __name__ == '__main__': a=[-1, -2, -3] n= len(a) max_sum = maxSum(a, n) print(max_sum) # This code is contributed by mohit kumar 29", "e": 30117, "s": 29090, "text": null }, { "code": "// C# implementation to find the// maximum sum of the array by// multiplying the prefix and suffix// of the array by -1using System; class GFG{ // Kadane's algorithm to find // the maximum subarray sum static int maxSubArraySum(int []a, int size) { int max_so_far = int.MinValue, max_ending_here = 0; // Loop to find the maximum subarray // array sum in the given array for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far; } // Function to find the maximum // sum of the array by multiplying // the prefix and suffix by -1 static int maxSum(int []a, int n) { // Total initial sum int S = 0; int i; // Loop to find the maximum // sum of the array for (i = 0; i < n; i++) S += a[i]; int X = maxSubArraySum(a, n); // Maximum value return 2 * X - S; } // Driver Code public static void Main(String []args) { int []a = { -1, -2, -3 }; int n = a.Length; int max_sum = maxSum(a, n); Console.Write(max_sum); }} // This code is contributed by sapnasingh4991", "e": 31555, "s": 30117, "text": null }, { "code": "<script> // Javascript implementation to find the// maximum sum of the array by// multiplying the prefix and suffix// of the array by -1 // Kadane's algorithm to find// the maximum subarray sumfunction maxSubArraySum(a, size){ var max_so_far = Number.MIN_VALUE, max_ending_here = 0; // Loop to find the maximum subarray // array sum in the given array for(i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far;} // Function to find the maximum// sum of the array by multiplying// the prefix and suffix by -1function maxSum(a, n){ // Total initial sum var S = 0; var i; // Loop to find the maximum // sum of the array for(i = 0; i < n; i++) S += a[i]; var X = maxSubArraySum(a, n); // Maximum value return 2 * X - S;} // Driver Codevar a = [ -1, -2, -3 ];var n = a.length;var max_sum = maxSum(a, n); document.write(max_sum); // This code is contributed by aashish1995 </script>", "e": 32721, "s": 31555, "text": null }, { "code": null, "e": 32723, "s": 32721, "text": "6" }, { "code": null, "e": 32748, "s": 32725, "text": "Time Complexity: O(N) " }, { "code": null, "e": 32763, "s": 32748, "text": "mohit kumar 29" }, { "code": null, "e": 32769, "s": 32763, "text": "ukasp" }, { "code": null, "e": 32784, "s": 32769, "text": "sapnasingh4991" }, { "code": null, "e": 32796, "s": 32784, "text": "aashish1995" }, { "code": null, "e": 32812, "s": 32796, "text": "simranarora5sos" }, { "code": null, "e": 32823, "s": 32812, "text": "Algorithms" }, { "code": null, "e": 32830, "s": 32823, "text": "Arrays" }, { "code": null, "e": 32850, "s": 32830, "text": "Dynamic Programming" }, { "code": null, "e": 32857, "s": 32850, "text": "Greedy" }, { "code": null, "e": 32864, "s": 32857, "text": "Arrays" }, { "code": null, "e": 32884, "s": 32864, "text": "Dynamic Programming" }, { "code": null, "e": 32891, "s": 32884, "text": "Greedy" }, { "code": null, "e": 32902, "s": 32891, "text": "Algorithms" }, { "code": null, "e": 33000, "s": 32902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33009, "s": 33000, "text": "Comments" }, { "code": null, "e": 33022, "s": 33009, "text": "Old Comments" }, { "code": null, "e": 33071, "s": 33022, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 33096, "s": 33071, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33123, "s": 33096, "text": "Introduction to Algorithms" }, { "code": null, "e": 33151, "s": 33123, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 33207, "s": 33151, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 33222, "s": 33207, "text": "Arrays in Java" }, { "code": null, "e": 33238, "s": 33222, "text": "Arrays in C/C++" }, { "code": null, "e": 33265, "s": 33238, "text": "Program for array rotation" }, { "code": null, "e": 33313, "s": 33265, "text": "Stack Data Structure (Introduction and Program)" } ]
Find the Intersection Point of Two Linked Lists in Java
A Linked List is a linear data structure in which each node has two blocks such that one block contains the value or data of the node and the other block contains the address of the next field. Let us assume that we have a linked list such that each node contains a random pointer which is pointing to the other nodes in the list. The task is to find the node at which two linked lists intersect each other. If they don’t intersect, then return NULL or empty as output. For Example Input-1: Output: 2 Explanation: Since the given linked list intersects at the node with the value ‘2’, we will return the value ‘2’ as the output. Input-2: Output: NULL Explanation: Since there are no common points, we will return NULL in this case. We have two linked lists with a common point where they intersect each other. To find the intersection point, we will traverse both the linked lists till we find that they are equally pointing to the same value. At some point, the pointer to the next node of the linked list will be the same. Thus we will return the value of that point. Take two linked lists with data and pointer to the next node. A function commonPoint(listnode*headA, listnode*headB) takes two pointers of linked list respectively and returns the value of the common or intersection point of the linked list. An integer function that finds the length of the linked list will return the length of both linked lists from the head of the list. Now create a pointer to the head of both lists and traverse the list which is greater in its length till (length of first list – length of second list). Now traverse the list till we find the next pointer is equal. Return the value of that particular node where both the lists intersect. Live Demo public class Solution { static listnode headA, headB; static class listnode { int data; listnode next; listnode(int d) { data = d; next = null; } } int count(listnode head) { int c = 0; while (head != null) { c++; head = head.next; } return c; } int commonPoint(listnode headA, listnode headB) { listnode p1 = headA; listnode p2 = headB; int c1 = count(headA); int c2 = count(headB); if (c1 > c2) { for (int i = 0; i < c1 - c2; i++) { if (p1 == null) { return - 1; } p1 = p1.next; } } if (c1 < c2) { for (int i = 0; i < c2 - c1; i++) { if (p2 == null) { return - 1; } p2 = p2.next; } } while (p1 != null &amp;&amp; p2 != null) { if (p1.data == p2.data) { return p1.data; } p1 = p1.next; p2 = p2.next; } return - 1; } public static void main(String[] args) { Solution list = new Solution(); list.headA = new listnode(5); list.headA.next = new listnode(4); list.headA.next.next = new listnode(9); list.headA.next.next.next = new listnode(7); list.headA.next.next.next.next = new listnode(1); list.headB = new listnode(6); list.headB.next = new listnode(7); list.headB.next.next = new listnode(1); System.out.println(list.commonPoint(headA, headB)); } } Running the above code will generate the output as, 7 Explanation: The given linked lists are intersecting at 7.
[ { "code": null, "e": 1256, "s": 1062, "text": "A Linked List is a linear data structure in which each node has two blocks such that one block contains the value or data of the node and the other block contains the address of the next field." }, { "code": null, "e": 1532, "s": 1256, "text": "Let us assume that we have a linked list such that each node contains a random pointer which is pointing to the other nodes in the list. The task is to find the node at which two linked lists intersect each other. If they don’t intersect, then return NULL or empty as output." }, { "code": null, "e": 1544, "s": 1532, "text": "For Example" }, { "code": null, "e": 1553, "s": 1544, "text": "Input-1:" }, { "code": null, "e": 1561, "s": 1553, "text": "Output:" }, { "code": null, "e": 1563, "s": 1561, "text": "2" }, { "code": null, "e": 1691, "s": 1563, "text": "Explanation: Since the given linked list intersects at the node with the value ‘2’, we will return the value ‘2’ as the output." }, { "code": null, "e": 1700, "s": 1691, "text": "Input-2:" }, { "code": null, "e": 1719, "s": 1711, "text": "Output:" }, { "code": null, "e": 1724, "s": 1719, "text": "NULL" }, { "code": null, "e": 1805, "s": 1724, "text": "Explanation: Since there are no common points, we will return NULL in this case." }, { "code": null, "e": 2143, "s": 1805, "text": "We have two linked lists with a common point where they intersect each other. To find the intersection point, we will traverse both the linked lists till we find that they are equally pointing to the same value. At some point, the pointer to the next node of the linked list will be the same. Thus we will return the value of that point." }, { "code": null, "e": 2205, "s": 2143, "text": "Take two linked lists with data and pointer to the next node." }, { "code": null, "e": 2385, "s": 2205, "text": "A function commonPoint(listnode*headA, listnode*headB) takes two pointers of linked list respectively and returns the value of the common or intersection point of the linked list." }, { "code": null, "e": 2517, "s": 2385, "text": "An integer function that finds the length of the linked list will return the length of both linked lists from the head of the list." }, { "code": null, "e": 2670, "s": 2517, "text": "Now create a pointer to the head of both lists and traverse the list which is greater in its length till (length of first list – length of second list)." }, { "code": null, "e": 2732, "s": 2670, "text": "Now traverse the list till we find the next pointer is equal." }, { "code": null, "e": 2805, "s": 2732, "text": "Return the value of that particular node where both the lists intersect." }, { "code": null, "e": 2815, "s": 2805, "text": "Live Demo" }, { "code": null, "e": 4392, "s": 2815, "text": "public class Solution {\n static listnode headA,\n headB;\n static class listnode {\n int data;\n listnode next;\n listnode(int d) {\n data = d;\n next = null;\n }\n }\n int count(listnode head) {\n int c = 0;\n while (head != null) {\n c++;\n head = head.next;\n }\n return c;\n }\n int commonPoint(listnode headA, listnode headB) {\n listnode p1 = headA;\n listnode p2 = headB;\n int c1 = count(headA);\n int c2 = count(headB);\n if (c1 > c2) {\n for (int i = 0; i < c1 - c2; i++) {\n if (p1 == null) {\n return - 1;\n }\n p1 = p1.next;\n }\n }\n if (c1 < c2) {\n for (int i = 0; i < c2 - c1; i++) {\n if (p2 == null) {\n return - 1;\n }\n p2 = p2.next;\n }\n }\n while (p1 != null &amp;&amp; p2 != null) {\n if (p1.data == p2.data) {\n return p1.data;\n }\n p1 = p1.next;\n p2 = p2.next;\n }\n return - 1;\n }\n public static void main(String[] args) {\n Solution list = new Solution();\n list.headA = new listnode(5);\n list.headA.next = new listnode(4);\n list.headA.next.next = new listnode(9);\n list.headA.next.next.next = new listnode(7);\n list.headA.next.next.next.next = new listnode(1);\n list.headB = new listnode(6);\n list.headB.next = new listnode(7);\n list.headB.next.next = new listnode(1);\n System.out.println(list.commonPoint(headA, headB));\n }\n}" }, { "code": null, "e": 4444, "s": 4392, "text": "Running the above code will generate the output as," }, { "code": null, "e": 4446, "s": 4444, "text": "7" }, { "code": null, "e": 4505, "s": 4446, "text": "Explanation: The given linked lists are intersecting at 7." } ]
Persistent Systems Interview Experience (On-Campus 2021 Batch) - GeeksforGeeks
15 Oct, 2020 Round 1 (Online Test): Round 1 was conducted on 4th September 2020 from 11:00 AM to 12:30 PM on AMCAT Platform. This round consists of two parts : Objective round: This was a 50 minutes test that comprised of MCQ’s on Operating systems, Computer Architecture, DBMS, Computer Networks, English Comprehension, and Logical reasoning, and 1 question from Linux. Ex. Find hamming distance Subjective round: This was a 40 minutes coding test in which you have to solve 2 coding questions. In my case, the first coding question was to find prime numbers from 2 to a given number. Visit https://www.geeksforgeeks.org/sieve-of-eratosthenes/ for the solution.I don’t remember the 2nd question but it was a little tricky. In my case, the first coding question was to find prime numbers from 2 to a given number. Visit https://www.geeksforgeeks.org/sieve-of-eratosthenes/ for the solution. I don’t remember the 2nd question but it was a little tricky. I solved both coding questions completely. After 5-6 hrs I got the mail and I qualified for the Advanced Coding Test(For higher package). Advanced Coding Test was on the same day from 06:30 PM to 09:00 PM but the time allotted was 45 minutes. Means any 45min between 6:30 to 9 pm. I was able to solve 1 problem 80% out of 2 problems, and I was not qualified for a higher package. On 6 Sept 2020, Our TPO received the list of selected students, and I was shortlisted for the interviews for the base package. Technical Interview 1: A technical interview was conducted on 6th Oct 2020. Questions asked me in the T1 interview IntroductionThen he told me to open the chatbox and asked what is written and how many times (hii was written 3 times)Given a C++ code and told to find an error if any or what is the outputC++C++Class A{ private int i;} class B : Class A{ private int j;} main(){ A a B b print(sizeof(a)) print(sizeof(b))}Note: Don’t check the syntaxPuzzle: 9 circles in a triangle. and 1-9 nos are given. Arrange the words so the addition of each side of the triangle should be equal.What is Compile Time BindingRun time bindingA real-life example of polymorphismProcess and threadsFind the middle of a linked list ( approach needed) (told 2 times traversal technique then he asked to do in the one traversal. I told two pointers technique)Reverse the Linked List (reverse Linked List function code needed) 5 min was given but after 2 mins told me to do in 1 min2-3 Codes given in chatbox and asked to find output, errors if any and whyTCP and UDP, unicast and multicastNormalisationMany to many relation real-life exampleWhat is recursionAgain Given a code asked what is this?fun() { main() } main() { fun() }Again given a code, what is the outputclass A { A(int a) { } ~A() { } } main() { A a(1) A b }Explain the codeint *ptr = 0; main() { for(1-10) //means 1 to 10 { ptr = malloc(12) } free(ptr) } Introduction Then he told me to open the chatbox and asked what is written and how many times (hii was written 3 times) Given a C++ code and told to find an error if any or what is the outputC++C++Class A{ private int i;} class B : Class A{ private int j;} main(){ A a B b print(sizeof(a)) print(sizeof(b))}Note: Don’t check the syntax C++ Class A{ private int i;} class B : Class A{ private int j;} main(){ A a B b print(sizeof(a)) print(sizeof(b))} Note: Don’t check the syntax Puzzle: 9 circles in a triangle. and 1-9 nos are given. Arrange the words so the addition of each side of the triangle should be equal. Puzzle: 9 circles in a triangle. and 1-9 nos are given. Arrange the words so the addition of each side of the triangle should be equal. What is Compile Time Binding What is Compile Time Binding Run time binding Run time binding A real-life example of polymorphism A real-life example of polymorphism Process and threads Process and threads Find the middle of a linked list ( approach needed) (told 2 times traversal technique then he asked to do in the one traversal. I told two pointers technique) Find the middle of a linked list ( approach needed) (told 2 times traversal technique then he asked to do in the one traversal. I told two pointers technique) Reverse the Linked List (reverse Linked List function code needed) 5 min was given but after 2 mins told me to do in 1 min Reverse the Linked List (reverse Linked List function code needed) 5 min was given but after 2 mins told me to do in 1 min 2-3 Codes given in chatbox and asked to find output, errors if any and why 2-3 Codes given in chatbox and asked to find output, errors if any and why TCP and UDP, unicast and multicast TCP and UDP, unicast and multicast Normalisation Normalisation Many to many relation real-life example Many to many relation real-life example What is recursion What is recursion Again Given a code asked what is this?fun() { main() } main() { fun() } Again Given a code asked what is this? fun() { main() } main() { fun() } Again given a code, what is the outputclass A { A(int a) { } ~A() { } } main() { A a(1) A b } Again given a code, what is the output class A { A(int a) { } ~A() { } } main() { A a(1) A b } Explain the codeint *ptr = 0; main() { for(1-10) //means 1 to 10 { ptr = malloc(12) } free(ptr) } Explain the code int *ptr = 0; main() { for(1-10) //means 1 to 10 { ptr = malloc(12) } free(ptr) } Do you have any questions, I asked 3 questions What are the benefits of being a persistent employee? He said I am a technical person. Better if you ask this question to HRIt was my first interview how did you feel interviewing me. He said: was goodAny suggestions for me. He said keep learning What are the benefits of being a persistent employee? He said I am a technical person. Better if you ask this question to HR It was my first interview how did you feel interviewing me. He said: was good Any suggestions for me. He said keep learning On the same day at 7:26 PM, I received the mail: You have shortlisted for the level 2 technical round. The interviews are scheduled for tomorrow. Technical Interview 2: Date: 07th October 2020 Questions asked: How are u?Where do you liveTell me about your last project(just title)Let’s assume we have to design a database schema for students and courses how will you design and what will be the relationship between student and course. I said many to many relationships, and we need to design 3 tables one for students, one for courses, and one for student-course relationship some questions on the database.What is encapsulation and its exampleWhat is inheritance? Example of inheritanceAbstractionDo you know about ML or AI? I said I’m going to learn that.On what projects you want to work on after joining persistent. I said ML. Then He said what if we don’t have an ML domain. Then I said in Cyber Security.What is a transaction? Where we use transactions. Example of transaction.Then he said we are done Mayur How are u? Where do you live Tell me about your last project(just title) Let’s assume we have to design a database schema for students and courses how will you design and what will be the relationship between student and course. I said many to many relationships, and we need to design 3 tables one for students, one for courses, and one for student-course relationship some questions on the database. What is encapsulation and its example What is inheritance? Example of inheritance Abstraction Do you know about ML or AI? I said I’m going to learn that. On what projects you want to work on after joining persistent. I said ML. Then He said what if we don’t have an ML domain. Then I said in Cyber Security. What is a transaction? Where we use transactions. Example of transaction. Then he said we are done Mayur Do you have any questions I said I’ve one question How did you feel interviewing me? He said good Keep learning. Not just python, ML, learn new technologies and told me everything about company culture in 3-4 mins. Then on 8th Oct 2020, I received mail that You have been shortlisted for the HR round at our base Package. HR round is scheduled today between 12:00 PM to 5:00 PM on the same day. HR Round: Date: 8th Oct 2020. This round was the best. Only 10 min round no technical questions. He asked me to introduceDo u know Linux?The Latest project titleWhy do u want to join?Then he said you need to work on your communicationThen he asked What do u know about us He asked me to introduce Do u know Linux? The Latest project title Why do u want to join? Then he said you need to work on your communication Then he asked What do u know about us Then he said Thank you, we are done with this After 3-4 days our TPO received the mail, and I was selected. Marketing On-Campus Persistent Systems Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 (On-Campus) Infosys Interview Experience for DSE - System Engineer | On-Campus 2022 Amazon Interview Experience for SDE-1 Oracle Interview Experience | Set 69 (Application Engineer) Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1 Infosys DSE Interview Experience 2021
[ { "code": null, "e": 24939, "s": 24911, "text": "\n15 Oct, 2020" }, { "code": null, "e": 25051, "s": 24939, "text": "Round 1 (Online Test): Round 1 was conducted on 4th September 2020 from 11:00 AM to 12:30 PM on AMCAT Platform." }, { "code": null, "e": 25086, "s": 25051, "text": "This round consists of two parts :" }, { "code": null, "e": 25297, "s": 25086, "text": "Objective round: This was a 50 minutes test that comprised of MCQ’s on Operating systems, Computer Architecture, DBMS, Computer Networks, English Comprehension, and Logical reasoning, and 1 question from Linux." }, { "code": null, "e": 25324, "s": 25297, "text": "Ex. Find hamming distance " }, { "code": null, "e": 25423, "s": 25324, "text": "Subjective round: This was a 40 minutes coding test in which you have to solve 2 coding questions." }, { "code": null, "e": 25651, "s": 25423, "text": "In my case, the first coding question was to find prime numbers from 2 to a given number. Visit https://www.geeksforgeeks.org/sieve-of-eratosthenes/ for the solution.I don’t remember the 2nd question but it was a little tricky." }, { "code": null, "e": 25818, "s": 25651, "text": "In my case, the first coding question was to find prime numbers from 2 to a given number. Visit https://www.geeksforgeeks.org/sieve-of-eratosthenes/ for the solution." }, { "code": null, "e": 25880, "s": 25818, "text": "I don’t remember the 2nd question but it was a little tricky." }, { "code": null, "e": 25923, "s": 25880, "text": "I solved both coding questions completely." }, { "code": null, "e": 26018, "s": 25923, "text": "After 5-6 hrs I got the mail and I qualified for the Advanced Coding Test(For higher package)." }, { "code": null, "e": 26161, "s": 26018, "text": "Advanced Coding Test was on the same day from 06:30 PM to 09:00 PM but the time allotted was 45 minutes. Means any 45min between 6:30 to 9 pm." }, { "code": null, "e": 26387, "s": 26161, "text": "I was able to solve 1 problem 80% out of 2 problems, and I was not qualified for a higher package. On 6 Sept 2020, Our TPO received the list of selected students, and I was shortlisted for the interviews for the base package." }, { "code": null, "e": 26463, "s": 26387, "text": "Technical Interview 1: A technical interview was conducted on 6th Oct 2020." }, { "code": null, "e": 26502, "s": 26463, "text": "Questions asked me in the T1 interview" }, { "code": null, "e": 27914, "s": 26502, "text": "IntroductionThen he told me to open the chatbox and asked what is written and how many times (hii was written 3 times)Given a C++ code and told to find an error if any or what is the outputC++C++Class A{ private int i;} class B : Class A{ private int j;} main(){ A a B b print(sizeof(a)) print(sizeof(b))}Note: Don’t check the syntaxPuzzle: 9 circles in a triangle. and 1-9 nos are given. Arrange the words so the addition of each side of the triangle should be equal.What is Compile Time BindingRun time bindingA real-life example of polymorphismProcess and threadsFind the middle of a linked list ( approach needed) (told 2 times traversal technique then he asked to do in the one traversal. I told two pointers technique)Reverse the Linked List (reverse Linked List function code needed) 5 min was given but after 2 mins told me to do in 1 min2-3 Codes given in chatbox and asked to find output, errors if any and whyTCP and UDP, unicast and multicastNormalisationMany to many relation real-life exampleWhat is recursionAgain Given a code asked what is this?fun()\n {\n main()\n }\nmain()\n {\n fun()\n }Again given a code, what is the outputclass A\n {\n A(int a)\n { }\n ~A()\n { }\n\n }\n\nmain()\n {\n A a(1)\n A b\n }Explain the codeint *ptr = 0;\nmain()\n{\nfor(1-10) //means 1 to 10\n{\nptr = malloc(12)\n}\nfree(ptr)\n}" }, { "code": null, "e": 27927, "s": 27914, "text": "Introduction" }, { "code": null, "e": 28034, "s": 27927, "text": "Then he told me to open the chatbox and asked what is written and how many times (hii was written 3 times)" }, { "code": null, "e": 28262, "s": 28034, "text": "Given a C++ code and told to find an error if any or what is the outputC++C++Class A{ private int i;} class B : Class A{ private int j;} main(){ A a B b print(sizeof(a)) print(sizeof(b))}Note: Don’t check the syntax" }, { "code": null, "e": 28266, "s": 28262, "text": "C++" }, { "code": "Class A{ private int i;} class B : Class A{ private int j;} main(){ A a B b print(sizeof(a)) print(sizeof(b))}", "e": 28389, "s": 28266, "text": null }, { "code": null, "e": 28418, "s": 28389, "text": "Note: Don’t check the syntax" }, { "code": null, "e": 28554, "s": 28418, "text": "Puzzle: 9 circles in a triangle. and 1-9 nos are given. Arrange the words so the addition of each side of the triangle should be equal." }, { "code": null, "e": 28690, "s": 28554, "text": "Puzzle: 9 circles in a triangle. and 1-9 nos are given. Arrange the words so the addition of each side of the triangle should be equal." }, { "code": null, "e": 28719, "s": 28690, "text": "What is Compile Time Binding" }, { "code": null, "e": 28748, "s": 28719, "text": "What is Compile Time Binding" }, { "code": null, "e": 28765, "s": 28748, "text": "Run time binding" }, { "code": null, "e": 28782, "s": 28765, "text": "Run time binding" }, { "code": null, "e": 28818, "s": 28782, "text": "A real-life example of polymorphism" }, { "code": null, "e": 28854, "s": 28818, "text": "A real-life example of polymorphism" }, { "code": null, "e": 28874, "s": 28854, "text": "Process and threads" }, { "code": null, "e": 28894, "s": 28874, "text": "Process and threads" }, { "code": null, "e": 29053, "s": 28894, "text": "Find the middle of a linked list ( approach needed) (told 2 times traversal technique then he asked to do in the one traversal. I told two pointers technique)" }, { "code": null, "e": 29212, "s": 29053, "text": "Find the middle of a linked list ( approach needed) (told 2 times traversal technique then he asked to do in the one traversal. I told two pointers technique)" }, { "code": null, "e": 29335, "s": 29212, "text": "Reverse the Linked List (reverse Linked List function code needed) 5 min was given but after 2 mins told me to do in 1 min" }, { "code": null, "e": 29458, "s": 29335, "text": "Reverse the Linked List (reverse Linked List function code needed) 5 min was given but after 2 mins told me to do in 1 min" }, { "code": null, "e": 29533, "s": 29458, "text": "2-3 Codes given in chatbox and asked to find output, errors if any and why" }, { "code": null, "e": 29608, "s": 29533, "text": "2-3 Codes given in chatbox and asked to find output, errors if any and why" }, { "code": null, "e": 29643, "s": 29608, "text": "TCP and UDP, unicast and multicast" }, { "code": null, "e": 29678, "s": 29643, "text": "TCP and UDP, unicast and multicast" }, { "code": null, "e": 29692, "s": 29678, "text": "Normalisation" }, { "code": null, "e": 29706, "s": 29692, "text": "Normalisation" }, { "code": null, "e": 29746, "s": 29706, "text": "Many to many relation real-life example" }, { "code": null, "e": 29786, "s": 29746, "text": "Many to many relation real-life example" }, { "code": null, "e": 29804, "s": 29786, "text": "What is recursion" }, { "code": null, "e": 29822, "s": 29804, "text": "What is recursion" }, { "code": null, "e": 29920, "s": 29822, "text": "Again Given a code asked what is this?fun()\n {\n main()\n }\nmain()\n {\n fun()\n }" }, { "code": null, "e": 29959, "s": 29920, "text": "Again Given a code asked what is this?" }, { "code": null, "e": 30019, "s": 29959, "text": "fun()\n {\n main()\n }\nmain()\n {\n fun()\n }" }, { "code": null, "e": 30202, "s": 30019, "text": "Again given a code, what is the outputclass A\n {\n A(int a)\n { }\n ~A()\n { }\n\n }\n\nmain()\n {\n A a(1)\n A b\n }" }, { "code": null, "e": 30241, "s": 30202, "text": "Again given a code, what is the output" }, { "code": null, "e": 30386, "s": 30241, "text": "class A\n {\n A(int a)\n { }\n ~A()\n { }\n\n }\n\nmain()\n {\n A a(1)\n A b\n }" }, { "code": null, "e": 30484, "s": 30386, "text": "Explain the codeint *ptr = 0;\nmain()\n{\nfor(1-10) //means 1 to 10\n{\nptr = malloc(12)\n}\nfree(ptr)\n}" }, { "code": null, "e": 30501, "s": 30484, "text": "Explain the code" }, { "code": null, "e": 30583, "s": 30501, "text": "int *ptr = 0;\nmain()\n{\nfor(1-10) //means 1 to 10\n{\nptr = malloc(12)\n}\nfree(ptr)\n}" }, { "code": null, "e": 30630, "s": 30583, "text": "Do you have any questions, I asked 3 questions" }, { "code": null, "e": 30877, "s": 30630, "text": "What are the benefits of being a persistent employee? He said I am a technical person. Better if you ask this question to HRIt was my first interview how did you feel interviewing me. He said: was goodAny suggestions for me. He said keep learning" }, { "code": null, "e": 31002, "s": 30877, "text": "What are the benefits of being a persistent employee? He said I am a technical person. Better if you ask this question to HR" }, { "code": null, "e": 31080, "s": 31002, "text": "It was my first interview how did you feel interviewing me. He said: was good" }, { "code": null, "e": 31126, "s": 31080, "text": "Any suggestions for me. He said keep learning" }, { "code": null, "e": 31272, "s": 31126, "text": "On the same day at 7:26 PM, I received the mail: You have shortlisted for the level 2 technical round. The interviews are scheduled for tomorrow." }, { "code": null, "e": 31319, "s": 31272, "text": "Technical Interview 2: Date: 07th October 2020" }, { "code": null, "e": 31336, "s": 31319, "text": "Questions asked:" }, { "code": null, "e": 32141, "s": 31336, "text": "How are u?Where do you liveTell me about your last project(just title)Let’s assume we have to design a database schema for students and courses how will you design and what will be the relationship between student and course. I said many to many relationships, and we need to design 3 tables one for students, one for courses, and one for student-course relationship some questions on the database.What is encapsulation and its exampleWhat is inheritance? Example of inheritanceAbstractionDo you know about ML or AI? I said I’m going to learn that.On what projects you want to work on after joining persistent. I said ML. Then He said what if we don’t have an ML domain. Then I said in Cyber Security.What is a transaction? Where we use transactions. Example of transaction.Then he said we are done Mayur" }, { "code": null, "e": 32152, "s": 32141, "text": "How are u?" }, { "code": null, "e": 32170, "s": 32152, "text": "Where do you live" }, { "code": null, "e": 32214, "s": 32170, "text": "Tell me about your last project(just title)" }, { "code": null, "e": 32543, "s": 32214, "text": "Let’s assume we have to design a database schema for students and courses how will you design and what will be the relationship between student and course. I said many to many relationships, and we need to design 3 tables one for students, one for courses, and one for student-course relationship some questions on the database." }, { "code": null, "e": 32581, "s": 32543, "text": "What is encapsulation and its example" }, { "code": null, "e": 32625, "s": 32581, "text": "What is inheritance? Example of inheritance" }, { "code": null, "e": 32637, "s": 32625, "text": "Abstraction" }, { "code": null, "e": 32697, "s": 32637, "text": "Do you know about ML or AI? I said I’m going to learn that." }, { "code": null, "e": 32851, "s": 32697, "text": "On what projects you want to work on after joining persistent. I said ML. Then He said what if we don’t have an ML domain. Then I said in Cyber Security." }, { "code": null, "e": 32925, "s": 32851, "text": "What is a transaction? Where we use transactions. Example of transaction." }, { "code": null, "e": 32956, "s": 32925, "text": "Then he said we are done Mayur" }, { "code": null, "e": 33007, "s": 32956, "text": "Do you have any questions I said I’ve one question" }, { "code": null, "e": 33054, "s": 33007, "text": "How did you feel interviewing me? He said good" }, { "code": null, "e": 33171, "s": 33054, "text": "Keep learning. Not just python, ML, learn new technologies and told me everything about company culture in 3-4 mins." }, { "code": null, "e": 33351, "s": 33171, "text": "Then on 8th Oct 2020, I received mail that You have been shortlisted for the HR round at our base Package. HR round is scheduled today between 12:00 PM to 5:00 PM on the same day." }, { "code": null, "e": 33448, "s": 33351, "text": "HR Round: Date: 8th Oct 2020. This round was the best. Only 10 min round no technical questions." }, { "code": null, "e": 33623, "s": 33448, "text": "He asked me to introduceDo u know Linux?The Latest project titleWhy do u want to join?Then he said you need to work on your communicationThen he asked What do u know about us" }, { "code": null, "e": 33648, "s": 33623, "text": "He asked me to introduce" }, { "code": null, "e": 33665, "s": 33648, "text": "Do u know Linux?" }, { "code": null, "e": 33690, "s": 33665, "text": "The Latest project title" }, { "code": null, "e": 33713, "s": 33690, "text": "Why do u want to join?" }, { "code": null, "e": 33765, "s": 33713, "text": "Then he said you need to work on your communication" }, { "code": null, "e": 33803, "s": 33765, "text": "Then he asked What do u know about us" }, { "code": null, "e": 33849, "s": 33803, "text": "Then he said Thank you, we are done with this" }, { "code": null, "e": 33911, "s": 33849, "text": "After 3-4 days our TPO received the mail, and I was selected." }, { "code": null, "e": 33921, "s": 33911, "text": "Marketing" }, { "code": null, "e": 33931, "s": 33921, "text": "On-Campus" }, { "code": null, "e": 33950, "s": 33931, "text": "Persistent Systems" }, { "code": null, "e": 33972, "s": 33950, "text": "Interview Experiences" }, { "code": null, "e": 34070, "s": 33972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34079, "s": 34070, "text": "Comments" }, { "code": null, "e": 34092, "s": 34079, "text": "Old Comments" }, { "code": null, "e": 34151, "s": 34092, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 34201, "s": 34151, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 34273, "s": 34201, "text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022" }, { "code": null, "e": 34311, "s": 34273, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 34371, "s": 34311, "text": "Oracle Interview Experience | Set 69 (Application Engineer)" }, { "code": null, "e": 34436, "s": 34371, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 34486, "s": 34436, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 34532, "s": 34486, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 34570, "s": 34532, "text": "Amazon Interview Experience for SDE-1" } ]
HashMap Operations | Practice | GeeksforGeeks
Implement different operations on Hashmap. Different types of queries will be provided. A query can be of four types: 1. a x y (adds an entry with key x and value y to the Hashmap) 2. b x (print value of x if present in the Hashmap else print -1. ) 3. c (prints the size of the Hashmap) 4. d x (removes an entry with key x from the Hashmap) Example 1 : Input: 5 a 1 2 a 66 3 b 66 d 1 c Output: 3 1 Explanation : There are five queries. Queries are performed in this order 1. a 1 2 ---> map has a key 1 with value 2 2. a 66 3 ---> map has a key 66 with value 3 3. b 66 ---> prints the value of key 66 if its present in the map ie 3. 4. d 1 ---> removes an entry from map with key 1 5. c ---> prints the size of the map ie 1 Example 2 : Input: 3 a 1 66 b 5 c Output: -1 1 Explanation : There are three queries. Queries are performed in this order 1. a 1 66 ---> adds a key 1 with a value of 66 in the map 2. b 5 ---> since the key 5 is not present in the map hence -1 is printed. 3. c ---> prints the size of the map ie 1 Your Task: You are required to complete the following functions: add_Value : Takes HashMap, x, y as arguments and maps x as key and y as its value. Does not return anything. find_value : Takes HashMap and x as arguments. If HM contains x key then return the value, else return -1. getSize : Takes HashMap as argument and just returns its size. removeKey : Takes HashMap and x as arguments and removes x if it exists. Does not return anything. Constraints: 1 <= Q <= 100 0 indiakamanthan2 months ago class GfG { /*Inserts an entry with key x and value y in map */ void add_Value(HashMap<Integer,Integer> hm, int x, int y) { //Your code here hm.put(x,y); } /*Returns the value with key x from the map */ int find_value(HashMap<Integer, Integer> hm, int x) { //Your code here if(hm.containsKey(x)) return hm.get(x); return -1; } /*Returns the size of the map */ int getSize(HashMap<Integer, Integer> hm) { //Your code here return hm.size(); } /*Removes the entry with key x from the map */ void removeKey(HashMap<Integer, Integer> hm, int x) { //Your code here hm.remove(x); } } 0 pankajkumarravi6 months ago *********************** Java Logic *********************** /*Inserts an entry with key x and value y in map */void add_Value(HashMap<Integer,Integer> hm, int x, int y) { //Your code here hm.put(x,y);}/*Returns the value with key x from the map */int find_value(HashMap<Integer, Integer> hm, int x) { //Your code here if (hm.containsKey(x)) return hm.get(x); else return -1;}/*Returns the size of the map */int getSize(HashMap<Integer, Integer> hm) { //Your code here return hm.size();}/*Removes the entry with key x from the map */void removeKey(HashMap<Integer, Integer> hm, int x) { //Your code here hm.remove(x);} 0 18r01a05f07 months ago class GfG { void add_Value(HashMap<Integer, Integer> hm, int x, int y) { HashMap<Integer, Integer> hm1 = new HashMap<>(); hm.put(x, y);} int find_value(HashMap<Integer, Integer> hm, int x) { if (hm.containsKey(x)) { return hm.get(x); } else { return -1; } } int getSize(HashMap<Integer, Integer> hm) { return hm.size();} void removeKey(HashMap<Integer, Integer> hm, int x) { hm.remove(x);}} 0 MAYUR.xxivk11 months ago MAYUR.xxivk https://uploads.disquscdn.c... 0 Amir Ansari1 year ago Amir Ansari Correct AnswerExecution Time:0.30 /*Inserts an entry with key x and value y in map */ void add_Value(HashMap<integer,integer> hm, int x, int y) {//Your code here hm.put(x,y); } /*Returns the value with key x from the map */ int find_value(HashMap<integer, integer=""> hm, int x) { //Your code here int result = hm.get(x) == null ? -1: hm.get(x); return result; } /*Returns the size of the map */ int getSize(HashMap<integer, integer=""> hm) {//Your code here return hm.size(); } /*Removes the entry with key x from the map */ void removeKey(HashMap<integer, integer=""> hm, int x) {//Your code here if( hm.get(x) != null){ hm.remove(x); } } 0 Paurash Dewangan1 year ago Paurash Dewangan class GfG{ void add_Value(HashMap<integer,integer> hm, int x, int y) {hm.put(x,y); } int find_value(HashMap<integer, integer=""> hm, int x) { if(hm.containsKey(x)){ return hm.get(x); }else{ return -1; } } int getSize(HashMap<integer, integer=""> hm) {return hm.size(); } void removeKey(HashMap<integer, integer=""> hm, int x) {hm.remove(x); }} 0 Piyush Raj2 years ago Piyush Raj void add_Value(HashMap<integer,integer> hm, int x, int y) { hm.put(x,y) } int find_value(HashMap<integer, integer=""> hm, int x) { //Your code here if(hm.containsKey(x)) return hm.get(x); else return -1; } int getSize(HashMap<integer, integer=""> hm) { return hm.size(); } void removeKey(HashMap<integer, integer=""> hm, int x) { if(hm.containsKey(x)) hm.remove(x); } 0 Riya kashyap This comment was deleted. 0 Vikram Shekhawat This comment was deleted. 0 Ivan Petrov This comment was deleted. 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": 580, "s": 238, "text": "Implement different operations on Hashmap. Different types of queries will be provided.\nA query can be of four types:\n1. a x y (adds an entry with key x and value y to the Hashmap)\n2. b x (print value of x if present in the Hashmap else print -1. )\n3. c (prints the size of the Hashmap)\n4. d x (removes an entry with key x from the Hashmap)" }, { "code": null, "e": 593, "s": 580, "text": "Example 1 : " }, { "code": null, "e": 980, "s": 593, "text": "Input:\n5 \na 1 2 a 66 3 b 66 d 1 c \n\nOutput:\n3 1 \n\nExplanation :\nThere are five queries. Queries are performed in this order\n1. a 1 2 ---> map has a key 1 with value 2\n2. a 66 3 ---> map has a key 66 with value 3\n3. b 66 ---> prints the value of key 66 if its present in the map ie 3.\n4. d 1 ---> removes an entry from map with key 1\n5. c ---> prints the size of the map ie 1" }, { "code": null, "e": 992, "s": 980, "text": "Example 2 :" }, { "code": null, "e": 1291, "s": 992, "text": "Input: \n3 \na 1 66 b 5 c\n\nOutput: \n-1 1\n\nExplanation :\nThere are three queries. Queries are performed in this order\n1. a 1 66 ---> adds a key 1 with a value of 66 in the map\n2. b 5 ---> since the key 5 is not present in the map hence -1 is printed.\n3. c ---> prints the size of the map ie 1" }, { "code": null, "e": 1734, "s": 1291, "text": "Your Task:\nYou are required to complete the following functions:\nadd_Value : Takes HashMap, x, y as arguments and maps x as key and y as its value. Does not return anything.\nfind_value : Takes HashMap and x as arguments. If HM contains x key then return the value, else return -1.\ngetSize : Takes HashMap as argument and just returns its size.\nremoveKey : Takes HashMap and x as arguments and removes x if it exists. Does not return anything." }, { "code": null, "e": 1761, "s": 1734, "text": "Constraints:\n1 <= Q <= 100" }, { "code": null, "e": 1767, "s": 1765, "text": "0" }, { "code": null, "e": 1794, "s": 1767, "text": "indiakamanthan2 months ago" }, { "code": null, "e": 2472, "s": 1794, "text": "class GfG\n{\n /*Inserts an entry with key x and value y in map */\n void add_Value(HashMap<Integer,Integer> hm, int x, int y)\n {\n\t//Your code here\n\thm.put(x,y);\n }\n\t\n /*Returns the value with key x from the map */\n int find_value(HashMap<Integer, Integer> hm, int x)\n {\n //Your code here\n if(hm.containsKey(x))\n return hm.get(x);\n return -1;\n }\n\t\n /*Returns the size of the map */\n int getSize(HashMap<Integer, Integer> hm)\n {\n\t//Your code here\n return hm.size();\n }\n\t\t\n /*Removes the entry with key x from the map */\t\n void removeKey(HashMap<Integer, Integer> hm, int x)\n {\n\t//Your code here\n\thm.remove(x);\n }\n}" }, { "code": null, "e": 2474, "s": 2472, "text": "0" }, { "code": null, "e": 2502, "s": 2474, "text": "pankajkumarravi6 months ago" }, { "code": null, "e": 2561, "s": 2502, "text": "*********************** Java Logic ***********************" }, { "code": null, "e": 3158, "s": 2561, "text": "/*Inserts an entry with key x and value y in map */void add_Value(HashMap<Integer,Integer> hm, int x, int y) { //Your code here hm.put(x,y);}/*Returns the value with key x from the map */int find_value(HashMap<Integer, Integer> hm, int x) { //Your code here if (hm.containsKey(x)) return hm.get(x); else return -1;}/*Returns the size of the map */int getSize(HashMap<Integer, Integer> hm) { //Your code here return hm.size();}/*Removes the entry with key x from the map */void removeKey(HashMap<Integer, Integer> hm, int x) { //Your code here hm.remove(x);}" }, { "code": null, "e": 3160, "s": 3158, "text": "0" }, { "code": null, "e": 3183, "s": 3160, "text": "18r01a05f07 months ago" }, { "code": null, "e": 3195, "s": 3183, "text": "class GfG {" }, { "code": null, "e": 3320, "s": 3195, "text": "void add_Value(HashMap<Integer, Integer> hm, int x, int y) { HashMap<Integer, Integer> hm1 = new HashMap<>(); hm.put(x, y);}" }, { "code": null, "e": 3441, "s": 3320, "text": "int find_value(HashMap<Integer, Integer> hm, int x) { if (hm.containsKey(x)) { return hm.get(x); } else { return -1; }" }, { "code": null, "e": 3443, "s": 3441, "text": "}" }, { "code": null, "e": 3506, "s": 3443, "text": "int getSize(HashMap<Integer, Integer> hm) { return hm.size();}" }, { "code": null, "e": 3576, "s": 3506, "text": "void removeKey(HashMap<Integer, Integer> hm, int x) { hm.remove(x);}}" }, { "code": null, "e": 3578, "s": 3576, "text": "0" }, { "code": null, "e": 3603, "s": 3578, "text": "MAYUR.xxivk11 months ago" }, { "code": null, "e": 3615, "s": 3603, "text": "MAYUR.xxivk" }, { "code": null, "e": 3646, "s": 3615, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 3648, "s": 3646, "text": "0" }, { "code": null, "e": 3670, "s": 3648, "text": "Amir Ansari1 year ago" }, { "code": null, "e": 3682, "s": 3670, "text": "Amir Ansari" }, { "code": null, "e": 3716, "s": 3682, "text": "Correct AnswerExecution Time:0.30" }, { "code": null, "e": 3873, "s": 3716, "text": "/*Inserts an entry with key x and value y in map */ void add_Value(HashMap<integer,integer> hm, int x, int y) {//Your code here hm.put(x,y); }" }, { "code": null, "e": 4066, "s": 3873, "text": " /*Returns the value with key x from the map */ int find_value(HashMap<integer, integer=\"\"> hm, int x) { //Your code here int result = hm.get(x) == null ? -1: hm.get(x);" }, { "code": null, "e": 4094, "s": 4066, "text": " return result; }" }, { "code": null, "e": 4224, "s": 4094, "text": " /*Returns the size of the map */ int getSize(HashMap<integer, integer=\"\"> hm) {//Your code here return hm.size(); }" }, { "code": null, "e": 4424, "s": 4224, "text": " /*Removes the entry with key x from the map */ void removeKey(HashMap<integer, integer=\"\"> hm, int x) {//Your code here if( hm.get(x) != null){ hm.remove(x); } }" }, { "code": null, "e": 4426, "s": 4424, "text": "0" }, { "code": null, "e": 4453, "s": 4426, "text": "Paurash Dewangan1 year ago" }, { "code": null, "e": 4470, "s": 4453, "text": "Paurash Dewangan" }, { "code": null, "e": 4893, "s": 4470, "text": "class GfG{ void add_Value(HashMap<integer,integer> hm, int x, int y) {hm.put(x,y); } int find_value(HashMap<integer, integer=\"\"> hm, int x) { if(hm.containsKey(x)){ return hm.get(x); }else{ return -1; } } int getSize(HashMap<integer, integer=\"\"> hm) {return hm.size(); } void removeKey(HashMap<integer, integer=\"\"> hm, int x) {hm.remove(x); }}" }, { "code": null, "e": 4895, "s": 4893, "text": "0" }, { "code": null, "e": 4917, "s": 4895, "text": "Piyush Raj2 years ago" }, { "code": null, "e": 4928, "s": 4917, "text": "Piyush Raj" }, { "code": null, "e": 5371, "s": 4928, "text": "void add_Value(HashMap<integer,integer> hm, int x, int y) { hm.put(x,y) } int find_value(HashMap<integer, integer=\"\"> hm, int x) { //Your code here if(hm.containsKey(x)) return hm.get(x); else return -1; } int getSize(HashMap<integer, integer=\"\"> hm) { return hm.size(); } void removeKey(HashMap<integer, integer=\"\"> hm, int x) { if(hm.containsKey(x)) hm.remove(x); }" }, { "code": null, "e": 5373, "s": 5371, "text": "0" }, { "code": null, "e": 5386, "s": 5373, "text": "Riya kashyap" }, { "code": null, "e": 5412, "s": 5386, "text": "This comment was deleted." }, { "code": null, "e": 5414, "s": 5412, "text": "0" }, { "code": null, "e": 5431, "s": 5414, "text": "Vikram Shekhawat" }, { "code": null, "e": 5457, "s": 5431, "text": "This comment was deleted." }, { "code": null, "e": 5459, "s": 5457, "text": "0" }, { "code": null, "e": 5471, "s": 5459, "text": "Ivan Petrov" }, { "code": null, "e": 5497, "s": 5471, "text": "This comment was deleted." }, { "code": null, "e": 5643, "s": 5497, "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": 5679, "s": 5643, "text": " Login to access your submissions. " }, { "code": null, "e": 5689, "s": 5679, "text": "\nProblem\n" }, { "code": null, "e": 5699, "s": 5689, "text": "\nContest\n" }, { "code": null, "e": 5762, "s": 5699, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5910, "s": 5762, "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": 6118, "s": 5910, "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": 6224, "s": 6118, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Angular 6 - Modules
Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application. In case you are developing a website, the header, footer, left, center and the right section become part of a module. To define module, we can use the NgModule. When you create a new project using the Angular -cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The NgModule needs to be imported as follows − import { NgModule } from '@angular/core'; The structure for the ngmodule is as shown below − @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) It starts with @NgModule and contains an object which has declarations, import s, providers and bootstrap. It is an array of components created. If any new component gets created, it will be imported first and the reference will be included in declarations as shown below − declarations: [ AppComponent, NewCmpComponent ] It is an array of modules required to be used in the application. It can also be used by the components in the Declaration array. For example, right now in the @NgModule we see the Browser Module imported. In case your application needs forms, you can include the module as follows − import { FormsModule } from '@angular/forms'; The import in the @NgModule will be like the following − imports: [ BrowserModule, FormsModule ] This will include the services created. This includes the main app component for starting the execution. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2138, "s": 1995, "text": "Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application." }, { "code": null, "e": 2256, "s": 2138, "text": "In case you are developing a website, the header, footer, left, center and the right section become part of a module." }, { "code": null, "e": 2448, "s": 2256, "text": "To define module, we can use the NgModule. When you create a new project using the Angular -cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows −" }, { "code": null, "e": 2770, "s": 2448, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 2817, "s": 2770, "text": "The NgModule needs to be imported as follows −" }, { "code": null, "e": 2860, "s": 2817, "text": "import { NgModule } from '@angular/core';\n" }, { "code": null, "e": 2911, "s": 2860, "text": "The structure for the ngmodule is as shown below −" }, { "code": null, "e": 3057, "s": 2911, "text": "@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})" }, { "code": null, "e": 3164, "s": 3057, "text": "It starts with @NgModule and contains an object which has declarations, import s, providers and bootstrap." }, { "code": null, "e": 3331, "s": 3164, "text": "It is an array of components created. If any new component gets created, it will be imported first and the reference will be included in declarations as shown below −" }, { "code": null, "e": 3386, "s": 3331, "text": "declarations: [\n AppComponent,\n NewCmpComponent\n]\n" }, { "code": null, "e": 3670, "s": 3386, "text": "It is an array of modules required to be used in the application. It can also be used by the components in the Declaration array. For example, right now in the @NgModule we see the Browser Module imported. In case your application needs forms, you can include the module as follows −" }, { "code": null, "e": 3717, "s": 3670, "text": "import { FormsModule } from '@angular/forms';\n" }, { "code": null, "e": 3774, "s": 3717, "text": "The import in the @NgModule will be like the following −" }, { "code": null, "e": 3821, "s": 3774, "text": "imports: [\n BrowserModule,\n FormsModule\n]\n" }, { "code": null, "e": 3861, "s": 3821, "text": "This will include the services created." }, { "code": null, "e": 3926, "s": 3861, "text": "This includes the main app component for starting the execution." }, { "code": null, "e": 3961, "s": 3926, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3975, "s": 3961, "text": " Anadi Sharma" }, { "code": null, "e": 4010, "s": 3975, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4024, "s": 4010, "text": " Anadi Sharma" }, { "code": null, "e": 4059, "s": 4024, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4079, "s": 4059, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4114, "s": 4079, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4131, "s": 4114, "text": " Frahaan Hussain" }, { "code": null, "e": 4164, "s": 4131, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4176, "s": 4164, "text": " Senol Atac" }, { "code": null, "e": 4211, "s": 4176, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4223, "s": 4211, "text": " Senol Atac" }, { "code": null, "e": 4230, "s": 4223, "text": " Print" }, { "code": null, "e": 4241, "s": 4230, "text": " Add Notes" } ]
HMNI: Fuzzy Name Matching with Machine Learning | Towards Data Science
It is often the case when working with external data that a common identifier such as a numerical key does not exist. In place of a unique identifier, a person’s full name can be used as part of a universal or composite key to link data, however, this is not a fail-safe solution. Let’s take for example the name Alan Turing; disparate data sources could have recorded the calling name Al Turing. Data entry may innocently record: Allan, Allen, or worse, undetected typos (Alam Turing) into their databases. Enterprise document scanning solutions (OCR) are also rife with misreadings. A human agent could intuitively assign these variations to the same entity of Alan Turing through the cognitive process of applying soft-logic to approximate the spelling and phonetic (sound) characteristics. Often shortened hypocorisms don’t always have these characteristics and are part of the agents’ learned associations i.e. Charles → Chip. What follows is a study of applying machine learning to achieve semblance of human-like logic and semantics for alternative name identification. I scraped multiple lists of common alternative spellings for first-names, around 17,500 pairings. The names are restricted to ASCII and include many Unicode-decoded cross-cultural examples to avoid over-fitting to western name conventions. The intuition of using first names as the core data for our model is to integrate ensemble methods on name-components, requiring exact or phonetic matching on surnames to ensure greater precision/less false positives at the cost of some recall. I decided to make the classes imbalanced (1:4) as under-sampling the negative class lead to a noticeable artificial bias towards positive class. It is difficult to approximate the a priori probabilities for each class, but it is assumed that the classes are imbalanced in favor of the negative class. There are many string metrics and phonetic algorithms to use as features, the base level model uses 20+ features including: Levenshtein distance Bigram similarity Jaro distance Editex distance Soundex coding Deep LSTM siamese networks have been shown to be effective in learning text similarities. I used TensorFlow to train these networks on name pairs and use out-of-fold predictions as a feature of the meta model. Names can be transformed to help our model learn new patterns from the same data. Transformations include: Splitting names into syllables to acquire meaningful multi-token string metrics (e.g. token-sort and token-set from fuzzywuzzy package) Removing high-frequency name endings Removing vowels Converting to IPA (International Phonetic Alphabet) I used the AutoML package TPOT to aide in selecting an optimized pipeline and hyperparameters for a base-level model with F1 as the scoring metric. The base model and character embedding networks were stacked via stratified 10-fold cross-validation to train a logistic regression meta-model. Some features from the base model were included to provide additional context and dimensionality for the meta-model. Grid-search was used to select the optimal parameters and features, affording priority to precision. Evaluation metrics for the international alternative first name test-set: This model was specifically trained to handle alternative names, but transfers well to correctly classify all the aforementioned variants including typographic errors. The methods used and resulting model is henceforth dubbed HMNI (Hello my name is). I've open-sourced this project (in beta status) as a Python package under the same moniker. pip install hmni I will keep this post updated with future releases of HMNI; including best performing models, language-specific configurations and data processing optimizations.
[ { "code": null, "e": 453, "s": 172, "text": "It is often the case when working with external data that a common identifier such as a numerical key does not exist. In place of a unique identifier, a person’s full name can be used as part of a universal or composite key to link data, however, this is not a fail-safe solution." }, { "code": null, "e": 757, "s": 453, "text": "Let’s take for example the name Alan Turing; disparate data sources could have recorded the calling name Al Turing. Data entry may innocently record: Allan, Allen, or worse, undetected typos (Alam Turing) into their databases. Enterprise document scanning solutions (OCR) are also rife with misreadings." }, { "code": null, "e": 1104, "s": 757, "text": "A human agent could intuitively assign these variations to the same entity of Alan Turing through the cognitive process of applying soft-logic to approximate the spelling and phonetic (sound) characteristics. Often shortened hypocorisms don’t always have these characteristics and are part of the agents’ learned associations i.e. Charles → Chip." }, { "code": null, "e": 1249, "s": 1104, "text": "What follows is a study of applying machine learning to achieve semblance of human-like logic and semantics for alternative name identification." }, { "code": null, "e": 1489, "s": 1249, "text": "I scraped multiple lists of common alternative spellings for first-names, around 17,500 pairings. The names are restricted to ASCII and include many Unicode-decoded cross-cultural examples to avoid over-fitting to western name conventions." }, { "code": null, "e": 1734, "s": 1489, "text": "The intuition of using first names as the core data for our model is to integrate ensemble methods on name-components, requiring exact or phonetic matching on surnames to ensure greater precision/less false positives at the cost of some recall." }, { "code": null, "e": 2035, "s": 1734, "text": "I decided to make the classes imbalanced (1:4) as under-sampling the negative class lead to a noticeable artificial bias towards positive class. It is difficult to approximate the a priori probabilities for each class, but it is assumed that the classes are imbalanced in favor of the negative class." }, { "code": null, "e": 2159, "s": 2035, "text": "There are many string metrics and phonetic algorithms to use as features, the base level model uses 20+ features including:" }, { "code": null, "e": 2180, "s": 2159, "text": "Levenshtein distance" }, { "code": null, "e": 2198, "s": 2180, "text": "Bigram similarity" }, { "code": null, "e": 2212, "s": 2198, "text": "Jaro distance" }, { "code": null, "e": 2228, "s": 2212, "text": "Editex distance" }, { "code": null, "e": 2243, "s": 2228, "text": "Soundex coding" }, { "code": null, "e": 2453, "s": 2243, "text": "Deep LSTM siamese networks have been shown to be effective in learning text similarities. I used TensorFlow to train these networks on name pairs and use out-of-fold predictions as a feature of the meta model." }, { "code": null, "e": 2560, "s": 2453, "text": "Names can be transformed to help our model learn new patterns from the same data. Transformations include:" }, { "code": null, "e": 2696, "s": 2560, "text": "Splitting names into syllables to acquire meaningful multi-token string metrics (e.g. token-sort and token-set from fuzzywuzzy package)" }, { "code": null, "e": 2733, "s": 2696, "text": "Removing high-frequency name endings" }, { "code": null, "e": 2749, "s": 2733, "text": "Removing vowels" }, { "code": null, "e": 2801, "s": 2749, "text": "Converting to IPA (International Phonetic Alphabet)" }, { "code": null, "e": 2949, "s": 2801, "text": "I used the AutoML package TPOT to aide in selecting an optimized pipeline and hyperparameters for a base-level model with F1 as the scoring metric." }, { "code": null, "e": 3311, "s": 2949, "text": "The base model and character embedding networks were stacked via stratified 10-fold cross-validation to train a logistic regression meta-model. Some features from the base model were included to provide additional context and dimensionality for the meta-model. Grid-search was used to select the optimal parameters and features, affording priority to precision." }, { "code": null, "e": 3385, "s": 3311, "text": "Evaluation metrics for the international alternative first name test-set:" }, { "code": null, "e": 3553, "s": 3385, "text": "This model was specifically trained to handle alternative names, but transfers well to correctly classify all the aforementioned variants including typographic errors." }, { "code": null, "e": 3728, "s": 3553, "text": "The methods used and resulting model is henceforth dubbed HMNI (Hello my name is). I've open-sourced this project (in beta status) as a Python package under the same moniker." }, { "code": null, "e": 3745, "s": 3728, "text": "pip install hmni" } ]
Check whether property exists in object or class with PHP
The property_exists() or the isset() function can be used to check if the property exists in the class or object. Below is the syntax of property_exists() function− property_exists( mixed $class , string $property ) Example if (property_exists($object, 'a_property')) Below is the syntax of isset() function− isset( mixed $var [, mixed $... ] ) Example if (isset($object->a_property)) The isset() will return false if the ‘a_property’ is null. Let us see an example − Live Demo <?php class Demo { public $one; private $two; static protected $VAL; static function VAL() { var_dump(property_exists('myClass', 'two')); } } var_dump(property_exists('Demo', 'one')); var_dump(property_exists(new Demo, 'one')); ?> This will produce the following output− bool(true) bool(true)
[ { "code": null, "e": 1176, "s": 1062, "text": "The property_exists() or the isset() function can be used to check if the property exists in the class or object." }, { "code": null, "e": 1227, "s": 1176, "text": "Below is the syntax of property_exists() function−" }, { "code": null, "e": 1278, "s": 1227, "text": "property_exists( mixed $class , string $property )" }, { "code": null, "e": 1286, "s": 1278, "text": "Example" }, { "code": null, "e": 1330, "s": 1286, "text": "if (property_exists($object, 'a_property'))" }, { "code": null, "e": 1371, "s": 1330, "text": "Below is the syntax of isset() function−" }, { "code": null, "e": 1407, "s": 1371, "text": "isset( mixed $var [, mixed $... ] )" }, { "code": null, "e": 1415, "s": 1407, "text": "Example" }, { "code": null, "e": 1447, "s": 1415, "text": "if (isset($object->a_property))" }, { "code": null, "e": 1506, "s": 1447, "text": "The isset() will return false if the ‘a_property’ is null." }, { "code": null, "e": 1530, "s": 1506, "text": "Let us see an example −" }, { "code": null, "e": 1541, "s": 1530, "text": " Live Demo" }, { "code": null, "e": 1823, "s": 1541, "text": "<?php\n class Demo {\n public $one;\n private $two;\n static protected $VAL;\n static function VAL() {\n var_dump(property_exists('myClass', 'two'));\n }\n }\n var_dump(property_exists('Demo', 'one'));\n var_dump(property_exists(new Demo, 'one'));\n?>" }, { "code": null, "e": 1863, "s": 1823, "text": "This will produce the following output−" }, { "code": null, "e": 1885, "s": 1863, "text": "bool(true)\nbool(true)" } ]
Pipenv to Heroku: Easy App Deployment | by Edward Krueger | Towards Data Science
By: Edward Krueger Data Scientist and Instructor and Douglas Franklin Teaching Assistant and Technical Writer. In this article, we will cover deploying an app with a Pipfile from a Github repository to make app deployment easy! Data scientists are often interdisciplinary and have not been taught to work collaboratively with others and push projects into production. Hence deployment, and proper environment and package management skills are often lacking. This creates difficulty reproducing, deploying and sharing projects. Reproducible data science projects are those that allow others to recreate and build upon your analysis and to reuse and modify your code easily. Newer developers often install everything at the system level do to a lack of understanding of, or experience with, virtual environments. Packages installed with pip are placed at the system level. The result of doing this for every project is a bloated and unmanageable singular Python environment. How can someone developing an app in this environment know what dependencies to include in their requrements.txt? Data scientists need to be able to put their models into production. Using good practices during the model development greatly simplifies the deployment process. Even Data scientists with separate deployment or development teams can benefit from learning the deployment process. The Data scientist who is aware of the complete development to deployment workflow can deliver a product that is much more ready for deployment. This awareness can take some strain off of developers and DevOps teams. Effective environment management saves time and allows developers and data scientists to create isolated software products that are easy to deploy. Pipenv combines package management and virtual environment control into one tool for installing, removing, tracking, and documenting your dependencies; and to create, use, and manage your virtual environments. Pipenv is essentially pip and virtualenv wrapped together into a single product. Heroku offers many software service products. We’ll need the Heroku cloud platform service to host apps. Don’t worry; creating an account and hosting an app is free. The cloud platform supports apps in many programming languages including, Python, Node.js, Scala, Ruby, Clojure, Java, PHP and Go. Once we have an app with a Pipfile pushed to GitHub, Heroku allows us to deploy an app from Github to Heroku quickly. Be sure to have your Pipfile at the project’s root directory. Our app uses an SQLite database for this deployment. We’ll need to make a couple of changes to our app project files so that the app can run on Heroku. Gunicorn is a Python WSGI HTTP server that will serve your Flask application on Heroku. By running the line below, you add gunicorn to your Pipfile, which is needed to run your app in Heroku’s containers. pipenv install gunicorn Create a Procfile in the project root folder and add the following line: web: gunicorn app:app The first app represents the name of the python file that runs your application or the name of the module where the app is located. The second app represents your app name, i.e., app.py. This Procfile works with gunicorn and Heroku's Dynos to serve your app remotely. Once we have our app tested and working locally, we push all code to the master branch. Then on Heroku, go to deploy a new app to see the page below. Next on Heroku, select GitHub and enter the name of the repository and hit search. Once your Username/repository appears, click connect. Select the desired branch and click deploy. Build logs will begin to populate a console on the page. Notice that Heroku looks for a requirements.txt file first then installs dependencies from Pipenv’s Pipfile.lock. Once your environment has been built from the Pipfile.lock and the build is successful, you will see the below message. The app is successfully deployed! Click to view button to see the deployed app on Heroku. We can enable automatic deployment to have changes to the Github master be displayed on Heroku as they are pushed. If you use this method, you’ll want to be sure that you always have a working master branch. Practicing good environment and package management is crucial for data scientists and developers who want their code deployed, built upon, or used in production. These development skills can help teams when used by data scientists and developers upstream in their workflow. Having a well managed Pipenv and Pipfile allowed Heroku’s severs to rebuild our app with minimal troubleshooting. This allowed us to take an app project directory from GitHub to a working published app in minutes. Using an environment and package manager such as Pipenv makes many processes, including deployment, comfortable and more efficient! For more information on virtual environments or getting started with Pipenv, check out this article. We hope this guide has been helpful. Thank you!
[ { "code": null, "e": 283, "s": 172, "text": "By: Edward Krueger Data Scientist and Instructor and Douglas Franklin Teaching Assistant and Technical Writer." }, { "code": null, "e": 400, "s": 283, "text": "In this article, we will cover deploying an app with a Pipfile from a Github repository to make app deployment easy!" }, { "code": null, "e": 845, "s": 400, "text": "Data scientists are often interdisciplinary and have not been taught to work collaboratively with others and push projects into production. Hence deployment, and proper environment and package management skills are often lacking. This creates difficulty reproducing, deploying and sharing projects. Reproducible data science projects are those that allow others to recreate and build upon your analysis and to reuse and modify your code easily." }, { "code": null, "e": 1259, "s": 845, "text": "Newer developers often install everything at the system level do to a lack of understanding of, or experience with, virtual environments. Packages installed with pip are placed at the system level. The result of doing this for every project is a bloated and unmanageable singular Python environment. How can someone developing an app in this environment know what dependencies to include in their requrements.txt?" }, { "code": null, "e": 1755, "s": 1259, "text": "Data scientists need to be able to put their models into production. Using good practices during the model development greatly simplifies the deployment process. Even Data scientists with separate deployment or development teams can benefit from learning the deployment process. The Data scientist who is aware of the complete development to deployment workflow can deliver a product that is much more ready for deployment. This awareness can take some strain off of developers and DevOps teams." }, { "code": null, "e": 1903, "s": 1755, "text": "Effective environment management saves time and allows developers and data scientists to create isolated software products that are easy to deploy." }, { "code": null, "e": 2194, "s": 1903, "text": "Pipenv combines package management and virtual environment control into one tool for installing, removing, tracking, and documenting your dependencies; and to create, use, and manage your virtual environments. Pipenv is essentially pip and virtualenv wrapped together into a single product." }, { "code": null, "e": 2491, "s": 2194, "text": "Heroku offers many software service products. We’ll need the Heroku cloud platform service to host apps. Don’t worry; creating an account and hosting an app is free. The cloud platform supports apps in many programming languages including, Python, Node.js, Scala, Ruby, Clojure, Java, PHP and Go." }, { "code": null, "e": 2724, "s": 2491, "text": "Once we have an app with a Pipfile pushed to GitHub, Heroku allows us to deploy an app from Github to Heroku quickly. Be sure to have your Pipfile at the project’s root directory. Our app uses an SQLite database for this deployment." }, { "code": null, "e": 2823, "s": 2724, "text": "We’ll need to make a couple of changes to our app project files so that the app can run on Heroku." }, { "code": null, "e": 3028, "s": 2823, "text": "Gunicorn is a Python WSGI HTTP server that will serve your Flask application on Heroku. By running the line below, you add gunicorn to your Pipfile, which is needed to run your app in Heroku’s containers." }, { "code": null, "e": 3052, "s": 3028, "text": "pipenv install gunicorn" }, { "code": null, "e": 3125, "s": 3052, "text": "Create a Procfile in the project root folder and add the following line:" }, { "code": null, "e": 3147, "s": 3125, "text": "web: gunicorn app:app" }, { "code": null, "e": 3415, "s": 3147, "text": "The first app represents the name of the python file that runs your application or the name of the module where the app is located. The second app represents your app name, i.e., app.py. This Procfile works with gunicorn and Heroku's Dynos to serve your app remotely." }, { "code": null, "e": 3565, "s": 3415, "text": "Once we have our app tested and working locally, we push all code to the master branch. Then on Heroku, go to deploy a new app to see the page below." }, { "code": null, "e": 3746, "s": 3565, "text": "Next on Heroku, select GitHub and enter the name of the repository and hit search. Once your Username/repository appears, click connect. Select the desired branch and click deploy." }, { "code": null, "e": 3917, "s": 3746, "text": "Build logs will begin to populate a console on the page. Notice that Heroku looks for a requirements.txt file first then installs dependencies from Pipenv’s Pipfile.lock." }, { "code": null, "e": 4037, "s": 3917, "text": "Once your environment has been built from the Pipfile.lock and the build is successful, you will see the below message." }, { "code": null, "e": 4127, "s": 4037, "text": "The app is successfully deployed! Click to view button to see the deployed app on Heroku." }, { "code": null, "e": 4335, "s": 4127, "text": "We can enable automatic deployment to have changes to the Github master be displayed on Heroku as they are pushed. If you use this method, you’ll want to be sure that you always have a working master branch." }, { "code": null, "e": 4609, "s": 4335, "text": "Practicing good environment and package management is crucial for data scientists and developers who want their code deployed, built upon, or used in production. These development skills can help teams when used by data scientists and developers upstream in their workflow." }, { "code": null, "e": 4823, "s": 4609, "text": "Having a well managed Pipenv and Pipfile allowed Heroku’s severs to rebuild our app with minimal troubleshooting. This allowed us to take an app project directory from GitHub to a working published app in minutes." } ]
DAX Text - LEFT function
Returns the specified number of characters from the start of a text string. LEFT (<text>, <num_chars>) text The text string containing the characters you want to extract, or a reference to a column that contains text. num_chars Optional. The number of characters you want LEFT to extract. If omitted, default is 1. A text string. DAX works with Unicode and stores all characters as the same length. Therefore, a single function LEFT is enough to extract the characters. If the num_chars argument is a number that is larger than the number of characters in the text string, DAX LEFT function returns the maximum characters available and does not raise any error. = CONCATENATE (LEFT([Product], 5), [No. of Units]) returns a calculated column with the first 5 characters of the Product value concatenated with the value in the No. of Units column in the same row. 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": 2077, "s": 2001, "text": "Returns the specified number of characters from the start of a text string." }, { "code": null, "e": 2106, "s": 2077, "text": "LEFT (<text>, <num_chars>) \n" }, { "code": null, "e": 2111, "s": 2106, "text": "text" }, { "code": null, "e": 2221, "s": 2111, "text": "The text string containing the characters you want to extract, or a reference to a column that contains text." }, { "code": null, "e": 2231, "s": 2221, "text": "num_chars" }, { "code": null, "e": 2241, "s": 2231, "text": "Optional." }, { "code": null, "e": 2292, "s": 2241, "text": "The number of characters you want LEFT to extract." }, { "code": null, "e": 2318, "s": 2292, "text": "If omitted, default is 1." }, { "code": null, "e": 2333, "s": 2318, "text": "A text string." }, { "code": null, "e": 2473, "s": 2333, "text": "DAX works with Unicode and stores all characters as the same length. Therefore, a single function LEFT is enough to extract the characters." }, { "code": null, "e": 2665, "s": 2473, "text": "If the num_chars argument is a number that is larger than the number of characters in the text string, DAX LEFT function returns the maximum characters available and does not raise any error." }, { "code": null, "e": 2717, "s": 2665, "text": "= CONCATENATE (LEFT([Product], 5), [No. of Units]) " }, { "code": null, "e": 2866, "s": 2717, "text": "returns a calculated column with the first 5 characters of the Product value concatenated with the value in the No. of Units column in the same row." }, { "code": null, "e": 2901, "s": 2866, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2915, "s": 2901, "text": " Abhay Gadiya" }, { "code": null, "e": 2948, "s": 2915, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2962, "s": 2948, "text": " Randy Minder" }, { "code": null, "e": 2997, "s": 2962, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3011, "s": 2997, "text": " Randy Minder" }, { "code": null, "e": 3018, "s": 3011, "text": " Print" }, { "code": null, "e": 3029, "s": 3018, "text": " Add Notes" } ]
How to extract the dataframe row with min or max values in R ? - GeeksforGeeks
21 Apr, 2021 The tabular arrangement of rows and columns to form a data frame in R Programming Language supports many ways to access and modify the data. Application of queries and aggregate functions, like min, max and count can easily be made over the data frame cell values. Therefore, it is relatively very easy to access a subset of the data frame based on the values contained in the cell. Example 1: Determining the row with min or max value based on the entire data frame values. An iteration is made over the data frame cells, by using two loops for each row and column of the data frame respectively. The cell value is compared to the initial minimum and maximum values respectively and updated in case the value satisfies the constraint. Also, a variable is declared to keep the current row index satisfying the condition. Then, the row at this index of the data frame is accessed. Time complexity is polynomial with respect to the size of the data frame. R # declaring a data frame in Rdata_frame = data.frame(C1 = c(5:8), C2 = c(1:4), C3 = c(9:12), C4 = c(13:16)) print("Original data frame")print(data_frame) # declaring initial values for min and maxmin = 32767max = -32767min_row_indx = 0max_row_indx = 0 # looping over the data frame valuesfor (i in 1:nrow(data_frame)){ # for-loop over columnsfor(j in 1:ncol(data_frame)) { # checking if the dataframe # cell value is less than minimum if(data_frame[i,j]<min){ # replacing the minimum # with the smaller value min = data_frame[i,j] # updating the row with the # smallest value found uptil now min_row_indx = i } # checking if the data frame # cell value is more than maximum if(data_frame[i,j]>max){ # replacing the minimum # with the smaller value max = data_frame[i,j] # updating the row with the # smallest value found uptil now max_row_indx = i } }}# printing the row with minimum valueprint ("Row with minimum value in the data frame")print (data_frame[min_row_indx,]) # printing the row with maximum valueprint ("Row with maximum value in the data frame")print (data_frame[max_row_indx,]) Output: [1] "Original data frame" C1 C2 C3 C4 1 5 1 9 13 2 6 2 10 14 3 7 3 11 15 4 8 4 12 16 [1] "Row with minimum value in the data frame" C1 C2 C3 C4 1 5 1 9 13 [1] "Row with maximum value in the data frame" C1 C2 C3 C4 4 8 4 12 16 Example 2: Determining the row with min or max value based on a data frame column The function which.min() in R can be used to compute the minimum of all the values in the object specified as argument, whether it be a list, matrix, or data frame. Similarly, which.max() computes the largest of all the values. In order to select a particular column of the data frame we use df$colname and then apply this as an index of the data frame to extract the complete row with the specified aggregate function. This approach can be applied to all the data types, numeric, string as well as factor. The time complexity required is linear with respect to the column length since we directly access and compare all the values of this particular column. The following syntax in R is used to extract the row with minimum or maximum value in the column specified in the argument : Syntax: df[which.min(df$colname),] Arguments : df – Data Frame to extract the minimum or maximum value from colname – Column name to consider calculating minimum or maximum from. Returns : The row with the maximum or minimum cell value in the particular column. Code: R # declaring a data frame in Rdata_frame = data.frame(C1 = c(1:4), C2 = c( 5:8), C3 = c(9:12), C4 = c(13:16)) print("Original data frame")print(data_frame) # extracting the row with# maximum value in C2 columnprint ("Row with max C2 value")data_frame[which.max(data_frame$C2),] # extracting the row with # minimum value in C4 columnprint ("Row with min C4 value")data_frame[which.min(data_frame$C4),] Output: [1] "Original data frame" C1 C2 C3 C4 1 1 5 9 13 2 2 6 10 14 3 3 7 11 15 4 4 8 12 16 [1] "Row with max C2 value" C1 C2 C3 C4 4 4 8 12 16 [1] "Row with min C4 value" C1 C2 C3 C4 1 1 5 9 13 In case the data frame contains string type variable values, the minimum and maximum are computed upon sorting this data lexicographically. R # declaring a data frame in Rdata_frame = data.frame(C1= c("a","b","c","d"), C2= c("geeks","dataframe","in","R"), C3= c(9:12),C4=c(13:16)) print("Original data frame")print(data_frame) # extracting the row with maximum value in # C2 columnprint ("Row with max C1 value")data_frame[which.max(data_frame$C1),] # extracting the row with minimum value in # C4 columnprint ("Row with min C2 value")data_frame[which.min(data_frame$C2),] Output [1] "Original data frame" C1 C2 C3 C4 1 a geeks 9 13 2 b dataframe 10 14 3 c in 11 15 4 d R 12 16 [1] "Row with max C1 value" C1 C2 C3 C4 4 d R 12 16 [1] "Row with min C2 value" C1 C2 C3 C4 2 b dataframe 10 14 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? How to Split Column Into Multiple Columns in R DataFrame? Remove rows with NA in one column of R DataFrame How to filter R DataFrame by values in a column?
[ { "code": null, "e": 24395, "s": 24367, "text": "\n21 Apr, 2021" }, { "code": null, "e": 24779, "s": 24395, "text": "The tabular arrangement of rows and columns to form a data frame in R Programming Language supports many ways to access and modify the data. Application of queries and aggregate functions, like min, max and count can easily be made over the data frame cell values. Therefore, it is relatively very easy to access a subset of the data frame based on the values contained in the cell. " }, { "code": null, "e": 24871, "s": 24779, "text": "Example 1: Determining the row with min or max value based on the entire data frame values." }, { "code": null, "e": 25351, "s": 24871, "text": "An iteration is made over the data frame cells, by using two loops for each row and column of the data frame respectively. The cell value is compared to the initial minimum and maximum values respectively and updated in case the value satisfies the constraint. Also, a variable is declared to keep the current row index satisfying the condition. Then, the row at this index of the data frame is accessed. Time complexity is polynomial with respect to the size of the data frame. " }, { "code": null, "e": 25353, "s": 25351, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1 = c(5:8), C2 = c(1:4), C3 = c(9:12), C4 = c(13:16)) print(\"Original data frame\")print(data_frame) # declaring initial values for min and maxmin = 32767max = -32767min_row_indx = 0max_row_indx = 0 # looping over the data frame valuesfor (i in 1:nrow(data_frame)){ # for-loop over columnsfor(j in 1:ncol(data_frame)) { # checking if the dataframe # cell value is less than minimum if(data_frame[i,j]<min){ # replacing the minimum # with the smaller value min = data_frame[i,j] # updating the row with the # smallest value found uptil now min_row_indx = i } # checking if the data frame # cell value is more than maximum if(data_frame[i,j]>max){ # replacing the minimum # with the smaller value max = data_frame[i,j] # updating the row with the # smallest value found uptil now max_row_indx = i } }}# printing the row with minimum valueprint (\"Row with minimum value in the data frame\")print (data_frame[min_row_indx,]) # printing the row with maximum valueprint (\"Row with maximum value in the data frame\")print (data_frame[max_row_indx,])", "e": 26788, "s": 25353, "text": null }, { "code": null, "e": 26796, "s": 26788, "text": "Output:" }, { "code": null, "e": 27039, "s": 26796, "text": "[1] \"Original data frame\"\n C1 C2 C3 C4\n1 5 1 9 13\n2 6 2 10 14\n3 7 3 11 15\n4 8 4 12 16\n[1] \"Row with minimum value in the data frame\"\n C1 C2 C3 C4\n1 5 1 9 13\n[1] \"Row with maximum value in the data frame\"\n C1 C2 C3 C4\n4 8 4 12 16" }, { "code": null, "e": 27121, "s": 27039, "text": "Example 2: Determining the row with min or max value based on a data frame column" }, { "code": null, "e": 27781, "s": 27121, "text": "The function which.min() in R can be used to compute the minimum of all the values in the object specified as argument, whether it be a list, matrix, or data frame. Similarly, which.max() computes the largest of all the values. In order to select a particular column of the data frame we use df$colname and then apply this as an index of the data frame to extract the complete row with the specified aggregate function. This approach can be applied to all the data types, numeric, string as well as factor. The time complexity required is linear with respect to the column length since we directly access and compare all the values of this particular column. " }, { "code": null, "e": 27907, "s": 27781, "text": "The following syntax in R is used to extract the row with minimum or maximum value in the column specified in the argument : " }, { "code": null, "e": 27942, "s": 27907, "text": "Syntax: df[which.min(df$colname),]" }, { "code": null, "e": 27955, "s": 27942, "text": "Arguments : " }, { "code": null, "e": 28016, "s": 27955, "text": "df – Data Frame to extract the minimum or maximum value from" }, { "code": null, "e": 28087, "s": 28016, "text": "colname – Column name to consider calculating minimum or maximum from." }, { "code": null, "e": 28171, "s": 28087, "text": "Returns : The row with the maximum or minimum cell value in the particular column. " }, { "code": null, "e": 28177, "s": 28171, "text": "Code:" }, { "code": null, "e": 28179, "s": 28177, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1 = c(1:4), C2 = c( 5:8), C3 = c(9:12), C4 = c(13:16)) print(\"Original data frame\")print(data_frame) # extracting the row with# maximum value in C2 columnprint (\"Row with max C2 value\")data_frame[which.max(data_frame$C2),] # extracting the row with # minimum value in C4 columnprint (\"Row with min C4 value\")data_frame[which.min(data_frame$C4),]", "e": 28651, "s": 28179, "text": null }, { "code": null, "e": 28659, "s": 28651, "text": "Output:" }, { "code": null, "e": 28864, "s": 28659, "text": "[1] \"Original data frame\"\n C1 C2 C3 C4\n1 1 5 9 13\n2 2 6 10 14\n3 3 7 11 15\n4 4 8 12 16\n[1] \"Row with max C2 value\"\n C1 C2 C3 C4\n4 4 8 12 16\n[1] \"Row with min C4 value\"\n C1 C2 C3 C4\n1 1 5 9 13" }, { "code": null, "e": 29005, "s": 28864, "text": "In case the data frame contains string type variable values, the minimum and maximum are computed upon sorting this data lexicographically. " }, { "code": null, "e": 29007, "s": 29005, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1= c(\"a\",\"b\",\"c\",\"d\"), C2= c(\"geeks\",\"dataframe\",\"in\",\"R\"), C3= c(9:12),C4=c(13:16)) print(\"Original data frame\")print(data_frame) # extracting the row with maximum value in # C2 columnprint (\"Row with max C1 value\")data_frame[which.max(data_frame$C1),] # extracting the row with minimum value in # C4 columnprint (\"Row with min C2 value\")data_frame[which.min(data_frame$C2),]", "e": 29487, "s": 29007, "text": null }, { "code": null, "e": 29494, "s": 29487, "text": "Output" }, { "code": null, "e": 29748, "s": 29494, "text": "[1] \"Original data frame\"\n C1 C2 C3 C4\n1 a geeks 9 13\n2 b dataframe 10 14\n3 c in 11 15\n4 d R 12 16\n[1] \"Row with max C1 value\"\n C1 C2 C3 C4\n4 d R 12 16\n[1] \"Row with min C2 value\"\n C1 C2 C3 C4\n2 b dataframe 10 14" }, { "code": null, "e": 29755, "s": 29748, "text": "Picked" }, { "code": null, "e": 29776, "s": 29755, "text": "R DataFrame-Programs" }, { "code": null, "e": 29788, "s": 29776, "text": "R-DataFrame" }, { "code": null, "e": 29799, "s": 29788, "text": "R Language" }, { "code": null, "e": 29810, "s": 29799, "text": "R Programs" }, { "code": null, "e": 29908, "s": 29810, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29917, "s": 29908, "text": "Comments" }, { "code": null, "e": 29930, "s": 29917, "text": "Old Comments" }, { "code": null, "e": 29988, "s": 29930, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 30032, "s": 29988, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 30084, "s": 30032, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 30136, "s": 30084, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30168, "s": 30136, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 30226, "s": 30168, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 30270, "s": 30226, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 30328, "s": 30270, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30377, "s": 30328, "text": "Remove rows with NA in one column of R DataFrame" } ]
Create table from DataFrame in R - GeeksforGeeks
07 Apr, 2021 In this article, we are going to discuss how to create a table from the given Data-Frame in the R Programming language. table(): This function is an essential function for performing interactive data analyses. As it simply creates tabular results of categorical variables. Syntax: table(..., exclude = if (useNA == “no”) c(NA, NaN),useNA = c(“no”, “ifany”, “always”), dnn = list.names(...), deparse.level = 1) Returns: It will return the frequency tables with conditions and cross-tabulations. Example 1: Creating a frequency table of the given data frame in R language:- In this example, we will be building up the simple frequency table in R language using the table() function in R language. This table just providing the frequencies of elements in the dataframe. R gfg_data <- data.frame( Country = c("France","Spain","Germany","Spain","Germany", "France","Spain","France","Germany","France"), age = c(44,27,30,38,40,35,52,48,45,37), salary = c(6000,5000,7000,4000,8000), Purchased=c("No","Yes","No","No","Yes", "Yes","No","Yes","No","Yes")) gfg_table<-table(gfg_data$Country)gfg_table Output: France Germany Spain 4 3 3 Example 2: Creating a frequency table with the proportion of the given data frame in R language: Here, we will be using the prop.table() function which works quite similar to the simple table() function to get the frequency table with proportion from the given data frame. R gfg_data <- data.frame( Country = c("France","Spain","Germany","Spain","Germany", "France","Spain","France","Germany","France"), age = c(44,27,30,38,40,35,52,48,45,37), salary = c(6000,5000,7000,4000,8000), Purchased=c("No","Yes","No","No","Yes","Yes", "No","Yes","No","Yes")) gfg_table = as.table(table(gfg_data$Country))prop.table(gfg_table) Output: France Germany Spain 0.4 0.3 0.3 Example 3: Creating a frequency table with condition from the given data frame in R language: In this example, we will be building up the simple frequency table in R language using the table() function with a condition inside it as the function parameter R language. This table just providing the frequencies of elements that match the given conditions in the function in the data frame. Here we will be making a frequency table of the salary column with the condition of a salary greater than 6000 from the data frame using the table() function in R language. R gfg_data <- data.frame( Country = c("France","Spain","Germany","Spain","Germany", "France","Spain","France","Germany","France"), age = c(44,27,30,38,40,35,52,48,45,37), salary = c(6000,5000,7000,4000,8000), Purchased=c("No","Yes","No","No","Yes","Yes", "No","Yes","No","Yes")) gfg_table =table(gfg_data$salary>6000)gfg_table Output: FALSE TRUE 6 4 Example 4: Creating a 2–way cross table from the given data frame in R language: In this example, we will be building up the simple 2-way cross table in R language using the table() function R language. This table just providing the frequencies of elements of the different columns in the data frame. R gfg_data <- data.frame( Country = c("France","Spain","Germany","Spain","Germany", "France","Spain","France","Germany","France"), age = c(44,27,30,38,40,35,52,48,45,37), salary = c(6000,5000,7000,4000,8000), Purchased=c("No","Yes","No","No","Yes","Yes", "No","Yes","No","Yes")) gfg_table =table(gfg_data$salary,gfg_data$Country)gfg_table Output: France Germany Spain 4000 0 1 1 5000 0 0 2 6000 2 0 0 7000 1 1 0 8000 1 1 0 Picked R-DataFrame R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Time Series Analysis in R R - if statement
[ { "code": null, "e": 25242, "s": 25214, "text": "\n07 Apr, 2021" }, { "code": null, "e": 25362, "s": 25242, "text": "In this article, we are going to discuss how to create a table from the given Data-Frame in the R Programming language." }, { "code": null, "e": 25515, "s": 25362, "text": "table(): This function is an essential function for performing interactive data analyses. As it simply creates tabular results of categorical variables." }, { "code": null, "e": 25652, "s": 25515, "text": "Syntax: table(..., exclude = if (useNA == “no”) c(NA, NaN),useNA = c(“no”, “ifany”, “always”), dnn = list.names(...), deparse.level = 1)" }, { "code": null, "e": 25736, "s": 25652, "text": "Returns: It will return the frequency tables with conditions and cross-tabulations." }, { "code": null, "e": 25814, "s": 25736, "text": "Example 1: Creating a frequency table of the given data frame in R language:-" }, { "code": null, "e": 26009, "s": 25814, "text": "In this example, we will be building up the simple frequency table in R language using the table() function in R language. This table just providing the frequencies of elements in the dataframe." }, { "code": null, "e": 26011, "s": 26009, "text": "R" }, { "code": "gfg_data <- data.frame( Country = c(\"France\",\"Spain\",\"Germany\",\"Spain\",\"Germany\", \"France\",\"Spain\",\"France\",\"Germany\",\"France\"), age = c(44,27,30,38,40,35,52,48,45,37), salary = c(6000,5000,7000,4000,8000), Purchased=c(\"No\",\"Yes\",\"No\",\"No\",\"Yes\", \"Yes\",\"No\",\"Yes\",\"No\",\"Yes\")) gfg_table<-table(gfg_data$Country)gfg_table", "e": 26377, "s": 26011, "text": null }, { "code": null, "e": 26385, "s": 26377, "text": "Output:" }, { "code": null, "e": 26435, "s": 26385, "text": " France Germany Spain \n 4 3 3 " }, { "code": null, "e": 26532, "s": 26435, "text": "Example 2: Creating a frequency table with the proportion of the given data frame in R language:" }, { "code": null, "e": 26708, "s": 26532, "text": "Here, we will be using the prop.table() function which works quite similar to the simple table() function to get the frequency table with proportion from the given data frame." }, { "code": null, "e": 26710, "s": 26708, "text": "R" }, { "code": "gfg_data <- data.frame( Country = c(\"France\",\"Spain\",\"Germany\",\"Spain\",\"Germany\", \"France\",\"Spain\",\"France\",\"Germany\",\"France\"), age = c(44,27,30,38,40,35,52,48,45,37), salary = c(6000,5000,7000,4000,8000), Purchased=c(\"No\",\"Yes\",\"No\",\"No\",\"Yes\",\"Yes\", \"No\",\"Yes\",\"No\",\"Yes\")) gfg_table = as.table(table(gfg_data$Country))prop.table(gfg_table)", "e": 27095, "s": 26710, "text": null }, { "code": null, "e": 27103, "s": 27095, "text": "Output:" }, { "code": null, "e": 27153, "s": 27103, "text": " France Germany Spain \n 0.4 0.3 0.3 " }, { "code": null, "e": 27247, "s": 27153, "text": "Example 3: Creating a frequency table with condition from the given data frame in R language:" }, { "code": null, "e": 27541, "s": 27247, "text": "In this example, we will be building up the simple frequency table in R language using the table() function with a condition inside it as the function parameter R language. This table just providing the frequencies of elements that match the given conditions in the function in the data frame." }, { "code": null, "e": 27714, "s": 27541, "text": "Here we will be making a frequency table of the salary column with the condition of a salary greater than 6000 from the data frame using the table() function in R language." }, { "code": null, "e": 27716, "s": 27714, "text": "R" }, { "code": "gfg_data <- data.frame( Country = c(\"France\",\"Spain\",\"Germany\",\"Spain\",\"Germany\", \"France\",\"Spain\",\"France\",\"Germany\",\"France\"), age = c(44,27,30,38,40,35,52,48,45,37), salary = c(6000,5000,7000,4000,8000), Purchased=c(\"No\",\"Yes\",\"No\",\"No\",\"Yes\",\"Yes\", \"No\",\"Yes\",\"No\",\"Yes\")) gfg_table =table(gfg_data$salary>6000)gfg_table", "e": 28082, "s": 27716, "text": null }, { "code": null, "e": 28090, "s": 28082, "text": "Output:" }, { "code": null, "e": 28116, "s": 28090, "text": "FALSE TRUE \n 6 4 " }, { "code": null, "e": 28197, "s": 28116, "text": "Example 4: Creating a 2–way cross table from the given data frame in R language:" }, { "code": null, "e": 28417, "s": 28197, "text": "In this example, we will be building up the simple 2-way cross table in R language using the table() function R language. This table just providing the frequencies of elements of the different columns in the data frame." }, { "code": null, "e": 28419, "s": 28417, "text": "R" }, { "code": "gfg_data <- data.frame( Country = c(\"France\",\"Spain\",\"Germany\",\"Spain\",\"Germany\", \"France\",\"Spain\",\"France\",\"Germany\",\"France\"), age = c(44,27,30,38,40,35,52,48,45,37), salary = c(6000,5000,7000,4000,8000), Purchased=c(\"No\",\"Yes\",\"No\",\"No\",\"Yes\",\"Yes\", \"No\",\"Yes\",\"No\",\"Yes\")) gfg_table =table(gfg_data$salary,gfg_data$Country)gfg_table", "e": 28797, "s": 28419, "text": null }, { "code": null, "e": 28805, "s": 28797, "text": "Output:" }, { "code": null, "e": 28973, "s": 28805, "text": " France Germany Spain\n 4000 0 1 1\n 5000 0 0 2\n 6000 2 0 0\n 7000 1 1 0\n 8000 1 1 0" }, { "code": null, "e": 28980, "s": 28973, "text": "Picked" }, { "code": null, "e": 28992, "s": 28980, "text": "R-DataFrame" }, { "code": null, "e": 29003, "s": 28992, "text": "R Language" }, { "code": null, "e": 29101, "s": 29003, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29153, "s": 29101, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29191, "s": 29153, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29226, "s": 29191, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29284, "s": 29226, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29333, "s": 29284, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29370, "s": 29333, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29420, "s": 29370, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29463, "s": 29420, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29489, "s": 29463, "text": "Time Series Analysis in R" } ]
Option pricing using the Black-Scholes model, without the formula | by Daniel Reti | Towards Data Science
Every university student taking a module on finance has seen the Black-Scholes-Merton option pricing formula. It is long, ugly, and confusing. It doesn’t even give an intuition for pricing options. The derivation of it is so difficult that Scholes and Merton received a Nobel prize for it in 1997 (Black died in 1995). It relies on the Feynman-Kac theorem and risk-neutral measures, but I will not get into it. (https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_equation). Pricing an option can be done using the Black-Scholes partial differential equation (BS PDE). The BS PDE can be derived by applying Ito’s Lemma to geometric Brownian motion and then setting the necessary conditions to satisfy the continuous-time delta hedging. We will solve this equation numerically, using Python. The main advantage of this method is that it bypasses very complicated analytical calculations with numerical methods, which are done by our computer. As we are trying to solve the PDE numerically, we need to establish a few things before. Firstly, we will use it to value a European call option with strike price K. The method I will be using is called the finite difference method and it involves setting up a grid of points. This grid will be used to simulate the PDE from point to point. The grid on the x-axis will represent the simulated times, which ranges from [0,1] and the y-axis will represent the possible stock prices, ranging from [S_min,S_max] . The result will be a 3D graph and our job is to determine the option price above each point on the grid. To simulate on the grid we need to determine 3 boundaries (edge) conditions of the grid. In our case, we can do this for the top, the bottom, and the last boundary of the grid. We will also see later, that because of this we will simulate the equation backward. The bottom is the easiest, we will set S_min=0 . The top condition is a bit more tricky. It should be well above the option’s strike price K to ensure the option’s value V = max( S-K, 0) will always (with negligible probability of not happening p < 0.0001) payout S-K . We can do this by setting S_max 8 standard deviations away from the mean, as the stock price is log-normally distributed. So, if we take S_max=8sigma*(T-t)^0.5 , we have ensured that property. The option value V at S_max can be deducted using a replication argument. If a derivative pays S-K at time t, we can replicate it by purchasing 1 unit of stock and putting e^(-r(1-t)*K it into a risk-free bank account. So this makes the value of the option for large S: V(t,S_max)=S_max — e^(-r(1-t)*K . The final boundary condition will be the European call option’s payoff, as that will give the exact value for the option. So the three boundary conditions are: We have now established the boundary conditions for the grid. Next, we need to discretize our space, which will allow us to use a central difference estimate for the derivatives of the BS PDE. In the stock price direction (vertical) we introduce M points. To think about this, imagine that the possible range of S is [0,100] with M=100 . This will make 100 stock points with 1 at every integer. We do the same in the time direction (horizontal) with N steps. This will create a N+1 x M+1 matrix, which we can use to create derivative estimates. With the discretized space, we can use central difference estimates for the derivatives of the option value (the delta and gamma from the greeks). Plugging these into the Black-Scholes PDE, we get This can be understood easily by visualizing what the above equation does. It basically takes 3 points and calculates a weighted average of those to arrive at a point 1 step forward in time. By iterating the above process we can simulate the above grid by going one step at a time. Note, that as we know the final boundary condition and not the first, we will be actually be going back in time. Applying the Euler-Maruyama scheme to the discretized Black-Scholes PDE, we get: This is a system of ODEs, where V is the column vector of option prices at each timestep. Moreover, we need to add a vector to the above equation that contains the boundary conditions at time t: W_t , and then we can rewrite the equation in matrix notation, such that Lambda contains the multipliers. This equation now contains all the information we have and is called the explicit method. It uses the backward difference estimate for V concerning t, which is equivalent to the forward's difference if we were simulating forward it time (We are simulating backward). So, to code it up we need functions for the boundary conditions. import numpy as npimport scipy.sparseimport matplolib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Ddef bottom_boundary_condition(K,T,S_min, r, t): return np.zeros(t.shape)def top_boundary_condition(K,T,S_max, r, t): return S_max-np.exp(-r*(T-t))*Kdef bottom_boundary_condition(K,T,S_min, r, t): return np.maximum(S-K,0) We also need functions to calculate the coefficients in Lamda . I wrote two functions for this, which I derived after doing some algebraic manipulations to the equation with the central difference estimates to isolate each V_i . def compute_abc( K, T, sigma, r, S, dt, dS ): a = -sigma**2 * S**2/(2* dS**2 ) + r*S/(2*dS) b = r + sigma**2 * S**2/(dS**2) c = -sigma**2 * S**2/(2* dS**2 ) - r*S/(2*dS) return a,b,cdef compute_lambda( a,b,c ): return scipy.sparse.diags( [a[1:],b,c[:-1]],offsets=[-1,0,1])def compute_W(a,b,c, V0, VM): M = len(b)+1 W = np.zeros(M-1) W[0] = a[0]*V0 W[-1] = c[-1]*VM return W Combining all this in a function that essentially populates the N x M matrix with option values, and returns the option value V , the times t and the stock prices S . def price_call_explicit( K, T, r, sigma, N, M): # Choose the shape of the grid dt = T/N S_min=0 S_max=K*np.exp(8*sigma*np.sqrt(T)) dS = (S_max-S_min)/M S = np.linspace(S_min,S_max,M+1) t = np.linspace(0,T,N+1) V = np.zeros((N+1,M+1)) #... # Set the boundary conditions V[:,-1] = top_boundary_condition(K,T,S_max,r,t) V[:,0] = bottom_boundary_condition(K,T,S_max,r,t) V[-1,:] = final_boundary_condition(K,T,S) #... # Apply the recurrence relation a,b,c = compute_abc(K,T,sigma,r,S[1:-1],dt,dS) Lambda =compute_lambda( a,b,c) identity = scipy.sparse.identity(M-1) for i in range(N,0,-1): W = compute_W(a,b,c,V[i,0],V[i,M]) # Use `dot` to multiply a vector by a sparse matrix V[i-1,1:M] = (identity-Lambda*dt).dot( V[i,1:M] ) - W*dt return V, t, S Plotting t and S against V , we get a very nice plot of the option payoff at every time-stock combination. We can see that at t=1 the option value is exactly equal to its payoff, which is a great sanity check. Below you can see how the curve evolves into the option payoff at the final time. This is exactly what we want. Pricing an option using the Black-Scholes PDE can be a very good intuition building example, but sadly it cannot really be used in practice. Mainly because it is slow to use and we have the formula to use. My above method can be made more robust by tuning the Crank-Nicholson method to simulate, which makes the process less sensitive. Let me know if you would like to know more about the derivation, or a more in-depth review of the code or the Crank-Nicholson method. I would like to add that I learned a lot from Dr. John Armstrong, my lecturer in financial maths at KCL. https://nms.kcl.ac.uk/john.armstrong/ If you are unfamiliar with the Black-Scholes model, have a look at this article to get a great introduction: https://medium.com/cantors-paradise/the-black-scholes-formula-explained-9e05b7865d8a
[ { "code": null, "e": 583, "s": 172, "text": "Every university student taking a module on finance has seen the Black-Scholes-Merton option pricing formula. It is long, ugly, and confusing. It doesn’t even give an intuition for pricing options. The derivation of it is so difficult that Scholes and Merton received a Nobel prize for it in 1997 (Black died in 1995). It relies on the Feynman-Kac theorem and risk-neutral measures, but I will not get into it." }, { "code": null, "e": 647, "s": 583, "text": "(https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_equation)." }, { "code": null, "e": 908, "s": 647, "text": "Pricing an option can be done using the Black-Scholes partial differential equation (BS PDE). The BS PDE can be derived by applying Ito’s Lemma to geometric Brownian motion and then setting the necessary conditions to satisfy the continuous-time delta hedging." }, { "code": null, "e": 1114, "s": 908, "text": "We will solve this equation numerically, using Python. The main advantage of this method is that it bypasses very complicated analytical calculations with numerical methods, which are done by our computer." }, { "code": null, "e": 1391, "s": 1114, "text": "As we are trying to solve the PDE numerically, we need to establish a few things before. Firstly, we will use it to value a European call option with strike price K. The method I will be using is called the finite difference method and it involves setting up a grid of points." }, { "code": null, "e": 1729, "s": 1391, "text": "This grid will be used to simulate the PDE from point to point. The grid on the x-axis will represent the simulated times, which ranges from [0,1] and the y-axis will represent the possible stock prices, ranging from [S_min,S_max] . The result will be a 3D graph and our job is to determine the option price above each point on the grid." }, { "code": null, "e": 2454, "s": 1729, "text": "To simulate on the grid we need to determine 3 boundaries (edge) conditions of the grid. In our case, we can do this for the top, the bottom, and the last boundary of the grid. We will also see later, that because of this we will simulate the equation backward. The bottom is the easiest, we will set S_min=0 . The top condition is a bit more tricky. It should be well above the option’s strike price K to ensure the option’s value V = max( S-K, 0) will always (with negligible probability of not happening p < 0.0001) payout S-K . We can do this by setting S_max 8 standard deviations away from the mean, as the stock price is log-normally distributed. So, if we take S_max=8sigma*(T-t)^0.5 , we have ensured that property." }, { "code": null, "e": 2758, "s": 2454, "text": "The option value V at S_max can be deducted using a replication argument. If a derivative pays S-K at time t, we can replicate it by purchasing 1 unit of stock and putting e^(-r(1-t)*K it into a risk-free bank account. So this makes the value of the option for large S: V(t,S_max)=S_max — e^(-r(1-t)*K ." }, { "code": null, "e": 2918, "s": 2758, "text": "The final boundary condition will be the European call option’s payoff, as that will give the exact value for the option. So the three boundary conditions are:" }, { "code": null, "e": 3111, "s": 2918, "text": "We have now established the boundary conditions for the grid. Next, we need to discretize our space, which will allow us to use a central difference estimate for the derivatives of the BS PDE." }, { "code": null, "e": 3463, "s": 3111, "text": "In the stock price direction (vertical) we introduce M points. To think about this, imagine that the possible range of S is [0,100] with M=100 . This will make 100 stock points with 1 at every integer. We do the same in the time direction (horizontal) with N steps. This will create a N+1 x M+1 matrix, which we can use to create derivative estimates." }, { "code": null, "e": 3610, "s": 3463, "text": "With the discretized space, we can use central difference estimates for the derivatives of the option value (the delta and gamma from the greeks)." }, { "code": null, "e": 3660, "s": 3610, "text": "Plugging these into the Black-Scholes PDE, we get" }, { "code": null, "e": 3851, "s": 3660, "text": "This can be understood easily by visualizing what the above equation does. It basically takes 3 points and calculates a weighted average of those to arrive at a point 1 step forward in time." }, { "code": null, "e": 4055, "s": 3851, "text": "By iterating the above process we can simulate the above grid by going one step at a time. Note, that as we know the final boundary condition and not the first, we will be actually be going back in time." }, { "code": null, "e": 4136, "s": 4055, "text": "Applying the Euler-Maruyama scheme to the discretized Black-Scholes PDE, we get:" }, { "code": null, "e": 4704, "s": 4136, "text": "This is a system of ODEs, where V is the column vector of option prices at each timestep. Moreover, we need to add a vector to the above equation that contains the boundary conditions at time t: W_t , and then we can rewrite the equation in matrix notation, such that Lambda contains the multipliers. This equation now contains all the information we have and is called the explicit method. It uses the backward difference estimate for V concerning t, which is equivalent to the forward's difference if we were simulating forward it time (We are simulating backward)." }, { "code": null, "e": 4769, "s": 4704, "text": "So, to code it up we need functions for the boundary conditions." }, { "code": null, "e": 5105, "s": 4769, "text": "import numpy as npimport scipy.sparseimport matplolib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Ddef bottom_boundary_condition(K,T,S_min, r, t): return np.zeros(t.shape)def top_boundary_condition(K,T,S_max, r, t): return S_max-np.exp(-r*(T-t))*Kdef bottom_boundary_condition(K,T,S_min, r, t): return np.maximum(S-K,0)" }, { "code": null, "e": 5334, "s": 5105, "text": "We also need functions to calculate the coefficients in Lamda . I wrote two functions for this, which I derived after doing some algebraic manipulations to the equation with the central difference estimates to isolate each V_i ." }, { "code": null, "e": 5741, "s": 5334, "text": "def compute_abc( K, T, sigma, r, S, dt, dS ): a = -sigma**2 * S**2/(2* dS**2 ) + r*S/(2*dS) b = r + sigma**2 * S**2/(dS**2) c = -sigma**2 * S**2/(2* dS**2 ) - r*S/(2*dS) return a,b,cdef compute_lambda( a,b,c ): return scipy.sparse.diags( [a[1:],b,c[:-1]],offsets=[-1,0,1])def compute_W(a,b,c, V0, VM): M = len(b)+1 W = np.zeros(M-1) W[0] = a[0]*V0 W[-1] = c[-1]*VM return W" }, { "code": null, "e": 5908, "s": 5741, "text": "Combining all this in a function that essentially populates the N x M matrix with option values, and returns the option value V , the times t and the stock prices S ." }, { "code": null, "e": 6749, "s": 5908, "text": "def price_call_explicit( K, T, r, sigma, N, M): # Choose the shape of the grid dt = T/N S_min=0 S_max=K*np.exp(8*sigma*np.sqrt(T)) dS = (S_max-S_min)/M S = np.linspace(S_min,S_max,M+1) t = np.linspace(0,T,N+1) V = np.zeros((N+1,M+1)) #... # Set the boundary conditions V[:,-1] = top_boundary_condition(K,T,S_max,r,t) V[:,0] = bottom_boundary_condition(K,T,S_max,r,t) V[-1,:] = final_boundary_condition(K,T,S) #... # Apply the recurrence relation a,b,c = compute_abc(K,T,sigma,r,S[1:-1],dt,dS) Lambda =compute_lambda( a,b,c) identity = scipy.sparse.identity(M-1) for i in range(N,0,-1): W = compute_W(a,b,c,V[i,0],V[i,M]) # Use `dot` to multiply a vector by a sparse matrix V[i-1,1:M] = (identity-Lambda*dt).dot( V[i,1:M] ) - W*dt return V, t, S" }, { "code": null, "e": 6856, "s": 6749, "text": "Plotting t and S against V , we get a very nice plot of the option payoff at every time-stock combination." }, { "code": null, "e": 7071, "s": 6856, "text": "We can see that at t=1 the option value is exactly equal to its payoff, which is a great sanity check. Below you can see how the curve evolves into the option payoff at the final time. This is exactly what we want." }, { "code": null, "e": 7407, "s": 7071, "text": "Pricing an option using the Black-Scholes PDE can be a very good intuition building example, but sadly it cannot really be used in practice. Mainly because it is slow to use and we have the formula to use. My above method can be made more robust by tuning the Crank-Nicholson method to simulate, which makes the process less sensitive." }, { "code": null, "e": 7541, "s": 7407, "text": "Let me know if you would like to know more about the derivation, or a more in-depth review of the code or the Crank-Nicholson method." }, { "code": null, "e": 7684, "s": 7541, "text": "I would like to add that I learned a lot from Dr. John Armstrong, my lecturer in financial maths at KCL. https://nms.kcl.ac.uk/john.armstrong/" } ]
GATE | GATE-CS-2015 (Set 2) | Question 54 - GeeksforGeeks
19 Nov, 2018 Consider the sequence of machine instructions given below: MUL R5, R0, R1 DIV R6, R2, R3 ADD R7, R5, R6 SUB R8, R7, R4 In the above sequence, R0 to R8 are general purpose registers. In the instructions shown, the first register stores the result of the operation performed on the second and the third registers. This sequence of instructions is to be executed in a pipelined instruction processor with the following 4 stages: (1) Instruction Fetch and Decode (IF), (2) Operand Fetch (OF), (3) Perform Operation (PO) and (4) Write back the Result (WB). The IF, OF and WB stages take 1 clock cycle each for any instruction. The PO stage takes 1 clock cycle for ADD or SUB instruction, 3 clock cycles for MUL instruction and 5 clock cycles for DIV instruction. The pipelined processor uses operand forwarding from the PO stage to the OF stage. The number of clock cycles taken for the execution of the above sequence of instructions is ___________(A) 11(B) 12(C) 13(D) 14Answer: (C)Explanation: 1 2 3 4 5 6 7 8 9 10 11 12 13 IF OF PO PO PO WB IF OF PO PO PO PO PO WB IF OF PO WB IF OF PO WB Quiz of this Question GATE-CS-2015 (Set 2) GATE-GATE-CS-2015 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE CS 2012 | Question 40
[ { "code": null, "e": 24089, "s": 24061, "text": "\n19 Nov, 2018" }, { "code": null, "e": 24148, "s": 24089, "text": "Consider the sequence of machine instructions given below:" }, { "code": null, "e": 24217, "s": 24148, "text": " MUL R5, R0, R1\n DIV R6, R2, R3\n ADD R7, R5, R6\n SUB R8, R7, R4 " }, { "code": null, "e": 25090, "s": 24217, "text": "In the above sequence, R0 to R8 are general purpose registers. In the instructions shown, the first register stores the result of the operation performed on the second and the third registers. This sequence of instructions is to be executed in a pipelined instruction processor with the following 4 stages: (1) Instruction Fetch and Decode (IF), (2) Operand Fetch (OF), (3) Perform Operation (PO) and (4) Write back the Result (WB). The IF, OF and WB stages take 1 clock cycle each for any instruction. The PO stage takes 1 clock cycle for ADD or SUB instruction, 3 clock cycles for MUL instruction and 5 clock cycles for DIV instruction. The pipelined processor uses operand forwarding from the PO stage to the OF stage. The number of clock cycles taken for the execution of the above sequence of instructions is ___________(A) 11(B) 12(C) 13(D) 14Answer: (C)Explanation:" }, { "code": null, "e": 25324, "s": 25090, "text": " 1 2 3 4 5 6 7 8 9 10 11 12 13\n IF OF PO PO PO WB\n IF OF PO PO PO PO PO WB\n IF OF PO WB\n IF OF PO WB" }, { "code": null, "e": 25346, "s": 25324, "text": "Quiz of this Question" }, { "code": null, "e": 25367, "s": 25346, "text": "GATE-CS-2015 (Set 2)" }, { "code": null, "e": 25393, "s": 25367, "text": "GATE-GATE-CS-2015 (Set 2)" }, { "code": null, "e": 25398, "s": 25393, "text": "GATE" }, { "code": null, "e": 25496, "s": 25398, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25505, "s": 25496, "text": "Comments" }, { "code": null, "e": 25518, "s": 25505, "text": "Old Comments" }, { "code": null, "e": 25560, "s": 25518, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25602, "s": 25560, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25636, "s": 25602, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 25678, "s": 25636, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25712, "s": 25678, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25754, "s": 25712, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 25787, "s": 25754, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25829, "s": 25787, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25883, "s": 25829, "text": "C++ Program to count Vowels in a string using Pointer" } ]
Distinct Substrings | Practice | GeeksforGeeks
Given a string s consisting of uppercase and lowercase alphabetic characters. Return the number of distinct substrings of size 2 that appear in s as contiguous substrings. Example Input : s = "ABCAB" Output : 3 Explanation: For "ABCAB", the three distinct substrings of size 2 are "AB", "BC" and "CA". Example Input : s = "XYZ" Output : 2 Explanation: For "XYZ", the two distinct substrings of size 2 are "XY" and "YZ". Your Task : You don't need to read input or print anything. You have to complete the function fun() which takes the string s as input parameter and returns the number of distinct contiguous substring of size 2. Expected Time Complexity : O(|s|) Expected Auxilliary Space : O(|s|) Constraints: 1<=|s|<=100 |s| denotes the length of the string s. +1 sai8382633 weeks ago class Solution { int fun(String s) { // code here Set<String> set=new HashSet<String>(); for(int i=0;i<s.length();i++) { for(int j=i;j<s.length();j++) { String str=s.substring(i,j+1); if(str.length()==2) { set.add(str); } } } return set.size(); }} 0 ankitparashxr2 months ago java Test Cases Passed: 127 / 127 Total Points Scored: 2/2 Total Time Taken: 0.1/1.2 Your Accuracy: 100% Set<String> set = new HashSet<>(); for(int i=0;i<s.length();i++) { for(int j=i;j<s.length();j++) { String str = s.substring(i,j+1); if(!set.contains(str) && str.length()==2) { set.add(str); } } } return set.size(); +1 rathoredivya1502 months ago int fun( string s) {set<string>p; for(int i=0;i<s.size()-1;i++){string t; t+=s[i]; t+=s[i+1]; p.insert(t);} int final=p.size(); return final;//code here} +1 sg6214283 months ago class Solution { int fun(String s) { int i=0; int count=0; String key=""; Map<String,Integer>map=new HashMap<>(); while((i+1)!=s.length()) { key=s.substring(i,i+2); if(!map.containsKey(key)) { map.put(key,i); count++; } i++; } return count; } } +1 rajat25gupta3 months ago Java Solution int fun(String s) { // code here HashSet<String> hs = new HashSet<>(); for(int i=0; i<s.length()-1; i++){ hs.add(s.substring(i, i+2)); } return hs.size(); } +1 abhiiishek074 months ago int fun(string s){ //code here unordered_set<string> st; for(int i=0;i<s.size()-1;i++) { string str= s.substr(i,2); st.insert(str); } return st.size();} 0 imranwahid6 months ago Easy C++ solution https://ide.geeksforgeeks.org/4YcCgitU6s int fun(string s) { unordered_set<string>dict; for(int i=0;i<s.length();i++) { if(i+1<s.length()) { string tmp=s.substr(i,2); dict.insert(tmp); } } return dict.size(); } +1 xahoor726 months ago Chck this Out... int fun(string s){ //code here unordered_map<string,int>mp; string st=""; int n=s.size(); for(int i=0;i<n;i++){ st+=s[i]; st+=s[i+1]; mp[st]++; st=""; } return mp.size()-1; } 0 Jayesh Badgujar8 months ago Jayesh Badgujar https://uploads.disquscdn.c... 0 Dipanshu Tomar11 months ago Dipanshu Tomar Execution Time:0.26 https://uploads.disquscdn.c... 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": 399, "s": 226, "text": "Given a string s consisting of uppercase and lowercase alphabetic characters. Return the number of distinct substrings of size 2 that appear in s as contiguous substrings." }, { "code": null, "e": 407, "s": 399, "text": "Example" }, { "code": null, "e": 533, "s": 407, "text": "Input :\ns = \"ABCAB\"\nOutput :\n3\nExplanation: For \"ABCAB\", the \nthree distinct substrings of size \n2 are \"AB\", \"BC\" and \"CA\". " }, { "code": null, "e": 541, "s": 533, "text": "Example" }, { "code": null, "e": 653, "s": 541, "text": "Input :\ns = \"XYZ\"\nOutput :\n2\nExplanation: For \"XYZ\", the \ntwo distinct substrings of size 2 are\n\"XY\" and \"YZ\".\n" }, { "code": null, "e": 665, "s": 653, "text": "Your Task :" }, { "code": null, "e": 864, "s": 665, "text": "You don't need to read input or print anything. You have to complete the function fun() which takes the string s as input parameter and returns the number of distinct contiguous substring of size 2." }, { "code": null, "e": 933, "s": 864, "text": "Expected Time Complexity : O(|s|)\nExpected Auxilliary Space : O(|s|)" }, { "code": null, "e": 958, "s": 933, "text": "Constraints:\n1<=|s|<=100" }, { "code": null, "e": 998, "s": 958, "text": "|s| denotes the length of the string s." }, { "code": null, "e": 1001, "s": 998, "text": "+1" }, { "code": null, "e": 1022, "s": 1001, "text": "sai8382633 weeks ago" }, { "code": null, "e": 1453, "s": 1022, "text": "class Solution { int fun(String s) { // code here Set<String> set=new HashSet<String>(); for(int i=0;i<s.length();i++) { for(int j=i;j<s.length();j++) { String str=s.substring(i,j+1); if(str.length()==2) { set.add(str); } } } return set.size(); }} " }, { "code": null, "e": 1455, "s": 1453, "text": "0" }, { "code": null, "e": 1481, "s": 1455, "text": "ankitparashxr2 months ago" }, { "code": null, "e": 1486, "s": 1481, "text": "java" }, { "code": null, "e": 1505, "s": 1486, "text": "Test Cases Passed:" }, { "code": null, "e": 1515, "s": 1505, "text": "127 / 127" }, { "code": null, "e": 1536, "s": 1515, "text": "Total Points Scored:" }, { "code": null, "e": 1540, "s": 1536, "text": "2/2" }, { "code": null, "e": 1558, "s": 1540, "text": "Total Time Taken:" }, { "code": null, "e": 1566, "s": 1558, "text": "0.1/1.2" }, { "code": null, "e": 1581, "s": 1566, "text": "Your Accuracy:" }, { "code": null, "e": 1586, "s": 1581, "text": "100%" }, { "code": null, "e": 1931, "s": 1588, "text": "Set<String> set = new HashSet<>(); for(int i=0;i<s.length();i++) { for(int j=i;j<s.length();j++) { String str = s.substring(i,j+1); if(!set.contains(str) && str.length()==2) { set.add(str); } } } return set.size();" }, { "code": null, "e": 1934, "s": 1931, "text": "+1" }, { "code": null, "e": 1962, "s": 1934, "text": "rathoredivya1502 months ago" }, { "code": null, "e": 1981, "s": 1962, "text": "int fun( string s)" }, { "code": null, "e": 2127, "s": 1981, "text": "{set<string>p; for(int i=0;i<s.size()-1;i++){string t; t+=s[i]; t+=s[i+1]; p.insert(t);} int final=p.size(); return final;//code here} " }, { "code": null, "e": 2130, "s": 2127, "text": "+1" }, { "code": null, "e": 2151, "s": 2130, "text": "sg6214283 months ago" }, { "code": null, "e": 2532, "s": 2151, "text": "class Solution \n{ \n int fun(String s) \n {\n int i=0;\n int count=0;\n String key=\"\";\n Map<String,Integer>map=new HashMap<>();\n while((i+1)!=s.length())\n {\n key=s.substring(i,i+2);\n if(!map.containsKey(key))\n {\n map.put(key,i);\n count++;\n }\n i++;\n }\n return count;\n }\n} " }, { "code": null, "e": 2535, "s": 2532, "text": "+1" }, { "code": null, "e": 2560, "s": 2535, "text": "rajat25gupta3 months ago" }, { "code": null, "e": 2574, "s": 2560, "text": "Java Solution" }, { "code": null, "e": 2778, "s": 2576, "text": "int fun(String s) { // code here HashSet<String> hs = new HashSet<>(); for(int i=0; i<s.length()-1; i++){ hs.add(s.substring(i, i+2)); } return hs.size(); }" }, { "code": null, "e": 2781, "s": 2778, "text": "+1" }, { "code": null, "e": 2806, "s": 2781, "text": "abhiiishek074 months ago" }, { "code": null, "e": 2983, "s": 2806, "text": "int fun(string s){ //code here unordered_set<string> st; for(int i=0;i<s.size()-1;i++) { string str= s.substr(i,2); st.insert(str); } return st.size();}" }, { "code": null, "e": 2985, "s": 2983, "text": "0" }, { "code": null, "e": 3008, "s": 2985, "text": "imranwahid6 months ago" }, { "code": null, "e": 3026, "s": 3008, "text": "Easy C++ solution" }, { "code": null, "e": 3067, "s": 3026, "text": "https://ide.geeksforgeeks.org/4YcCgitU6s" }, { "code": null, "e": 3305, "s": 3067, "text": "int fun(string s)\n{\n unordered_set<string>dict;\n for(int i=0;i<s.length();i++)\n {\n if(i+1<s.length())\n {\n string tmp=s.substr(i,2);\n dict.insert(tmp);\n }\n }\n return dict.size();\n}" }, { "code": null, "e": 3308, "s": 3305, "text": "+1" }, { "code": null, "e": 3329, "s": 3308, "text": "xahoor726 months ago" }, { "code": null, "e": 3346, "s": 3329, "text": "Chck this Out..." }, { "code": null, "e": 3564, "s": 3346, "text": "int fun(string s){ //code here unordered_map<string,int>mp; string st=\"\"; int n=s.size(); for(int i=0;i<n;i++){ st+=s[i]; st+=s[i+1]; mp[st]++; st=\"\"; } return mp.size()-1; }" }, { "code": null, "e": 3566, "s": 3564, "text": "0" }, { "code": null, "e": 3594, "s": 3566, "text": "Jayesh Badgujar8 months ago" }, { "code": null, "e": 3610, "s": 3594, "text": "Jayesh Badgujar" }, { "code": null, "e": 3641, "s": 3610, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 3643, "s": 3641, "text": "0" }, { "code": null, "e": 3671, "s": 3643, "text": "Dipanshu Tomar11 months ago" }, { "code": null, "e": 3686, "s": 3671, "text": "Dipanshu Tomar" }, { "code": null, "e": 3737, "s": 3686, "text": "Execution Time:0.26 https://uploads.disquscdn.c..." }, { "code": null, "e": 3883, "s": 3737, "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": 3919, "s": 3883, "text": " Login to access your submissions. " }, { "code": null, "e": 3929, "s": 3919, "text": "\nProblem\n" }, { "code": null, "e": 3939, "s": 3929, "text": "\nContest\n" }, { "code": null, "e": 4002, "s": 3939, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4150, "s": 4002, "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": 4358, "s": 4150, "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": 4464, "s": 4358, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
K- means clustering with SciPy - GeeksforGeeks
15 Mar, 2021 Prerequisite: K-Means clustering The K-Means clustering is one of the partitioning approaches and each cluster will be represented with a calculated centroid. All the data points in the cluster will have a minimum distance from the computed centroid. Scipy is an open-source library that can be used for complex computations. It is mostly used with NumPy arrays. It can be installed by running the command given below. pip install scipy It has dedicated packages for the process of clustering. There are two modules that can offer clustering methods. cluster.vqcluster.hierarchy cluster.vq cluster.hierarchy This module gives the feature of vector quantization to use with the K-Means clustering method. The quantization of vectors plays a major role in reducing the distortion and improving the accuracy. Mostly the distortion here is calculated using the Euclidean distance between the centroid and each vector. Based on this the vector od data points are assigned to a cluster. This module provides methods for general hierarchical clustering and its types such as agglomerative clustering. It has various routines that can be used for applying statistical methods on the hierarchies, visualizing the clusters, plotting the clusters, checking linkages in the clusters, and also checking whether two different hierarchies are equivalent. In this article, cluster.vq module will be used to carry out the K-Means clustering. The K-means clustering can be done on given data by executing the following steps. Normalize the data points.Compute the centroids (referred to as code and the 2D array of centroids is referred to as code book).Form clusters and assign the data points (referred to as mapping from code book). Normalize the data points. Compute the centroids (referred to as code and the 2D array of centroids is referred to as code book). Form clusters and assign the data points (referred to as mapping from code book). This method is used to normalize the data points. Normalization is very important when the attributes considered are of different units. For example, if the length is given in meters and breadth is given in inches, it may produce an unequal variance for the vectors. It is always preferred to have unit variance while performing K-Means clustering to get accurate clusters. Thus, the data array has to pass to whiten() method before any other steps. cluster.vq.whiten(input_array, check_finite) Parameters: input_array : The array of data points to be normalized.check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking. input_array : The array of data points to be normalized. check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking. This vq module has two methods namely kmeans() and kmeans2(). The kmeans() method uses a threshold value which on becoming less than or equal to the change in distortion in the last iteration, the algorithm terminates. This method returns the centroids calculated and the mean value of the Euclidean distances between the observations and the centroids. cluster.vq.kmeans(input_array, k, iterations, threshold, check_finite) Parameters: input_array : The array of data points to be normalized.k : No.of.clusters (centroids)iterations : No.of.iterations to perform kmeans so that distortion is minimized. If k is specified it is ignored.threshold : An integer value which if becomes less than or equal to change in distortion in last iteration, the algorithm terminates.check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking. input_array : The array of data points to be normalized. k : No.of.clusters (centroids) iterations : No.of.iterations to perform kmeans so that distortion is minimized. If k is specified it is ignored. threshold : An integer value which if becomes less than or equal to change in distortion in last iteration, the algorithm terminates. check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking. The kmeans2() method does not use the threshold value to check for convergence. It has more parameters that decide the method of initialization of centroids, a method to handle empty clusters, and validating whether the input matrices contain only finite numbers. This method returns centroids and the clusters to which the vector belongs. cluster.vq.kmeans2(input_array, k, iterations, threshold, minit, missing, check_finite) Parameters: input_array : The array of data points to be normalized.k : No.of.clusters (centroids)iterations : No.of.iterations to perform kmeans so that distortion is minimized. If k is specified it is ignored.threshold : An integer value which if becomes less than or equal to change in distortion in last iteration, the algorithm terminates.minit : A string which denotes the initialization method of the centroids. Possible values are ‘random’, ‘points’, ‘++’, ‘matrix’.missing : A string which denotes action upon empty clusters. Possible values are ‘warn’, ‘raise’.check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking. input_array : The array of data points to be normalized. k : No.of.clusters (centroids) iterations : No.of.iterations to perform kmeans so that distortion is minimized. If k is specified it is ignored. threshold : An integer value which if becomes less than or equal to change in distortion in last iteration, the algorithm terminates. minit : A string which denotes the initialization method of the centroids. Possible values are ‘random’, ‘points’, ‘++’, ‘matrix’. missing : A string which denotes action upon empty clusters. Possible values are ‘warn’, ‘raise’. check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking. This method maps the observations to appropriate centroids which are calculated by the kmeans() method. It requires the input matrices to be normalized. It takes the normalized inputs and generated code-book as input. It returns the index in the code-book to which the observation corresponds to and the distance between the observation and its code (centroid). Step 1: Import the required modules. Python3 # import modulesimport numpy as npfrom scipy.cluster.vq import whiten, kmeans, vq, kmeans2 Step 2: Import/generate data. Normalize the data. Python3 # observationsdata = np.array([[1, 3, 4, 5, 2], [2, 3, 1, 6, 3], [1, 5, 2, 3, 1], [3, 4, 9, 2, 1]]) # normalizedata = whiten(data) print(data) Output Step 3: Calculate the centroids and generate the code book for mapping using kmeans() method Python3 # code book generationcentroids, mean_value = kmeans(data, 3) print("Code book :\n", centroids, "\n")print("Mean of Euclidean distances :", mean_value.round(4)) Output Step 4: Map the centroids calculated in the previous step to the clusters. Python3 # mapping the centroidsclusters, distances = vq(data, centroids) print("Cluster index :", clusters, "\n")print("Distance from the centroids :", distances) Output Consider the same example with kmeans2(). This does not require the additional step of calling vq() method. Repeat steps 1 and 2, then use the following snippet. Python3 # assign centroids and clusterscentroids, clusters = kmeans2(data, 3, minit='random') print("Centroids :\n", centroids, "\n")print("Clusters :", clusters) Output Example 2: K-Means clustering of Diabetes dataset The dataset contains the following attributes based on which a patient is either placed in diabetic cluster or non-diabetic cluster. Pregnancies Glucose Blood Pressure Skin Thickness Insulin BMI Diabetes Pedigree Function Age Python3 # import modulesimport matplotlib.pyplot as pltimport numpy as npfrom scipy.cluster.vq import whiten, kmeans, vq # load the datasetdataset = np.loadtxt(r"{your-path}\diabetes-train.csv", delimiter=",") # excluding the outcome columndataset = dataset[:, 0:8] print("Data :\n", dataset, "\n") # normalizedataset = whiten(dataset) # generate code bookcentroids, mean_dist = kmeans(dataset, 2)print("Code-book :\n", centroids, "\n") clusters, dist = vq(dataset, centroids)print("Clusters :\n", clusters, "\n") # count non-diabetic patientsnon_diab = list(clusters).count(0) # count diabetic patientsdiab = list(clusters).count(1) # depict illustrationx_axis = []x_axis.append(diab)x_axis.append(non_diab) colors = ['green', 'orange'] print("No.of.diabetic patients : " + str(x_axis[0]) + "\nNo.of.non-diabetic patients : " + str(x_axis[1])) y = ['diabetic', 'non-diabetic'] plt.pie(x_axis, labels=y, colors=colors, shadow='true')plt.show() Output Picked Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23901, "s": 23873, "text": "\n15 Mar, 2021" }, { "code": null, "e": 23934, "s": 23901, "text": "Prerequisite: K-Means clustering" }, { "code": null, "e": 24152, "s": 23934, "text": "The K-Means clustering is one of the partitioning approaches and each cluster will be represented with a calculated centroid. All the data points in the cluster will have a minimum distance from the computed centroid." }, { "code": null, "e": 24320, "s": 24152, "text": "Scipy is an open-source library that can be used for complex computations. It is mostly used with NumPy arrays. It can be installed by running the command given below." }, { "code": null, "e": 24338, "s": 24320, "text": "pip install scipy" }, { "code": null, "e": 24453, "s": 24338, "text": "It has dedicated packages for the process of clustering. There are two modules that can offer clustering methods. " }, { "code": null, "e": 24481, "s": 24453, "text": "cluster.vqcluster.hierarchy" }, { "code": null, "e": 24492, "s": 24481, "text": "cluster.vq" }, { "code": null, "e": 24510, "s": 24492, "text": "cluster.hierarchy" }, { "code": null, "e": 24883, "s": 24510, "text": "This module gives the feature of vector quantization to use with the K-Means clustering method. The quantization of vectors plays a major role in reducing the distortion and improving the accuracy. Mostly the distortion here is calculated using the Euclidean distance between the centroid and each vector. Based on this the vector od data points are assigned to a cluster." }, { "code": null, "e": 25242, "s": 24883, "text": "This module provides methods for general hierarchical clustering and its types such as agglomerative clustering. It has various routines that can be used for applying statistical methods on the hierarchies, visualizing the clusters, plotting the clusters, checking linkages in the clusters, and also checking whether two different hierarchies are equivalent." }, { "code": null, "e": 25327, "s": 25242, "text": "In this article, cluster.vq module will be used to carry out the K-Means clustering." }, { "code": null, "e": 25410, "s": 25327, "text": "The K-means clustering can be done on given data by executing the following steps." }, { "code": null, "e": 25620, "s": 25410, "text": "Normalize the data points.Compute the centroids (referred to as code and the 2D array of centroids is referred to as code book).Form clusters and assign the data points (referred to as mapping from code book)." }, { "code": null, "e": 25647, "s": 25620, "text": "Normalize the data points." }, { "code": null, "e": 25750, "s": 25647, "text": "Compute the centroids (referred to as code and the 2D array of centroids is referred to as code book)." }, { "code": null, "e": 25832, "s": 25750, "text": "Form clusters and assign the data points (referred to as mapping from code book)." }, { "code": null, "e": 26282, "s": 25832, "text": "This method is used to normalize the data points. Normalization is very important when the attributes considered are of different units. For example, if the length is given in meters and breadth is given in inches, it may produce an unequal variance for the vectors. It is always preferred to have unit variance while performing K-Means clustering to get accurate clusters. Thus, the data array has to pass to whiten() method before any other steps." }, { "code": null, "e": 26327, "s": 26282, "text": "cluster.vq.whiten(input_array, check_finite)" }, { "code": null, "e": 26339, "s": 26327, "text": "Parameters:" }, { "code": null, "e": 26523, "s": 26339, "text": "input_array : The array of data points to be normalized.check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking." }, { "code": null, "e": 26580, "s": 26523, "text": "input_array : The array of data points to be normalized." }, { "code": null, "e": 26708, "s": 26580, "text": "check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking." }, { "code": null, "e": 26771, "s": 26708, "text": "This vq module has two methods namely kmeans() and kmeans2(). " }, { "code": null, "e": 27064, "s": 26771, "text": "The kmeans() method uses a threshold value which on becoming less than or equal to the change in distortion in the last iteration, the algorithm terminates. This method returns the centroids calculated and the mean value of the Euclidean distances between the observations and the centroids. " }, { "code": null, "e": 27135, "s": 27064, "text": "cluster.vq.kmeans(input_array, k, iterations, threshold, check_finite)" }, { "code": null, "e": 27147, "s": 27135, "text": "Parameters:" }, { "code": null, "e": 27607, "s": 27147, "text": "input_array : The array of data points to be normalized.k : No.of.clusters (centroids)iterations : No.of.iterations to perform kmeans so that distortion is minimized. If k is specified it is ignored.threshold : An integer value which if becomes less than or equal to change in distortion in last iteration, the algorithm terminates.check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking." }, { "code": null, "e": 27664, "s": 27607, "text": "input_array : The array of data points to be normalized." }, { "code": null, "e": 27695, "s": 27664, "text": "k : No.of.clusters (centroids)" }, { "code": null, "e": 27809, "s": 27695, "text": "iterations : No.of.iterations to perform kmeans so that distortion is minimized. If k is specified it is ignored." }, { "code": null, "e": 27943, "s": 27809, "text": "threshold : An integer value which if becomes less than or equal to change in distortion in last iteration, the algorithm terminates." }, { "code": null, "e": 28071, "s": 27943, "text": "check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking." }, { "code": null, "e": 28411, "s": 28071, "text": "The kmeans2() method does not use the threshold value to check for convergence. It has more parameters that decide the method of initialization of centroids, a method to handle empty clusters, and validating whether the input matrices contain only finite numbers. This method returns centroids and the clusters to which the vector belongs." }, { "code": null, "e": 28499, "s": 28411, "text": "cluster.vq.kmeans2(input_array, k, iterations, threshold, minit, missing, check_finite)" }, { "code": null, "e": 28511, "s": 28499, "text": "Parameters:" }, { "code": null, "e": 29198, "s": 28511, "text": "input_array : The array of data points to be normalized.k : No.of.clusters (centroids)iterations : No.of.iterations to perform kmeans so that distortion is minimized. If k is specified it is ignored.threshold : An integer value which if becomes less than or equal to change in distortion in last iteration, the algorithm terminates.minit : A string which denotes the initialization method of the centroids. Possible values are ‘random’, ‘points’, ‘++’, ‘matrix’.missing : A string which denotes action upon empty clusters. Possible values are ‘warn’, ‘raise’.check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking." }, { "code": null, "e": 29255, "s": 29198, "text": "input_array : The array of data points to be normalized." }, { "code": null, "e": 29286, "s": 29255, "text": "k : No.of.clusters (centroids)" }, { "code": null, "e": 29400, "s": 29286, "text": "iterations : No.of.iterations to perform kmeans so that distortion is minimized. If k is specified it is ignored." }, { "code": null, "e": 29534, "s": 29400, "text": "threshold : An integer value which if becomes less than or equal to change in distortion in last iteration, the algorithm terminates." }, { "code": null, "e": 29665, "s": 29534, "text": "minit : A string which denotes the initialization method of the centroids. Possible values are ‘random’, ‘points’, ‘++’, ‘matrix’." }, { "code": null, "e": 29763, "s": 29665, "text": "missing : A string which denotes action upon empty clusters. Possible values are ‘warn’, ‘raise’." }, { "code": null, "e": 29891, "s": 29763, "text": "check_finite : If set to true, checks whether the input matrix contains only finite numbers. If set to false, ignores checking." }, { "code": null, "e": 30253, "s": 29891, "text": "This method maps the observations to appropriate centroids which are calculated by the kmeans() method. It requires the input matrices to be normalized. It takes the normalized inputs and generated code-book as input. It returns the index in the code-book to which the observation corresponds to and the distance between the observation and its code (centroid)." }, { "code": null, "e": 30290, "s": 30253, "text": "Step 1: Import the required modules." }, { "code": null, "e": 30298, "s": 30290, "text": "Python3" }, { "code": "# import modulesimport numpy as npfrom scipy.cluster.vq import whiten, kmeans, vq, kmeans2", "e": 30389, "s": 30298, "text": null }, { "code": null, "e": 30439, "s": 30389, "text": "Step 2: Import/generate data. Normalize the data." }, { "code": null, "e": 30447, "s": 30439, "text": "Python3" }, { "code": "# observationsdata = np.array([[1, 3, 4, 5, 2], [2, 3, 1, 6, 3], [1, 5, 2, 3, 1], [3, 4, 9, 2, 1]]) # normalizedata = whiten(data) print(data)", "e": 30640, "s": 30447, "text": null }, { "code": null, "e": 30647, "s": 30640, "text": "Output" }, { "code": null, "e": 30740, "s": 30647, "text": "Step 3: Calculate the centroids and generate the code book for mapping using kmeans() method" }, { "code": null, "e": 30748, "s": 30740, "text": "Python3" }, { "code": "# code book generationcentroids, mean_value = kmeans(data, 3) print(\"Code book :\\n\", centroids, \"\\n\")print(\"Mean of Euclidean distances :\", mean_value.round(4))", "e": 30916, "s": 30748, "text": null }, { "code": null, "e": 30923, "s": 30916, "text": "Output" }, { "code": null, "e": 30998, "s": 30923, "text": "Step 4: Map the centroids calculated in the previous step to the clusters." }, { "code": null, "e": 31006, "s": 30998, "text": "Python3" }, { "code": "# mapping the centroidsclusters, distances = vq(data, centroids) print(\"Cluster index :\", clusters, \"\\n\")print(\"Distance from the centroids :\", distances)", "e": 31162, "s": 31006, "text": null }, { "code": null, "e": 31169, "s": 31162, "text": "Output" }, { "code": null, "e": 31331, "s": 31169, "text": "Consider the same example with kmeans2(). This does not require the additional step of calling vq() method. Repeat steps 1 and 2, then use the following snippet." }, { "code": null, "e": 31339, "s": 31331, "text": "Python3" }, { "code": "# assign centroids and clusterscentroids, clusters = kmeans2(data, 3, minit='random') print(\"Centroids :\\n\", centroids, \"\\n\")print(\"Clusters :\", clusters)", "e": 31525, "s": 31339, "text": null }, { "code": null, "e": 31532, "s": 31525, "text": "Output" }, { "code": null, "e": 31582, "s": 31532, "text": "Example 2: K-Means clustering of Diabetes dataset" }, { "code": null, "e": 31715, "s": 31582, "text": "The dataset contains the following attributes based on which a patient is either placed in diabetic cluster or non-diabetic cluster." }, { "code": null, "e": 31727, "s": 31715, "text": "Pregnancies" }, { "code": null, "e": 31735, "s": 31727, "text": "Glucose" }, { "code": null, "e": 31750, "s": 31735, "text": "Blood Pressure" }, { "code": null, "e": 31765, "s": 31750, "text": "Skin Thickness" }, { "code": null, "e": 31773, "s": 31765, "text": "Insulin" }, { "code": null, "e": 31777, "s": 31773, "text": "BMI" }, { "code": null, "e": 31804, "s": 31777, "text": "Diabetes Pedigree Function" }, { "code": null, "e": 31808, "s": 31804, "text": "Age" }, { "code": null, "e": 31816, "s": 31808, "text": "Python3" }, { "code": "# import modulesimport matplotlib.pyplot as pltimport numpy as npfrom scipy.cluster.vq import whiten, kmeans, vq # load the datasetdataset = np.loadtxt(r\"{your-path}\\diabetes-train.csv\", delimiter=\",\") # excluding the outcome columndataset = dataset[:, 0:8] print(\"Data :\\n\", dataset, \"\\n\") # normalizedataset = whiten(dataset) # generate code bookcentroids, mean_dist = kmeans(dataset, 2)print(\"Code-book :\\n\", centroids, \"\\n\") clusters, dist = vq(dataset, centroids)print(\"Clusters :\\n\", clusters, \"\\n\") # count non-diabetic patientsnon_diab = list(clusters).count(0) # count diabetic patientsdiab = list(clusters).count(1) # depict illustrationx_axis = []x_axis.append(diab)x_axis.append(non_diab) colors = ['green', 'orange'] print(\"No.of.diabetic patients : \" + str(x_axis[0]) + \"\\nNo.of.non-diabetic patients : \" + str(x_axis[1])) y = ['diabetic', 'non-diabetic'] plt.pie(x_axis, labels=y, colors=colors, shadow='true')plt.show()", "e": 32790, "s": 31816, "text": null }, { "code": null, "e": 32797, "s": 32790, "text": "Output" }, { "code": null, "e": 32804, "s": 32797, "text": "Picked" }, { "code": null, "e": 32817, "s": 32804, "text": "Python-scipy" }, { "code": null, "e": 32824, "s": 32817, "text": "Python" }, { "code": null, "e": 32922, "s": 32824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32931, "s": 32922, "text": "Comments" }, { "code": null, "e": 32944, "s": 32931, "text": "Old Comments" }, { "code": null, "e": 32980, "s": 32944, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 33003, "s": 32980, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 33042, "s": 33003, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 33075, "s": 33042, "text": "Python | Convert set into a list" }, { "code": null, "e": 33124, "s": 33075, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 33165, "s": 33124, "text": "Python - Call function from another file" }, { "code": null, "e": 33181, "s": 33165, "text": "loops in python" }, { "code": null, "e": 33232, "s": 33181, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 33264, "s": 33232, "text": "Python Dictionary keys() method" } ]
Python | Combining tuples in list of tuples - GeeksforGeeks
13 May, 2019 Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with the each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let’s discuss certain ways in which this can be performed. Method #1 : Using list comprehensionWe can solve this particular problem using the list comprehension technique in which we can iterate for each tuple list and join it with other tuple attribute to join. # Python3 code to demonstrate# Combining tuples in list of tuples# Using list comprehension # initializing listtest_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')] # printing original listprint("The original list : " + str(test_list)) # Using list comprehension# Combining tuples in list of tuplesres = [ (tup1, tup2) for i, tup2 in test_list for tup1 in i ] # print resultprint("The list tuple combination : " + str(res)) The original list : [([1, 2, 3], ‘gfg’), ([5, 4, 3], ‘cs’)]The list tuple combination : [(1, ‘gfg’), (2, ‘gfg’), (3, ‘gfg’), (5, ‘cs’), (4, ‘cs’), (3, ‘cs’)] Method #2 : Using product() + list comprehensionApart from using the tuple for generation of tuples, the product function can be used to get Cartesian product of list elements with tuple element, using the iterator internally. # Python3 code to demonstrate# Combining tuples in list of tuples# Using product() + list comprehensionfrom itertools import product # initializing listtest_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')] # printing original listprint("The original list : " + str(test_list)) # Using product() + list comprehension# Combining tuples in list of tuplesres = [ele for i, j in test_list for ele in product(i, [j])] # print resultprint("The list tuple combination : " + str(res)) The original list : [([1, 2, 3], ‘gfg’), ([5, 4, 3], ‘cs’)]The list tuple combination : [(1, ‘gfg’), (2, ‘gfg’), (3, ‘gfg’), (5, ‘cs’), (4, ‘cs’), (3, ‘cs’)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Split string into list of characters Python Program for Binary Search (Recursive and Iterative)
[ { "code": null, "e": 23901, "s": 23873, "text": "\n13 May, 2019" }, { "code": null, "e": 24238, "s": 23901, "text": "Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with the each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 24442, "s": 24238, "text": "Method #1 : Using list comprehensionWe can solve this particular problem using the list comprehension technique in which we can iterate for each tuple list and join it with other tuple attribute to join." }, { "code": "# Python3 code to demonstrate# Combining tuples in list of tuples# Using list comprehension # initializing listtest_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')] # printing original listprint(\"The original list : \" + str(test_list)) # Using list comprehension# Combining tuples in list of tuplesres = [ (tup1, tup2) for i, tup2 in test_list for tup1 in i ] # print resultprint(\"The list tuple combination : \" + str(res))", "e": 24868, "s": 24442, "text": null }, { "code": null, "e": 25026, "s": 24868, "text": "The original list : [([1, 2, 3], ‘gfg’), ([5, 4, 3], ‘cs’)]The list tuple combination : [(1, ‘gfg’), (2, ‘gfg’), (3, ‘gfg’), (5, ‘cs’), (4, ‘cs’), (3, ‘cs’)]" }, { "code": null, "e": 25255, "s": 25028, "text": "Method #2 : Using product() + list comprehensionApart from using the tuple for generation of tuples, the product function can be used to get Cartesian product of list elements with tuple element, using the iterator internally." }, { "code": "# Python3 code to demonstrate# Combining tuples in list of tuples# Using product() + list comprehensionfrom itertools import product # initializing listtest_list = [([1, 2, 3], 'gfg'), ([5, 4, 3], 'cs')] # printing original listprint(\"The original list : \" + str(test_list)) # Using product() + list comprehension# Combining tuples in list of tuplesres = [ele for i, j in test_list for ele in product(i, [j])] # print resultprint(\"The list tuple combination : \" + str(res))", "e": 25733, "s": 25255, "text": null }, { "code": null, "e": 25891, "s": 25733, "text": "The original list : [([1, 2, 3], ‘gfg’), ([5, 4, 3], ‘cs’)]The list tuple combination : [(1, ‘gfg’), (2, ‘gfg’), (3, ‘gfg’), (5, ‘cs’), (4, ‘cs’), (3, ‘cs’)]" }, { "code": null, "e": 25912, "s": 25891, "text": "Python list-programs" }, { "code": null, "e": 25919, "s": 25912, "text": "Python" }, { "code": null, "e": 25935, "s": 25919, "text": "Python Programs" }, { "code": null, "e": 26033, "s": 25935, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26042, "s": 26033, "text": "Comments" }, { "code": null, "e": 26055, "s": 26042, "text": "Old Comments" }, { "code": null, "e": 26091, "s": 26055, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26114, "s": 26091, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26153, "s": 26114, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26186, "s": 26153, "text": "Python | Convert set into a list" }, { "code": null, "e": 26235, "s": 26186, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26257, "s": 26235, "text": "Defaultdict in Python" }, { "code": null, "e": 26296, "s": 26257, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26334, "s": 26296, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 26380, "s": 26334, "text": "Python | Split string into list of characters" } ]
Data Science on Windows Subsystem for Linux 2 — What, Why, and How? | by Nikki Aaron Mirova | Towards Data Science
When a budding data scientist decides to buy a new laptop for college, they inevitably come to their friends, classmates, or Stack Overflow to ask the question, “What operating system should I use for data science?” This question is as contentious among programmers as “Should I use tabs or spaces?” If you ask me, there is not a single best answer to this question. The answer for each person is based on individual preferences, experience, and external limitations. For some people, the answer may be Windows. For example, are you limited to Windows because of workplace requirements? Do you not have the budget to switch to a new Apple machine? Do you not have the time or knowledge to install a Linux OS on your PC? Are Windows and Microsoft Office suite what you are most comfortable with? Or perhaps you don’t want to have to replace all the Windows software for which you have spent a small fortune purchasing licenses. Windows can handle data science, especially if you aren’t going much further than installing Python, Anaconda, and R with some common packages. If you are in your first year of college, this setup will work beautifully. But, the more complex your work becomes, the more drawbacks you will encounter with Windows. You may run into issues with speed, compatibility is woefully lacking, debugging is much harder than it should be, and almost every Stack Overflow post gives you instructions that only work in Unix/Linux. To get past the limitations of programming in Windows, you could dual-boot Linux and Windows on the same machine and switch between the partitions as your tasks require. But you may not be comfortable with this process, and oh what a pain it is to log in and out every time you switch tasks. So next you may consider spinning up virtual machine environments in Windows. These are often difficult to set up, difficult to reproduce, and full of compatibility issues despite their supposed isolation from the Windows OS. If you want to vastly improve your development experience on Windows, I suggest you forego the aforementioned options and instead consider Windows Subsystem for Linux (WSL). Not only will you get better performance with less issues, but you will be training yourself to program in an environment that is very close to what you would use on a full Linux or Apple OS. Switching to one of these systems later, or transferring your code to one of these systems should be easy. However, this option might be too much for you if you are just starting out and are completely new to using the command line. WSL 2 currently does not support GUI apps in Linux. (Though Microsoft plans to support them in the future.) So while you can use Anaconda 100% via the command line, you will miss out on helpful GUIs like Anaconda Navigator. Eventually you will want to graduate to working without the GUI — if not for the speed, then for the incredible feeling of having family and friends believe you are a super hacker. But that transition will come with time, and there is nothing wrong with learning to walk before you run. Content Unavailable Sorry, this content is not available in your location. The original release of WSL was a layer on top of Windows that let you run Linux executables on Windows 10. That was a good start, but still nowhere close to offering full Linux/GNU support. The real magic came with Microsoft’s 2019 release of WSL 2. This new architecture offers its own Linux kernel instead of a compatibility layer. So you get faster performance, full compatibility for system calls, the ability to run a lot more apps (like Docker) on the Linux kernel, and updates will be released without waiting for Microsoft to “translate” the changes for WSL. Basically, with WSL 2 you will be able to work smoothly in a fully functional Linux environment while on Windows! There are also features that blend the two systems quite elegantly. You can have the Linux environment open Windows programs like your browser or IDE. And you can browse files from both the Windows and WSL filesystems using the normal file explorer or the command line. On some IDEs, you can use the Linux kernel to run and debug your code, even though the IDE software is installed in Windows. Follow Microsoft’s instructions on how to install WSL 2. You must be on Windows 10, and you must be updated to version 2004, build 19041 or higher. Getting this update can be a little tricky. For some users (like myself), checking for updates and installing the latest available still did not get me to this required version. If this happens, you can manually install the required build by using the Windows Update Assistant as directed. You will need to choose a Linux distribution to install. This can be changed later, and you can even install multiple distributions if you like. If you are not familiar or have no preference, choose Ubuntu. Be sure to note the username and password you set up for your distribution. Your Linux “home” folder will be located at “\\wsl$\Ubuntu\home\{username}” , and your password will be used for commands requiring admin privileges. Currently, you pretty much have to do everything through the command line terminal, file explorer, and apps that run in the browser (like Jupyter Notebook). Though Microsoft has announced it plans to add GUI app support as well as GPU hardware acceleration. There are many flavors of terminal applications and terminal shells. I recommend starting with Windows Terminal. This recently released Microsoft application is snappy to use and allows you to customize things like theming, key bindings, and override default behaviors. The best part though, is that you can open tabbed terminals for different environments inside a single window. So you can have separate profiles for easily launching Powershell, Ubuntu, Bash, Anaconda, or a host of other supported environments. Use the instructions on Microsoft’s GitHub to install Windows Terminal, then click the down caret and Settings to edit your settings.json file. You can read the documentation to get familiar with the settings options, or check out a gist of my settings file for example. Profiles for your WSL distributions and Powershell are included be default. To customize these profiles and to add more, edit the “profiles” object in settings.json. The “defaults” object applies default settings to all profiles. “profiles”: { “defaults”: { “acrylicOpacity”: 0.85000002384185791, “background”: “#012456”, “closeOnExit”: false, “colorScheme”: “Solarized Dark”, “cursorColor”: “#FFFFFF”, “cursorShape”: “bar”, “fontFace”: “Fira Code”, “fontSize”: 12, “historySize”: 9001, “padding”: “0, 0, 0, 0”, “snapOnInput”: true, “useAcrylic”: true, “startingDirectory”: “%USERPROFILE%” }} Next you will want to add profile settings for specific terminal applications in the “list” array. Each item in the list will need a unique guid identifier surrounded by braces. Generate a new guid by typing new-guid in Powershell or uuidgen in Ubuntu. You can then customize the name and icon of the tab, which executable is used to open the command line, and what directory to start in. Be sure not to leave any hanging commas at the end of lists, as this is invalid json syntax and will throw an error. “profiles”: { “defaults”: { ... }, "list: [ { “guid”: “{2c4de342–38b7–51cf-b940–2309a097f518}”, “name”: “Ubuntu”, “source”: “Windows.Terminal.Wsl”, “startingDirectory”: “//wsl$/Ubuntu/home/nadev” }, { “guid”: “{61c54bbd-c2c6–5271–96e7–009a87ff44bf}”, “name”: “PowerShell”, “tabTitle”: “PowerShell”, “commandline”: “powershell.exe” } ]} Choose the profile that will open by default in new tabs by setting its guid and braces as “defaultProfile” at the top level of settings.json. My default is Ubuntu. “defaultProfile”: “{2c4de342–38b7–51cf-b940–2309a097f518}” Now you are all set up and ready to start using Windows Subsystem for Linux! Check out some common terminal commands to learn how to navigate directories from the command line. I will give you a rundown on the applications I have installed in WSL for Data Science. Just like terminal applications, there are a lot of code editors to choose from. Everyone has their own preferences, and whatever your preference is after trying a few is just dandy! Visual Studio Code is very popular and features an extension specifically designed to work with WSL2. I had an easy time getting Jupyter Notebooks, Python code, and the debugger working with WSL2. If you want to try something a little more fancy for Python coding, check out PyCharm from the JetBrains suite of products. Unlike VS Code, you can only use PyCharm with a paid license or apply for a free student license. PyCharm allows you to use WSL Python as your interpreter, and now supports Git in your WSL2 filesystem. This system may need more work to be fully compatible with WSL2. For example, I could not get the debugger or the Jupyter tool window working. Git is the standard for keeping track of code changes, versioning, and backing up our files on repositories. Windows and each Linux distribution you install have different filesystems, and you will need to install Git on each one. For your Windows filesystem, install Git for Windows with the recommended options selected. This install also includes the Git Bash terminal application. I like to use Git Bash instead of Powershell because command syntax is just like bash in Linux, so you are using the same kinds of commands everywhere. Powershell is better suited for users who write automation scripts, and work with Windows servers. Since we will want to use this new terminal application regularly, add it as a new profile in your Windows Terminal settings. “profiles”: { “defaults”: { ... }, "list: [ ..., { “guid”: “{8d04ce37-c00f-43ac-ba47–992cb1393215}”, “name”: “Git Bash”, “tabTitle”: “Bash”, // the -i -l commands below are added to load .bashrc “commandline”: “\”%PROGRAMFILES%\\git\\usr\\bin\\bash.exe\” -i -l”, “icon”: “%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for- windows.ico” } ]} On Linux distributions, git is usually already included, but you can run sudo apt-get install git in the Ubuntu profile of Windows Terminal to either install it or update to the latest version. If you do not have an account, go create one now. You might want to go into your GitHub account Settings > Emails and hide your personal email address. In this case, you will be given a generated email address to use when configuring Git. This allows you to commit to GitHub without revealing your personal email address to the public. The next time you try to push to GitHub, you will be asked for your username and password, and these credentials will be stored for future use. Once you have a GitHub account created. Run the commands below in Ubuntu and Git Bash to configure your name and email address in Git. The config will be stored in a file called .gitconfig located in your home directory. git config --global user.name "Your Name"git config --global user.email "[email protected]"git config --global credential.helper store I will also mention a little more here about Bash. In Windows and in your distributions, there will be a few files that are executed when Bash opens. These are .bashrc, .bash_profile, and optionally .profile. If you are not seeing them in File Explorer, you may need to set hidden files as visible. To view them in command line, enter ls ls -a (the -a option shows all files, including hidden ones). I will leave it to you to research the purpose of these files, but in general the first two will be auto-generated and you will edit personal aliases and environment variables inside of .profile. After changing any of these files, you will need to run source ~/.bashrc to load the changes. If you plan to work in Python and R for Data Science, conda makes managing environments and packages much easier. You can either install Miniconda to get just what you need to start, or Anaconda which is fully preloaded with tons of packages. Again though, the Anaconda Navigator GUI is not going to work if installed in WSL, only in Windows. I installed Miniconda for Python 3 in Ubuntu with the following commands, but some people install it in Windows as well. (If you know why people are installing in both environments instead of just WSL, please let me know in the comments.) # To install Anaconda for Python 3wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.shsh ./Anaconda3-2020.02-Linux-x86_64.sh# To install Miniconda for Python 3 wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exesh ./Miniconda3-latest-Windows-x86_64.exe After you complete the installation, close and re-open your Ubuntu terminal and type which python and which conda. You should get one of the following sets of paths depending on which package you installed. # Path to Python executable in Anaconda/home/{username}/anaconda3/bin/python/home/{username}/anaconda3/bin/conda# Path to Python executable in Miniconda/home/{username}/miniconda3/bin/python/home/{username}/miniconda3/bin/conda# Then update all installed packagesconda update --all If not, open .profile and add one the following export lines as appropriate, enter source ~/.bashrc, and try again. # Add Anaconda Python to PATHexport PATH=/home/{username}/anaconda3/bin:$PATH# Add Miniconda Python to PATHexport PATH=/home/{username}/miniconda3/bin:$PATH Now you are ready to use conda to create environments. It is best to keep packages out of your base environment and create a new environment for different types of projects. This prevents compatibility issues. See the documentation for more on managing environments. # To create an environment called 'pandasenv' with the pandas package installed.conda create --name pandasenv pandas To present your work to others, you will likely start with using Jupyter Notebook. This tool lets you run python code inside your conda environments, annotate the code with markdown, and display graphs and other visuals. Anaconda comes with Jupyter Notebook pre-included. On Miniconda, open your Ububtu terminal (your base conda environment will be automatically activated), and type the following to install. conda install jupyter Similar to the way we checked we are using the correct python executable, we want to also check jupyter using which jupyter. # Path to Jupyter executable in Anaconda/home/{username}/anaconda3/bin/jupyter# Path to Jupyter executable in Miniconda/home/{username}/miniconda3/bin/jupyter For me, this path was incorrect and it took some sleuthing to find the issue. During installation of Miniconda, its bin directory was added to $PATH inside of .bashrc. This is great, as it tells the OS to search that directory for executables when a command is run. But my local bin directory was also being added in .profile. This was leading to $HOME/.local/bin being checked for executables before $HOME/miniconda3/bin. To remedy this, I moved the Miniconda export line to be executed last by making part of my file at /home/{username}/.profile look like the following. # set PATH so it includes user's private bin if it existsif [ -d "$HOME/.local/bin" ] ; then PATH="$HOME/.local/bin:$PATH"fi# set PATH so it includes miniconda's binif [ -d "$HOME/miniconda3/bin" ] ; then PATH="$HOME/miniconda3/bin:$PATH"fi When launching Jupyter Notebook using the command jupyter notebook you will notice that a warning message pops up and either your browser does not launch or it tries to launch a file that does not render Jupyter Notebook. To fix this we need to do a few things. First add a BROWSER variable to you path by adding the following to .profile. # Path to your browser executableexport BROWSER='/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe' Next, tell Jupyter Notebooks not to try to launch using the redirect file that is not working in WSL2 by generating a jupyter config file and uncommenting the line listed below. # Generate a config file at /home/{username}/.jupyter/jupyter_notebook_config.pyjupyter lab --generate-config# Uncomment the linec.NotebookApp.use_redirect_file = False And that’s it! Your Jupyter notebook should now launch appropriately in the browser at http://localhost:8888/. I hope this setup serves you as well as it has me. If you have any issues or tips for improving this environment, leave a comment below.
[ { "code": null, "e": 639, "s": 171, "text": "When a budding data scientist decides to buy a new laptop for college, they inevitably come to their friends, classmates, or Stack Overflow to ask the question, “What operating system should I use for data science?” This question is as contentious among programmers as “Should I use tabs or spaces?” If you ask me, there is not a single best answer to this question. The answer for each person is based on individual preferences, experience, and external limitations." }, { "code": null, "e": 1098, "s": 639, "text": "For some people, the answer may be Windows. For example, are you limited to Windows because of workplace requirements? Do you not have the budget to switch to a new Apple machine? Do you not have the time or knowledge to install a Linux OS on your PC? Are Windows and Microsoft Office suite what you are most comfortable with? Or perhaps you don’t want to have to replace all the Windows software for which you have spent a small fortune purchasing licenses." }, { "code": null, "e": 1616, "s": 1098, "text": "Windows can handle data science, especially if you aren’t going much further than installing Python, Anaconda, and R with some common packages. If you are in your first year of college, this setup will work beautifully. But, the more complex your work becomes, the more drawbacks you will encounter with Windows. You may run into issues with speed, compatibility is woefully lacking, debugging is much harder than it should be, and almost every Stack Overflow post gives you instructions that only work in Unix/Linux." }, { "code": null, "e": 2134, "s": 1616, "text": "To get past the limitations of programming in Windows, you could dual-boot Linux and Windows on the same machine and switch between the partitions as your tasks require. But you may not be comfortable with this process, and oh what a pain it is to log in and out every time you switch tasks. So next you may consider spinning up virtual machine environments in Windows. These are often difficult to set up, difficult to reproduce, and full of compatibility issues despite their supposed isolation from the Windows OS." }, { "code": null, "e": 2607, "s": 2134, "text": "If you want to vastly improve your development experience on Windows, I suggest you forego the aforementioned options and instead consider Windows Subsystem for Linux (WSL). Not only will you get better performance with less issues, but you will be training yourself to program in an environment that is very close to what you would use on a full Linux or Apple OS. Switching to one of these systems later, or transferring your code to one of these systems should be easy." }, { "code": null, "e": 3244, "s": 2607, "text": "However, this option might be too much for you if you are just starting out and are completely new to using the command line. WSL 2 currently does not support GUI apps in Linux. (Though Microsoft plans to support them in the future.) So while you can use Anaconda 100% via the command line, you will miss out on helpful GUIs like Anaconda Navigator. Eventually you will want to graduate to working without the GUI — if not for the speed, then for the incredible feeling of having family and friends believe you are a super hacker. But that transition will come with time, and there is nothing wrong with learning to walk before you run." }, { "code": null, "e": 3264, "s": 3244, "text": "Content Unavailable" }, { "code": null, "e": 3319, "s": 3264, "text": "Sorry, this content is not available in your location." }, { "code": null, "e": 3887, "s": 3319, "text": "The original release of WSL was a layer on top of Windows that let you run Linux executables on Windows 10. That was a good start, but still nowhere close to offering full Linux/GNU support. The real magic came with Microsoft’s 2019 release of WSL 2. This new architecture offers its own Linux kernel instead of a compatibility layer. So you get faster performance, full compatibility for system calls, the ability to run a lot more apps (like Docker) on the Linux kernel, and updates will be released without waiting for Microsoft to “translate” the changes for WSL." }, { "code": null, "e": 4396, "s": 3887, "text": "Basically, with WSL 2 you will be able to work smoothly in a fully functional Linux environment while on Windows! There are also features that blend the two systems quite elegantly. You can have the Linux environment open Windows programs like your browser or IDE. And you can browse files from both the Windows and WSL filesystems using the normal file explorer or the command line. On some IDEs, you can use the Linux kernel to run and debug your code, even though the IDE software is installed in Windows." }, { "code": null, "e": 4834, "s": 4396, "text": "Follow Microsoft’s instructions on how to install WSL 2. You must be on Windows 10, and you must be updated to version 2004, build 19041 or higher. Getting this update can be a little tricky. For some users (like myself), checking for updates and installing the latest available still did not get me to this required version. If this happens, you can manually install the required build by using the Windows Update Assistant as directed." }, { "code": null, "e": 5267, "s": 4834, "text": "You will need to choose a Linux distribution to install. This can be changed later, and you can even install multiple distributions if you like. If you are not familiar or have no preference, choose Ubuntu. Be sure to note the username and password you set up for your distribution. Your Linux “home” folder will be located at “\\\\wsl$\\Ubuntu\\home\\{username}” , and your password will be used for commands requiring admin privileges." }, { "code": null, "e": 5525, "s": 5267, "text": "Currently, you pretty much have to do everything through the command line terminal, file explorer, and apps that run in the browser (like Jupyter Notebook). Though Microsoft has announced it plans to add GUI app support as well as GPU hardware acceleration." }, { "code": null, "e": 6040, "s": 5525, "text": "There are many flavors of terminal applications and terminal shells. I recommend starting with Windows Terminal. This recently released Microsoft application is snappy to use and allows you to customize things like theming, key bindings, and override default behaviors. The best part though, is that you can open tabbed terminals for different environments inside a single window. So you can have separate profiles for easily launching Powershell, Ubuntu, Bash, Anaconda, or a host of other supported environments." }, { "code": null, "e": 6311, "s": 6040, "text": "Use the instructions on Microsoft’s GitHub to install Windows Terminal, then click the down caret and Settings to edit your settings.json file. You can read the documentation to get familiar with the settings options, or check out a gist of my settings file for example." }, { "code": null, "e": 6541, "s": 6311, "text": "Profiles for your WSL distributions and Powershell are included be default. To customize these profiles and to add more, edit the “profiles” object in settings.json. The “defaults” object applies default settings to all profiles." }, { "code": null, "e": 6944, "s": 6541, "text": "“profiles”: { “defaults”: { “acrylicOpacity”: 0.85000002384185791, “background”: “#012456”, “closeOnExit”: false, “colorScheme”: “Solarized Dark”, “cursorColor”: “#FFFFFF”, “cursorShape”: “bar”, “fontFace”: “Fira Code”, “fontSize”: 12, “historySize”: 9001, “padding”: “0, 0, 0, 0”, “snapOnInput”: true, “useAcrylic”: true, “startingDirectory”: “%USERPROFILE%” }}" }, { "code": null, "e": 7450, "s": 6944, "text": "Next you will want to add profile settings for specific terminal applications in the “list” array. Each item in the list will need a unique guid identifier surrounded by braces. Generate a new guid by typing new-guid in Powershell or uuidgen in Ubuntu. You can then customize the name and icon of the tab, which executable is used to open the command line, and what directory to start in. Be sure not to leave any hanging commas at the end of lists, as this is invalid json syntax and will throw an error." }, { "code": null, "e": 7845, "s": 7450, "text": "“profiles”: { “defaults”: { ... }, \"list: [ { “guid”: “{2c4de342–38b7–51cf-b940–2309a097f518}”, “name”: “Ubuntu”, “source”: “Windows.Terminal.Wsl”, “startingDirectory”: “//wsl$/Ubuntu/home/nadev” }, { “guid”: “{61c54bbd-c2c6–5271–96e7–009a87ff44bf}”, “name”: “PowerShell”, “tabTitle”: “PowerShell”, “commandline”: “powershell.exe” } ]}" }, { "code": null, "e": 8010, "s": 7845, "text": "Choose the profile that will open by default in new tabs by setting its guid and braces as “defaultProfile” at the top level of settings.json. My default is Ubuntu." }, { "code": null, "e": 8069, "s": 8010, "text": "“defaultProfile”: “{2c4de342–38b7–51cf-b940–2309a097f518}”" }, { "code": null, "e": 8146, "s": 8069, "text": "Now you are all set up and ready to start using Windows Subsystem for Linux!" }, { "code": null, "e": 8246, "s": 8146, "text": "Check out some common terminal commands to learn how to navigate directories from the command line." }, { "code": null, "e": 8334, "s": 8246, "text": "I will give you a rundown on the applications I have installed in WSL for Data Science." }, { "code": null, "e": 8714, "s": 8334, "text": "Just like terminal applications, there are a lot of code editors to choose from. Everyone has their own preferences, and whatever your preference is after trying a few is just dandy! Visual Studio Code is very popular and features an extension specifically designed to work with WSL2. I had an easy time getting Jupyter Notebooks, Python code, and the debugger working with WSL2." }, { "code": null, "e": 9183, "s": 8714, "text": "If you want to try something a little more fancy for Python coding, check out PyCharm from the JetBrains suite of products. Unlike VS Code, you can only use PyCharm with a paid license or apply for a free student license. PyCharm allows you to use WSL Python as your interpreter, and now supports Git in your WSL2 filesystem. This system may need more work to be fully compatible with WSL2. For example, I could not get the debugger or the Jupyter tool window working." }, { "code": null, "e": 9414, "s": 9183, "text": "Git is the standard for keeping track of code changes, versioning, and backing up our files on repositories. Windows and each Linux distribution you install have different filesystems, and you will need to install Git on each one." }, { "code": null, "e": 9945, "s": 9414, "text": "For your Windows filesystem, install Git for Windows with the recommended options selected. This install also includes the Git Bash terminal application. I like to use Git Bash instead of Powershell because command syntax is just like bash in Linux, so you are using the same kinds of commands everywhere. Powershell is better suited for users who write automation scripts, and work with Windows servers. Since we will want to use this new terminal application regularly, add it as a new profile in your Windows Terminal settings." }, { "code": null, "e": 10336, "s": 9945, "text": "“profiles”: { “defaults”: { ... }, \"list: [ ..., { “guid”: “{8d04ce37-c00f-43ac-ba47–992cb1393215}”, “name”: “Git Bash”, “tabTitle”: “Bash”, // the -i -l commands below are added to load .bashrc “commandline”: “\\”%PROGRAMFILES%\\\\git\\\\usr\\\\bin\\\\bash.exe\\” -i -l”, “icon”: “%PROGRAMFILES%\\\\Git\\\\mingw64\\\\share\\\\git\\\\git-for- windows.ico” } ]}" }, { "code": null, "e": 10530, "s": 10336, "text": "On Linux distributions, git is usually already included, but you can run sudo apt-get install git in the Ubuntu profile of Windows Terminal to either install it or update to the latest version." }, { "code": null, "e": 11010, "s": 10530, "text": "If you do not have an account, go create one now. You might want to go into your GitHub account Settings > Emails and hide your personal email address. In this case, you will be given a generated email address to use when configuring Git. This allows you to commit to GitHub without revealing your personal email address to the public. The next time you try to push to GitHub, you will be asked for your username and password, and these credentials will be stored for future use." }, { "code": null, "e": 11231, "s": 11010, "text": "Once you have a GitHub account created. Run the commands below in Ubuntu and Git Bash to configure your name and email address in Git. The config will be stored in a file called .gitconfig located in your home directory." }, { "code": null, "e": 11370, "s": 11231, "text": "git config --global user.name \"Your Name\"git config --global user.email \"[email protected]\"git config --global credential.helper store" }, { "code": null, "e": 12060, "s": 11370, "text": "I will also mention a little more here about Bash. In Windows and in your distributions, there will be a few files that are executed when Bash opens. These are .bashrc, .bash_profile, and optionally .profile. If you are not seeing them in File Explorer, you may need to set hidden files as visible. To view them in command line, enter ls ls -a (the -a option shows all files, including hidden ones). I will leave it to you to research the purpose of these files, but in general the first two will be auto-generated and you will edit personal aliases and environment variables inside of .profile. After changing any of these files, you will need to run source ~/.bashrc to load the changes." }, { "code": null, "e": 12642, "s": 12060, "text": "If you plan to work in Python and R for Data Science, conda makes managing environments and packages much easier. You can either install Miniconda to get just what you need to start, or Anaconda which is fully preloaded with tons of packages. Again though, the Anaconda Navigator GUI is not going to work if installed in WSL, only in Windows. I installed Miniconda for Python 3 in Ubuntu with the following commands, but some people install it in Windows as well. (If you know why people are installing in both environments instead of just WSL, please let me know in the comments.)" }, { "code": null, "e": 12941, "s": 12642, "text": "# To install Anaconda for Python 3wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.shsh ./Anaconda3-2020.02-Linux-x86_64.sh# To install Miniconda for Python 3 wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exesh ./Miniconda3-latest-Windows-x86_64.exe" }, { "code": null, "e": 13148, "s": 12941, "text": "After you complete the installation, close and re-open your Ubuntu terminal and type which python and which conda. You should get one of the following sets of paths depending on which package you installed." }, { "code": null, "e": 13430, "s": 13148, "text": "# Path to Python executable in Anaconda/home/{username}/anaconda3/bin/python/home/{username}/anaconda3/bin/conda# Path to Python executable in Miniconda/home/{username}/miniconda3/bin/python/home/{username}/miniconda3/bin/conda# Then update all installed packagesconda update --all" }, { "code": null, "e": 13546, "s": 13430, "text": "If not, open .profile and add one the following export lines as appropriate, enter source ~/.bashrc, and try again." }, { "code": null, "e": 13703, "s": 13546, "text": "# Add Anaconda Python to PATHexport PATH=/home/{username}/anaconda3/bin:$PATH# Add Miniconda Python to PATHexport PATH=/home/{username}/miniconda3/bin:$PATH" }, { "code": null, "e": 13970, "s": 13703, "text": "Now you are ready to use conda to create environments. It is best to keep packages out of your base environment and create a new environment for different types of projects. This prevents compatibility issues. See the documentation for more on managing environments." }, { "code": null, "e": 14087, "s": 13970, "text": "# To create an environment called 'pandasenv' with the pandas package installed.conda create --name pandasenv pandas" }, { "code": null, "e": 14497, "s": 14087, "text": "To present your work to others, you will likely start with using Jupyter Notebook. This tool lets you run python code inside your conda environments, annotate the code with markdown, and display graphs and other visuals. Anaconda comes with Jupyter Notebook pre-included. On Miniconda, open your Ububtu terminal (your base conda environment will be automatically activated), and type the following to install." }, { "code": null, "e": 14519, "s": 14497, "text": "conda install jupyter" }, { "code": null, "e": 14644, "s": 14519, "text": "Similar to the way we checked we are using the correct python executable, we want to also check jupyter using which jupyter." }, { "code": null, "e": 14803, "s": 14644, "text": "# Path to Jupyter executable in Anaconda/home/{username}/anaconda3/bin/jupyter# Path to Jupyter executable in Miniconda/home/{username}/miniconda3/bin/jupyter" }, { "code": null, "e": 15376, "s": 14803, "text": "For me, this path was incorrect and it took some sleuthing to find the issue. During installation of Miniconda, its bin directory was added to $PATH inside of .bashrc. This is great, as it tells the OS to search that directory for executables when a command is run. But my local bin directory was also being added in .profile. This was leading to $HOME/.local/bin being checked for executables before $HOME/miniconda3/bin. To remedy this, I moved the Miniconda export line to be executed last by making part of my file at /home/{username}/.profile look like the following." }, { "code": null, "e": 15623, "s": 15376, "text": "# set PATH so it includes user's private bin if it existsif [ -d \"$HOME/.local/bin\" ] ; then PATH=\"$HOME/.local/bin:$PATH\"fi# set PATH so it includes miniconda's binif [ -d \"$HOME/miniconda3/bin\" ] ; then PATH=\"$HOME/miniconda3/bin:$PATH\"fi" }, { "code": null, "e": 15963, "s": 15623, "text": "When launching Jupyter Notebook using the command jupyter notebook you will notice that a warning message pops up and either your browser does not launch or it tries to launch a file that does not render Jupyter Notebook. To fix this we need to do a few things. First add a BROWSER variable to you path by adding the following to .profile." }, { "code": null, "e": 16077, "s": 15963, "text": "# Path to your browser executableexport BROWSER='/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'" }, { "code": null, "e": 16255, "s": 16077, "text": "Next, tell Jupyter Notebooks not to try to launch using the redirect file that is not working in WSL2 by generating a jupyter config file and uncommenting the line listed below." }, { "code": null, "e": 16424, "s": 16255, "text": "# Generate a config file at /home/{username}/.jupyter/jupyter_notebook_config.pyjupyter lab --generate-config# Uncomment the linec.NotebookApp.use_redirect_file = False" }, { "code": null, "e": 16535, "s": 16424, "text": "And that’s it! Your Jupyter notebook should now launch appropriately in the browser at http://localhost:8888/." } ]
Tutorial: Build a lane detector. Lane detector with Hough Transform and... | by David Chuan-En Lin | Towards Data Science
Waymo’s self-driving taxi service just hit the road this month — but how do autonomous vehicles even work? The lines drawn on roads indicate to human drivers where the lanes are and act as a guiding reference to which direction to steer the vehicle accordingly and convention to how vehicle agents interact harmoniously on the road. Likewise, the ability to identify and track lanes is cardinal for developing algorithms for driverless vehicles. In this tutorial, we will learn how to build a software pipeline for tracking road lanes using computer vision techniques. We will approach this task through two different approaches. Approach 1: Hough TransformApproach 2: Spatial CNN Most lanes are designed to be relatively straightforward not only as to encourage orderliness but also to make it easier for human drivers to steer vehicles with consistent speed. Therefore, our intuitive approach may be to first detect prominent straight lines in the camera feed through edge detection and feature extraction techniques. We will be using OpenCV, an open source library of computer vision algorithms, for implementation. The following diagram is an overview of our pipeline. Before we start, here is a demo of our outcome: If you do not already have OpenCV installed, open Terminal and run: pip install opencv-python Now, clone the tutorial repository by running: git clone https://github.com/chuanenlin/lane-detector.git Next, open detector.py with your text editor. We will be writing all of the code of this section in this Python file. We will feed in our sample video for lane detection as a series of continuous frames (images) by intervals of 10 milliseconds. We can also quit the program anytime by pressing the ‘q’ key. The Canny Detector is a multi-stage algorithm optimized for fast real-time edge detection. The fundamental goal of the algorithm is to detect sharp changes in luminosity (large gradients), such as a shift from white to black, and defines them as edges, given a set of thresholds. The Canny algorithm has four main stages: A. Noise reduction As with all edge detection algorithms, noise is a crucial issue that often leads to false detection. A 5x5 Gaussian filter is applied to convolve (smooth) the image to lower the detector’s sensitivity to noise. This is done by using a kernel (in this case, a 5x5 kernel) of normally distributed numbers to run across the entire image, setting each pixel value equal to the weighted average of its neighboring pixels. B. Intensity gradient The smoothened image is then applied with a Sobel, Roberts, or Prewitt kernel (Sobel is used in OpenCV) along the x-axis and y-axis to detect whether the edges are horizontal, vertical, or diagonal. C. Non-maximum suppression Non-maximum suppression is applied to “thin” and effectively sharpen the edges. For each pixel, the value is checked if it is a local maximum in the direction of the gradient calculated previously. A is on the edge with a vertical direction. As gradient is normal to the edge direction, pixel values of B and C are compared with pixel values of A to determine if A is a local maximum. If A is local maximum, non-maximum suppression is tested for the next point. Otherwise, the pixel value of A is set to zero and A is suppressed. D. Hysteresis thresholding After non-maximum suppression, strong pixels are confirmed to be in the final map of edges. However, weak pixels should be further analyzed to determine whether it constitutes as edge or noise. Applying two pre-defined minVal and maxVal threshold values, we set that any pixel with intensity gradient higher than maxVal are edges and any pixel with intensity gradient lower than minVal are not edges and discarded. Pixels with intensity gradient in between minVal and maxVal are only considered edges if they are connected to a pixel with intensity gradient above maxVal. Edge A is above maxVal so is considered an edge. Edge B is in between maxVal and minVal but is not connected to any edge above maxVal so is discarded. Edge C is in between maxVal and minVal and is connected to edge A, an edge above maxVal, so is considered an edge. For our pipeline, our frame is first grayscaled because we only need the luminance channel for detecting edges and a 5 by 5 gaussian blur is applied to decrease noise to reduce false edges. We will handcraft a triangular mask to segment the lane area and discard the irrelevant areas in the frame to increase the effectiveness of our later stages. In the Cartesian coordinate system, we can represent a straight line as y = mx + b by plotting y against x. However, we can also represent this line as a single point in Hough space by plotting b against m. For example, a line with the equation y = 2x + 1 may be represented as (2, 1) in Hough space. Now, what if instead of a line, we had to plot a point in the Cartesian coordinate system. There are many possible lines which can pass through this point, each line with different values for parameters m and b. For example, a point at (2, 12) can be passed by y = 2x + 8, y = 3x + 6, y = 4x + 4, y = 5x + 2, y = 6x, and so on. These possible lines can be plotted in Hough space as (2, 8), (3, 6), (4, 4), (5, 2), (6, 0). Notice that this produces a line of m against b coordinates in Hough space. Whenever we see a series of points in a Cartesian coordinate system and know that these points are connected by some line, we can find the equation of that line by first plotting each point in the Cartesian coordinate system to the corresponding line in Hough space, then finding the point of intersection in Hough space. The point of intersection in Hough space represents the m and b values that pass consistently through all of the points in the series. Since our frame passed through the Canny Detector may be interpreted simply as a series of white points representing the edges in our image space, we can apply the same technique to identify which of these points are connected to the same line, and if they are connected, what its equation is so that we can plot this line on our frame. For the simplicity of explanation, we used Cartesian coordinates to correspond to Hough space. However, there is one mathematical flaw with this approach: When the line is vertical, the gradient is infinity and cannot be represented in Hough space. To solve this problem, we will use Polar coordinates instead. The process is still the same just that other than plotting m against b in Hough space, we will be plotting r against θ. For example, for the points on the Polar coordinate system with x = 8 and y = 6, x = 4 and y = 9, x = 12 and y = 3, we can plot the corresponding Hough space. We see that the lines in Hough space intersect at θ = 0.925 and r = 9.6. Since a line in the Polar coordinate system is given by r = xcosθ + ysinθ, we can induce that a single line crossing through all these points is defined as 9.6 = xcos0.925 + ysin0.925. Generally, the more curves intersecting in Hough space means that the line represented by that intersection corresponds to more points. For our implementation, we will define a minimum threshold number of intersections in Hough space to detect a line. Therefore, Hough transform basically keeps track of the Hough space intersections of every point in the frame. If the number of intersections exceeds a defined threshold, we identify a line with the corresponding θ and r parameters. We apply Hough Transform to identify two straight lines — which will be our left and right lane boundaries The lane is visualized as two light green, linearly fitted polynomials which will be overlayed on our input frame. Now, open Terminal and run python detector.py to test your simple lane detector! In case you have missed any code, here is the full solution with comments: This rather handcrafted traditional method in Approach 1 seems to work decently... at least for clear straight roads. However, it is fairly obvious that this method would break instantly on curved lanes or sharp turns. Also, we noticed that the presence of markings consisting of straight lines on the lanes, such as painted arrow signs, may confuse the lane detector from time to time, evident from the glitches in the demo rendering. One way to overcome this may be to further refine the triangular mask into two separate, more precise masks. Nonetheless, these rather arbitrary mask parameters simply cannot adapt to various changing road environments. Another shortcoming is that lanes with dotted markings or with no clear markings at all are also ignored by the lane detector since there are no continuous straight lines that satisfy the Hough transform threshold. Finally, weather and lighting conditions affecting the visibility of the lines may also be an issue. While Convolutional Neural Networks (CNNs) have proven to be effective architectures for both recognizing simple features at lower layers of images (e.g. edges, color gradients) as well as complex features and entities in deeper levels (e.g. object recognition), they often struggle to represent the “pose” of these features and entities — that is, CNNs are great for extracting semantics from raw pixels but perform poorly on capturing the spatial relationships (e.g. rotational and translational relationships) of pixels in a frame. These spatial relationships, however, are important for the task of lane detection, where there are strong shape priors but weak appearance coherences. For example, it is hard to determine traffic poles solely by extracting semantic features as they lack distinct and coherent appearance cues and are often occluded. However, since we know traffic poles usually exhibit similar spatial relationships such as to stand vertically and are placed alongside the left and right of roads, we see the importance of reinforcing spatial information. A similar case follows for detecting lanes. To address this issue, Spatial CNN (SCNN) proposes an architecture which “generalizes traditional deep layer-by-layer convolutions to slice-by slice convolutions within feature maps”. What does this mean? In a traditional layer-by-layer CNN, each convolution layer receives input from its preceding layer, applies convolutions and nonlinear activation, and sends the output to the succeeding layer. SCNN takes this a step further by treating individual feature map rows and columns as the “layers”, applying the same process sequentially (where sequentially means that a slice passes information to the succeeding slice only after it has received information from the preceding slices), allowing message passing of pixel information between neurons within the same layer, effectively increasing emphasis on spatial information. SCNN is relatively new, published only earlier this year (2018), but have already outperformed the likes of ReNet (RNN), MRFNet (MRF+CNN), much deeper ResNet architectures, and placed first on the TuSimple Benchmark Lane Detection Challenge with 96.53% accuracy. In addition, alongside the publication of SCNN, the authors also released CULane Dataset, a large scale dataset with annotations of traffic lanes with cubic spines. CULane Dataset also contains many challenging scenarios, including occlusions and varying lighting conditions. Lane detection requires precise pixel-wise identification and prediction of lane curves. Instead of training for lane presence directly and performing clustering afterwards, the authors of SCNN treated the blue, green, red, and yellow lane markings as four separate classes. The model outputs probability maps (probmaps) for each curve, similar to semantic segmentation tasks, then passes the probmaps through a small network to predict the final cubic spines. The model is based on the DeepLab-LargeFOV model variant. For each lane marking with over 0.5 existence value, the corresponding probmap is searched by 20 row intervals for the position with the highest response. To determine whether if a lane marking is detected, the Intersection-over-Union (IoU) between the ground truth (correct labels) and prediction is calculated, where IoUs above a set threshold are evaluated as true positives (TP) to calculate precision and recall. You can follow this repository to reproduce the results in the SCNN paper or test your own model with the CULane Dataset. And that’s it! 🎉 Hopefully this tutorial showed you how to build a simple lane detector using the traditional approach which involves many handcrafted features and fine-tuning, and also introduced you to an alternative method which follows the recent trend of solving almost any type of computer vision problem: you can add a convolutional neural network to that! Hats off to you for completing this tutorial and I hope you enjoyed it 🎩. Feel free to follow for more upcoming tutorials! :)
[ { "code": null, "e": 618, "s": 172, "text": "Waymo’s self-driving taxi service just hit the road this month — but how do autonomous vehicles even work? The lines drawn on roads indicate to human drivers where the lanes are and act as a guiding reference to which direction to steer the vehicle accordingly and convention to how vehicle agents interact harmoniously on the road. Likewise, the ability to identify and track lanes is cardinal for developing algorithms for driverless vehicles." }, { "code": null, "e": 802, "s": 618, "text": "In this tutorial, we will learn how to build a software pipeline for tracking road lanes using computer vision techniques. We will approach this task through two different approaches." }, { "code": null, "e": 853, "s": 802, "text": "Approach 1: Hough TransformApproach 2: Spatial CNN" }, { "code": null, "e": 1345, "s": 853, "text": "Most lanes are designed to be relatively straightforward not only as to encourage orderliness but also to make it easier for human drivers to steer vehicles with consistent speed. Therefore, our intuitive approach may be to first detect prominent straight lines in the camera feed through edge detection and feature extraction techniques. We will be using OpenCV, an open source library of computer vision algorithms, for implementation. The following diagram is an overview of our pipeline." }, { "code": null, "e": 1393, "s": 1345, "text": "Before we start, here is a demo of our outcome:" }, { "code": null, "e": 1461, "s": 1393, "text": "If you do not already have OpenCV installed, open Terminal and run:" }, { "code": null, "e": 1487, "s": 1461, "text": "pip install opencv-python" }, { "code": null, "e": 1534, "s": 1487, "text": "Now, clone the tutorial repository by running:" }, { "code": null, "e": 1592, "s": 1534, "text": "git clone https://github.com/chuanenlin/lane-detector.git" }, { "code": null, "e": 1710, "s": 1592, "text": "Next, open detector.py with your text editor. We will be writing all of the code of this section in this Python file." }, { "code": null, "e": 1899, "s": 1710, "text": "We will feed in our sample video for lane detection as a series of continuous frames (images) by intervals of 10 milliseconds. We can also quit the program anytime by pressing the ‘q’ key." }, { "code": null, "e": 2221, "s": 1899, "text": "The Canny Detector is a multi-stage algorithm optimized for fast real-time edge detection. The fundamental goal of the algorithm is to detect sharp changes in luminosity (large gradients), such as a shift from white to black, and defines them as edges, given a set of thresholds. The Canny algorithm has four main stages:" }, { "code": null, "e": 2240, "s": 2221, "text": "A. Noise reduction" }, { "code": null, "e": 2657, "s": 2240, "text": "As with all edge detection algorithms, noise is a crucial issue that often leads to false detection. A 5x5 Gaussian filter is applied to convolve (smooth) the image to lower the detector’s sensitivity to noise. This is done by using a kernel (in this case, a 5x5 kernel) of normally distributed numbers to run across the entire image, setting each pixel value equal to the weighted average of its neighboring pixels." }, { "code": null, "e": 2679, "s": 2657, "text": "B. Intensity gradient" }, { "code": null, "e": 2878, "s": 2679, "text": "The smoothened image is then applied with a Sobel, Roberts, or Prewitt kernel (Sobel is used in OpenCV) along the x-axis and y-axis to detect whether the edges are horizontal, vertical, or diagonal." }, { "code": null, "e": 2905, "s": 2878, "text": "C. Non-maximum suppression" }, { "code": null, "e": 3103, "s": 2905, "text": "Non-maximum suppression is applied to “thin” and effectively sharpen the edges. For each pixel, the value is checked if it is a local maximum in the direction of the gradient calculated previously." }, { "code": null, "e": 3435, "s": 3103, "text": "A is on the edge with a vertical direction. As gradient is normal to the edge direction, pixel values of B and C are compared with pixel values of A to determine if A is a local maximum. If A is local maximum, non-maximum suppression is tested for the next point. Otherwise, the pixel value of A is set to zero and A is suppressed." }, { "code": null, "e": 3462, "s": 3435, "text": "D. Hysteresis thresholding" }, { "code": null, "e": 4034, "s": 3462, "text": "After non-maximum suppression, strong pixels are confirmed to be in the final map of edges. However, weak pixels should be further analyzed to determine whether it constitutes as edge or noise. Applying two pre-defined minVal and maxVal threshold values, we set that any pixel with intensity gradient higher than maxVal are edges and any pixel with intensity gradient lower than minVal are not edges and discarded. Pixels with intensity gradient in between minVal and maxVal are only considered edges if they are connected to a pixel with intensity gradient above maxVal." }, { "code": null, "e": 4300, "s": 4034, "text": "Edge A is above maxVal so is considered an edge. Edge B is in between maxVal and minVal but is not connected to any edge above maxVal so is discarded. Edge C is in between maxVal and minVal and is connected to edge A, an edge above maxVal, so is considered an edge." }, { "code": null, "e": 4490, "s": 4300, "text": "For our pipeline, our frame is first grayscaled because we only need the luminance channel for detecting edges and a 5 by 5 gaussian blur is applied to decrease noise to reduce false edges." }, { "code": null, "e": 4648, "s": 4490, "text": "We will handcraft a triangular mask to segment the lane area and discard the irrelevant areas in the frame to increase the effectiveness of our later stages." }, { "code": null, "e": 4949, "s": 4648, "text": "In the Cartesian coordinate system, we can represent a straight line as y = mx + b by plotting y against x. However, we can also represent this line as a single point in Hough space by plotting b against m. For example, a line with the equation y = 2x + 1 may be represented as (2, 1) in Hough space." }, { "code": null, "e": 5447, "s": 4949, "text": "Now, what if instead of a line, we had to plot a point in the Cartesian coordinate system. There are many possible lines which can pass through this point, each line with different values for parameters m and b. For example, a point at (2, 12) can be passed by y = 2x + 8, y = 3x + 6, y = 4x + 4, y = 5x + 2, y = 6x, and so on. These possible lines can be plotted in Hough space as (2, 8), (3, 6), (4, 4), (5, 2), (6, 0). Notice that this produces a line of m against b coordinates in Hough space." }, { "code": null, "e": 5904, "s": 5447, "text": "Whenever we see a series of points in a Cartesian coordinate system and know that these points are connected by some line, we can find the equation of that line by first plotting each point in the Cartesian coordinate system to the corresponding line in Hough space, then finding the point of intersection in Hough space. The point of intersection in Hough space represents the m and b values that pass consistently through all of the points in the series." }, { "code": null, "e": 6241, "s": 5904, "text": "Since our frame passed through the Canny Detector may be interpreted simply as a series of white points representing the edges in our image space, we can apply the same technique to identify which of these points are connected to the same line, and if they are connected, what its equation is so that we can plot this line on our frame." }, { "code": null, "e": 6673, "s": 6241, "text": "For the simplicity of explanation, we used Cartesian coordinates to correspond to Hough space. However, there is one mathematical flaw with this approach: When the line is vertical, the gradient is infinity and cannot be represented in Hough space. To solve this problem, we will use Polar coordinates instead. The process is still the same just that other than plotting m against b in Hough space, we will be plotting r against θ." }, { "code": null, "e": 6832, "s": 6673, "text": "For example, for the points on the Polar coordinate system with x = 8 and y = 6, x = 4 and y = 9, x = 12 and y = 3, we can plot the corresponding Hough space." }, { "code": null, "e": 7090, "s": 6832, "text": "We see that the lines in Hough space intersect at θ = 0.925 and r = 9.6. Since a line in the Polar coordinate system is given by r = xcosθ + ysinθ, we can induce that a single line crossing through all these points is defined as 9.6 = xcos0.925 + ysin0.925." }, { "code": null, "e": 7575, "s": 7090, "text": "Generally, the more curves intersecting in Hough space means that the line represented by that intersection corresponds to more points. For our implementation, we will define a minimum threshold number of intersections in Hough space to detect a line. Therefore, Hough transform basically keeps track of the Hough space intersections of every point in the frame. If the number of intersections exceeds a defined threshold, we identify a line with the corresponding θ and r parameters." }, { "code": null, "e": 7682, "s": 7575, "text": "We apply Hough Transform to identify two straight lines — which will be our left and right lane boundaries" }, { "code": null, "e": 7797, "s": 7682, "text": "The lane is visualized as two light green, linearly fitted polynomials which will be overlayed on our input frame." }, { "code": null, "e": 7953, "s": 7797, "text": "Now, open Terminal and run python detector.py to test your simple lane detector! In case you have missed any code, here is the full solution with comments:" }, { "code": null, "e": 8925, "s": 7953, "text": "This rather handcrafted traditional method in Approach 1 seems to work decently... at least for clear straight roads. However, it is fairly obvious that this method would break instantly on curved lanes or sharp turns. Also, we noticed that the presence of markings consisting of straight lines on the lanes, such as painted arrow signs, may confuse the lane detector from time to time, evident from the glitches in the demo rendering. One way to overcome this may be to further refine the triangular mask into two separate, more precise masks. Nonetheless, these rather arbitrary mask parameters simply cannot adapt to various changing road environments. Another shortcoming is that lanes with dotted markings or with no clear markings at all are also ignored by the lane detector since there are no continuous straight lines that satisfy the Hough transform threshold. Finally, weather and lighting conditions affecting the visibility of the lines may also be an issue." }, { "code": null, "e": 9612, "s": 8925, "text": "While Convolutional Neural Networks (CNNs) have proven to be effective architectures for both recognizing simple features at lower layers of images (e.g. edges, color gradients) as well as complex features and entities in deeper levels (e.g. object recognition), they often struggle to represent the “pose” of these features and entities — that is, CNNs are great for extracting semantics from raw pixels but perform poorly on capturing the spatial relationships (e.g. rotational and translational relationships) of pixels in a frame. These spatial relationships, however, are important for the task of lane detection, where there are strong shape priors but weak appearance coherences." }, { "code": null, "e": 9777, "s": 9612, "text": "For example, it is hard to determine traffic poles solely by extracting semantic features as they lack distinct and coherent appearance cues and are often occluded." }, { "code": null, "e": 10044, "s": 9777, "text": "However, since we know traffic poles usually exhibit similar spatial relationships such as to stand vertically and are placed alongside the left and right of roads, we see the importance of reinforcing spatial information. A similar case follows for detecting lanes." }, { "code": null, "e": 10872, "s": 10044, "text": "To address this issue, Spatial CNN (SCNN) proposes an architecture which “generalizes traditional deep layer-by-layer convolutions to slice-by slice convolutions within feature maps”. What does this mean? In a traditional layer-by-layer CNN, each convolution layer receives input from its preceding layer, applies convolutions and nonlinear activation, and sends the output to the succeeding layer. SCNN takes this a step further by treating individual feature map rows and columns as the “layers”, applying the same process sequentially (where sequentially means that a slice passes information to the succeeding slice only after it has received information from the preceding slices), allowing message passing of pixel information between neurons within the same layer, effectively increasing emphasis on spatial information." }, { "code": null, "e": 11135, "s": 10872, "text": "SCNN is relatively new, published only earlier this year (2018), but have already outperformed the likes of ReNet (RNN), MRFNet (MRF+CNN), much deeper ResNet architectures, and placed first on the TuSimple Benchmark Lane Detection Challenge with 96.53% accuracy." }, { "code": null, "e": 11411, "s": 11135, "text": "In addition, alongside the publication of SCNN, the authors also released CULane Dataset, a large scale dataset with annotations of traffic lanes with cubic spines. CULane Dataset also contains many challenging scenarios, including occlusions and varying lighting conditions." }, { "code": null, "e": 11930, "s": 11411, "text": "Lane detection requires precise pixel-wise identification and prediction of lane curves. Instead of training for lane presence directly and performing clustering afterwards, the authors of SCNN treated the blue, green, red, and yellow lane markings as four separate classes. The model outputs probability maps (probmaps) for each curve, similar to semantic segmentation tasks, then passes the probmaps through a small network to predict the final cubic spines. The model is based on the DeepLab-LargeFOV model variant." }, { "code": null, "e": 12348, "s": 11930, "text": "For each lane marking with over 0.5 existence value, the corresponding probmap is searched by 20 row intervals for the position with the highest response. To determine whether if a lane marking is detected, the Intersection-over-Union (IoU) between the ground truth (correct labels) and prediction is calculated, where IoUs above a set threshold are evaluated as true positives (TP) to calculate precision and recall." }, { "code": null, "e": 12470, "s": 12348, "text": "You can follow this repository to reproduce the results in the SCNN paper or test your own model with the CULane Dataset." }, { "code": null, "e": 12834, "s": 12470, "text": "And that’s it! 🎉 Hopefully this tutorial showed you how to build a simple lane detector using the traditional approach which involves many handcrafted features and fine-tuning, and also introduced you to an alternative method which follows the recent trend of solving almost any type of computer vision problem: you can add a convolutional neural network to that!" } ]
Dynamic Time Warping. Explanation and Code Implementation | by Jeremy Zhang | Towards Data Science
Sounds like time traveling or some kind of future technic, however, it is not. Dynamic Time Warping is used to compare the similarity or calculate the distance between two arrays or time series with different length. Suppose we want to calculate the distance of two equal-length arrays: a = [1, 2, 3]b = [3, 2, 2] How to do that? One obvious way is to match up a and b in 1-to-1 fashion and sum up the total distance of each component. This sounds easy, but what if a and b have different lengths? a = [1, 2, 3]b = [2, 2, 2, 3, 4] How to match them up? Which should map to which? To solve the problem, there comes dynamic time warping. Just as its name indicates, to warp the series so that they can match up. Before digging into the algorithm, you might have the question that is it useful? Do we really need to compare the distance between two unequal-length time series? Yes, in a lot of scenarios DTW is playing a key role. One use case is to detect the sound pattern of the same kind. Suppose we want to recognise the voice of a person by analysing his sound track, and we are able to collect his sound track of saying Hello in one scenario. However, people speak in the same word in different ways, what if he speaks hello in a much slower pace like Heeeeeeelloooooo , we will need an algorithm to match up the sound track of different lengths and be able to identify they come from the same person. In a stock market, people always hope to be able to predict the future, however using general machine learning algorithms can be exhaustive, as most prediction task requires test and training set to have the same dimension of features. However, if you ever speculate in the stock market, you will know that even the same pattern of a stock can have very different length reflection on klines and indicators. A concise explanation of DTW from wiki, In time series analysis, dynamic time warping (DTW) is one of the algorithms for measuring similarity between two temporal sequences, which may vary in speed. DTW has been applied to temporal sequences of video, audio, and graphics data — indeed, any data that can be turned into a linear sequence can be analysed with DTW. The idea to compare arrays with different length is to build one-to-many and many-to-one matches so that the total distance can be minimised between the two. Suppose we have two different arrays red and blue with different length: Clearly these two series follow the same pattern, but the blue curve is longer than the red. If we apply the one-to-one match, shown in the top, the mapping is not perfectly synced up and the tail of the blue curve is being left out. DTW overcomes the issue by developing a one-to-many match so that the troughs and peaks with the same pattern are perfectly matched, and there is no left out for both curves(shown in the bottom top). In general, DTW is a method that calculates an optimal match between two given sequences (e.g. time series) with certain restriction and rules(comes from wiki): Every index from the first sequence must be matched with one or more indices from the other sequence and vice versa The first index from the first sequence must be matched with the first index from the other sequence (but it does not have to be its only match) The last index from the first sequence must be matched with the last index from the other sequence (but it does not have to be its only match) The mapping of the indices from the first sequence to indices from the other sequence must be monotonically increasing, and vice versa, i.e. if j > i are indices from the first sequence, then there must not be two indices l > k in the other sequence, such that index i is matched with index l and index j is matched with index k , and vice versa The optimal match is denoted by the match that satisfies all the restrictions and the rules and that has the minimal cost, where the cost is computed as the sum of absolute differences, for each matched pair of indices, between their values. To summarise is that head and tail must be positionally matched, no cross-match and no left out. The implementation of the algorithm looks extremely concise: where DTW[i, j] is the distance between s[1:i] and t[1:j] with the best alignment. The key lies in: DTW[i, j] := cost + minimum(DTW[i-1, j ], DTW[i , j-1], DTW[i-1, j-1]) Which is saying that the cost of between two arrays with length i and j equals the distance between the tails + the minimum of cost in arrays with length i-1, j , i, j-1 , and i-1, j-1 . Put it in python would be: Example: The distance between a and b would be the last element of the matrix, which is 2. One issue of the above algorithm is that we allow one element in an array to match an unlimited number of elements in the other array(as long as the tail can match in the end), this would cause the mapping to bent over a lot, for example, the following array: a = [1, 2, 3]b = [1, 2, 2, 2, 2, 2, 2, 2, ..., 5] To minimise the distance, the element 2 in array a would match all the 2 in array b , which causes an array b to bent severely. To avoid this, we can add a window constraint to limit the number of elements one can match: The key difference is that now each element is confined to match elements in range i — w and i + w . The w := max(w, abs(n-m)) guarantees all indices can be matched up. The implementation and example would be: There is also contributed packages available on Pypi to use directly. Here I demonstrate an example using fastdtw: It gives you the distance of two lists and index mapping(the example can extend to a multi-dimension array). Lastly, you can check out the implementation here.
[ { "code": null, "e": 264, "s": 47, "text": "Sounds like time traveling or some kind of future technic, however, it is not. Dynamic Time Warping is used to compare the similarity or calculate the distance between two arrays or time series with different length." }, { "code": null, "e": 334, "s": 264, "text": "Suppose we want to calculate the distance of two equal-length arrays:" }, { "code": null, "e": 361, "s": 334, "text": "a = [1, 2, 3]b = [3, 2, 2]" }, { "code": null, "e": 545, "s": 361, "text": "How to do that? One obvious way is to match up a and b in 1-to-1 fashion and sum up the total distance of each component. This sounds easy, but what if a and b have different lengths?" }, { "code": null, "e": 578, "s": 545, "text": "a = [1, 2, 3]b = [2, 2, 2, 3, 4]" }, { "code": null, "e": 757, "s": 578, "text": "How to match them up? Which should map to which? To solve the problem, there comes dynamic time warping. Just as its name indicates, to warp the series so that they can match up." }, { "code": null, "e": 921, "s": 757, "text": "Before digging into the algorithm, you might have the question that is it useful? Do we really need to compare the distance between two unequal-length time series?" }, { "code": null, "e": 975, "s": 921, "text": "Yes, in a lot of scenarios DTW is playing a key role." }, { "code": null, "e": 1453, "s": 975, "text": "One use case is to detect the sound pattern of the same kind. Suppose we want to recognise the voice of a person by analysing his sound track, and we are able to collect his sound track of saying Hello in one scenario. However, people speak in the same word in different ways, what if he speaks hello in a much slower pace like Heeeeeeelloooooo , we will need an algorithm to match up the sound track of different lengths and be able to identify they come from the same person." }, { "code": null, "e": 1861, "s": 1453, "text": "In a stock market, people always hope to be able to predict the future, however using general machine learning algorithms can be exhaustive, as most prediction task requires test and training set to have the same dimension of features. However, if you ever speculate in the stock market, you will know that even the same pattern of a stock can have very different length reflection on klines and indicators." }, { "code": null, "e": 1901, "s": 1861, "text": "A concise explanation of DTW from wiki," }, { "code": null, "e": 2225, "s": 1901, "text": "In time series analysis, dynamic time warping (DTW) is one of the algorithms for measuring similarity between two temporal sequences, which may vary in speed. DTW has been applied to temporal sequences of video, audio, and graphics data — indeed, any data that can be turned into a linear sequence can be analysed with DTW." }, { "code": null, "e": 2383, "s": 2225, "text": "The idea to compare arrays with different length is to build one-to-many and many-to-one matches so that the total distance can be minimised between the two." }, { "code": null, "e": 2456, "s": 2383, "text": "Suppose we have two different arrays red and blue with different length:" }, { "code": null, "e": 2690, "s": 2456, "text": "Clearly these two series follow the same pattern, but the blue curve is longer than the red. If we apply the one-to-one match, shown in the top, the mapping is not perfectly synced up and the tail of the blue curve is being left out." }, { "code": null, "e": 2890, "s": 2690, "text": "DTW overcomes the issue by developing a one-to-many match so that the troughs and peaks with the same pattern are perfectly matched, and there is no left out for both curves(shown in the bottom top)." }, { "code": null, "e": 3051, "s": 2890, "text": "In general, DTW is a method that calculates an optimal match between two given sequences (e.g. time series) with certain restriction and rules(comes from wiki):" }, { "code": null, "e": 3167, "s": 3051, "text": "Every index from the first sequence must be matched with one or more indices from the other sequence and vice versa" }, { "code": null, "e": 3312, "s": 3167, "text": "The first index from the first sequence must be matched with the first index from the other sequence (but it does not have to be its only match)" }, { "code": null, "e": 3455, "s": 3312, "text": "The last index from the first sequence must be matched with the last index from the other sequence (but it does not have to be its only match)" }, { "code": null, "e": 3801, "s": 3455, "text": "The mapping of the indices from the first sequence to indices from the other sequence must be monotonically increasing, and vice versa, i.e. if j > i are indices from the first sequence, then there must not be two indices l > k in the other sequence, such that index i is matched with index l and index j is matched with index k , and vice versa" }, { "code": null, "e": 4043, "s": 3801, "text": "The optimal match is denoted by the match that satisfies all the restrictions and the rules and that has the minimal cost, where the cost is computed as the sum of absolute differences, for each matched pair of indices, between their values." }, { "code": null, "e": 4140, "s": 4043, "text": "To summarise is that head and tail must be positionally matched, no cross-match and no left out." }, { "code": null, "e": 4201, "s": 4140, "text": "The implementation of the algorithm looks extremely concise:" }, { "code": null, "e": 4284, "s": 4201, "text": "where DTW[i, j] is the distance between s[1:i] and t[1:j] with the best alignment." }, { "code": null, "e": 4301, "s": 4284, "text": "The key lies in:" }, { "code": null, "e": 4428, "s": 4301, "text": "DTW[i, j] := cost + minimum(DTW[i-1, j ], DTW[i , j-1], DTW[i-1, j-1])" }, { "code": null, "e": 4615, "s": 4428, "text": "Which is saying that the cost of between two arrays with length i and j equals the distance between the tails + the minimum of cost in arrays with length i-1, j , i, j-1 , and i-1, j-1 ." }, { "code": null, "e": 4642, "s": 4615, "text": "Put it in python would be:" }, { "code": null, "e": 4651, "s": 4642, "text": "Example:" }, { "code": null, "e": 4733, "s": 4651, "text": "The distance between a and b would be the last element of the matrix, which is 2." }, { "code": null, "e": 4993, "s": 4733, "text": "One issue of the above algorithm is that we allow one element in an array to match an unlimited number of elements in the other array(as long as the tail can match in the end), this would cause the mapping to bent over a lot, for example, the following array:" }, { "code": null, "e": 5043, "s": 4993, "text": "a = [1, 2, 3]b = [1, 2, 2, 2, 2, 2, 2, 2, ..., 5]" }, { "code": null, "e": 5264, "s": 5043, "text": "To minimise the distance, the element 2 in array a would match all the 2 in array b , which causes an array b to bent severely. To avoid this, we can add a window constraint to limit the number of elements one can match:" }, { "code": null, "e": 5433, "s": 5264, "text": "The key difference is that now each element is confined to match elements in range i — w and i + w . The w := max(w, abs(n-m)) guarantees all indices can be matched up." }, { "code": null, "e": 5474, "s": 5433, "text": "The implementation and example would be:" }, { "code": null, "e": 5589, "s": 5474, "text": "There is also contributed packages available on Pypi to use directly. Here I demonstrate an example using fastdtw:" }, { "code": null, "e": 5698, "s": 5589, "text": "It gives you the distance of two lists and index mapping(the example can extend to a multi-dimension array)." } ]
Standalone React.js basic example
Lets first start with writing a simple HTML code and see how we can use React Basic React example − Create a simple div like below − <div class="player"> <h1>Steve</h1> <p>My hobby: Cricket</p> </div> Add some styling elements .player{ border:1px solid #eee; width:200px; box-shadow:0 2px 2px #ccc; padding: 22px; display:inline-block; margin:10px; } This is just like normal html data in web app. Now, we may have multiple same players and we then have to replicate the same div like below <div class="player"> <h1>David</h1> <p>My hobby: Cricket</p> </div> These div are same in structure but having different data inside. Here, React is very useful which can create a reusable components for us to avoid the repeated html structures and working with logical actions on components. For the basic usage, we will use a standalone React library. We will have to use two main library scripts − Note − when deploying, replace “development.js” with “production.min.js” Below script is used to create components and perform actions on it. <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> The react-dom script is used to render the actual components to html dom <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> We will also use standalone babel preprocessor to compile for the latest JavaScript <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> React uses a special syntax of JavaScript called as jsx which looks much similar to html itself. So lets create a React function component. The name of function component starts with Capital letter to make it work correctly. function Player(){ return( <div class="player"> <h1>Steve</h1> <p>My hobby: Cricket</p> </div> ); } so in actual html file we can replace the first div player with below div − <div id="first"></div> Now, we have to render the component to html with ReactDOM as below − Render method requires the React component as argument and location where it needs to render on html. ReactDOM.render(<Player/>,document.querySelector('#first')); The function component is used as first argument like a html tag. Second argument to render method can be a html element selector. If we put all these pieces together we can have below html file to test − <!DOCTYPE html> <html> <head> <title>React Example</title> <style> .player{ border:1px solid #eee; width:200px; box-shadow:0 2px 2px #ccc; padding: 22px; display:inline-block; margin:10px; } </style> </head> <body> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <!-- Load React. --> <!-- Note: when deploying, replace "development.js" with "production.min.js". --> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <div id="first"></div> <div class="player"> <h1>David</h1> <p>My hobby: Cricket</p> </div> <script type="text/babel"> function Player(){ return( <div className="player"> <h1>Steve</h1> <p>My hobby: Cricket</p> </div> ); } ReactDOM.render(<Player/>,document.querySelector('#first')); </script> </body> </html> It's not really reusable as the second player div we used is still not from React component. To make it reusable we have to use dynamic function with a argument called as props as below − function Player(props){ <div className="player"> <h1>{props.name}</h1> <p>My hobby: {props.hobby}</p> </div> } The argument props contains the attributes of the player. Now, we can create smaller replacement div for second player like − <div id="second"></div> we will pass the player attributes in render method as below − ReactDOM.render( <Player name="Steve" hobbey="Cricket"/>, document.querySelector('#first') ); ReactDOM.render( <Player name="David" hobbey="Cricket"/>, document.querySelector('#second') ); Now, you have observed the potential of reusable React components. Instead of having two separate ReactDOM.render we can combine them together //we can have only one div in html <div id="app"></div> //and in react script we can have: var app= ( <div> <Player name="Steve" hobbey="Cricket"/> <Player name="David" hobbey="Cricket"/> </div> ); //Now, we will map our app component using ReactDOM: ReactDOM.render(app,document.querySelector('#app')); <!DOCTYPE html> <html> <head> <title>React Example</title> <style> .player{ border:1px solid #eee; width:200px; box-shadow:0 2px 2px #ccc; padding: 22px; display:inline-block; margin:10px; } </style> </head> <body> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <!-- Load React. --> <!-- Note: when deploying, replace "development.js" with "production.min.js". --> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <div id="app"></div> <script type="text/babel"> function Player(props){ //it returns the reusable code that //we want to render on actual html page return( //we are adding the first player div info <div className="player"> <h1>{props.name}</h1> <p>My hobby: {props.hobby}</p> </div> ); } var app= ( <div> <Player name="Steve" hobbey="Cricket"/> <Player name="David" hobbey="Cricket"/> </div> ); ReactDOM.render(app,document.querySelector('#app')); </script> </body> </html>
[ { "code": null, "e": 1140, "s": 1062, "text": "Lets first start with writing a simple HTML code and see how we can use React" }, { "code": null, "e": 1196, "s": 1140, "text": "Basic React example − Create a simple div like below −" }, { "code": null, "e": 1270, "s": 1196, "text": "<div class=\"player\">\n <h1>Steve</h1>\n <p>My hobby: Cricket</p>\n</div>" }, { "code": null, "e": 1296, "s": 1270, "text": "Add some styling elements" }, { "code": null, "e": 1438, "s": 1296, "text": ".player{\n border:1px solid #eee;\n width:200px;\n box-shadow:0 2px 2px #ccc;\n padding: 22px;\n display:inline-block;\n margin:10px;\n}" }, { "code": null, "e": 1578, "s": 1438, "text": "This is just like normal html data in web app. Now, we may have multiple same players and we then have to replicate the same div like below" }, { "code": null, "e": 1652, "s": 1578, "text": "<div class=\"player\">\n <h1>David</h1>\n <p>My hobby: Cricket</p>\n</div>" }, { "code": null, "e": 1877, "s": 1652, "text": "These div are same in structure but having different data inside. Here, React is very useful which can create a reusable components for us to avoid the repeated html structures and working with logical actions on components." }, { "code": null, "e": 1938, "s": 1877, "text": "For the basic usage, we will use a standalone React library." }, { "code": null, "e": 1985, "s": 1938, "text": "We will have to use two main library scripts −" }, { "code": null, "e": 2058, "s": 1985, "text": "Note − when deploying, replace “development.js” with “production.min.js”" }, { "code": null, "e": 2127, "s": 2058, "text": "Below script is used to create components and perform actions on it." }, { "code": null, "e": 2215, "s": 2127, "text": "<script src=\"https://unpkg.com/react@16/umd/react.development.js\" crossorigin></script>" }, { "code": null, "e": 2288, "s": 2215, "text": "The react-dom script is used to render the actual components to html dom" }, { "code": null, "e": 2384, "s": 2288, "text": "<script src=\"https://unpkg.com/react-dom@16/umd/react-dom.development.js\" crossorigin></script>" }, { "code": null, "e": 2468, "s": 2384, "text": "We will also use standalone babel preprocessor to compile for the latest JavaScript" }, { "code": null, "e": 2542, "s": 2468, "text": "<script src=\"https://unpkg.com/babel-standalone@6/babel.min.js\"></script>" }, { "code": null, "e": 2682, "s": 2542, "text": "React uses a special syntax of JavaScript called as jsx which looks much similar to html itself. So lets create a React function component." }, { "code": null, "e": 2767, "s": 2682, "text": "The name of function component starts with Capital letter to make it work correctly." }, { "code": null, "e": 2903, "s": 2767, "text": "function Player(){\n return(\n <div class=\"player\">\n <h1>Steve</h1>\n <p>My hobby: Cricket</p>\n </div>\n );\n}" }, { "code": null, "e": 2979, "s": 2903, "text": "so in actual html file we can replace the first div player with below div −" }, { "code": null, "e": 3002, "s": 2979, "text": "<div id=\"first\"></div>" }, { "code": null, "e": 3072, "s": 3002, "text": "Now, we have to render the component to html with ReactDOM as below −" }, { "code": null, "e": 3174, "s": 3072, "text": "Render method requires the React component as argument and location where it needs to render on html." }, { "code": null, "e": 3235, "s": 3174, "text": "ReactDOM.render(<Player/>,document.querySelector('#first'));" }, { "code": null, "e": 3366, "s": 3235, "text": "The function component is used as first argument like a html tag. Second argument to render method can be a html element selector." }, { "code": null, "e": 3440, "s": 3366, "text": "If we put all these pieces together we can have below html file to test −" }, { "code": null, "e": 4430, "s": 3440, "text": "<!DOCTYPE html>\n<html>\n<head>\n<title>React Example</title>\n<style>\n .player{\n border:1px solid #eee;\n width:200px;\n box-shadow:0 2px 2px #ccc;\n padding: 22px;\n display:inline-block;\n margin:10px;\n }\n</style>\n</head>\n<body>\n<script src=\"https://unpkg.com/babel-standalone@6/babel.min.js\"></script>\n<!-- Load React. -->\n<!-- Note: when deploying, replace \"development.js\" with \"production.min.js\". -->\n<script src=\"https://unpkg.com/react@16/umd/react.development.js\" crossorigin></script>\n<script src=\"https://unpkg.com/react-dom@16/umd/react-dom.development.js\" crossorigin></script>\n<div id=\"first\"></div>\n<div class=\"player\">\n<h1>David</h1>\n<p>My hobby: Cricket</p>\n</div>\n<script type=\"text/babel\">\n function Player(){\n return(\n <div className=\"player\">\n <h1>Steve</h1>\n <p>My hobby: Cricket</p>\n </div>\n );\n }\n ReactDOM.render(<Player/>,document.querySelector('#first'));\n</script>\n</body>\n</html>" }, { "code": null, "e": 4618, "s": 4430, "text": "It's not really reusable as the second player div we used is still not from React component. To make it reusable we have to use dynamic function with a argument called as props as below −" }, { "code": null, "e": 4747, "s": 4618, "text": "function Player(props){\n <div className=\"player\">\n <h1>{props.name}</h1>\n <p>My hobby: {props.hobby}</p>\n </div>\n}" }, { "code": null, "e": 4873, "s": 4747, "text": "The argument props contains the attributes of the player. Now, we can create smaller replacement div for second player like −" }, { "code": null, "e": 4897, "s": 4873, "text": "<div id=\"second\"></div>" }, { "code": null, "e": 4960, "s": 4897, "text": "we will pass the player attributes in render method as below −" }, { "code": null, "e": 5161, "s": 4960, "text": "ReactDOM.render(\n <Player name=\"Steve\" hobbey=\"Cricket\"/>,\n document.querySelector('#first')\n);\nReactDOM.render(\n <Player name=\"David\" hobbey=\"Cricket\"/>,\n document.querySelector('#second')\n);" }, { "code": null, "e": 5228, "s": 5161, "text": "Now, you have observed the potential of reusable React components." }, { "code": null, "e": 5304, "s": 5228, "text": "Instead of having two separate ReactDOM.render we can combine them together" }, { "code": null, "e": 5626, "s": 5304, "text": "//we can have only one div in html\n<div id=\"app\"></div>\n//and in react script we can have:\nvar app= (\n <div>\n <Player name=\"Steve\" hobbey=\"Cricket\"/>\n <Player name=\"David\" hobbey=\"Cricket\"/>\n </div>\n);\n//Now, we will map our app component using ReactDOM:\nReactDOM.render(app,document.querySelector('#app'));" }, { "code": null, "e": 6838, "s": 5626, "text": "<!DOCTYPE html>\n<html>\n<head>\n<title>React Example</title>\n<style>\n .player{\n border:1px solid #eee;\n width:200px;\n box-shadow:0 2px 2px #ccc;\n padding: 22px;\n display:inline-block;\n margin:10px;\n }\n</style>\n</head>\n<body>\n<script src=\"https://unpkg.com/babel-standalone@6/babel.min.js\"></script>\n<!-- Load React. -->\n<!-- Note: when deploying, replace \"development.js\" with \"production.min.js\". -->\n<script src=\"https://unpkg.com/react@16/umd/react.development.js\" crossorigin></script>\n<script src=\"https://unpkg.com/react-dom@16/umd/react-dom.development.js\" crossorigin></script>\n<div id=\"app\"></div>\n<script type=\"text/babel\">\n function Player(props){\n //it returns the reusable code that\n //we want to render on actual html page\n return(\n //we are adding the first player div info\n <div className=\"player\">\n <h1>{props.name}</h1>\n <p>My hobby: {props.hobby}</p>\n </div>\n );\n }\n var app= (\n <div>\n <Player name=\"Steve\" hobbey=\"Cricket\"/>\n <Player name=\"David\" hobbey=\"Cricket\"/>\n </div>\n );\n ReactDOM.render(app,document.querySelector('#app'));\n</script>\n</body>\n</html>" } ]
Using “WHERE binary” in SQL?
The binary keyword can be used after WHERE clause to compare a value with exact case sensitive match. The following is an example − Case 1 − Case insensitive match The query is as follows − mysql> select 'joHN'='JOHN' as Result; The following is the output − +--------+ | Result | +--------+ | 1 | +--------+ 1 row in set (0.00 sec) In the above sample output, the result is true while we know joHN and JOHN are two different words. This is not a case sensitive match. Case 2 − If you want case sensitive match, use the binary keyword. The query is as follows − mysql> select binary 'joHN'='JOHN' as Result; The following is the output − +--------+ | Result | +--------+ | 0 | +--------+ 1 row in set (0.00 sec) Let us now see another query − mysql> select binary 'JOHN'='JOHN' as Result; The following is the output − +--------+ | Result | +--------+ | 1 | +--------+ 1 row in set (0.00 sec) NOTE − You can use binary keyword to make your column case sensitive with the help of binary keyword whenever you create a table. To understand the above concept, let us create a table. The query to create a table is as follows − mysql> create table binaryKeywordDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(10) binary, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.88 sec) Insert some records in the table using INSERT command. The query is as follows − mysql> insert into binaryKeywordDemo(Name) values('bOB'); Query OK, 1 row affected (0.15 sec) mysql> insert into binaryKeywordDemo(Name) values('bob'); Query OK, 1 row affected (0.13 sec) mysql> insert into binaryKeywordDemo(Name) values('BOB'); Query OK, 1 row affected (0.18 sec) mysql> insert into binaryKeywordDemo(Name) values('Bob'); Query OK, 1 row affected (0.18 sec) mysql> insert into binaryKeywordDemo(Name) values('bOb'); Query OK, 1 row affected (0.15 sec) mysql> insert into binaryKeywordDemo(Name) values('boB'); Query OK, 1 row affected (0.21 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from binaryKeywordDemo; The following is the output − +----+------+ | Id | Name | +----+------+ | 1 | bOB | | 2 | bob | | 3 | BOB | | 4 | Bob | | 5 | bOb | | 6 | boB | +----+------+ 6 rows in set (0.00 sec) The following is the query to exact match like case sensitive − mysql> select *from binaryKeywordDemo where Name='Bob'; Here is the output − +----+------+ | Id | Name | +----+------+ | 4 | Bob | +----+------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1164, "s": 1062, "text": "The binary keyword can be used after WHERE clause to compare a value with exact case sensitive match." }, { "code": null, "e": 1194, "s": 1164, "text": "The following is an example −" }, { "code": null, "e": 1226, "s": 1194, "text": "Case 1 − Case insensitive match" }, { "code": null, "e": 1252, "s": 1226, "text": "The query is as follows −" }, { "code": null, "e": 1291, "s": 1252, "text": "mysql> select 'joHN'='JOHN' as Result;" }, { "code": null, "e": 1321, "s": 1291, "text": "The following is the output −" }, { "code": null, "e": 1400, "s": 1321, "text": "+--------+\n| Result |\n+--------+\n| 1 |\n+--------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1536, "s": 1400, "text": "In the above sample output, the result is true while we know joHN and JOHN are two different words. This is not a case sensitive match." }, { "code": null, "e": 1603, "s": 1536, "text": "Case 2 − If you want case sensitive match, use the binary keyword." }, { "code": null, "e": 1629, "s": 1603, "text": "The query is as follows −" }, { "code": null, "e": 1675, "s": 1629, "text": "mysql> select binary 'joHN'='JOHN' as Result;" }, { "code": null, "e": 1705, "s": 1675, "text": "The following is the output −" }, { "code": null, "e": 1784, "s": 1705, "text": "+--------+\n| Result |\n+--------+\n| 0 |\n+--------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1815, "s": 1784, "text": "Let us now see another query −" }, { "code": null, "e": 1861, "s": 1815, "text": "mysql> select binary 'JOHN'='JOHN' as Result;" }, { "code": null, "e": 1891, "s": 1861, "text": "The following is the output −" }, { "code": null, "e": 1970, "s": 1891, "text": "+--------+\n| Result |\n+--------+\n| 1 |\n+--------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2100, "s": 1970, "text": "NOTE − You can use binary keyword to make your column case sensitive with the help of binary keyword whenever you create a table." }, { "code": null, "e": 2200, "s": 2100, "text": "To understand the above concept, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 2383, "s": 2200, "text": "mysql> create table binaryKeywordDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Name varchar(10) binary,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.88 sec)" }, { "code": null, "e": 2464, "s": 2383, "text": "Insert some records in the table using INSERT command. The query is as follows −" }, { "code": null, "e": 3028, "s": 2464, "text": "mysql> insert into binaryKeywordDemo(Name) values('bOB');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into binaryKeywordDemo(Name) values('bob');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into binaryKeywordDemo(Name) values('BOB');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into binaryKeywordDemo(Name) values('Bob');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into binaryKeywordDemo(Name) values('bOb');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into binaryKeywordDemo(Name) values('boB');\nQuery OK, 1 row affected (0.21 sec)" }, { "code": null, "e": 3113, "s": 3028, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 3152, "s": 3113, "text": "mysql> select *from binaryKeywordDemo;" }, { "code": null, "e": 3182, "s": 3152, "text": "The following is the output −" }, { "code": null, "e": 3347, "s": 3182, "text": "+----+------+\n| Id | Name |\n+----+------+\n| 1 | bOB |\n| 2 | bob |\n| 3 | BOB |\n| 4 | Bob |\n| 5 | bOb |\n| 6 | boB |\n+----+------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 3411, "s": 3347, "text": "The following is the query to exact match like case sensitive −" }, { "code": null, "e": 3467, "s": 3411, "text": "mysql> select *from binaryKeywordDemo where Name='Bob';" }, { "code": null, "e": 3488, "s": 3467, "text": "Here is the output −" }, { "code": null, "e": 3582, "s": 3488, "text": "+----+------+\n| Id | Name |\n+----+------+\n| 4 | Bob |\n+----+------+\n1 row in set (0.00 sec)" } ]
How to use Fade In and Fade Out Android Animation in Java?
Fade in and fade out animation works based on alpha animation class. This example demonstrate about How to use Fade In and Fade Out Android Animation in Java. 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/login.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:orientation="vertical"> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/> <Button android:id="@+id/fadeIn" android:text="Fade In" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/fadeOut" android:text="Fade Out" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have taken imageview and two button. FadeIn button will provide fade enter animation to image view and FadeOut button provide fade exit animation to imageview. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.animation.ObjectAnimator; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ImageView imageView = findViewById(R.id.imageView); Button fadeIn = findViewById(R.id.fadeIn); fadeIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f); alphaAnimation.setDuration(1000); alphaAnimation.setRepeatCount(1); alphaAnimation.setRepeatMode(Animation.REVERSE); imageView.startAnimation(alphaAnimation); } }); Button fadeOut = findViewById(R.id.fadeOut); fadeOut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ObjectAnimator fadeOut = ObjectAnimator.ofFloat(imageView, "alpha", 1f, 0); fadeOut.setDuration(2000); fadeOut.start(); } }); } } To provide fade in animation to imageview, use the following code - AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f); alphaAnimation.setDuration(1000); alphaAnimation.setRepeatCount(1); alphaAnimation.setRepeatMode(Animation.REVERSE); imageView.startAnimation(alphaAnimation); To provide fade out animation to imageview, use the following code - ObjectAnimator fadeOut = ObjectAnimator.ofFloat(imageView, "alpha", 1f, 0); fadeOut.setDuration(2000); fadeOut.start(); 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 − Now click on fade in button it will provide animation to imageview as shown below - now click on fade out animation, it will provide fade out animation to imageview as shown below - Click here to download the project code
[ { "code": null, "e": 1221, "s": 1062, "text": "Fade in and fade out animation works based on alpha animation class. This example demonstrate about How to use Fade In and Fade Out Android Animation in Java." }, { "code": null, "e": 1350, "s": 1221, "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": 1407, "s": 1350, "text": "Step 2 − Add the following code to res/layout/login.xml." }, { "code": null, "e": 2283, "s": 1407, "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:orientation=\"vertical\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:src=\"@mipmap/ic_launcher\"/>\n <Button\n android:id=\"@+id/fadeIn\"\n android:text=\"Fade In\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/fadeOut\"\n android:text=\"Fade Out\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2465, "s": 2283, "text": "In the above code, we have taken imageview and two button. FadeIn button will provide fade enter animation to image view and FadeOut button provide fade exit animation to imageview." }, { "code": null, "e": 2522, "s": 2465, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4083, "s": 2522, "text": "package com.example.andy.myapplication;\nimport android.animation.ObjectAnimator;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.view.animation.AlphaAnimation;\nimport android.view.animation.Animation;\nimport android.widget.Button;\nimport android.widget.ImageView;\n\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ImageView imageView = findViewById(R.id.imageView);\n Button fadeIn = findViewById(R.id.fadeIn);\n fadeIn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);\n alphaAnimation.setDuration(1000);\n alphaAnimation.setRepeatCount(1);\n alphaAnimation.setRepeatMode(Animation.REVERSE);\n imageView.startAnimation(alphaAnimation);\n }\n });\n Button fadeOut = findViewById(R.id.fadeOut);\n fadeOut.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n ObjectAnimator fadeOut = ObjectAnimator.ofFloat(imageView, \"alpha\", 1f, 0);\n fadeOut.setDuration(2000);\n fadeOut.start();\n }\n });\n }\n}" }, { "code": null, "e": 4151, "s": 4083, "text": "To provide fade in animation to imageview, use the following code -" }, { "code": null, "e": 4374, "s": 4151, "text": "AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);\nalphaAnimation.setDuration(1000);\nalphaAnimation.setRepeatCount(1);\nalphaAnimation.setRepeatMode(Animation.REVERSE);\nimageView.startAnimation(alphaAnimation);" }, { "code": null, "e": 4443, "s": 4374, "text": "To provide fade out animation to imageview, use the following code -" }, { "code": null, "e": 4563, "s": 4443, "text": "ObjectAnimator fadeOut = ObjectAnimator.ofFloat(imageView, \"alpha\", 1f, 0);\nfadeOut.setDuration(2000);\nfadeOut.start();" }, { "code": null, "e": 4910, "s": 4563, "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": 4994, "s": 4910, "text": "Now click on fade in button it will provide animation to imageview as shown below -" }, { "code": null, "e": 5092, "s": 4994, "text": "now click on fade out animation, it will provide fade out animation to imageview as shown below -" }, { "code": null, "e": 5132, "s": 5092, "text": "Click here to download the project code" } ]
bind command in Linux with Examples - GeeksforGeeks
18 Apr, 2019 bind command is Bash shell builtin command. It is used to set Readline key bindings and variables. The keybindings are the keyboard actions that are bound to a function. So it can be used to change how the bash will react to keys or combinations of keys, being pressed on the keyboard. Syntax: bind [-lpsvPSVX] [-m keymap] [-q name] [-f filename] [-u name] [-r keyseq] [-x keyseq:shell-command] [keyseq:readline-function or readline-command] Options: -m keymap: It uses KEYMAP as the key mapping scheme for the duration of the current command sequence. Acceptable keymap names are as follows : emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. -l: It list names of functions. -P: It list function names and bindings. -p: It list functions and bindings in a form that can be reused as input. -S: It list key sequences that invoke macros and their values. -s: It list key sequences that invoke macros and their values in a form that can be reused as input. -V: It list variable names and values. -v: It list variable names and values in a form that canbe reused as input. -q function-name: It query about which keys invoke the named function. -u function-name: It unbind all keys which are bound to the named function. -r keyseq: It remove the binding for KEYSEQ. -f filename: It read key bindings from FILENAME. -x keyseq:shell-command: It cause SHELL-COMMAND to be executed when KEYSEQ is entered. -XIt lists key sequences bound with -x and associated commands in a form that can be reused as input. Examples: -m: It use KEYMAP as the keymap for the duration of this command. Here we are using vi keymapping in bash, which allows us to manipulate text on the command line as you would in vi.bind -m vi bind -m vi -l: List all the readline function names. There are around 150 functions that are available by default in this list.bind -l bind -l -p: It will display both the keybindings and the corresponding function names.bind -p bind -p -P: It will list of all functions along with the bindings where they appear. It is a little bit easier to read when liked to view all the keybindings for a particular function name.bind -P bind -P -f: It read key bindings from FILENAME. First of all, create a file containing keybindings.cat > bindand then write the keybinding in it for example “\C-i”: yank. Now to load keybindings from FILENAME.bind -f bind bind -p | grep yank cat > bind and then write the keybinding in it for example “\C-i”: yank. Now to load keybindings from FILENAME. bind -f bind bind -p | grep yank -q: It is used to view keybindings only for a specific function.bind -q yank bind -q yank -r: Remove all bindings for the particular key sequence.bind -r "\C-y" bind -r "\C-y" -u: It also unbinds a keybinding. It will remove the key combinations that is assigned to a particular function.bind -u yank bind -u yank -v: It is used to view all the readline variables.bind -v bind -v Note:To check the help page of bind command, use the following command: bind --help linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples Docker - COPY Instruction mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n18 Apr, 2019" }, { "code": null, "e": 25937, "s": 25651, "text": "bind command is Bash shell builtin command. It is used to set Readline key bindings and variables. The keybindings are the keyboard actions that are bound to a function. So it can be used to change how the bash will react to keys or combinations of keys, being pressed on the keyboard." }, { "code": null, "e": 25945, "s": 25937, "text": "Syntax:" }, { "code": null, "e": 26099, "s": 25945, "text": "bind [-lpsvPSVX] [-m keymap] [-q name] [-f filename] [-u name] [-r keyseq]\n [-x keyseq:shell-command] [keyseq:readline-function or readline-command]\n" }, { "code": null, "e": 26108, "s": 26099, "text": "Options:" }, { "code": null, "e": 26338, "s": 26108, "text": "-m keymap: It uses KEYMAP as the key mapping scheme for the duration of the current command sequence. Acceptable keymap names are as follows : emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert." }, { "code": null, "e": 26370, "s": 26338, "text": "-l: It list names of functions." }, { "code": null, "e": 26411, "s": 26370, "text": "-P: It list function names and bindings." }, { "code": null, "e": 26485, "s": 26411, "text": "-p: It list functions and bindings in a form that can be reused as input." }, { "code": null, "e": 26548, "s": 26485, "text": "-S: It list key sequences that invoke macros and their values." }, { "code": null, "e": 26649, "s": 26548, "text": "-s: It list key sequences that invoke macros and their values in a form that can be reused as input." }, { "code": null, "e": 26688, "s": 26649, "text": "-V: It list variable names and values." }, { "code": null, "e": 26764, "s": 26688, "text": "-v: It list variable names and values in a form that canbe reused as input." }, { "code": null, "e": 26835, "s": 26764, "text": "-q function-name: It query about which keys invoke the named function." }, { "code": null, "e": 26911, "s": 26835, "text": "-u function-name: It unbind all keys which are bound to the named function." }, { "code": null, "e": 26956, "s": 26911, "text": "-r keyseq: It remove the binding for KEYSEQ." }, { "code": null, "e": 27005, "s": 26956, "text": "-f filename: It read key bindings from FILENAME." }, { "code": null, "e": 27092, "s": 27005, "text": "-x keyseq:shell-command: It cause SHELL-COMMAND to be executed when KEYSEQ is entered." }, { "code": null, "e": 27194, "s": 27092, "text": "-XIt lists key sequences bound with -x and associated commands in a form that can be reused as input." }, { "code": null, "e": 27204, "s": 27194, "text": "Examples:" }, { "code": null, "e": 27396, "s": 27204, "text": "-m: It use KEYMAP as the keymap for the duration of this command. Here we are using vi keymapping in bash, which allows us to manipulate text on the command line as you would in vi.bind -m vi" }, { "code": null, "e": 27407, "s": 27396, "text": "bind -m vi" }, { "code": null, "e": 27531, "s": 27407, "text": "-l: List all the readline function names. There are around 150 functions that are available by default in this list.bind -l" }, { "code": null, "e": 27539, "s": 27531, "text": "bind -l" }, { "code": null, "e": 27625, "s": 27539, "text": "-p: It will display both the keybindings and the corresponding function names.bind -p" }, { "code": null, "e": 27633, "s": 27625, "text": "bind -p" }, { "code": null, "e": 27822, "s": 27633, "text": "-P: It will list of all functions along with the bindings where they appear. It is a little bit easier to read when liked to view all the keybindings for a particular function name.bind -P" }, { "code": null, "e": 27830, "s": 27822, "text": "bind -P" }, { "code": null, "e": 28066, "s": 27830, "text": "-f: It read key bindings from FILENAME. First of all, create a file containing keybindings.cat > bindand then write the keybinding in it for example “\\C-i”: yank. Now to load keybindings from FILENAME.bind -f bind\nbind -p | grep yank \n" }, { "code": null, "e": 28077, "s": 28066, "text": "cat > bind" }, { "code": null, "e": 28178, "s": 28077, "text": "and then write the keybinding in it for example “\\C-i”: yank. Now to load keybindings from FILENAME." }, { "code": null, "e": 28213, "s": 28178, "text": "bind -f bind\nbind -p | grep yank \n" }, { "code": null, "e": 28290, "s": 28213, "text": "-q: It is used to view keybindings only for a specific function.bind -q yank" }, { "code": null, "e": 28303, "s": 28290, "text": "bind -q yank" }, { "code": null, "e": 28374, "s": 28303, "text": "-r: Remove all bindings for the particular key sequence.bind -r \"\\C-y\"" }, { "code": null, "e": 28389, "s": 28374, "text": "bind -r \"\\C-y\"" }, { "code": null, "e": 28514, "s": 28389, "text": "-u: It also unbinds a keybinding. It will remove the key combinations that is assigned to a particular function.bind -u yank" }, { "code": null, "e": 28527, "s": 28514, "text": "bind -u yank" }, { "code": null, "e": 28585, "s": 28527, "text": "-v: It is used to view all the readline variables.bind -v" }, { "code": null, "e": 28593, "s": 28585, "text": "bind -v" }, { "code": null, "e": 28665, "s": 28593, "text": "Note:To check the help page of bind command, use the following command:" }, { "code": null, "e": 28677, "s": 28665, "text": "bind --help" }, { "code": null, "e": 28691, "s": 28677, "text": "linux-command" }, { "code": null, "e": 28711, "s": 28691, "text": "Linux-misc-commands" }, { "code": null, "e": 28718, "s": 28711, "text": "Picked" }, { "code": null, "e": 28729, "s": 28718, "text": "Linux-Unix" }, { "code": null, "e": 28827, "s": 28729, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28862, "s": 28827, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28888, "s": 28862, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28922, "s": 28888, "text": "mv command in Linux with examples" }, { "code": null, "e": 28951, "s": 28922, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28988, "s": 28951, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29025, "s": 28988, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29067, "s": 29025, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 29093, "s": 29067, "text": "Thread functions in C/C++" }, { "code": null, "e": 29129, "s": 29093, "text": "uniq Command in LINUX with examples" } ]
How to read password protected excel file in R ? - GeeksforGeeks
18 Jul, 2021 In this article, we are going to see how to read password-protected Excel files in R programming language. File in use: file Here we will use excel.link package to read the file with a password. Installation: install.packages(“excel.link”) xl.read.file() function is used to read Excel files in R programming. Syntax: xl.read.file( “file_name”, password = “pass”) Example 1: R # import liblibrary("excel.link") # read file with passdf <- xl.read.file("data.xlsx", password = "gfg@123") # display dfhead(df) Output: The same module can be used to first unlock the file and then copy its contents onto another so that it can be accessed again without any password. Here we save the file with a password NULL value and save it to another file. Syntax: xl.save.file( file.object, “New_file”, password = NULL , write.res.password = NULL) Program: R # import liblibrary("excel.link") # read file with passdf <- xl.read.file("data.xlsx", password = "gfg@123") # save the df into new filexl.save.file(df, "Output.xlsx", password = NULL, write.res.password = NULL) # read file without any passworddf1 <- xl.read.file("Output.xlsx") head(df) Output: Here we will use XLConnect package to read the password-protected file. This package provides comprehensive functionality to read, write and format Excel data. loadWorkbook() function loads Microsoft Excel workbooks. Syntax: loadWorkbook(filename , password ) readWorksheet() function reads data from worksheets. Syntax: readWorksheet( object, sheet). Parameters: Object: The ‘>workbook to use Sheet: The name or index of the worksheet to read from Program: R # import liblibrary(XLConnect) # load the fileworkbook <- loadWorkbook("data.xlsx", password = "gfg@123") # read the objectdf <- readWorksheet(workbook, "sheet1") # display dfhead(df) Output: Picked R-Excel R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R R - if statement Logistic Regression in R Programming
[ { "code": null, "e": 26487, "s": 26459, "text": "\n18 Jul, 2021" }, { "code": null, "e": 26594, "s": 26487, "text": "In this article, we are going to see how to read password-protected Excel files in R programming language." }, { "code": null, "e": 26613, "s": 26594, "text": "File in use: file" }, { "code": null, "e": 26683, "s": 26613, "text": "Here we will use excel.link package to read the file with a password." }, { "code": null, "e": 26697, "s": 26683, "text": "Installation:" }, { "code": null, "e": 26728, "s": 26697, "text": "install.packages(“excel.link”)" }, { "code": null, "e": 26798, "s": 26728, "text": "xl.read.file() function is used to read Excel files in R programming." }, { "code": null, "e": 26807, "s": 26798, "text": "Syntax: " }, { "code": null, "e": 26853, "s": 26807, "text": "xl.read.file( “file_name”, password = “pass”)" }, { "code": null, "e": 26865, "s": 26853, "text": "Example 1: " }, { "code": null, "e": 26867, "s": 26865, "text": "R" }, { "code": "# import liblibrary(\"excel.link\") # read file with passdf <- xl.read.file(\"data.xlsx\", password = \"gfg@123\") # display dfhead(df)", "e": 26999, "s": 26867, "text": null }, { "code": null, "e": 27007, "s": 26999, "text": "Output:" }, { "code": null, "e": 27233, "s": 27007, "text": "The same module can be used to first unlock the file and then copy its contents onto another so that it can be accessed again without any password. Here we save the file with a password NULL value and save it to another file." }, { "code": null, "e": 27242, "s": 27233, "text": "Syntax: " }, { "code": null, "e": 27326, "s": 27242, "text": "xl.save.file( file.object, “New_file”, password = NULL , write.res.password = NULL)" }, { "code": null, "e": 27335, "s": 27326, "text": "Program:" }, { "code": null, "e": 27337, "s": 27335, "text": "R" }, { "code": "# import liblibrary(\"excel.link\") # read file with passdf <- xl.read.file(\"data.xlsx\", password = \"gfg@123\") # save the df into new filexl.save.file(df, \"Output.xlsx\", password = NULL, write.res.password = NULL) # read file without any passworddf1 <- xl.read.file(\"Output.xlsx\") head(df)", "e": 27641, "s": 27337, "text": null }, { "code": null, "e": 27649, "s": 27641, "text": "Output:" }, { "code": null, "e": 27809, "s": 27649, "text": "Here we will use XLConnect package to read the password-protected file. This package provides comprehensive functionality to read, write and format Excel data." }, { "code": null, "e": 27866, "s": 27809, "text": "loadWorkbook() function loads Microsoft Excel workbooks." }, { "code": null, "e": 27875, "s": 27866, "text": "Syntax: " }, { "code": null, "e": 27910, "s": 27875, "text": "loadWorkbook(filename , password )" }, { "code": null, "e": 27963, "s": 27910, "text": "readWorksheet() function reads data from worksheets." }, { "code": null, "e": 28002, "s": 27963, "text": "Syntax: readWorksheet( object, sheet)." }, { "code": null, "e": 28015, "s": 28002, "text": "Parameters: " }, { "code": null, "e": 28045, "s": 28015, "text": "Object: The ‘>workbook to use" }, { "code": null, "e": 28100, "s": 28045, "text": "Sheet: The name or index of the worksheet to read from" }, { "code": null, "e": 28109, "s": 28100, "text": "Program:" }, { "code": null, "e": 28111, "s": 28109, "text": "R" }, { "code": "# import liblibrary(XLConnect) # load the fileworkbook <- loadWorkbook(\"data.xlsx\", password = \"gfg@123\") # read the objectdf <- readWorksheet(workbook, \"sheet1\") # display dfhead(df)", "e": 28298, "s": 28111, "text": null }, { "code": null, "e": 28306, "s": 28298, "text": "Output:" }, { "code": null, "e": 28313, "s": 28306, "text": "Picked" }, { "code": null, "e": 28321, "s": 28313, "text": "R-Excel" }, { "code": null, "e": 28332, "s": 28321, "text": "R Language" }, { "code": null, "e": 28430, "s": 28332, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28482, "s": 28430, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28517, "s": 28482, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28555, "s": 28517, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28613, "s": 28555, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28656, "s": 28613, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28693, "s": 28656, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28742, "s": 28693, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28768, "s": 28742, "text": "Time Series Analysis in R" }, { "code": null, "e": 28785, "s": 28768, "text": "R - if statement" } ]
How to validate URL in ReactJS? - GeeksforGeeks
15 Mar, 2022 URL (Uniform Resource Locator) is a reference/address to a resource on the Internet. For example, www.geeksforgeeks.com is a URL. The following example shows how to validate the user entered data and check whether it is valid or not using the npm module in the ReactJS application. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the validator module using the following command: npm install validator Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React, { useState } from "react";import validator from 'validator' const App = () => { const [errorMessage, setErrorMessage] = useState('') const validate = (value) => { if (validator.isURL(value)) { setErrorMessage('Is Valid URL') } else { setErrorMessage('Is Not Valid URL') } } return ( <div style={{ marginLeft: '200px', }}> <pre> <h2>Validating URL in ReactJS</h2> <span>Enter URL: </span><input type="text" onChange={(e) => validate(e.target.value)}></input> <br /> <span style={{ fontWeight: 'bold', color: 'red', }}>{errorMessage}</span> </pre> </div> );} export default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: The following will be the output if the user enters an invalid URL as shown below: The following will be the output if the user enters a valid URL as shown below: react-js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using 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 ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25871, "s": 25843, "text": "\n15 Mar, 2022" }, { "code": null, "e": 26154, "s": 25871, "text": "URL (Uniform Resource Locator) is a reference/address to a resource on the Internet. For example, www.geeksforgeeks.com is a URL. The following example shows how to validate the user entered data and check whether it is valid or not using the npm module in the ReactJS application. " }, { "code": null, "e": 26204, "s": 26154, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26268, "s": 26204, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 26300, "s": 26268, "text": "npx create-react-app foldername" }, { "code": null, "e": 26400, "s": 26300, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 26414, "s": 26400, "text": "cd foldername" }, { "code": null, "e": 26520, "s": 26414, "text": "Step 3: After creating the ReactJS application, Install the validator module using the following command:" }, { "code": null, "e": 26542, "s": 26520, "text": "npm install validator" }, { "code": null, "e": 26594, "s": 26542, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26612, "s": 26594, "text": "Project Structure" }, { "code": null, "e": 26741, "s": 26612, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26752, "s": 26741, "text": "Javascript" }, { "code": "import React, { useState } from \"react\";import validator from 'validator' const App = () => { const [errorMessage, setErrorMessage] = useState('') const validate = (value) => { if (validator.isURL(value)) { setErrorMessage('Is Valid URL') } else { setErrorMessage('Is Not Valid URL') } } return ( <div style={{ marginLeft: '200px', }}> <pre> <h2>Validating URL in ReactJS</h2> <span>Enter URL: </span><input type=\"text\" onChange={(e) => validate(e.target.value)}></input> <br /> <span style={{ fontWeight: 'bold', color: 'red', }}>{errorMessage}</span> </pre> </div> );} export default App", "e": 27458, "s": 26752, "text": null }, { "code": null, "e": 27571, "s": 27458, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27581, "s": 27571, "text": "npm start" }, { "code": null, "e": 27589, "s": 27581, "text": "Output:" }, { "code": null, "e": 27672, "s": 27589, "text": "The following will be the output if the user enters an invalid URL as shown below:" }, { "code": null, "e": 27752, "s": 27672, "text": "The following will be the output if the user enters a valid URL as shown below:" }, { "code": null, "e": 27761, "s": 27752, "text": "react-js" }, { "code": null, "e": 27772, "s": 27761, "text": "JavaScript" }, { "code": null, "e": 27789, "s": 27772, "text": "Web Technologies" }, { "code": null, "e": 27887, "s": 27789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27927, "s": 27887, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27972, "s": 27927, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28033, "s": 27972, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28105, "s": 28033, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28157, "s": 28105, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28197, "s": 28157, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28230, "s": 28197, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28275, "s": 28230, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28318, "s": 28275, "text": "How to fetch data from an API in ReactJS ?" } ]
Python - Bernoulli Distribution in Statistics - GeeksforGeeks
31 Dec, 2019 scipy.stats.bernoulli() is a Bernoulli discrete random variable. It is inherited from the of generic methods as an instance of the rv_discrete class. It completes the methods with details specific for this particular distribution. Parameters : x : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : Bernoulli discrete random variable Code #1 : Creating Bernoulli discrete random variable # importing library from scipy.stats import bernoulli numargs = bernoulli .numargs a, b = 0.2, 0.8rv = bernoulli (a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x0000016A4C0FC108 Code #2 : Bernoulli discrete variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = bernoulli .rvs(a, b, size = 10) print ("Random Variates : \n", R) # PDF x = np.linspace(bernoulli.ppf(0.01, a, b), bernoulli.ppf(0.99, a, b), 10)R = bernoulli.ppf(x, 1, 3)print ("\nProbability Distribution : \n", R) Output : Random Variates : [0 0 0 0 0 0 0 0 0 1] Probability Distribution : [ 4. 4. nan nan nan nan nan nan nan nan] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 2)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.ppf(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 = bernoulli.ppf(x, a, b) y2 = bernoulli.pmf(x, a, b) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python-scipy 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": 26071, "s": 26043, "text": "\n31 Dec, 2019" }, { "code": null, "e": 26302, "s": 26071, "text": "scipy.stats.bernoulli() is a Bernoulli discrete random variable. It is inherited from the of generic methods as an instance of the rv_discrete class. It completes the methods with details specific for this particular distribution." }, { "code": null, "e": 26315, "s": 26302, "text": "Parameters :" }, { "code": null, "e": 26567, "s": 26315, "text": "x : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 26612, "s": 26567, "text": "Results : Bernoulli discrete random variable" }, { "code": null, "e": 26666, "s": 26612, "text": "Code #1 : Creating Bernoulli discrete random variable" }, { "code": "# importing library from scipy.stats import bernoulli numargs = bernoulli .numargs a, b = 0.2, 0.8rv = bernoulli (a, b) print (\"RV : \\n\", rv) ", "e": 26819, "s": 26666, "text": null }, { "code": null, "e": 26828, "s": 26819, "text": "Output :" }, { "code": null, "e": 26909, "s": 26828, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x0000016A4C0FC108\n" }, { "code": null, "e": 26976, "s": 26909, "text": "Code #2 : Bernoulli discrete variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = bernoulli .rvs(a, b, size = 10) print (\"Random Variates : \\n\", R) # PDF x = np.linspace(bernoulli.ppf(0.01, a, b), bernoulli.ppf(0.99, a, b), 10)R = bernoulli.ppf(x, 1, 3)print (\"\\nProbability Distribution : \\n\", R) ", "e": 27289, "s": 26976, "text": null }, { "code": null, "e": 27298, "s": 27289, "text": "Output :" }, { "code": null, "e": 27414, "s": 27298, "text": "Random Variates : \n [0 0 0 0 0 0 0 0 0 1]\n\nProbability Distribution : \n [ 4. 4. nan nan nan nan nan nan nan nan]\n\n" }, { "code": null, "e": 27450, "s": 27414, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 2)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.ppf(distribution)) ", "e": 27661, "s": 27450, "text": null }, { "code": null, "e": 27670, "s": 27661, "text": "Output :" }, { "code": null, "e": 28249, "s": 27670, "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": 28288, "s": 28249, "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 = bernoulli.ppf(x, a, b) y2 = bernoulli.pmf(x, a, b) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 28496, "s": 28288, "text": null }, { "code": null, "e": 28505, "s": 28496, "text": "Output :" }, { "code": null, "e": 28534, "s": 28505, "text": "Python scipy-stats-functions" }, { "code": null, "e": 28547, "s": 28534, "text": "Python-scipy" }, { "code": null, "e": 28554, "s": 28547, "text": "Python" }, { "code": null, "e": 28652, "s": 28554, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28670, "s": 28652, "text": "Python Dictionary" }, { "code": null, "e": 28705, "s": 28670, "text": "Read a file line by line in Python" }, { "code": null, "e": 28737, "s": 28705, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28759, "s": 28737, "text": "Enumerate() in Python" }, { "code": null, "e": 28801, "s": 28759, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28831, "s": 28801, "text": "Iterate over a list in Python" }, { "code": null, "e": 28857, "s": 28831, "text": "Python String | replace()" }, { "code": null, "e": 28886, "s": 28857, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28930, "s": 28886, "text": "Reading and Writing to text files in Python" } ]
Application for Internet speed test using pyspeedtest in Python - GeeksforGeeks
05 Sep, 2020 While troubleshooting with Internet speed. We need to first check internet bandwidth speed. So, pyspeedtest module test network bandwidth using Speedtest.net servers. So, before starting we need to install pyspeedtest into your system. Run these code to your command line pip install pyspeedtest Approach: Import pyspeedtest Create object for SpeedTest() Check ping with ping() Check Download speed with download() Check Upload speed with upload() Below is the implementation. Python3 import pyspeedtest test = pyspeedtest.SpeedTest("www.youtube.com") test.ping()test.download()test.upload() Output: 253.4427046775818 16461.88637373227 19425388.307319913 Speed Test Application with Tkinter: This Script implements the above Implementation into a GUI. Python3 import pyspeedtestfrom tkinter import * def Speed_test(): t = pyspeedtest.SpeedTest(e1.get()) myping.set(t.ping()) down.set(t.download()) master = Tk()myping = StringVar()down = StringVar() Label(master, text="Website URL").grid(row=0, sticky=W)Label(master, text="Ping Result:").grid(row=3, sticky=W)Label(master, text="Download Result:").grid(row=4, sticky=W) result = Label(master, text="", textvariable=myping, ).grid(row=3, column=1, sticky=W) result2 = Label(master, text="", textvariable=down, ).grid(row=4, column=1, sticky=W) e1 = Entry(master)e1.grid(row=0, column=1)b = Button(master, text="Cheak", command=Speed_test)b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) mainloop() Output: python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary 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 Convert integer to string in Python
[ { "code": null, "e": 25783, "s": 25755, "text": "\n05 Sep, 2020" }, { "code": null, "e": 26055, "s": 25783, "text": "While troubleshooting with Internet speed. We need to first check internet bandwidth speed. So, pyspeedtest module test network bandwidth using Speedtest.net servers. So, before starting we need to install pyspeedtest into your system. Run these code to your command line" }, { "code": null, "e": 26079, "s": 26055, "text": "pip install pyspeedtest" }, { "code": null, "e": 26089, "s": 26079, "text": "Approach:" }, { "code": null, "e": 26108, "s": 26089, "text": "Import pyspeedtest" }, { "code": null, "e": 26138, "s": 26108, "text": "Create object for SpeedTest()" }, { "code": null, "e": 26161, "s": 26138, "text": "Check ping with ping()" }, { "code": null, "e": 26198, "s": 26161, "text": "Check Download speed with download()" }, { "code": null, "e": 26231, "s": 26198, "text": "Check Upload speed with upload()" }, { "code": null, "e": 26260, "s": 26231, "text": "Below is the implementation." }, { "code": null, "e": 26268, "s": 26260, "text": "Python3" }, { "code": "import pyspeedtest test = pyspeedtest.SpeedTest(\"www.youtube.com\") test.ping()test.download()test.upload()", "e": 26379, "s": 26268, "text": null }, { "code": null, "e": 26387, "s": 26379, "text": "Output:" }, { "code": null, "e": 26443, "s": 26387, "text": "253.4427046775818\n16461.88637373227\n19425388.307319913\n" }, { "code": null, "e": 26540, "s": 26443, "text": "Speed Test Application with Tkinter: This Script implements the above Implementation into a GUI." }, { "code": null, "e": 26548, "s": 26540, "text": "Python3" }, { "code": "import pyspeedtestfrom tkinter import * def Speed_test(): t = pyspeedtest.SpeedTest(e1.get()) myping.set(t.ping()) down.set(t.download()) master = Tk()myping = StringVar()down = StringVar() Label(master, text=\"Website URL\").grid(row=0, sticky=W)Label(master, text=\"Ping Result:\").grid(row=3, sticky=W)Label(master, text=\"Download Result:\").grid(row=4, sticky=W) result = Label(master, text=\"\", textvariable=myping, ).grid(row=3, column=1, sticky=W) result2 = Label(master, text=\"\", textvariable=down, ).grid(row=4, column=1, sticky=W) e1 = Entry(master)e1.grid(row=0, column=1)b = Button(master, text=\"Cheak\", command=Speed_test)b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) mainloop()", "e": 27304, "s": 26548, "text": null }, { "code": null, "e": 27312, "s": 27304, "text": "Output:" }, { "code": null, "e": 27327, "s": 27312, "text": "python-utility" }, { "code": null, "e": 27334, "s": 27327, "text": "Python" }, { "code": null, "e": 27432, "s": 27334, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27450, "s": 27432, "text": "Python Dictionary" }, { "code": null, "e": 27482, "s": 27450, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27504, "s": 27482, "text": "Enumerate() in Python" }, { "code": null, "e": 27546, "s": 27504, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27576, "s": 27546, "text": "Iterate over a list in Python" }, { "code": null, "e": 27602, "s": 27576, "text": "Python String | replace()" }, { "code": null, "e": 27631, "s": 27602, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27675, "s": 27631, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27712, "s": 27675, "text": "Create a Pandas DataFrame from Lists" } ]
Why is a[i] == i[a] in C/C++ arrays? - GeeksforGeeks
01 Jul, 2017 The definition of [] subscript operator operator in C, according to (C99, 6.5.2.1p2), is that E1[E2] is identical to (*((E1)+(E2))) Compilers use pointer arithmetic internally to access array elements. And because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero). Therefore, a[b] is defined as : a[b] == *(a + b) So will evaluate to a[8] == *(a + 8) Here, a is a pointer to the first element of the array and a[8] is the value of an elements which is 8 elements further from a, which is the same as *(a + 8) and 8[a] will evaluate to following which means both are same. 8[a] == *(8 + a) So by addition commutative property, a[8] == 8[a] Sample program showing above results : // C program to illustrate// a[i] == i[a] in arrays #include <stdio.h>int main(){ int a[] = {1, 2, 3, 4, 5, 6, 7}; printf("a[5] is %d\n", a[5]); printf("5[a] is %d\n", 5[a]); return 0;} Output: a[5] is 6 5[a] is 6 This article is contributed by Mandeep Singh. 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. C Language C++ CPP 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 Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25479, "s": 25451, "text": "\n01 Jul, 2017" }, { "code": null, "e": 25573, "s": 25479, "text": "The definition of [] subscript operator operator in C, according to (C99, 6.5.2.1p2), is that" }, { "code": null, "e": 25612, "s": 25573, "text": " E1[E2] is identical to (*((E1)+(E2)))" }, { "code": null, "e": 25934, "s": 25612, "text": "Compilers use pointer arithmetic internally to access array elements. And because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero)." }, { "code": null, "e": 25966, "s": 25934, "text": "Therefore, a[b] is defined as :" }, { "code": null, "e": 25984, "s": 25966, "text": "a[b] == *(a + b)\n" }, { "code": null, "e": 26004, "s": 25984, "text": "So will evaluate to" }, { "code": null, "e": 26022, "s": 26004, "text": "a[8] == *(a + 8)\n" }, { "code": null, "e": 26243, "s": 26022, "text": "Here, a is a pointer to the first element of the array and a[8] is the value of an elements which is 8 elements further from a, which is the same as *(a + 8) and 8[a] will evaluate to following which means both are same." }, { "code": null, "e": 26261, "s": 26243, "text": "8[a] == *(8 + a)\n" }, { "code": null, "e": 26311, "s": 26261, "text": "So by addition commutative property, a[8] == 8[a]" }, { "code": null, "e": 26350, "s": 26311, "text": "Sample program showing above results :" }, { "code": "// C program to illustrate// a[i] == i[a] in arrays #include <stdio.h>int main(){ int a[] = {1, 2, 3, 4, 5, 6, 7}; printf(\"a[5] is %d\\n\", a[5]); printf(\"5[a] is %d\\n\", 5[a]); return 0;}", "e": 26548, "s": 26350, "text": null }, { "code": null, "e": 26556, "s": 26548, "text": "Output:" }, { "code": null, "e": 26577, "s": 26556, "text": "a[5] is 6\n5[a] is 6\n" }, { "code": null, "e": 26878, "s": 26577, "text": "This article is contributed by Mandeep Singh. 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": 27003, "s": 26878, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27014, "s": 27003, "text": "C Language" }, { "code": null, "e": 27018, "s": 27014, "text": "C++" }, { "code": null, "e": 27022, "s": 27018, "text": "CPP" }, { "code": null, "e": 27120, "s": 27022, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27158, "s": 27120, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27184, "s": 27158, "text": "Exception Handling in C++" }, { "code": null, "e": 27204, "s": 27184, "text": "Multithreading in C" }, { "code": null, "e": 27226, "s": 27204, "text": "'this' pointer in C++" }, { "code": null, "e": 27267, "s": 27226, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27285, "s": 27267, "text": "Vector in C++ STL" }, { "code": null, "e": 27331, "s": 27285, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 27350, "s": 27331, "text": "Inheritance in C++" }, { "code": null, "e": 27393, "s": 27350, "text": "Map in C++ Standard Template Library (STL)" } ]
Identifying handwritten digits using Logistic Regression in PyTorch - GeeksforGeeks
12 Aug, 2021 Logistic Regression is a very commonly used statistical method that allows us to predict a binary output from a set of independent variables. The various properties of logistic regression and its Python implementation have been covered in this article previously. Now, we shall find out how to implement this in PyTorch, a very popular deep learning library that is being developed by Facebook.Now, we shall see how to classify handwritten digits from the MNIST dataset using Logistic Regression in PyTorch. Firstly, you will need to install PyTorch into your Python environment. The easiest way to do this is to use the pip or conda tool. Visit pytorch.org and install the version of your Python interpreter and the package manager that you would like to use.With PyTorch installed, let us now have a look at the code. Write the three lines given below to import the required library functions and objects. Python3 import torchimport torch.nn as nnimport torchvision.datasets as dsetsimport torchvision.transforms as transformsfrom torch.autograd import Variable Here, the torch.nn module contains the code required for the model, torchvision.datasets contain the MNIST dataset. It contains the dataset of handwritten digits that we shall be using here. The torchvision.transforms module contains various methods to transform objects into others. Here, we shall be using it to transform from images to PyTorch tensors. Also, the torch.autograd module contains the Variable class amongst others, which will be used by us while defining our tensors.Next, we shall download and load the dataset to memory. Python3 # MNIST Dataset (Images and Labels)train_dataset = dsets.MNIST(root ='./data', train = True, transform = transforms.ToTensor(), download = True) test_dataset = dsets.MNIST(root ='./data', train = False, transform = transforms.ToTensor()) # Dataset Loader (Input Pipeline)train_loader = torch.utils.data.DataLoader(dataset = train_dataset, batch_size = batch_size, shuffle = True) test_loader = torch.utils.data.DataLoader(dataset = test_dataset, batch_size = batch_size, shuffle = False) Now, we shall define our hyperparameters. Python3 # Hyper Parameters input_size = 784num_classes = 10num_epochs = 5batch_size = 100learning_rate = 0.001 In our dataset, the image size is 28*28. Thus, our input size is 784. Also, 10 digits are present in this and hence, we can have 10 different outputs. Thus, we set num_classes as 10. Also, we shall train five times on the entire dataset. Finally, we will train in small batches of 100 images each so as to prevent the crashing of the program due to memory overflow.After this, we shall be defining our model as below. Here, we shall initialize our model as a subclass of torch.nn.Module and then define the forward pass. In the code that we are writing, the softmax is internally calculated during each forward pass and hence we do not need to specify it inside the forward() function. Python3 class LogisticRegression(nn.Module): def __init__(self, input_size, num_classes): super(LogisticRegression, self).__init__() self.linear = nn.Linear(input_size, num_classes) def forward(self, x): out = self.linear(x) return out Having defined our class, now we instantiate an object for the same. Python3 model = LogisticRegression(input_size, num_classes) Next, we set our loss function and the optimizer. Here, we shall be using the cross-entropy loss and for the optimizer, we shall be using the stochastic gradient descent algorithm with a learning rate of 0.001 as defined in the hyperparameter above. Python3 criterion = nn.CrossEntropyLoss()optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate) Now, we shall start the training. Here, we shall be performing the following tasks: Reset all gradients to 0.Make a forward pass.Calculate the loss.Perform backpropagation.Update all weights. Reset all gradients to 0. Make a forward pass. Calculate the loss. Perform backpropagation. Update all weights. Python3 # Training the Modelfor epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): images = Variable(images.view(-1, 28 * 28)) labels = Variable(labels) # Forward + Backward + Optimize optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() if (i + 1) % 100 == 0: print('Epoch: [% d/% d], Step: [% d/% d], Loss: %.4f' % (epoch + 1, num_epochs, i + 1, len(train_dataset) // batch_size, loss.data[0])) Finally, we shall be testing out the model by using the following code. Python3 # Test the Modelcorrect = 0total = 0for images, labels in test_loader: images = Variable(images.view(-1, 28 * 28)) outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum() print('Accuracy of the model on the 10000 test images: % d %%' % ( 100 * correct / total)) Assuming that you performed all steps correctly, you will get an accuracy of 82%, which is far off from today’s state-of-the-art model, which uses a special type of neural network architecture. For your reference, you can find the entire code for this article below: Python3 import torchimport torch.nn as nnimport torchvision.datasets as dsetsimport torchvision.transforms as transformsfrom torch.autograd import Variable # MNIST Dataset (Images and Labels)train_dataset = dsets.MNIST(root ='./data', train = True, transform = transforms.ToTensor(), download = True) test_dataset = dsets.MNIST(root ='./data', train = False, transform = transforms.ToTensor()) # Dataset Loader (Input Pipeline)train_loader = torch.utils.data.DataLoader(dataset = train_dataset, batch_size = batch_size, shuffle = True) test_loader = torch.utils.data.DataLoader(dataset = test_dataset, batch_size = batch_size, shuffle = False) # Hyper Parametersinput_size = 784num_classes = 10num_epochs = 5batch_size = 100learning_rate = 0.001 # Modelclass LogisticRegression(nn.Module): def __init__(self, input_size, num_classes): super(LogisticRegression, self).__init__() self.linear = nn.Linear(input_size, num_classes) def forward(self, x): out = self.linear(x) return out model = LogisticRegression(input_size, num_classes) # Loss and Optimizer# Softmax is internally computed.# Set parameters to be updated.criterion = nn.CrossEntropyLoss()optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate) # Training the Modelfor epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): images = Variable(images.view(-1, 28 * 28)) labels = Variable(labels) # Forward + Backward + Optimize optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() if (i + 1) % 100 == 0: print('Epoch: [% d/% d], Step: [% d/% d], Loss: %.4f' % (epoch + 1, num_epochs, i + 1, len(train_dataset) // batch_size, loss.data[0])) # Test the Modelcorrect = 0total = 0for images, labels in test_loader: images = Variable(images.view(-1, 28 * 28)) outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum() print('Accuracy of the model on the 10000 test images: % d %%' % ( 100 * correct / total)) References: PyTorchZeroToAll yunjey on Github punamsingh628700 rajeev0719singh Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Activation functions in Neural Networks Introduction to Recurrent Neural Network Decision Tree Introduction with example Support Vector Machine Algorithm Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25533, "s": 25505, "text": "\n12 Aug, 2021" }, { "code": null, "e": 26441, "s": 25533, "text": "Logistic Regression is a very commonly used statistical method that allows us to predict a binary output from a set of independent variables. The various properties of logistic regression and its Python implementation have been covered in this article previously. Now, we shall find out how to implement this in PyTorch, a very popular deep learning library that is being developed by Facebook.Now, we shall see how to classify handwritten digits from the MNIST dataset using Logistic Regression in PyTorch. Firstly, you will need to install PyTorch into your Python environment. The easiest way to do this is to use the pip or conda tool. Visit pytorch.org and install the version of your Python interpreter and the package manager that you would like to use.With PyTorch installed, let us now have a look at the code. Write the three lines given below to import the required library functions and objects." }, { "code": null, "e": 26449, "s": 26441, "text": "Python3" }, { "code": "import torchimport torch.nn as nnimport torchvision.datasets as dsetsimport torchvision.transforms as transformsfrom torch.autograd import Variable", "e": 26597, "s": 26449, "text": null }, { "code": null, "e": 27137, "s": 26597, "text": "Here, the torch.nn module contains the code required for the model, torchvision.datasets contain the MNIST dataset. It contains the dataset of handwritten digits that we shall be using here. The torchvision.transforms module contains various methods to transform objects into others. Here, we shall be using it to transform from images to PyTorch tensors. Also, the torch.autograd module contains the Variable class amongst others, which will be used by us while defining our tensors.Next, we shall download and load the dataset to memory." }, { "code": null, "e": 27145, "s": 27137, "text": "Python3" }, { "code": "# MNIST Dataset (Images and Labels)train_dataset = dsets.MNIST(root ='./data', train = True, transform = transforms.ToTensor(), download = True) test_dataset = dsets.MNIST(root ='./data', train = False, transform = transforms.ToTensor()) # Dataset Loader (Input Pipeline)train_loader = torch.utils.data.DataLoader(dataset = train_dataset, batch_size = batch_size, shuffle = True) test_loader = torch.utils.data.DataLoader(dataset = test_dataset, batch_size = batch_size, shuffle = False)", "e": 27943, "s": 27145, "text": null }, { "code": null, "e": 27985, "s": 27943, "text": "Now, we shall define our hyperparameters." }, { "code": null, "e": 27993, "s": 27985, "text": "Python3" }, { "code": "# Hyper Parameters input_size = 784num_classes = 10num_epochs = 5batch_size = 100learning_rate = 0.001", "e": 28096, "s": 27993, "text": null }, { "code": null, "e": 28782, "s": 28096, "text": "In our dataset, the image size is 28*28. Thus, our input size is 784. Also, 10 digits are present in this and hence, we can have 10 different outputs. Thus, we set num_classes as 10. Also, we shall train five times on the entire dataset. Finally, we will train in small batches of 100 images each so as to prevent the crashing of the program due to memory overflow.After this, we shall be defining our model as below. Here, we shall initialize our model as a subclass of torch.nn.Module and then define the forward pass. In the code that we are writing, the softmax is internally calculated during each forward pass and hence we do not need to specify it inside the forward() function." }, { "code": null, "e": 28790, "s": 28782, "text": "Python3" }, { "code": "class LogisticRegression(nn.Module): def __init__(self, input_size, num_classes): super(LogisticRegression, self).__init__() self.linear = nn.Linear(input_size, num_classes) def forward(self, x): out = self.linear(x) return out", "e": 29054, "s": 28790, "text": null }, { "code": null, "e": 29123, "s": 29054, "text": "Having defined our class, now we instantiate an object for the same." }, { "code": null, "e": 29131, "s": 29123, "text": "Python3" }, { "code": "model = LogisticRegression(input_size, num_classes)", "e": 29183, "s": 29131, "text": null }, { "code": null, "e": 29433, "s": 29183, "text": "Next, we set our loss function and the optimizer. Here, we shall be using the cross-entropy loss and for the optimizer, we shall be using the stochastic gradient descent algorithm with a learning rate of 0.001 as defined in the hyperparameter above." }, { "code": null, "e": 29441, "s": 29433, "text": "Python3" }, { "code": "criterion = nn.CrossEntropyLoss()optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)", "e": 29542, "s": 29441, "text": null }, { "code": null, "e": 29626, "s": 29542, "text": "Now, we shall start the training. Here, we shall be performing the following tasks:" }, { "code": null, "e": 29734, "s": 29626, "text": "Reset all gradients to 0.Make a forward pass.Calculate the loss.Perform backpropagation.Update all weights." }, { "code": null, "e": 29760, "s": 29734, "text": "Reset all gradients to 0." }, { "code": null, "e": 29781, "s": 29760, "text": "Make a forward pass." }, { "code": null, "e": 29801, "s": 29781, "text": "Calculate the loss." }, { "code": null, "e": 29826, "s": 29801, "text": "Perform backpropagation." }, { "code": null, "e": 29846, "s": 29826, "text": "Update all weights." }, { "code": null, "e": 29854, "s": 29846, "text": "Python3" }, { "code": "# Training the Modelfor epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): images = Variable(images.view(-1, 28 * 28)) labels = Variable(labels) # Forward + Backward + Optimize optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() if (i + 1) % 100 == 0: print('Epoch: [% d/% d], Step: [% d/% d], Loss: %.4f' % (epoch + 1, num_epochs, i + 1, len(train_dataset) // batch_size, loss.data[0]))", "e": 30450, "s": 29854, "text": null }, { "code": null, "e": 30522, "s": 30450, "text": "Finally, we shall be testing out the model by using the following code." }, { "code": null, "e": 30530, "s": 30522, "text": "Python3" }, { "code": "# Test the Modelcorrect = 0total = 0for images, labels in test_loader: images = Variable(images.view(-1, 28 * 28)) outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum() print('Accuracy of the model on the 10000 test images: % d %%' % ( 100 * correct / total))", "e": 30892, "s": 30530, "text": null }, { "code": null, "e": 31159, "s": 30892, "text": "Assuming that you performed all steps correctly, you will get an accuracy of 82%, which is far off from today’s state-of-the-art model, which uses a special type of neural network architecture. For your reference, you can find the entire code for this article below:" }, { "code": null, "e": 31167, "s": 31159, "text": "Python3" }, { "code": "import torchimport torch.nn as nnimport torchvision.datasets as dsetsimport torchvision.transforms as transformsfrom torch.autograd import Variable # MNIST Dataset (Images and Labels)train_dataset = dsets.MNIST(root ='./data', train = True, transform = transforms.ToTensor(), download = True) test_dataset = dsets.MNIST(root ='./data', train = False, transform = transforms.ToTensor()) # Dataset Loader (Input Pipeline)train_loader = torch.utils.data.DataLoader(dataset = train_dataset, batch_size = batch_size, shuffle = True) test_loader = torch.utils.data.DataLoader(dataset = test_dataset, batch_size = batch_size, shuffle = False) # Hyper Parametersinput_size = 784num_classes = 10num_epochs = 5batch_size = 100learning_rate = 0.001 # Modelclass LogisticRegression(nn.Module): def __init__(self, input_size, num_classes): super(LogisticRegression, self).__init__() self.linear = nn.Linear(input_size, num_classes) def forward(self, x): out = self.linear(x) return out model = LogisticRegression(input_size, num_classes) # Loss and Optimizer# Softmax is internally computed.# Set parameters to be updated.criterion = nn.CrossEntropyLoss()optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate) # Training the Modelfor epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): images = Variable(images.view(-1, 28 * 28)) labels = Variable(labels) # Forward + Backward + Optimize optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() if (i + 1) % 100 == 0: print('Epoch: [% d/% d], Step: [% d/% d], Loss: %.4f' % (epoch + 1, num_epochs, i + 1, len(train_dataset) // batch_size, loss.data[0])) # Test the Modelcorrect = 0total = 0for images, labels in test_loader: images = Variable(images.view(-1, 28 * 28)) outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum() print('Accuracy of the model on the 10000 test images: % d %%' % ( 100 * correct / total))", "e": 33684, "s": 31167, "text": null }, { "code": null, "e": 33696, "s": 33684, "text": "References:" }, { "code": null, "e": 33713, "s": 33696, "text": "PyTorchZeroToAll" }, { "code": null, "e": 33730, "s": 33713, "text": "yunjey on Github" }, { "code": null, "e": 33749, "s": 33732, "text": "punamsingh628700" }, { "code": null, "e": 33765, "s": 33749, "text": "rajeev0719singh" }, { "code": null, "e": 33782, "s": 33765, "text": "Machine Learning" }, { "code": null, "e": 33789, "s": 33782, "text": "Python" }, { "code": null, "e": 33806, "s": 33789, "text": "Machine Learning" }, { "code": null, "e": 33904, "s": 33806, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33918, "s": 33904, "text": "Decision Tree" }, { "code": null, "e": 33958, "s": 33918, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 33999, "s": 33958, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 34039, "s": 33999, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 34072, "s": 34039, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 34100, "s": 34072, "text": "Read JSON file using Python" }, { "code": null, "e": 34150, "s": 34100, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 34172, "s": 34150, "text": "Python map() function" } ]
HTML | DOM Form Object - GeeksforGeeks
31 Jan, 2019 The Form Object in HTML DOM is used to represent the HTML < form > element.This tag is used to set or get the properties of < form > element. This element can be accessed by using getElementById() method. Syntax: document.getElementById("Form_ID"); This Form_ID is assigned to HTML < form > element. Example-1: Returning “form id” using document.getElementById(“myForm”).id; <!DOCTYPE html><html> <head> <title> HTML DOM Form Object </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>DOM Form Object</h2> <form align="center" id="myForm" method="GET" target="_blank" action="/action_page.php"> First name: <br> <input type="text" name="fname" placeholder="FName"> <br> <br> Last name: <br> <input type="text" name="lname" placeholder="LName"> <br> <br> </form> <button onclick="myGeeks()"> Submit </button> <p id="Geek_p" style="color:green; font-size:30px;"> </p> <script> function myGeeks() { // Accessing form element. var txt = document.getElementById( "myForm").id; document.getElementById( "Geek_p").innerHTML = txt; } </script></body> </html> Output Before click on the button: After click on the button: Example-2: Returning the value of the target attribute in the form using document.getElementById(“Form_ID”).target;. <!DOCTYPE html><html> <head> <title> HTML DOM Form Object </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>DOM Form Object</h2> <form align="center" id="myForm" method="GET" target="_blank" action="/action_page.php"> First name: <br> <input type="text" name="fname" placeholder="FName"> <br> <br> Last name: <br> <input type="text" name="lname" placeholder="LName"> <br> <br> </form> <button onclick="myGeeks()"> Submit </button> <p id="Geek_p" style="color:green; font-size:30px;"> </p> <script> function myGeeks() { // Accessing form. var txt = document.getElementById( "myForm").target; document.getElementById( "Geek_p").innerHTML = txt; } </script></body> </html> Output Before click on the button: After click on the button: Example-3: Returning the number of elements in the form using document.getElementById(“Form_ID”).length;. <!DOCTYPE html><html> <head> <title> HTML DOM Form Object </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>DOM Form Object</h2> <form align="center" id="myForm" method="GET" target="_blank" action="/action_page.php"> First name: <br> <input type="text" name="fname" placeholder="FName"> <br> <br> Last name: <br> <input type="text" name="lname" placeholder="LName"> <br> <br> </form> <button onclick="myGeeks()"> Submit </button> <p id="Geek_p" style="color:green; font-size:30px;"> </p> <script> function myGeeks() { //Accessing form element. var txt = document.getElementById( "myForm").length; document.getElementById( "Geek_p").innerHTML = txt; } </script></body> </html> Output Before click on the button: After click on the button: Supported Browsers: Google Chrome Mozilla Firefox Edge Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property 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": 25319, "s": 25291, "text": "\n31 Jan, 2019" }, { "code": null, "e": 25524, "s": 25319, "text": "The Form Object in HTML DOM is used to represent the HTML < form > element.This tag is used to set or get the properties of < form > element. This element can be accessed by using getElementById() method." }, { "code": null, "e": 25532, "s": 25524, "text": "Syntax:" }, { "code": null, "e": 25569, "s": 25532, "text": "document.getElementById(\"Form_ID\");\n" }, { "code": null, "e": 25620, "s": 25569, "text": "This Form_ID is assigned to HTML < form > element." }, { "code": null, "e": 25695, "s": 25620, "text": "Example-1: Returning “form id” using document.getElementById(“myForm”).id;" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Form Object </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>DOM Form Object</h2> <form align=\"center\" id=\"myForm\" method=\"GET\" target=\"_blank\" action=\"/action_page.php\"> First name: <br> <input type=\"text\" name=\"fname\" placeholder=\"FName\"> <br> <br> Last name: <br> <input type=\"text\" name=\"lname\" placeholder=\"LName\"> <br> <br> </form> <button onclick=\"myGeeks()\"> Submit </button> <p id=\"Geek_p\" style=\"color:green; font-size:30px;\"> </p> <script> function myGeeks() { // Accessing form element. var txt = document.getElementById( \"myForm\").id; document.getElementById( \"Geek_p\").innerHTML = txt; } </script></body> </html>", "e": 26769, "s": 25695, "text": null }, { "code": null, "e": 26776, "s": 26769, "text": "Output" }, { "code": null, "e": 26804, "s": 26776, "text": "Before click on the button:" }, { "code": null, "e": 26831, "s": 26804, "text": "After click on the button:" }, { "code": null, "e": 26948, "s": 26831, "text": "Example-2: Returning the value of the target attribute in the form using document.getElementById(“Form_ID”).target;." }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Form Object </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>DOM Form Object</h2> <form align=\"center\" id=\"myForm\" method=\"GET\" target=\"_blank\" action=\"/action_page.php\"> First name: <br> <input type=\"text\" name=\"fname\" placeholder=\"FName\"> <br> <br> Last name: <br> <input type=\"text\" name=\"lname\" placeholder=\"LName\"> <br> <br> </form> <button onclick=\"myGeeks()\"> Submit </button> <p id=\"Geek_p\" style=\"color:green; font-size:30px;\"> </p> <script> function myGeeks() { // Accessing form. var txt = document.getElementById( \"myForm\").target; document.getElementById( \"Geek_p\").innerHTML = txt; } </script></body> </html>", "e": 28042, "s": 26948, "text": null }, { "code": null, "e": 28049, "s": 28042, "text": "Output" }, { "code": null, "e": 28077, "s": 28049, "text": "Before click on the button:" }, { "code": null, "e": 28104, "s": 28077, "text": "After click on the button:" }, { "code": null, "e": 28210, "s": 28104, "text": "Example-3: Returning the number of elements in the form using document.getElementById(“Form_ID”).length;." }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Form Object </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>DOM Form Object</h2> <form align=\"center\" id=\"myForm\" method=\"GET\" target=\"_blank\" action=\"/action_page.php\"> First name: <br> <input type=\"text\" name=\"fname\" placeholder=\"FName\"> <br> <br> Last name: <br> <input type=\"text\" name=\"lname\" placeholder=\"LName\"> <br> <br> </form> <button onclick=\"myGeeks()\"> Submit </button> <p id=\"Geek_p\" style=\"color:green; font-size:30px;\"> </p> <script> function myGeeks() { //Accessing form element. var txt = document.getElementById( \"myForm\").length; document.getElementById( \"Geek_p\").innerHTML = txt; } </script></body> </html>", "e": 29289, "s": 28210, "text": null }, { "code": null, "e": 29296, "s": 29289, "text": "Output" }, { "code": null, "e": 29324, "s": 29296, "text": "Before click on the button:" }, { "code": null, "e": 29351, "s": 29324, "text": "After click on the button:" }, { "code": null, "e": 29371, "s": 29351, "text": "Supported Browsers:" }, { "code": null, "e": 29385, "s": 29371, "text": "Google Chrome" }, { "code": null, "e": 29401, "s": 29385, "text": "Mozilla Firefox" }, { "code": null, "e": 29406, "s": 29401, "text": "Edge" }, { "code": null, "e": 29413, "s": 29406, "text": "Safari" }, { "code": null, "e": 29419, "s": 29413, "text": "Opera" }, { "code": null, "e": 29556, "s": 29419, "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": 29565, "s": 29556, "text": "HTML-DOM" }, { "code": null, "e": 29572, "s": 29565, "text": "Picked" }, { "code": null, "e": 29577, "s": 29572, "text": "HTML" }, { "code": null, "e": 29594, "s": 29577, "text": "Web Technologies" }, { "code": null, "e": 29599, "s": 29594, "text": "HTML" }, { "code": null, "e": 29697, "s": 29599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29759, "s": 29697, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29809, "s": 29759, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29857, "s": 29809, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29917, "s": 29857, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29970, "s": 29917, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 30010, "s": 29970, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30043, "s": 30010, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30088, "s": 30043, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30131, "s": 30088, "text": "How to fetch data from an API in ReactJS ?" } ]
How to download File Using JavaScript/jQuery ? - GeeksforGeeks
03 Aug, 2021 Suppose you want to download a file when you click on a link. For downloading the file, we mentioned here to implementation as well as folder structure where you can see the file location. Approach: Create an anchor tag link on the normal HTML page. We want to download a file when we click on an anchor tag link(Download this file). html <!DOCTYPE html><html> <head> <title> Download File Using JavaScript/jQuery </title></head> <body> <h1> Download File Using JavaScript/jQuery </h1> <a id="link" href="#"> Download this file </a></body> </html> Provide with the below JavaScript Code: $(document).ready(function () { $("#link").click(function (e) { e.preventDefault(); window.location.href = "File/randomfile.docx"; }); }); // Note: url= your file path Note: Replace the above URL with your file path. Implementation and Folder structure is as shown below. Example: html <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script></head> <body> <h1> Download File Using JavaScript/jQuery </h1> <h3> For Downloading, Click on the below link. </h3> <a id="link" href="no-script.html"> Download this file </a> <script> $(document).ready(function () { $("#link").click(function (e) { e.preventDefault(); window.location.href = "File/randomfile.docx"; }); }); </script></body> </html> Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. JavaScript-Misc jQuery-Misc Picked JavaScript JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? 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 fetch data from JSON file and display in HTML table using jQuery ? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 26630, "s": 26602, "text": "\n03 Aug, 2021" }, { "code": null, "e": 26819, "s": 26630, "text": "Suppose you want to download a file when you click on a link. For downloading the file, we mentioned here to implementation as well as folder structure where you can see the file location." }, { "code": null, "e": 26829, "s": 26819, "text": "Approach:" }, { "code": null, "e": 26964, "s": 26829, "text": "Create an anchor tag link on the normal HTML page. We want to download a file when we click on an anchor tag link(Download this file)." }, { "code": null, "e": 26969, "s": 26964, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Download File Using JavaScript/jQuery </title></head> <body> <h1> Download File Using JavaScript/jQuery </h1> <a id=\"link\" href=\"#\"> Download this file </a></body> </html>", "e": 27238, "s": 26969, "text": null }, { "code": null, "e": 27278, "s": 27238, "text": "Provide with the below JavaScript Code:" }, { "code": null, "e": 27480, "s": 27278, "text": "$(document).ready(function () {\n $(\"#link\").click(function (e) {\n e.preventDefault();\n window.location.href = \"File/randomfile.docx\";\n });\n});\n\n// Note: url= your file path\n" }, { "code": null, "e": 27584, "s": 27480, "text": "Note: Replace the above URL with your file path. Implementation and Folder structure is as shown below." }, { "code": null, "e": 27593, "s": 27584, "text": "Example:" }, { "code": null, "e": 27598, "s": 27593, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"> </script></head> <body> <h1> Download File Using JavaScript/jQuery </h1> <h3> For Downloading, Click on the below link. </h3> <a id=\"link\" href=\"no-script.html\"> Download this file </a> <script> $(document).ready(function () { $(\"#link\").click(function (e) { e.preventDefault(); window.location.href = \"File/randomfile.docx\"; }); }); </script></body> </html>", "e": 28258, "s": 27598, "text": null }, { "code": null, "e": 28266, "s": 28258, "text": "Output:" }, { "code": null, "e": 28534, "s": 28266, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 28550, "s": 28534, "text": "JavaScript-Misc" }, { "code": null, "e": 28562, "s": 28550, "text": "jQuery-Misc" }, { "code": null, "e": 28569, "s": 28562, "text": "Picked" }, { "code": null, "e": 28580, "s": 28569, "text": "JavaScript" }, { "code": null, "e": 28587, "s": 28580, "text": "JQuery" }, { "code": null, "e": 28604, "s": 28587, "text": "Web Technologies" }, { "code": null, "e": 28702, "s": 28604, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28742, "s": 28702, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28803, "s": 28742, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28844, "s": 28803, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28866, "s": 28844, "text": "JavaScript | Promises" }, { "code": null, "e": 28920, "s": 28866, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28966, "s": 28920, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 28995, "s": 28966, "text": "Form validation using jQuery" }, { "code": null, "e": 29058, "s": 28995, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 29132, "s": 29058, "text": "How to fetch data from JSON file and display in HTML table using jQuery ?" } ]
rdiff-backup Command in Linux with Examples - GeeksforGeeks
05 Aug, 2021 rdiff-backup is a command in Linux that is used to backup files over server or local machine and even has a feature of incremental backup which means it only contains those files that have been modified or changed. Its source code is written in python and hence it needs a python interpreter to function. It comes packed with many features like incremental and mirror backup and even it allows you to backup files over a network through SSH To install it use the following commands as per your Linux distribution. In case of Debian/Ubuntu $sudo apt-get install librsync-dev rdiff-backup In case of CentOS/RedHat $wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-9.noarch.rpm $rpm -ivh epel-release-7-9.noarch.rpm $yum install librsync rdiff-backup In case of Fedora OS $yum install librsync rdiff-backup 1. To backup a folder. $rdiff-backup ./backup_folder ./backup_folder.backup This will create a backup file of the folder. 2. To exclude a file from the backup folder. $rdiff-backup --exclude-filelist backup_folder/hii ./backup_folder/ backup_file.backup This will exclude the specified file from the backup file. 3. To exclude files of a type. $rdiff-backup --exclude '**ii' backup_folder/ backup_file.backup/ Here it will exclude all files with the suffix “ii”. 4. To list the modifications or increments. $rdiff-backup -l backup_file.backup This will list all the changes done so far in the backup file. 5. To restore a file from its previous versions. $rdiff-backup backup_file.backup/rdiff-backup-data/increments/hii.2020-05-17T13\:52\:57+05\:30.diff.gz restore/hii This will restore the file when it was previously backed up 6.To include specific type of files and exclude everything else. $rdiff-backup --include "**ii" --exclude '**' backup_folder/ backup_file.backup/ This will include only those files that have the suffix “ii”. surinderdawra388 linux-command Linux-file-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples Docker - COPY Instruction mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n05 Aug, 2021" }, { "code": null, "e": 26093, "s": 25651, "text": "rdiff-backup is a command in Linux that is used to backup files over server or local machine and even has a feature of incremental backup which means it only contains those files that have been modified or changed. Its source code is written in python and hence it needs a python interpreter to function. It comes packed with many features like incremental and mirror backup and even it allows you to backup files over a network through SSH " }, { "code": null, "e": 26167, "s": 26093, "text": "To install it use the following commands as per your Linux distribution. " }, { "code": null, "e": 26194, "s": 26167, "text": "In case of Debian/Ubuntu " }, { "code": null, "e": 26242, "s": 26194, "text": "$sudo apt-get install librsync-dev rdiff-backup" }, { "code": null, "e": 26269, "s": 26242, "text": "In case of CentOS/RedHat " }, { "code": null, "e": 26424, "s": 26269, "text": "$wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-9.noarch.rpm\n$rpm -ivh epel-release-7-9.noarch.rpm\n$yum install librsync rdiff-backup" }, { "code": null, "e": 26447, "s": 26424, "text": "In case of Fedora OS " }, { "code": null, "e": 26482, "s": 26447, "text": "$yum install librsync rdiff-backup" }, { "code": null, "e": 26507, "s": 26482, "text": "1. To backup a folder. " }, { "code": null, "e": 26561, "s": 26507, "text": "$rdiff-backup ./backup_folder ./backup_folder.backup " }, { "code": null, "e": 26608, "s": 26561, "text": "This will create a backup file of the folder. " }, { "code": null, "e": 26655, "s": 26608, "text": "2. To exclude a file from the backup folder. " }, { "code": null, "e": 26742, "s": 26655, "text": "$rdiff-backup --exclude-filelist backup_folder/hii ./backup_folder/ backup_file.backup" }, { "code": null, "e": 26802, "s": 26742, "text": "This will exclude the specified file from the backup file. " }, { "code": null, "e": 26835, "s": 26802, "text": "3. To exclude files of a type. " }, { "code": null, "e": 26901, "s": 26835, "text": "$rdiff-backup --exclude '**ii' backup_folder/ backup_file.backup/" }, { "code": null, "e": 26955, "s": 26901, "text": "Here it will exclude all files with the suffix “ii”. " }, { "code": null, "e": 27001, "s": 26955, "text": "4. To list the modifications or increments. " }, { "code": null, "e": 27037, "s": 27001, "text": "$rdiff-backup -l backup_file.backup" }, { "code": null, "e": 27101, "s": 27037, "text": "This will list all the changes done so far in the backup file. " }, { "code": null, "e": 27151, "s": 27101, "text": "5. To restore a file from its previous versions. " }, { "code": null, "e": 27268, "s": 27151, "text": "$rdiff-backup backup_file.backup/rdiff-backup-data/increments/hii.2020-05-17T13\\:52\\:57+05\\:30.diff.gz restore/hii " }, { "code": null, "e": 27329, "s": 27268, "text": "This will restore the file when it was previously backed up " }, { "code": null, "e": 27396, "s": 27329, "text": "6.To include specific type of files and exclude everything else. " }, { "code": null, "e": 27478, "s": 27396, "text": "$rdiff-backup --include \"**ii\" --exclude '**' backup_folder/ backup_file.backup/ " }, { "code": null, "e": 27541, "s": 27478, "text": "This will include only those files that have the suffix “ii”. " }, { "code": null, "e": 27558, "s": 27541, "text": "surinderdawra388" }, { "code": null, "e": 27572, "s": 27558, "text": "linux-command" }, { "code": null, "e": 27592, "s": 27572, "text": "Linux-file-commands" }, { "code": null, "e": 27603, "s": 27592, "text": "Linux-Unix" }, { "code": null, "e": 27701, "s": 27603, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27736, "s": 27701, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27762, "s": 27736, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27796, "s": 27762, "text": "mv command in Linux with examples" }, { "code": null, "e": 27825, "s": 27796, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27862, "s": 27825, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27899, "s": 27862, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27941, "s": 27899, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27967, "s": 27941, "text": "Thread functions in C/C++" }, { "code": null, "e": 28003, "s": 27967, "text": "uniq Command in LINUX with examples" } ]
Maximum consecutive numbers present in an array - GeeksforGeeks
22 Mar, 2022 Find the length of maximum number of consecutive numbers jumbled up in an array.Examples: Input : arr[] = {1, 94, 93, 1000, 5, 92, 78}; Output : 3 The largest set of consecutive elements is 92, 93, 94 Input : arr[] = {1, 5, 92, 4, 78, 6, 7}; Output : 4 The largest set of consecutive elements is 4, 5, 6, 7 The idea is to use hashing. We traverse through the array and for every element, we check if it is the starting element of its sequence. If yes then by incrementing its value we search the set and increment the length. By repeating this for all elements, we can find the lengths of all consecutive sets in array. Finally we return length of the largest set. C++ Java Python3 C# Javascript // CPP program to find largest consecutive numbers// present in arr[].#include <bits/stdc++.h>using namespace std; int findLongestConseqSubseq(int arr[], int n){ /* We insert all the array elements into unordered set. */ unordered_set<int> S; for (int i = 0; i < n; i++) S.insert(arr[i]); // check each possible sequence from the start // then update optimal length int ans = 0; for (int i = 0; i < n; i++) { // if current element is the starting // element of a sequence if (S.find(arr[i] - 1) == S.end()) { // Then check for next elements in the // sequence int j = arr[i]; // increment the value of array element // and repeat search in the set while (S.find(j) != S.end()) j++; // Update optimal length if this length // is more. To get the length as it is // incremented one by one ans = max(ans, j - arr[i]); } } return ans;} // Driver codeint main(){ int arr[] = { 1, 94, 93, 1000, 5, 92, 78 }; int n = sizeof(arr) / sizeof(int); cout << findLongestConseqSubseq(arr, n) << endl; return 0;} // Java program to find largest consecutive// numbers present in arr[].import java.util.*; class GFG{ static int findLongestConseqSubseq(int arr[], int n){ /* We insert all the array elements into unordered set. */ HashSet<Integer> S = new HashSet<Integer>(); for (int i = 0; i < n; i++) S.add(arr[i]); // check each possible sequence from the start // then update optimal length int ans = 0; for (int i = 0; i < n; i++) { // if current element is the starting // element of a sequence if(S.contains(arr[i])) { // Then check for next elements in the // sequence int j = arr[i]; // increment the value of array element // and repeat search in the set while (S.contains(j)) j++; // Update optimal length if this length // is more. To get the length as it is // incremented one by one ans = Math.max(ans, j - arr[i]); } } return ans;} // Driver codepublic static void main(String[] args){ int arr[] = {1, 94, 93, 1000, 5, 92, 78}; int n = arr.length; System.out.println(findLongestConseqSubseq(arr, n));}} // This code contributed by Rajput-Ji # Python3 program to find largest consecutive# numbers present in arr. def findLongestConseqSubseq(arr, n): '''We insert all the array elements into unordered set.''' S = set(); for i in range(n): S.add(arr[i]); # check each possible sequence from the start # then update optimal length ans = 0; for i in range(n): # if current element is the starting # element of a sequence if S.__contains__(arr[i]): # Then check for next elements in the # sequence j = arr[i]; # increment the value of array element # and repeat search in the set while(S.__contains__(j)): j += 1; # Update optimal length if this length # is more. To get the length as it is # incremented one by one ans = max(ans, j - arr[i]); return ans; # Driver codeif __name__ == '__main__': arr = [ 1, 94, 93, 1000, 5, 92, 78 ]; n = len(arr); print(findLongestConseqSubseq(arr, n)); # This code is contributed by 29AjayKumar // C# program to find largest consecutive// numbers present in arr[].using System;using System.Collections.Generic; public class GFG{ static int findLongestConseqSubseq(int []arr, int n){ /* We insert all the array elements into unordered set. */ HashSet<int> S = new HashSet<int>(); for (int i = 0; i < n; i++) S.Add(arr[i]); // check each possible sequence from the start // then update optimal length int ans = 0; for (int i = 0; i < n; i++) { // if current element is the starting // element of a sequence if(S.Contains(arr[i])) { // Then check for next elements in the // sequence int j = arr[i]; // increment the value of array element // and repeat search in the set while (S.Contains(j)) j++; // Update optimal length if this length // is more. To get the length as it is // incremented one by one ans = Math.Max(ans, j - arr[i]); } } return ans;} // Driver codepublic static void Main(String[] args){ int []arr = {1, 94, 93, 1000, 5, 92, 78}; int n = arr.Length; Console.WriteLine(findLongestConseqSubseq(arr, n));}} // This code has been contributed by 29AjayKumar <script> // JavaScript program to find largest consecutive numbers// present in arr[]. function findLongestConseqSubseq(arr, n) { /* We insert all the array elements into unordered set. */ let S = new Set(); for (let i = 0; i < n; i++) S.add(arr[i]); // check each possible sequence from the start // then update optimal length let ans = 0; for (let i = 0; i < n; i++) { // if current element is the starting // element of a sequence if (!S.has(arr[i] - 1)) { // Then check for next elements in the // sequence let j = arr[i]; // increment the value of array element // and repeat search in the set while (S.has(j)) j++; // Update optimal length if this length // is more. To get the length as it is // incremented one by one ans = Math.max(ans, j - arr[i]); } } return ans;} // Driver code let arr = [1, 94, 93, 1000, 5, 92, 78];let n = arr.length;document.write(findLongestConseqSubseq(arr, n) + "<br>"); </script> 3 Time complexity : O(n2)Space complexity: O(n) Another approach: The idea is to sort the array. We will traverse through the array and check if the difference between the current element and the previous element is one or not. If the difference is one we will increment the count of the length of the current sequence. Otherwise, we will check if the count of the length of our current subsequence is greater than the length of our previously counted sequence. If it is, we will update our answer and then we will update the count to one to start counting the length of another sequence. By repeating this for all elements, we can find the lengths of all consecutive sequences in the array. Finally, we return the length of the largest sequence. Python3 # Python3 program to find largest consecutive# numbers present in arr. def findLongestConseqSubseq(arr, n): #The longest sequence in an empty array is, of course, 0, so we can simply return that. if n==0: return 0 #We will arrange array elements in ascending order using sort function. arr.sort() # check each possible sequence from the start # then update optimal length ans = 1 count = 1 for i in range(1, n): #For handling duplicate elements if arr[i]!=arr[i-1]: # if difference between current element and previous element is 1 # then we want to update our current sequence count if arr[i]-arr[i-1] == 1: count += 1 # otherwise, we will update our count to zero to check for other sequences. # before updating count value we have to check if current sequence length is more than our ans. # if count > ans then we want to update our ans. else: ans = max(ans, count) count = 1 return max(ans,count) #To handle the case in which last element is present in longest sequence. # Driver codeif __name__ == '__main__': arr = [1, 94, 93, 1000, 5, 92, 78] n = len(arr) print(findLongestConseqSubseq(arr, n)) # This code is contributed by sanjanasikarwar24 3 Time complexity : O(nlogn) Space complexity: O(1) Another approach: The idea is to use hashing. We traverse through the array and for every element, we check if it is the starting element of its sequence( no element whose value is less than the current element by one is present in the set ). If yes then by incrementing its value we search for other valid elements that could be present in the set and increment the length of the sequence accordingly. By repeating this for all elements, we can find the lengths of all consecutive sequences in the array. Finally, we return the length of the largest sequence Python3 # Python3 program to find largest consecutive# numbers present in arr. def findLongestConseqSubseq(arr, n): '''We insert all the array elements into set.''' S = set(arr) # check each possible sequence from the start # then update optimal length ans = 0 for e in arr: # i contains current element of array i = e # count represents the length of current sequence count = 1 # if current element is the starting # element of a sequence if i-1 not in S: # Then check for next elements in the # sequence while i+1 in S: # increment the value of array element # and repeat search in the set i += 1 count += 1 # Update optimal length if this length # is more. ans = max(ans, count) return ans # Driver codeif __name__ == '__main__': arr = [1, 94, 93, 1000, 5, 92, 78] n = len(arr) print(findLongestConseqSubseq(arr, n)) # This code is contributed by sanjanasikarwar24 3 Time complexity: O(n) Space complexity: O(n) Rajput-Ji 29AjayKumar gfgking UserHandle0 sanjanasikarwar24 Arrays Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 26065, "s": 26037, "text": "\n22 Mar, 2022" }, { "code": null, "e": 26157, "s": 26065, "text": "Find the length of maximum number of consecutive numbers jumbled up in an array.Examples: " }, { "code": null, "e": 26379, "s": 26157, "text": "Input : arr[] = {1, 94, 93, 1000, 5, 92, 78};\nOutput : 3 \nThe largest set of consecutive elements is\n92, 93, 94 \n\nInput : arr[] = {1, 5, 92, 4, 78, 6, 7};\nOutput : 4 \nThe largest set of consecutive elements is\n4, 5, 6, 7" }, { "code": null, "e": 26740, "s": 26381, "text": "The idea is to use hashing. We traverse through the array and for every element, we check if it is the starting element of its sequence. If yes then by incrementing its value we search the set and increment the length. By repeating this for all elements, we can find the lengths of all consecutive sets in array. Finally we return length of the largest set. " }, { "code": null, "e": 26744, "s": 26740, "text": "C++" }, { "code": null, "e": 26749, "s": 26744, "text": "Java" }, { "code": null, "e": 26757, "s": 26749, "text": "Python3" }, { "code": null, "e": 26760, "s": 26757, "text": "C#" }, { "code": null, "e": 26771, "s": 26760, "text": "Javascript" }, { "code": "// CPP program to find largest consecutive numbers// present in arr[].#include <bits/stdc++.h>using namespace std; int findLongestConseqSubseq(int arr[], int n){ /* We insert all the array elements into unordered set. */ unordered_set<int> S; for (int i = 0; i < n; i++) S.insert(arr[i]); // check each possible sequence from the start // then update optimal length int ans = 0; for (int i = 0; i < n; i++) { // if current element is the starting // element of a sequence if (S.find(arr[i] - 1) == S.end()) { // Then check for next elements in the // sequence int j = arr[i]; // increment the value of array element // and repeat search in the set while (S.find(j) != S.end()) j++; // Update optimal length if this length // is more. To get the length as it is // incremented one by one ans = max(ans, j - arr[i]); } } return ans;} // Driver codeint main(){ int arr[] = { 1, 94, 93, 1000, 5, 92, 78 }; int n = sizeof(arr) / sizeof(int); cout << findLongestConseqSubseq(arr, n) << endl; return 0;}", "e": 27979, "s": 26771, "text": null }, { "code": "// Java program to find largest consecutive// numbers present in arr[].import java.util.*; class GFG{ static int findLongestConseqSubseq(int arr[], int n){ /* We insert all the array elements into unordered set. */ HashSet<Integer> S = new HashSet<Integer>(); for (int i = 0; i < n; i++) S.add(arr[i]); // check each possible sequence from the start // then update optimal length int ans = 0; for (int i = 0; i < n; i++) { // if current element is the starting // element of a sequence if(S.contains(arr[i])) { // Then check for next elements in the // sequence int j = arr[i]; // increment the value of array element // and repeat search in the set while (S.contains(j)) j++; // Update optimal length if this length // is more. To get the length as it is // incremented one by one ans = Math.max(ans, j - arr[i]); } } return ans;} // Driver codepublic static void main(String[] args){ int arr[] = {1, 94, 93, 1000, 5, 92, 78}; int n = arr.length; System.out.println(findLongestConseqSubseq(arr, n));}} // This code contributed by Rajput-Ji", "e": 29242, "s": 27979, "text": null }, { "code": "# Python3 program to find largest consecutive# numbers present in arr. def findLongestConseqSubseq(arr, n): '''We insert all the array elements into unordered set.''' S = set(); for i in range(n): S.add(arr[i]); # check each possible sequence from the start # then update optimal length ans = 0; for i in range(n): # if current element is the starting # element of a sequence if S.__contains__(arr[i]): # Then check for next elements in the # sequence j = arr[i]; # increment the value of array element # and repeat search in the set while(S.__contains__(j)): j += 1; # Update optimal length if this length # is more. To get the length as it is # incremented one by one ans = max(ans, j - arr[i]); return ans; # Driver codeif __name__ == '__main__': arr = [ 1, 94, 93, 1000, 5, 92, 78 ]; n = len(arr); print(findLongestConseqSubseq(arr, n)); # This code is contributed by 29AjayKumar", "e": 30350, "s": 29242, "text": null }, { "code": "// C# program to find largest consecutive// numbers present in arr[].using System;using System.Collections.Generic; public class GFG{ static int findLongestConseqSubseq(int []arr, int n){ /* We insert all the array elements into unordered set. */ HashSet<int> S = new HashSet<int>(); for (int i = 0; i < n; i++) S.Add(arr[i]); // check each possible sequence from the start // then update optimal length int ans = 0; for (int i = 0; i < n; i++) { // if current element is the starting // element of a sequence if(S.Contains(arr[i])) { // Then check for next elements in the // sequence int j = arr[i]; // increment the value of array element // and repeat search in the set while (S.Contains(j)) j++; // Update optimal length if this length // is more. To get the length as it is // incremented one by one ans = Math.Max(ans, j - arr[i]); } } return ans;} // Driver codepublic static void Main(String[] args){ int []arr = {1, 94, 93, 1000, 5, 92, 78}; int n = arr.Length; Console.WriteLine(findLongestConseqSubseq(arr, n));}} // This code has been contributed by 29AjayKumar", "e": 31643, "s": 30350, "text": null }, { "code": "<script> // JavaScript program to find largest consecutive numbers// present in arr[]. function findLongestConseqSubseq(arr, n) { /* We insert all the array elements into unordered set. */ let S = new Set(); for (let i = 0; i < n; i++) S.add(arr[i]); // check each possible sequence from the start // then update optimal length let ans = 0; for (let i = 0; i < n; i++) { // if current element is the starting // element of a sequence if (!S.has(arr[i] - 1)) { // Then check for next elements in the // sequence let j = arr[i]; // increment the value of array element // and repeat search in the set while (S.has(j)) j++; // Update optimal length if this length // is more. To get the length as it is // incremented one by one ans = Math.max(ans, j - arr[i]); } } return ans;} // Driver code let arr = [1, 94, 93, 1000, 5, 92, 78];let n = arr.length;document.write(findLongestConseqSubseq(arr, n) + \"<br>\"); </script>", "e": 32756, "s": 31643, "text": null }, { "code": null, "e": 32759, "s": 32756, "text": "3\n" }, { "code": null, "e": 32805, "s": 32759, "text": "Time complexity : O(n2)Space complexity: O(n)" }, { "code": null, "e": 33504, "s": 32805, "text": "Another approach: The idea is to sort the array. We will traverse through the array and check if the difference between the current element and the previous element is one or not. If the difference is one we will increment the count of the length of the current sequence. Otherwise, we will check if the count of the length of our current subsequence is greater than the length of our previously counted sequence. If it is, we will update our answer and then we will update the count to one to start counting the length of another sequence. By repeating this for all elements, we can find the lengths of all consecutive sequences in the array. Finally, we return the length of the largest sequence." }, { "code": null, "e": 33512, "s": 33504, "text": "Python3" }, { "code": "# Python3 program to find largest consecutive# numbers present in arr. def findLongestConseqSubseq(arr, n): #The longest sequence in an empty array is, of course, 0, so we can simply return that. if n==0: return 0 #We will arrange array elements in ascending order using sort function. arr.sort() # check each possible sequence from the start # then update optimal length ans = 1 count = 1 for i in range(1, n): #For handling duplicate elements if arr[i]!=arr[i-1]: # if difference between current element and previous element is 1 # then we want to update our current sequence count if arr[i]-arr[i-1] == 1: count += 1 # otherwise, we will update our count to zero to check for other sequences. # before updating count value we have to check if current sequence length is more than our ans. # if count > ans then we want to update our ans. else: ans = max(ans, count) count = 1 return max(ans,count) #To handle the case in which last element is present in longest sequence. # Driver codeif __name__ == '__main__': arr = [1, 94, 93, 1000, 5, 92, 78] n = len(arr) print(findLongestConseqSubseq(arr, n)) # This code is contributed by sanjanasikarwar24", "e": 34816, "s": 33512, "text": null }, { "code": null, "e": 34819, "s": 34816, "text": "3\n" }, { "code": null, "e": 34846, "s": 34819, "text": "Time complexity : O(nlogn)" }, { "code": null, "e": 34869, "s": 34846, "text": "Space complexity: O(1)" }, { "code": null, "e": 35429, "s": 34869, "text": "Another approach: The idea is to use hashing. We traverse through the array and for every element, we check if it is the starting element of its sequence( no element whose value is less than the current element by one is present in the set ). If yes then by incrementing its value we search for other valid elements that could be present in the set and increment the length of the sequence accordingly. By repeating this for all elements, we can find the lengths of all consecutive sequences in the array. Finally, we return the length of the largest sequence" }, { "code": null, "e": 35437, "s": 35429, "text": "Python3" }, { "code": "# Python3 program to find largest consecutive# numbers present in arr. def findLongestConseqSubseq(arr, n): '''We insert all the array elements into set.''' S = set(arr) # check each possible sequence from the start # then update optimal length ans = 0 for e in arr: # i contains current element of array i = e # count represents the length of current sequence count = 1 # if current element is the starting # element of a sequence if i-1 not in S: # Then check for next elements in the # sequence while i+1 in S: # increment the value of array element # and repeat search in the set i += 1 count += 1 # Update optimal length if this length # is more. ans = max(ans, count) return ans # Driver codeif __name__ == '__main__': arr = [1, 94, 93, 1000, 5, 92, 78] n = len(arr) print(findLongestConseqSubseq(arr, n)) # This code is contributed by sanjanasikarwar24", "e": 36509, "s": 35437, "text": null }, { "code": null, "e": 36512, "s": 36509, "text": "3\n" }, { "code": null, "e": 36534, "s": 36512, "text": "Time complexity: O(n)" }, { "code": null, "e": 36557, "s": 36534, "text": "Space complexity: O(n)" }, { "code": null, "e": 36567, "s": 36557, "text": "Rajput-Ji" }, { "code": null, "e": 36579, "s": 36567, "text": "29AjayKumar" }, { "code": null, "e": 36587, "s": 36579, "text": "gfgking" }, { "code": null, "e": 36599, "s": 36587, "text": "UserHandle0" }, { "code": null, "e": 36617, "s": 36599, "text": "sanjanasikarwar24" }, { "code": null, "e": 36624, "s": 36617, "text": "Arrays" }, { "code": null, "e": 36629, "s": 36624, "text": "Hash" }, { "code": null, "e": 36636, "s": 36629, "text": "Arrays" }, { "code": null, "e": 36641, "s": 36636, "text": "Hash" }, { "code": null, "e": 36739, "s": 36641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36770, "s": 36739, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 36795, "s": 36770, "text": "Window Sliding Technique" }, { "code": null, "e": 36833, "s": 36795, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36854, "s": 36833, "text": "Next Greater Element" }, { "code": null, "e": 36912, "s": 36854, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 36948, "s": 36912, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 36979, "s": 36948, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 37013, "s": 36979, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 37040, "s": 37013, "text": "Count pairs with given sum" } ]
How to Replace a value if null or undefined in JavaScript? - GeeksforGeeks
02 Mar, 2020 In JavaScript if a variable is not initialised with any value, then it is set to undefined. We can set a default value if a value is undefined. This can be done using two ways. Example 1: By using if checks (Brute force). In this method, we will manually check whether a value is not null or not undefined, if so then set it to some default value. Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Demo</title></head> <body> <h1 style="color: green; text-align: center;"> GeeksforGeeks </h1> <h3 style="text-align: center;"> Replace a value if null or undefined </h3> <div style="margin-top: 50px; text-align: center;"> <input type="text" id="anyId"> <button type="submit" onclick="defaultValue_ifcheck()"> Submit </button> </div> <script> // By using if-check function defaultValue_ifcheck() { var oldValue = document.getElementById("anyId").value; var newValue; if (!oldValue) { newValue = "This is default value: Geeksforgeeks"; } else { newValue = oldValue; } alert(newValue); } </script></body></html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Demo</title></head> <body> <h1 style="color: green; text-align: center;"> GeeksforGeeks </h1> <h3 style="text-align: center;"> Replace a value if null or undefined </h3> <div style="margin-top: 50px; text-align: center;"> <input type="text" id="anyId"> <button type="submit" onclick="defaultValue_ifcheck()"> Submit </button> </div> <script> // By using if-check function defaultValue_ifcheck() { var oldValue = document.getElementById("anyId").value; var newValue; if (!oldValue) { newValue = "This is default value: Geeksforgeeks"; } else { newValue = oldValue; } alert(newValue); } </script></body></html> Output: Example 2: By using logical OR (||) operator. In this method, if the value is null or undefined, then it will simply replaced by default value set by user. Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Replace a value if null or undefined</title></head> <body> <h1 style="color: green; text-align: center;"> GeeksforGeeks </h1> <h3 style="text-align: center;"> Replace a value if null or undefined </h3> <div style="margin-top: 50px; text-align: center;"> <input type="text" id="anyId"> <button type="submit" onclick="defaultValue_or()"> Submit </button> </div></body><script> // By using Logical OR (||) function defaultValue_or() { var oldValue = document.getElementById("anyId") .value; var newValue = oldValue || "This is default value: Geeksforgeeks"; alert(newValue); }</script> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Replace a value if null or undefined</title></head> <body> <h1 style="color: green; text-align: center;"> GeeksforGeeks </h1> <h3 style="text-align: center;"> Replace a value if null or undefined </h3> <div style="margin-top: 50px; text-align: center;"> <input type="text" id="anyId"> <button type="submit" onclick="defaultValue_or()"> Submit </button> </div></body><script> // By using Logical OR (||) function defaultValue_or() { var oldValue = document.getElementById("anyId") .value; var newValue = oldValue || "This is default value: Geeksforgeeks"; alert(newValue); }</script> </html> Output: Note: In Method 2, don’t use the following newValue = 10 || oldValue;. It will always set newValue to 10 because 10 will always return true. CSS-Misc HTML-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 26029, "s": 26001, "text": "\n02 Mar, 2020" }, { "code": null, "e": 26206, "s": 26029, "text": "In JavaScript if a variable is not initialised with any value, then it is set to undefined. We can set a default value if a value is undefined. This can be done using two ways." }, { "code": null, "e": 26377, "s": 26206, "text": "Example 1: By using if checks (Brute force). In this method, we will manually check whether a value is not null or not undefined, if so then set it to some default value." }, { "code": null, "e": 27488, "s": 26377, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Demo</title></head> <body> <h1 style=\"color: green; text-align: center;\"> GeeksforGeeks </h1> <h3 style=\"text-align: center;\"> Replace a value if null or undefined </h3> <div style=\"margin-top: 50px; text-align: center;\"> <input type=\"text\" id=\"anyId\"> <button type=\"submit\" onclick=\"defaultValue_ifcheck()\"> Submit </button> </div> <script> // By using if-check function defaultValue_ifcheck() { var oldValue = document.getElementById(\"anyId\").value; var newValue; if (!oldValue) { newValue = \"This is default value: Geeksforgeeks\"; } else { newValue = oldValue; } alert(newValue); } </script></body></html> " }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Demo</title></head> <body> <h1 style=\"color: green; text-align: center;\"> GeeksforGeeks </h1> <h3 style=\"text-align: center;\"> Replace a value if null or undefined </h3> <div style=\"margin-top: 50px; text-align: center;\"> <input type=\"text\" id=\"anyId\"> <button type=\"submit\" onclick=\"defaultValue_ifcheck()\"> Submit </button> </div> <script> // By using if-check function defaultValue_ifcheck() { var oldValue = document.getElementById(\"anyId\").value; var newValue; if (!oldValue) { newValue = \"This is default value: Geeksforgeeks\"; } else { newValue = oldValue; } alert(newValue); } </script></body></html> ", "e": 28591, "s": 27488, "text": null }, { "code": null, "e": 28599, "s": 28591, "text": "Output:" }, { "code": null, "e": 28755, "s": 28599, "text": "Example 2: By using logical OR (||) operator. In this method, if the value is null or undefined, then it will simply replaced by default value set by user." }, { "code": null, "e": 29754, "s": 28755, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Replace a value if null or undefined</title></head> <body> <h1 style=\"color: green; text-align: center;\"> GeeksforGeeks </h1> <h3 style=\"text-align: center;\"> Replace a value if null or undefined </h3> <div style=\"margin-top: 50px; text-align: center;\"> <input type=\"text\" id=\"anyId\"> <button type=\"submit\" onclick=\"defaultValue_or()\"> Submit </button> </div></body><script> // By using Logical OR (||) function defaultValue_or() { var oldValue = document.getElementById(\"anyId\") .value; var newValue = oldValue || \"This is default value: Geeksforgeeks\"; alert(newValue); }</script> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Replace a value if null or undefined</title></head> <body> <h1 style=\"color: green; text-align: center;\"> GeeksforGeeks </h1> <h3 style=\"text-align: center;\"> Replace a value if null or undefined </h3> <div style=\"margin-top: 50px; text-align: center;\"> <input type=\"text\" id=\"anyId\"> <button type=\"submit\" onclick=\"defaultValue_or()\"> Submit </button> </div></body><script> // By using Logical OR (||) function defaultValue_or() { var oldValue = document.getElementById(\"anyId\") .value; var newValue = oldValue || \"This is default value: Geeksforgeeks\"; alert(newValue); }</script> </html>", "e": 30745, "s": 29754, "text": null }, { "code": null, "e": 30753, "s": 30745, "text": "Output:" }, { "code": null, "e": 30894, "s": 30753, "text": "Note: In Method 2, don’t use the following newValue = 10 || oldValue;. It will always set newValue to 10 because 10 will always return true." }, { "code": null, "e": 30903, "s": 30894, "text": "CSS-Misc" }, { "code": null, "e": 30913, "s": 30903, "text": "HTML-Misc" }, { "code": null, "e": 30920, "s": 30913, "text": "Picked" }, { "code": null, "e": 30924, "s": 30920, "text": "CSS" }, { "code": null, "e": 30929, "s": 30924, "text": "HTML" }, { "code": null, "e": 30940, "s": 30929, "text": "JavaScript" }, { "code": null, "e": 30957, "s": 30940, "text": "Web Technologies" }, { "code": null, "e": 30984, "s": 30957, "text": "Web technologies Questions" }, { "code": null, "e": 30989, "s": 30984, "text": "HTML" }, { "code": null, "e": 31087, "s": 30989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31142, "s": 31087, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 31179, "s": 31142, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 31243, "s": 31179, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 31280, "s": 31243, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31341, "s": 31280, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 31401, "s": 31341, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31454, "s": 31401, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 31515, "s": 31454, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 31565, "s": 31515, "text": "How to Insert Form Data into Database using PHP ?" } ]
Combine Multiple ggplot2 Legend in R - GeeksforGeeks
23 May, 2021 In this article, we will see how to combine multiple ggplot2 Legends in the R programming language. First, load the ggplot2 package by using the library() function. If you have not installed it yet, you can simply install it by writing the below command in R Console. install.packages("ggplot2") To create an R plot, we use ggplot() function and for make it scatter plot we add geom_point() function to ggplot() function. Let us first create a plot with multiple legends in the same plot without combining so that the difference is apparent. Example: R # Load Packagelibrary("ggplot2") # Create a DataFrame data <- data.frame(Xdata = rnorm(6), Ydata = rnorm(6), Group1 = c("ld-01", "ld-02", "ld-03", "ld-04", "ld-05", "ld-06"), Group2 = c("ld-01", "ld-02", "ld-03", "ld-04", "ld-05", "ld-06")) # Create a Scatter Plot With Multiple Legendsggplot(data, aes(Xdata, Ydata, color = Group1, shape = Group2)) + geom_point(size = 7) Output: Scatterplot with multiple legends As you can see in the above plot the two legends Group1 represents color and Group2 represents shape of Points in scatter plot are differently outlined. To Combine them into one legend, We should choose only one out of both Legends. Here we have chosen Group2, So we assign Group2 to color and shape parameters of aes() function. You can also choose Group1. Example: R # Load Packagelibrary("ggplot2") # Create a DataFrame data <- data.frame(Xdata = rnorm(6), Ydata = rnorm(6), Group1 = c("ld-01", "ld-02", "ld-03", "ld-04", "ld-05", "ld-06"), Group2 = c("ld-01", "ld-02", "ld-03", "ld-04", "ld-05", "ld-06")) # Create a Scatter Plot with Combined# multiple legendsggplot(data, aes(Xdata, Ydata, color = Group2, shape = Group2)) + geom_point(size = 7) Output: Scatteplot with Combined multiple Legends Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R R - if statement Logistic Regression in R Programming
[ { "code": null, "e": 26487, "s": 26459, "text": "\n23 May, 2021" }, { "code": null, "e": 26587, "s": 26487, "text": "In this article, we will see how to combine multiple ggplot2 Legends in the R programming language." }, { "code": null, "e": 26755, "s": 26587, "text": "First, load the ggplot2 package by using the library() function. If you have not installed it yet, you can simply install it by writing the below command in R Console." }, { "code": null, "e": 26783, "s": 26755, "text": "install.packages(\"ggplot2\")" }, { "code": null, "e": 27029, "s": 26783, "text": "To create an R plot, we use ggplot() function and for make it scatter plot we add geom_point() function to ggplot() function. Let us first create a plot with multiple legends in the same plot without combining so that the difference is apparent." }, { "code": null, "e": 27038, "s": 27029, "text": "Example:" }, { "code": null, "e": 27040, "s": 27038, "text": "R" }, { "code": "# Load Packagelibrary(\"ggplot2\") # Create a DataFrame data <- data.frame(Xdata = rnorm(6), Ydata = rnorm(6), Group1 = c(\"ld-01\", \"ld-02\", \"ld-03\", \"ld-04\", \"ld-05\", \"ld-06\"), Group2 = c(\"ld-01\", \"ld-02\", \"ld-03\", \"ld-04\", \"ld-05\", \"ld-06\")) # Create a Scatter Plot With Multiple Legendsggplot(data, aes(Xdata, Ydata, color = Group1, shape = Group2)) + geom_point(size = 7)", "e": 27576, "s": 27040, "text": null }, { "code": null, "e": 27584, "s": 27576, "text": "Output:" }, { "code": null, "e": 27618, "s": 27584, "text": "Scatterplot with multiple legends" }, { "code": null, "e": 27976, "s": 27618, "text": "As you can see in the above plot the two legends Group1 represents color and Group2 represents shape of Points in scatter plot are differently outlined. To Combine them into one legend, We should choose only one out of both Legends. Here we have chosen Group2, So we assign Group2 to color and shape parameters of aes() function. You can also choose Group1." }, { "code": null, "e": 27985, "s": 27976, "text": "Example:" }, { "code": null, "e": 27987, "s": 27985, "text": "R" }, { "code": "# Load Packagelibrary(\"ggplot2\") # Create a DataFrame data <- data.frame(Xdata = rnorm(6), Ydata = rnorm(6), Group1 = c(\"ld-01\", \"ld-02\", \"ld-03\", \"ld-04\", \"ld-05\", \"ld-06\"), Group2 = c(\"ld-01\", \"ld-02\", \"ld-03\", \"ld-04\", \"ld-05\", \"ld-06\")) # Create a Scatter Plot with Combined# multiple legendsggplot(data, aes(Xdata, Ydata, color = Group2, shape = Group2)) + geom_point(size = 7)", "e": 28534, "s": 27987, "text": null }, { "code": null, "e": 28542, "s": 28534, "text": "Output:" }, { "code": null, "e": 28584, "s": 28542, "text": "Scatteplot with Combined multiple Legends" }, { "code": null, "e": 28591, "s": 28584, "text": "Picked" }, { "code": null, "e": 28600, "s": 28591, "text": "R-ggplot" }, { "code": null, "e": 28611, "s": 28600, "text": "R Language" }, { "code": null, "e": 28709, "s": 28611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28761, "s": 28709, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28796, "s": 28761, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28834, "s": 28796, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28892, "s": 28834, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28935, "s": 28892, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28972, "s": 28935, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29021, "s": 28972, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29047, "s": 29021, "text": "Time Series Analysis in R" }, { "code": null, "e": 29064, "s": 29047, "text": "R - if statement" } ]
Counters in Python | Set 2 (Accessing Counters) - GeeksforGeeks
04 Feb, 2020 Counters in Python | Set 1 (Initialization and Updation) Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value’s count is shown as 0. Example : # Python program to demonstrate accessing of# Counter elementsfrom collections import Counter # Create a listz = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']col_count = Counter(z)print(col_count) col = ['blue','red','yellow','green'] # Here green is not in col_count # so count of green will be zerofor color in col: print (color, col_count[color]) Output: Counter({'blue': 3, 'red': 2, 'yellow': 1}) blue 3 red 2 yellow 1 green 0 elements() :The elements() method returns an iterator that produces all of the items known to the Counter.Note : Elements with count <= 0 are not included. Example : # Python example to demonstrate elements() on# Counter (gives back list)from collections import Counter coun = Counter(a=1, b=2, c=3)print(coun) print(list(coun.elements())) Output : Counter({'c': 3, 'b': 2, 'a': 1}) ['a', 'b', 'b', 'c', 'c', 'c'] most_common() :most_common() is used to produce a sequence of the n most frequently encountered input values and their respective counts. # Python example to demonstrate most_elements() on# Counterfrom collections import Counter coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219) # This prints 3 most frequent charactersfor letter, count in coun.most_common(3): print('%s: %d' % (letter, count)) Output : f: 219 d: 120 c: 3 YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=rqzSa8O97TM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Mayank Rawat .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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": 25419, "s": 25391, "text": "\n04 Feb, 2020" }, { "code": null, "e": 25476, "s": 25419, "text": "Counters in Python | Set 1 (Initialization and Updation)" }, { "code": null, "e": 25648, "s": 25476, "text": "Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value’s count is shown as 0." }, { "code": null, "e": 25658, "s": 25648, "text": "Example :" }, { "code": "# Python program to demonstrate accessing of# Counter elementsfrom collections import Counter # Create a listz = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']col_count = Counter(z)print(col_count) col = ['blue','red','yellow','green'] # Here green is not in col_count # so count of green will be zerofor color in col: print (color, col_count[color])", "e": 26017, "s": 25658, "text": null }, { "code": null, "e": 26025, "s": 26017, "text": "Output:" }, { "code": null, "e": 26100, "s": 26025, "text": "Counter({'blue': 3, 'red': 2, 'yellow': 1})\nblue 3\nred 2\nyellow 1\ngreen 0\n" }, { "code": null, "e": 26256, "s": 26100, "text": "elements() :The elements() method returns an iterator that produces all of the items known to the Counter.Note : Elements with count <= 0 are not included." }, { "code": null, "e": 26266, "s": 26256, "text": "Example :" }, { "code": "# Python example to demonstrate elements() on# Counter (gives back list)from collections import Counter coun = Counter(a=1, b=2, c=3)print(coun) print(list(coun.elements()))", "e": 26442, "s": 26266, "text": null }, { "code": null, "e": 26451, "s": 26442, "text": "Output :" }, { "code": null, "e": 26517, "s": 26451, "text": "Counter({'c': 3, 'b': 2, 'a': 1})\n['a', 'b', 'b', 'c', 'c', 'c']\n" }, { "code": null, "e": 26655, "s": 26517, "text": "most_common() :most_common() is used to produce a sequence of the n most frequently encountered input values and their respective counts." }, { "code": "# Python example to demonstrate most_elements() on# Counterfrom collections import Counter coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219) # This prints 3 most frequent charactersfor letter, count in coun.most_common(3): print('%s: %d' % (letter, count))", "e": 26916, "s": 26655, "text": null }, { "code": null, "e": 26925, "s": 26916, "text": "Output :" }, { "code": null, "e": 26945, "s": 26925, "text": "f: 219\nd: 120\nc: 3\n" }, { "code": null, "e": 27237, "s": 26945, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=rqzSa8O97TM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 27537, "s": 27237, "text": "This article is contributed by Mayank Rawat .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": 27662, "s": 27537, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27669, "s": 27662, "text": "Python" }, { "code": null, "e": 27767, "s": 27669, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27785, "s": 27767, "text": "Python Dictionary" }, { "code": null, "e": 27820, "s": 27785, "text": "Read a file line by line in Python" }, { "code": null, "e": 27852, "s": 27820, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27874, "s": 27852, "text": "Enumerate() in Python" }, { "code": null, "e": 27916, "s": 27874, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27946, "s": 27916, "text": "Iterate over a list in Python" }, { "code": null, "e": 27972, "s": 27946, "text": "Python String | replace()" }, { "code": null, "e": 28001, "s": 27972, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28045, "s": 28001, "text": "Reading and Writing to text files in Python" } ]
Bigram formation from a given Python list - GeeksforGeeks
11 Dec, 2020 When we are dealing with text classification, sometimes we need to do certain kind of natural language processing and hence sometimes require to form bigrams of words for processing. In case of absence of appropriate library, its difficult and having to do the same is always quite useful. Let’s discuss certain ways in which this can be achieved. Method #1 : Using list comprehension + enumerate() + split()The combination of above three functions can be used to achieve this particular task. The enumerate function performs the possible iteration, split function is used to make pairs and list comprehension is used to combine the logic. # Python3 code to demonstrate# Bigram formation# using list comprehension + enumerate() + split() # initializing list test_list = ['geeksforgeeks is best', 'I love it'] # printing the original list print ("The original list is : " + str(test_list)) # using list comprehension + enumerate() + split()# for Bigram formationres = [(x, i.split()[j + 1]) for i in test_list for j, x in enumerate(i.split()) if j < len(i.split()) - 1] # printing resultprint ("The formed bigrams are : " + str(res)) Output : The original list is : [‘geeksforgeeks is best’, ‘I love it’]The formed bigrams are : [(‘geeksforgeeks’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)] Method #2 : Using zip() + split() + list comprehensionThe task that enumerate performed in the above method can also be performed by the zip function by using the iterator and hence in a faster way. Let’s discuss certain ways in which this can be done. # Python3 code to demonstrate# Bigram formation# using zip() + split() + list comprehension # initializing list test_list = ['geeksforgeeks is best', 'I love it'] # printing the original list print ("The original list is : " + str(test_list)) # using zip() + split() + list comprehension# for Bigram formationres = [i for j in test_list for i in zip(j.split(" ")[:-1], j.split(" ")[1:])] # printing resultprint ("The formed bigrams are : " + str(res)) Output : The original list is : [‘geeksforgeeks is best’, ‘I love it’]The formed bigrams are : [(‘geeksforgeeks’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)] Natural-language-processing Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25709, "s": 25681, "text": "\n11 Dec, 2020" }, { "code": null, "e": 26057, "s": 25709, "text": "When we are dealing with text classification, sometimes we need to do certain kind of natural language processing and hence sometimes require to form bigrams of words for processing. In case of absence of appropriate library, its difficult and having to do the same is always quite useful. Let’s discuss certain ways in which this can be achieved." }, { "code": null, "e": 26349, "s": 26057, "text": "Method #1 : Using list comprehension + enumerate() + split()The combination of above three functions can be used to achieve this particular task. The enumerate function performs the possible iteration, split function is used to make pairs and list comprehension is used to combine the logic." }, { "code": "# Python3 code to demonstrate# Bigram formation# using list comprehension + enumerate() + split() # initializing list test_list = ['geeksforgeeks is best', 'I love it'] # printing the original list print (\"The original list is : \" + str(test_list)) # using list comprehension + enumerate() + split()# for Bigram formationres = [(x, i.split()[j + 1]) for i in test_list for j, x in enumerate(i.split()) if j < len(i.split()) - 1] # printing resultprint (\"The formed bigrams are : \" + str(res))", "e": 26854, "s": 26349, "text": null }, { "code": null, "e": 26863, "s": 26854, "text": "Output :" }, { "code": null, "e": 27022, "s": 26863, "text": "The original list is : [‘geeksforgeeks is best’, ‘I love it’]The formed bigrams are : [(‘geeksforgeeks’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)]" }, { "code": null, "e": 27276, "s": 27022, "text": " Method #2 : Using zip() + split() + list comprehensionThe task that enumerate performed in the above method can also be performed by the zip function by using the iterator and hence in a faster way. Let’s discuss certain ways in which this can be done." }, { "code": "# Python3 code to demonstrate# Bigram formation# using zip() + split() + list comprehension # initializing list test_list = ['geeksforgeeks is best', 'I love it'] # printing the original list print (\"The original list is : \" + str(test_list)) # using zip() + split() + list comprehension# for Bigram formationres = [i for j in test_list for i in zip(j.split(\" \")[:-1], j.split(\" \")[1:])] # printing resultprint (\"The formed bigrams are : \" + str(res))", "e": 27740, "s": 27276, "text": null }, { "code": null, "e": 27749, "s": 27740, "text": "Output :" }, { "code": null, "e": 27908, "s": 27749, "text": "The original list is : [‘geeksforgeeks is best’, ‘I love it’]The formed bigrams are : [(‘geeksforgeeks’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)]" }, { "code": null, "e": 27936, "s": 27908, "text": "Natural-language-processing" }, { "code": null, "e": 27957, "s": 27936, "text": "Python list-programs" }, { "code": null, "e": 27964, "s": 27957, "text": "Python" }, { "code": null, "e": 27980, "s": 27964, "text": "Python Programs" }, { "code": null, "e": 28078, "s": 27980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28096, "s": 28078, "text": "Python Dictionary" }, { "code": null, "e": 28131, "s": 28096, "text": "Read a file line by line in Python" }, { "code": null, "e": 28163, "s": 28131, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28185, "s": 28163, "text": "Enumerate() in Python" }, { "code": null, "e": 28227, "s": 28185, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28270, "s": 28227, "text": "Python program to convert a list to string" }, { "code": null, "e": 28292, "s": 28270, "text": "Defaultdict in Python" }, { "code": null, "e": 28331, "s": 28292, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28369, "s": 28331, "text": "Python | Convert a list to dictionary" } ]
PLSQL | LPAD Function - GeeksforGeeks
24 Sep, 2019 The PLSQL LPAD function is used for padding the left-side of a string with a specific set of characters. a prerequisite for this is that string shouldn’t be NULL. The LPAD function in PLSQL is useful for formatting the output of a query. The LPAD function accepts three parameters which are input_string, padded_length and the pad_string. Both input_string and pad_string can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 datatype if input_string is a character datatype. The argument padded_length must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer. If you do not specify pad_string, then the default is a single blank. If input_string is longer than padded_length, then this function returns the portion of input_string that fits in padded_length. Syntax: LPAD( input_string, padded_length, pad_string ) Parameters Used: input_string – It is used to specify the string which needs to be formatted. padded_length – It is used to specify the number of characters to return. If the padded_length is smaller than the original string, the LPAD function will truncate the string to the size of padded_length. pad_string – It is an optional parameter which is used to specify the input_string that will be padded to the left-hand side of string. If this parameter is omitted, the LPAD function will pad spaces to the left-side of string1. Supported Versions of Oracle/PLSQL: Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i Oracle 12c Oracle 11g Oracle 10g Oracle 9i Oracle 8i Example-1: DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(LPAD(Test_String, '5')); END; Output: Geeks Example-2: DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(LPAD(Test_String, '17')); END; Output: Geeksforgeeks Example-3: DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(LPAD(Test_String, '17', '0')); END; Output: 0000Geeksforgeeks Example-4: DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(LPAD(Test_String, '12', '0')); END; Output: Geeksforgeeks SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL? Difference between DDL and DML in DBMS SQL | GROUP BY SQL | Views Difference between DELETE, DROP and TRUNCATE Difference between DELETE and TRUNCATE SQL - ORDER BY
[ { "code": null, "e": 25225, "s": 25197, "text": "\n24 Sep, 2019" }, { "code": null, "e": 25564, "s": 25225, "text": "The PLSQL LPAD function is used for padding the left-side of a string with a specific set of characters. a prerequisite for this is that string shouldn’t be NULL. The LPAD function in PLSQL is useful for formatting the output of a query. The LPAD function accepts three parameters which are input_string, padded_length and the pad_string." }, { "code": null, "e": 26076, "s": 25564, "text": "Both input_string and pad_string can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 datatype if input_string is a character datatype. The argument padded_length must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer. If you do not specify pad_string, then the default is a single blank. If input_string is longer than padded_length, then this function returns the portion of input_string that fits in padded_length." }, { "code": null, "e": 26084, "s": 26076, "text": "Syntax:" }, { "code": null, "e": 26132, "s": 26084, "text": "LPAD( input_string, padded_length, pad_string )" }, { "code": null, "e": 26149, "s": 26132, "text": "Parameters Used:" }, { "code": null, "e": 26226, "s": 26149, "text": "input_string – It is used to specify the string which needs to be formatted." }, { "code": null, "e": 26431, "s": 26226, "text": "padded_length – It is used to specify the number of characters to return. If the padded_length is smaller than the original string, the LPAD function will truncate the string to the size of padded_length." }, { "code": null, "e": 26660, "s": 26431, "text": "pad_string – It is an optional parameter which is used to specify the input_string that will be padded to the left-hand side of string. If this parameter is omitted, the LPAD function will pad spaces to the left-side of string1." }, { "code": null, "e": 26696, "s": 26660, "text": "Supported Versions of Oracle/PLSQL:" }, { "code": null, "e": 26745, "s": 26696, "text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i" }, { "code": null, "e": 26756, "s": 26745, "text": "Oracle 12c" }, { "code": null, "e": 26767, "s": 26756, "text": "Oracle 11g" }, { "code": null, "e": 26778, "s": 26767, "text": "Oracle 10g" }, { "code": null, "e": 26788, "s": 26778, "text": "Oracle 9i" }, { "code": null, "e": 26798, "s": 26788, "text": "Oracle 8i" }, { "code": null, "e": 26809, "s": 26798, "text": "Example-1:" }, { "code": null, "e": 26935, "s": 26809, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(LPAD(Test_String, '5')); \n \nEND; " }, { "code": null, "e": 26943, "s": 26935, "text": "Output:" }, { "code": null, "e": 26950, "s": 26943, "text": "Geeks " }, { "code": null, "e": 26961, "s": 26950, "text": "Example-2:" }, { "code": null, "e": 27088, "s": 26961, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(LPAD(Test_String, '17')); \n \nEND; " }, { "code": null, "e": 27096, "s": 27088, "text": "Output:" }, { "code": null, "e": 27111, "s": 27096, "text": "Geeksforgeeks " }, { "code": null, "e": 27122, "s": 27111, "text": "Example-3:" }, { "code": null, "e": 27255, "s": 27122, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(LPAD(Test_String, '17', '0')); \n \nEND; " }, { "code": null, "e": 27263, "s": 27255, "text": "Output:" }, { "code": null, "e": 27282, "s": 27263, "text": "0000Geeksforgeeks " }, { "code": null, "e": 27293, "s": 27282, "text": "Example-4:" }, { "code": null, "e": 27431, "s": 27293, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \n \nBEGIN \n dbms_output.put_line(LPAD(Test_String, '12', '0')); \n \nEND; " }, { "code": null, "e": 27439, "s": 27431, "text": "Output:" }, { "code": null, "e": 27454, "s": 27439, "text": "Geeksforgeeks " }, { "code": null, "e": 27465, "s": 27454, "text": "SQL-PL/SQL" }, { "code": null, "e": 27469, "s": 27465, "text": "SQL" }, { "code": null, "e": 27473, "s": 27469, "text": "SQL" }, { "code": null, "e": 27571, "s": 27473, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27595, "s": 27571, "text": "SQL Interview Questions" }, { "code": null, "e": 27606, "s": 27595, "text": "CTE in SQL" }, { "code": null, "e": 27637, "s": 27606, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 27703, "s": 27637, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27742, "s": 27703, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 27757, "s": 27742, "text": "SQL | GROUP BY" }, { "code": null, "e": 27769, "s": 27757, "text": "SQL | Views" }, { "code": null, "e": 27814, "s": 27769, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 27853, "s": 27814, "text": "Difference between DELETE and TRUNCATE" } ]
Build a COVID19 Vaccine Tracker Using Python - GeeksforGeeks
29 Dec, 2020 As we know the world is facing an unprecedented challenge with communities and economies everywhere affected by the COVID19. So, we are going to do some fun during this time by tracking their vaccine. Let’s see a simple Python script to improve for tracking the COVID19 vaccine. bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not comes built-in with Python. To install this type the below command in the terminal. pip install bs4 requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal. pip install requests Approach: Extract data form given URL Scrape the data with the help of requests and Beautiful Soup Convert that data into html code. Find the required details and filter them. Let’s see the stepwise execution of the script Step 1: Import all dependence Python3 import requestsfrom bs4 import BeautifulSoup Step 2: Create a URL get function Python3 def getdata(url): r = requests.get(url) return r.text Step 3: Now pass the URL into the getdata function and Convert that data into HTML code Python3 htmldata = getdata("https://covid-19tracker.milkeninstitute.org/")soup = BeautifulSoup(htmldata, 'html.parser')res = soup.find_all("div", class_="is_h5-2 is_developer w-richtext")print(str(res)) Output: Note: These scripts will give you only Raw data in String format you have to print your data with your needs. Complete code: Python3 import requestsfrom bs4 import BeautifulSoup def getdata(url): r = requests.get(url) return r.text htmldata = getdata("https://covid-19tracker.milkeninstitute.org/")soup = BeautifulSoup(htmldata, 'html.parser')result = str(soup.find_all("div", class_="is_h5-2 is_developer w-richtext")) print("NO 1 " + result[46:86])print("NO 2 "+result[139:226])print("NO 3 "+result[279:305])print("NO 4 "+result[358:375])print("NO 5 "+result[428:509]) Output: Python web-scraping-exercises Python-projects Python-requests python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python
[ { "code": null, "e": 26229, "s": 26201, "text": "\n29 Dec, 2020" }, { "code": null, "e": 26508, "s": 26229, "text": "As we know the world is facing an unprecedented challenge with communities and economies everywhere affected by the COVID19. So, we are going to do some fun during this time by tracking their vaccine. Let’s see a simple Python script to improve for tracking the COVID19 vaccine." }, { "code": null, "e": 26702, "s": 26508, "text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not comes built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 26718, "s": 26702, "text": "pip install bs4" }, { "code": null, "e": 26903, "s": 26718, "text": "requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 26924, "s": 26903, "text": "pip install requests" }, { "code": null, "e": 26934, "s": 26924, "text": "Approach:" }, { "code": null, "e": 26962, "s": 26934, "text": "Extract data form given URL" }, { "code": null, "e": 27023, "s": 26962, "text": "Scrape the data with the help of requests and Beautiful Soup" }, { "code": null, "e": 27057, "s": 27023, "text": "Convert that data into html code." }, { "code": null, "e": 27100, "s": 27057, "text": "Find the required details and filter them." }, { "code": null, "e": 27147, "s": 27100, "text": "Let’s see the stepwise execution of the script" }, { "code": null, "e": 27180, "s": 27147, "text": "Step 1: Import all dependence " }, { "code": null, "e": 27188, "s": 27180, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup", "e": 27233, "s": 27188, "text": null }, { "code": null, "e": 27267, "s": 27233, "text": "Step 2: Create a URL get function" }, { "code": null, "e": 27275, "s": 27267, "text": "Python3" }, { "code": "def getdata(url): r = requests.get(url) return r.text", "e": 27335, "s": 27275, "text": null }, { "code": null, "e": 27423, "s": 27335, "text": "Step 3: Now pass the URL into the getdata function and Convert that data into HTML code" }, { "code": null, "e": 27431, "s": 27423, "text": "Python3" }, { "code": "htmldata = getdata(\"https://covid-19tracker.milkeninstitute.org/\")soup = BeautifulSoup(htmldata, 'html.parser')res = soup.find_all(\"div\", class_=\"is_h5-2 is_developer w-richtext\")print(str(res))", "e": 27626, "s": 27431, "text": null }, { "code": null, "e": 27634, "s": 27626, "text": "Output:" }, { "code": null, "e": 27745, "s": 27634, "text": "Note: These scripts will give you only Raw data in String format you have to print your data with your needs. " }, { "code": null, "e": 27760, "s": 27745, "text": "Complete code:" }, { "code": null, "e": 27768, "s": 27760, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup def getdata(url): r = requests.get(url) return r.text htmldata = getdata(\"https://covid-19tracker.milkeninstitute.org/\")soup = BeautifulSoup(htmldata, 'html.parser')result = str(soup.find_all(\"div\", class_=\"is_h5-2 is_developer w-richtext\")) print(\"NO 1 \" + result[46:86])print(\"NO 2 \"+result[139:226])print(\"NO 3 \"+result[279:305])print(\"NO 4 \"+result[358:375])print(\"NO 5 \"+result[428:509])", "e": 28217, "s": 27768, "text": null }, { "code": null, "e": 28225, "s": 28217, "text": "Output:" }, { "code": null, "e": 28255, "s": 28225, "text": "Python web-scraping-exercises" }, { "code": null, "e": 28271, "s": 28255, "text": "Python-projects" }, { "code": null, "e": 28287, "s": 28271, "text": "Python-requests" }, { "code": null, "e": 28302, "s": 28287, "text": "python-utility" }, { "code": null, "e": 28309, "s": 28302, "text": "Python" }, { "code": null, "e": 28407, "s": 28309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28425, "s": 28407, "text": "Python Dictionary" }, { "code": null, "e": 28457, "s": 28425, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28479, "s": 28457, "text": "Enumerate() in Python" }, { "code": null, "e": 28521, "s": 28479, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28547, "s": 28521, "text": "Python String | replace()" }, { "code": null, "e": 28591, "s": 28547, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28620, "s": 28591, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28656, "s": 28620, "text": "Convert integer to string in Python" }, { "code": null, "e": 28693, "s": 28656, "text": "Create a Pandas DataFrame from Lists" } ]
TreeMap floorEntry() Method in Java With Examples - GeeksforGeeks
02 Sep, 2020 The java.util.TreeMap.floorEntry() method is used to return a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key. Syntax: tree_map.floorEntry(K key) Parameters: This method takes one parameter key to be matched while mapping. Return Value: This method returns an entry with the greatest key less than or equal to key, or null if there is no such key. Exceptions: ClassCastException : This exception is thrown if the specified key cannot be compared with the keys currently in the map. NullPointerException : This exception is thrown if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys. Example 1: When there is a key Java // Java program to illustrate// TreeMap floorEntry() methodimport java.util.*; public class GFG { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Mapping string values to int keys treemap.put(20, "Twenty"); treemap.put(10, "Ten"); treemap.put(13, "Thirteen"); treemap.put(60, "Sixty"); treemap.put(50, "Fifty"); System.out.println("The greatest key-value less than 18 is : " + treemap.floorEntry(18)); }} The greatest key-value less than 18 is : 13=Thirteen Example 2: When there is no such key Java // Java program to illustrate// TreeMap floorEntry() methodimport java.util.TreeMap; public class GFG { public static void main(String args[]) { // Creating an empty TreeMap TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Mapping string values to int keys treemap.put(10, "Akash"); treemap.put(20, "Pratik"); treemap.put(30, "Vaibhav"); treemap.put(40, "Sagar"); treemap.put(50, "Abhishek"); // Printing floor entry System.out.println("The greatest key-value less than 5 is : " + treemap.floorEntry(5)); }} The greatest key-value less than 5 is : null Java-Collections java-TreeMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Multithreading in Java Collections in Java Initializing a List in Java
[ { "code": null, "e": 25509, "s": 25481, "text": "\n02 Sep, 2020" }, { "code": null, "e": 25692, "s": 25509, "text": "The java.util.TreeMap.floorEntry() method is used to return a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key." }, { "code": null, "e": 25700, "s": 25692, "text": "Syntax:" }, { "code": null, "e": 25727, "s": 25700, "text": "tree_map.floorEntry(K key)" }, { "code": null, "e": 25804, "s": 25727, "text": "Parameters: This method takes one parameter key to be matched while mapping." }, { "code": null, "e": 25930, "s": 25804, "text": "Return Value: This method returns an entry with the greatest key less than or equal to key, or null if there is no such key." }, { "code": null, "e": 25944, "s": 25930, "text": "Exceptions: " }, { "code": null, "e": 26067, "s": 25944, "text": " ClassCastException : This exception is thrown if the specified key cannot be compared with the keys currently in the map." }, { "code": null, "e": 26226, "s": 26067, "text": " NullPointerException : This exception is thrown if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys." }, { "code": null, "e": 26257, "s": 26226, "text": "Example 1: When there is a key" }, { "code": null, "e": 26262, "s": 26257, "text": "Java" }, { "code": "// Java program to illustrate// TreeMap floorEntry() methodimport java.util.*; public class GFG { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Mapping string values to int keys treemap.put(20, \"Twenty\"); treemap.put(10, \"Ten\"); treemap.put(13, \"Thirteen\"); treemap.put(60, \"Sixty\"); treemap.put(50, \"Fifty\"); System.out.println(\"The greatest key-value less than 18 is : \" + treemap.floorEntry(18)); }}", "e": 26882, "s": 26262, "text": null }, { "code": null, "e": 26936, "s": 26882, "text": "The greatest key-value less than 18 is : 13=Thirteen\n" }, { "code": null, "e": 26973, "s": 26936, "text": "Example 2: When there is no such key" }, { "code": null, "e": 26978, "s": 26973, "text": "Java" }, { "code": "// Java program to illustrate// TreeMap floorEntry() methodimport java.util.TreeMap; public class GFG { public static void main(String args[]) { // Creating an empty TreeMap TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Mapping string values to int keys treemap.put(10, \"Akash\"); treemap.put(20, \"Pratik\"); treemap.put(30, \"Vaibhav\"); treemap.put(40, \"Sagar\"); treemap.put(50, \"Abhishek\"); // Printing floor entry System.out.println(\"The greatest key-value less than 5 is : \" + treemap.floorEntry(5)); }}", "e": 27632, "s": 26978, "text": null }, { "code": null, "e": 27678, "s": 27632, "text": "The greatest key-value less than 5 is : null\n" }, { "code": null, "e": 27695, "s": 27678, "text": "Java-Collections" }, { "code": null, "e": 27708, "s": 27695, "text": "java-TreeMap" }, { "code": null, "e": 27713, "s": 27708, "text": "Java" }, { "code": null, "e": 27718, "s": 27713, "text": "Java" }, { "code": null, "e": 27735, "s": 27718, "text": "Java-Collections" }, { "code": null, "e": 27833, "s": 27735, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27848, "s": 27833, "text": "Stream In Java" }, { "code": null, "e": 27867, "s": 27848, "text": "Interfaces in Java" }, { "code": null, "e": 27885, "s": 27867, "text": "ArrayList in Java" }, { "code": null, "e": 27917, "s": 27885, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27937, "s": 27917, "text": "Stack Class in Java" }, { "code": null, "e": 27961, "s": 27937, "text": "Singleton Class in Java" }, { "code": null, "e": 27993, "s": 27961, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28016, "s": 27993, "text": "Multithreading in Java" }, { "code": null, "e": 28036, "s": 28016, "text": "Collections in Java" } ]
Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors
09 Jun, 2022 Given an integer N. The task is to find the number of integers 1 < x < N, for which x and x + 1 have the same number of positive divisors. Examples: Input: N = 3 Output: 1 Divisors(1) = 1 Divisors(2) = 1 and 2 Divisors(3) = 1 and 3 Only valid x is 2. Input: N = 15 Output: 2 Approach: Find the number of divisors of all numbers below N and store them in an array. And count the number of integers x such that x and x + 1 have the same number of positive divisors by running a loop. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 100005 // To store number of divisors and// Prefix sum of such numbersint d[N], pre[N]; // Function to find the number of integers// 1 < x < N for which x and x + 1 have// the same number of positive divisorsvoid Positive_Divisors(){ // Count the number of divisors for (int i = 1; i < N; i++) { // Run a loop upto sqrt(i) for (int j = 1; j * j <= i; j++) { // If j is divisor of i if (i % j == 0) { // If it is perfect square if (j * j == i) d[i]++; else d[i] += 2; } } } int ans = 0; // x and x+1 have same number of // positive divisors for (int i = 2; i < N; i++) { if (d[i] == d[i - 1]) ans++; pre[i] = ans; }} // Driver codeint main(){ // Function call Positive_Divisors(); int n = 15; // Required answer cout << pre[n] << endl; return 0;} // Java implementation of the approachclass GFG{ static int N =100005; // To store number of divisors and// Prefix sum of such numbersstatic int d[] = new int[N], pre[] = new int[N]; // Function to find the number of integers// 1 < x < N for which x and x + 1 have// the same number of positive divisorsstatic void Positive_Divisors(){ // Count the number of divisors for (int i = 1; i < N; i++) { // Run a loop upto sqrt(i) for (int j = 1; j * j <= i; j++) { // If j is divisor of i if (i % j == 0) { // If it is perfect square if (j * j == i) d[i]++; else d[i] += 2; } } } int ans = 0; // x and x+1 have same number of // positive divisors for (int i = 2; i < N; i++) { if (d[i] == d[i - 1]) ans++; pre[i] = ans; }} // Driver codepublic static void main(String[] args){ // Function call Positive_Divisors(); int n = 15; // Required answer System.out.println(pre[n]);}} /* This code contributed by PrinciRaj1992 */ # Python3 implementation of the above approachfrom math import sqrt; N = 100005 # To store number of divisors and# Prefix sum of such numbersd = [0] * Npre = [0] * N # Function to find the number of integers# 1 < x < N for which x and x + 1 have# the same number of positive divisorsdef Positive_Divisors() : # Count the number of divisors for i in range(N) : # Run a loop upto sqrt(i) for j in range(1, int(sqrt(i)) + 1) : # If j is divisor of i if (i % j == 0) : # If it is perfect square if (j * j == i) : d[i] += 1 else : d[i] += 2 ans = 0 # x and x+1 have same number of # positive divisors for i in range(2, N) : if (d[i] == d[i - 1]) : ans += 1 pre[i] = ans # Driver codeif __name__ == "__main__" : # Function call Positive_Divisors() n = 15 # Required answer print(pre[n]) # This code is contributed by Ryuga // C# implementation of the approachusing System; class GFG{ static int N =100005; // To store number of divisors and// Prefix sum of such numbersstatic int []d = new int[N];static int []pre = new int[N]; // Function to find the number of integers// 1 < x < N for which x and x + 1 have// the same number of positive divisorsstatic void Positive_Divisors(){ // Count the number of divisors for (int i = 1; i < N; i++) { // Run a loop upto sqrt(i) for (int j = 1; j * j <= i; j++) { // If j is divisor of i if (i % j == 0) { // If it is perfect square if (j * j == i) d[i]++; else d[i] += 2; } } } int ans = 0; // x and x+1 have same number of // positive divisors for (int i = 2; i < N; i++) { if (d[i] == d[i - 1]) ans++; pre[i] = ans; }} // Driver codepublic static void Main(String[] args){ // Function call Positive_Divisors(); int n = 15; // Required answer Console.WriteLine(pre[n]);}} // This code has been contributed by 29AjayKumar <?php // PHP implementation of the approach $N = 100005; // To store number of divisors and// Prefix sum of such numbers$d = array_fill(0,$N,NULL);$pre = array_fill(0,$N,NULL); // Function to find the number of integers// 1 < x < N for which x and x + 1 have// the same number of positive divisorsfunction Positive_Divisors(){ global $N,$d,$pre; // Count the number of divisors for ($i = 1; $i < $N; $i++) { // Run a loop upto sqrt(i) for ($j = 1; $j * $j <= $i; $j++) { // If j is divisor of i if ($i % $j == 0) { // If it is perfect square if ($j * $j == $i) $d[$i]++; else $d[$i] += 2; } } } $ans = 0; // x and x+1 have same number of // positive divisors for ($i = 2; $i < $N; $i++) { if ($d[$i] == $d[$i - 1]) $ans++; $pre[$i] = $ans; }} // Driver code // Function call Positive_Divisors(); $n = 15; // Required answer echo $pre[$n] ; return 0; // This code is contributed by ChitraNayal?> <script> // Javascript implementation of the approachconst N = 100005; // To store number of divisors and// Prefix sum of such numberslet d = new Array(N).fill(0);let pre = new Array(N).fill(0); // Function to find the number of integers// 1 < x < N for which x and x + 1 have// the same number of positive divisorsfunction Positive_Divisors(){ // Count the number of divisors for(let i = 1; i < N; i++) { // Run a loop upto sqrt(i) for(let j = 1; j * j <= i; j++) { // If j is divisor of i if (i % j == 0) { // If it is perfect square if (j * j == i) d[i]++; else d[i] += 2; } } } let ans = 0; // x and x+1 have same number of // positive divisors for(let i = 2; i < N; i++) { if (d[i] == d[i - 1]) ans++; pre[i] = ans; }} // Driver code // Function callPositive_Divisors();let n = 15; // Required answerdocument.write(pre[n]); // This code is contributed by souravmahato348 </script> 2 Time complexity: O(N3/2) Auxiliary Space: O(N) ankthon princiraj1992 29AjayKumar ukasp souravmahato348 samim2000 rishavnitro divisors frequency-counting number-theory prefix-sum Mathematical prefix-sum number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jun, 2022" }, { "code": null, "e": 167, "s": 28, "text": "Given an integer N. The task is to find the number of integers 1 < x < N, for which x and x + 1 have the same number of positive divisors." }, { "code": null, "e": 179, "s": 167, "text": "Examples: " }, { "code": null, "e": 281, "s": 179, "text": "Input: N = 3 Output: 1 Divisors(1) = 1 Divisors(2) = 1 and 2 Divisors(3) = 1 and 3 Only valid x is 2." }, { "code": null, "e": 308, "s": 281, "text": "Input: N = 15 Output: 2 " }, { "code": null, "e": 515, "s": 308, "text": "Approach: Find the number of divisors of all numbers below N and store them in an array. And count the number of integers x such that x and x + 1 have the same number of positive divisors by running a loop." }, { "code": null, "e": 568, "s": 515, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 572, "s": 568, "text": "C++" }, { "code": null, "e": 577, "s": 572, "text": "Java" }, { "code": null, "e": 585, "s": 577, "text": "Python3" }, { "code": null, "e": 588, "s": 585, "text": "C#" }, { "code": null, "e": 592, "s": 588, "text": "PHP" }, { "code": null, "e": 603, "s": 592, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 100005 // To store number of divisors and// Prefix sum of such numbersint d[N], pre[N]; // Function to find the number of integers// 1 < x < N for which x and x + 1 have// the same number of positive divisorsvoid Positive_Divisors(){ // Count the number of divisors for (int i = 1; i < N; i++) { // Run a loop upto sqrt(i) for (int j = 1; j * j <= i; j++) { // If j is divisor of i if (i % j == 0) { // If it is perfect square if (j * j == i) d[i]++; else d[i] += 2; } } } int ans = 0; // x and x+1 have same number of // positive divisors for (int i = 2; i < N; i++) { if (d[i] == d[i - 1]) ans++; pre[i] = ans; }} // Driver codeint main(){ // Function call Positive_Divisors(); int n = 15; // Required answer cout << pre[n] << endl; return 0;}", "e": 1652, "s": 603, "text": null }, { "code": "// Java implementation of the approachclass GFG{ static int N =100005; // To store number of divisors and// Prefix sum of such numbersstatic int d[] = new int[N], pre[] = new int[N]; // Function to find the number of integers// 1 < x < N for which x and x + 1 have// the same number of positive divisorsstatic void Positive_Divisors(){ // Count the number of divisors for (int i = 1; i < N; i++) { // Run a loop upto sqrt(i) for (int j = 1; j * j <= i; j++) { // If j is divisor of i if (i % j == 0) { // If it is perfect square if (j * j == i) d[i]++; else d[i] += 2; } } } int ans = 0; // x and x+1 have same number of // positive divisors for (int i = 2; i < N; i++) { if (d[i] == d[i - 1]) ans++; pre[i] = ans; }} // Driver codepublic static void main(String[] args){ // Function call Positive_Divisors(); int n = 15; // Required answer System.out.println(pre[n]);}} /* This code contributed by PrinciRaj1992 */", "e": 2804, "s": 1652, "text": null }, { "code": "# Python3 implementation of the above approachfrom math import sqrt; N = 100005 # To store number of divisors and# Prefix sum of such numbersd = [0] * Npre = [0] * N # Function to find the number of integers# 1 < x < N for which x and x + 1 have# the same number of positive divisorsdef Positive_Divisors() : # Count the number of divisors for i in range(N) : # Run a loop upto sqrt(i) for j in range(1, int(sqrt(i)) + 1) : # If j is divisor of i if (i % j == 0) : # If it is perfect square if (j * j == i) : d[i] += 1 else : d[i] += 2 ans = 0 # x and x+1 have same number of # positive divisors for i in range(2, N) : if (d[i] == d[i - 1]) : ans += 1 pre[i] = ans # Driver codeif __name__ == \"__main__\" : # Function call Positive_Divisors() n = 15 # Required answer print(pre[n]) # This code is contributed by Ryuga", "e": 3815, "s": 2804, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int N =100005; // To store number of divisors and// Prefix sum of such numbersstatic int []d = new int[N];static int []pre = new int[N]; // Function to find the number of integers// 1 < x < N for which x and x + 1 have// the same number of positive divisorsstatic void Positive_Divisors(){ // Count the number of divisors for (int i = 1; i < N; i++) { // Run a loop upto sqrt(i) for (int j = 1; j * j <= i; j++) { // If j is divisor of i if (i % j == 0) { // If it is perfect square if (j * j == i) d[i]++; else d[i] += 2; } } } int ans = 0; // x and x+1 have same number of // positive divisors for (int i = 2; i < N; i++) { if (d[i] == d[i - 1]) ans++; pre[i] = ans; }} // Driver codepublic static void Main(String[] args){ // Function call Positive_Divisors(); int n = 15; // Required answer Console.WriteLine(pre[n]);}} // This code has been contributed by 29AjayKumar", "e": 4992, "s": 3815, "text": null }, { "code": "<?php // PHP implementation of the approach $N = 100005; // To store number of divisors and// Prefix sum of such numbers$d = array_fill(0,$N,NULL);$pre = array_fill(0,$N,NULL); // Function to find the number of integers// 1 < x < N for which x and x + 1 have// the same number of positive divisorsfunction Positive_Divisors(){ global $N,$d,$pre; // Count the number of divisors for ($i = 1; $i < $N; $i++) { // Run a loop upto sqrt(i) for ($j = 1; $j * $j <= $i; $j++) { // If j is divisor of i if ($i % $j == 0) { // If it is perfect square if ($j * $j == $i) $d[$i]++; else $d[$i] += 2; } } } $ans = 0; // x and x+1 have same number of // positive divisors for ($i = 2; $i < $N; $i++) { if ($d[$i] == $d[$i - 1]) $ans++; $pre[$i] = $ans; }} // Driver code // Function call Positive_Divisors(); $n = 15; // Required answer echo $pre[$n] ; return 0; // This code is contributed by ChitraNayal?>", "e": 6107, "s": 4992, "text": null }, { "code": "<script> // Javascript implementation of the approachconst N = 100005; // To store number of divisors and// Prefix sum of such numberslet d = new Array(N).fill(0);let pre = new Array(N).fill(0); // Function to find the number of integers// 1 < x < N for which x and x + 1 have// the same number of positive divisorsfunction Positive_Divisors(){ // Count the number of divisors for(let i = 1; i < N; i++) { // Run a loop upto sqrt(i) for(let j = 1; j * j <= i; j++) { // If j is divisor of i if (i % j == 0) { // If it is perfect square if (j * j == i) d[i]++; else d[i] += 2; } } } let ans = 0; // x and x+1 have same number of // positive divisors for(let i = 2; i < N; i++) { if (d[i] == d[i - 1]) ans++; pre[i] = ans; }} // Driver code // Function callPositive_Divisors();let n = 15; // Required answerdocument.write(pre[n]); // This code is contributed by souravmahato348 </script>", "e": 7254, "s": 6107, "text": null }, { "code": null, "e": 7256, "s": 7254, "text": "2" }, { "code": null, "e": 7283, "s": 7258, "text": "Time complexity: O(N3/2)" }, { "code": null, "e": 7305, "s": 7283, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 7313, "s": 7305, "text": "ankthon" }, { "code": null, "e": 7327, "s": 7313, "text": "princiraj1992" }, { "code": null, "e": 7339, "s": 7327, "text": "29AjayKumar" }, { "code": null, "e": 7345, "s": 7339, "text": "ukasp" }, { "code": null, "e": 7361, "s": 7345, "text": "souravmahato348" }, { "code": null, "e": 7371, "s": 7361, "text": "samim2000" }, { "code": null, "e": 7383, "s": 7371, "text": "rishavnitro" }, { "code": null, "e": 7392, "s": 7383, "text": "divisors" }, { "code": null, "e": 7411, "s": 7392, "text": "frequency-counting" }, { "code": null, "e": 7425, "s": 7411, "text": "number-theory" }, { "code": null, "e": 7436, "s": 7425, "text": "prefix-sum" }, { "code": null, "e": 7449, "s": 7436, "text": "Mathematical" }, { "code": null, "e": 7460, "s": 7449, "text": "prefix-sum" }, { "code": null, "e": 7474, "s": 7460, "text": "number-theory" }, { "code": null, "e": 7487, "s": 7474, "text": "Mathematical" }, { "code": null, "e": 7585, "s": 7487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7609, "s": 7585, "text": "Merge two sorted arrays" }, { "code": null, "e": 7630, "s": 7609, "text": "Operators in C / C++" }, { "code": null, "e": 7652, "s": 7630, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 7666, "s": 7652, "text": "Prime Numbers" }, { "code": null, "e": 7708, "s": 7666, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 7761, "s": 7708, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 7798, "s": 7761, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 7830, "s": 7798, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 7873, "s": 7830, "text": "The Knight's tour problem | Backtracking-1" } ]
Convert Double to Integer in Java
At first, initialize a double value − double val = 978.65; Now, convert the Double to Integer value using intValue() method − Double d = new Double(val); int res = d.intValue(); Following is the program to convert Double to Integer in Java − public class Demo { public static void main(String args[]) { double val = 978.65; System.out.println("Double = "+val); Double d = new Double(val); int res = d.intValue(); System.out.println("Double to Integer value = "+res); } } Double = 978.65 Double to Integer value = 978
[ { "code": null, "e": 1225, "s": 1187, "text": "At first, initialize a double value −" }, { "code": null, "e": 1246, "s": 1225, "text": "double val = 978.65;" }, { "code": null, "e": 1313, "s": 1246, "text": "Now, convert the Double to Integer value using intValue() method −" }, { "code": null, "e": 1365, "s": 1313, "text": "Double d = new Double(val);\nint res = d.intValue();" }, { "code": null, "e": 1429, "s": 1365, "text": "Following is the program to convert Double to Integer in Java −" }, { "code": null, "e": 1694, "s": 1429, "text": "public class Demo {\n public static void main(String args[]) {\n double val = 978.65;\n System.out.println(\"Double = \"+val);\n Double d = new Double(val);\n int res = d.intValue();\n System.out.println(\"Double to Integer value = \"+res);\n }\n}" }, { "code": null, "e": 1740, "s": 1694, "text": "Double = 978.65\nDouble to Integer value = 978" } ]
Painting Fence Algorithm
03 Jun, 2021 Given a fence with n posts and k colors, find out the number of ways of painting the fence such that at most 2 adjacent posts have the same color. Since answer can be large return it modulo 10^9 + 7.Examples: Input : n = 2 k = 4 Output : 16 We have 4 colors and 2 posts. Ways when both posts have same color : 4 Ways when both posts have diff color : 4(choices for 1st post) * 3(choices for 2nd post) = 12 Input : n = 3 k = 2 Output : 6 Following image depicts the 6 possible ways of painting 3 posts with 2 colors: Consider the following image in which c, c’ and c” are respective colors of posts i, i-1, and i -2. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. According to the constraint of the problem, c = c’ = c” is not possible simultaneously, so either c’ != c or c” != c or both. There are k – 1 possibilities for c’ != c and k – 1 for c” != c. diff = no of ways when color of last two posts is different same = no of ways when color of last two posts is same total ways = diff + sum for n = 1 diff = k, same = 0 total = k for n = 2 diff = k * (k-1) //k choices for first post, k-1 for next same = k //k choices for common color of two posts total = k + k * (k-1) for n = 3 diff = k * (k-1)* (k-1) //(k-1) choices for the first place // k choices for the second place //(k-1) choices for the third place same = k * (k-1) * 2 // 2 is multiplied because consider two color R and B // R R B or B R R // B B R or R B B c'' != c, (k-1) choices for it Hence we deduce that, total[i] = same[i] + diff[i] same[i] = diff[i-1] diff[i] = (diff[i-1] + diff[i-2]) * (k-1) = total[i-1] * (k-1) Below is the implementation of the problem: C++ Java Python3 C# Javascript // C++ program for Painting Fence Algorithm// optimised version #include <bits/stdc++.h>using namespace std; // Returns count of ways to color k postslong countWays(int n, int k){ long dp[n + 1]; memset(dp, 0, sizeof(dp)); long long mod = 1000000007; dp[1] = k; dp[2] = k * k; for (int i = 3; i <= n; i++) { dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])) % mod; } return dp[n];} // Driver codeint main(){ int n = 3, k = 2; cout << countWays(n, k) << endl; return 0;} // Java program for Painting Fence Algorithmimport java.util.*; class GfG { // Returns count of ways to color k posts // using k colors static long countWays(int n, int k) { // To store results for subproblems long dp[] = new long[n + 1]; Arrays.fill(dp, 0); int mod = 1000000007; // There are k ways to color first post dp[1] = k; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) int same = 0, diff = k; // Fill for 2 posts onwards for (int i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = (int)(dp[i - 1] * (k - 1)); diff = diff % mod; // Total choices till i. dp[i] = (same + diff) % mod; } return dp[n]; } // Driver code public static void main(String[] args) { int n = 3, k = 2; System.out.println(countWays(n, k)); }} // This code contributed by Rajput-Ji # Python3 program for Painting Fence Algorithm# optimised version # Returns count of ways to color k postsdef countWays(n, k): dp = [0] * (n + 1) total = k mod = 1000000007 dp[1] = k dp[2] = k * k for i in range(3,n+1): dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])) % mod return dp[n] # Driver coden = 3k = 2print(countWays(n, k)) # This code is contributed by shubhamsingh10 // C# program for Painting Fence Algorithmusing System;public class GFG{ // Returns count of ways to color k posts // using k colors static long countWays(int n, int k) { // To store results for subproblems long[] dp = new long[n + 1]; Array.Fill(dp, 0); int mod = 1000000007; // There are k ways to color first post dp[1] = k; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) int same = 0, diff = k; // Fill for 2 posts onwards for (int i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = (int)(dp[i - 1] * (k - 1)); diff = diff % mod; // Total choices till i. dp[i] = (same + diff) % mod; } return dp[n]; } // Driver code static public void Main () { int n = 3, k = 2; Console.WriteLine(countWays(n, k)); }} // This code is contributed by avanitrachhadiya2155 <script> // Javascript program for Painting Fence Algorithm // Returns count of ways to color k posts // using k colors function countWays(n, k) { // To store results for subproblems let dp = new Array(n + 1); dp.fill(0); let mod = 1000000007; // There are k ways to color first post dp[1] = k; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) let same = 0, diff = k; // Fill for 2 posts onwards for (let i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = (dp[i - 1] * (k - 1)); diff = diff % mod; // Total choices till i. dp[i] = (same + diff) % mod; } return dp[n]; } let n = 3, k = 2; document.write(countWays(n, k)); // This code is contributed by divyeshrabadiya07.</script> Output: 6 Space optimization : We can optimize the above solution to use one variable instead of a table.Below is the implementation of the problem: C++ Java Python3 C# PHP Javascript // C++ program for Painting Fence Algorithm#include <bits/stdc++.h>using namespace std; // Returns count of ways to color k posts// using k colorslong countWays(int n, int k){ // There are k ways to color first post long total = k; int mod = 1000000007; // There are 0 ways for single post to // violate (same color) and k ways to // not violate (different color) int same = 0, diff = k; // Fill for 2 posts onwards for (int i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = total * (k - 1); diff = diff % mod; // Total choices till i. total = (same + diff) % mod; } return total;} // Driver codeint main(){ int n = 3, k = 2; cout << countWays(n, k) << endl; return 0;} // Java program for Painting Fence Algorithmclass GFG { // Returns count of ways to color k posts // using k colors static long countWays(int n, int k) { // There are k ways to color first post long total = k; int mod = 1000000007; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) int same = 0, diff = k; // Fill for 2 posts onwards for (int i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = (int)total * (k - 1); diff = diff % mod; // Total choices till i. total = (same + diff) % mod; } return total; } // Driver code public static void main(String[] args) { int n = 3, k = 2; System.out.println(countWays(n, k)); }} // This code is contributed by Mukul Singh # Python3 program for Painting# Fence Algorithm # Returns count of ways to color# k posts using k colorsdef countWays(n, k) : # There are k ways to color first post total = k mod = 1000000007 # There are 0 ways for single post to # violate (same color_ and k ways to # not violate (different color) same, diff = 0, k # Fill for 2 posts onwards for i in range(2, n + 1) : # Current same is same as # previous diff same = diff # We always have k-1 choices # for next post diff = total * (k - 1) diff = diff % mod # Total choices till i. total = (same + diff) % mod return total # Driver codeif __name__ == "__main__" : n, k = 3, 2 print(countWays(n, k)) # This code is contributed by Ryuga // C# program for Painting Fence Algorithmusing System; class GFG { // Returns count of ways to color k posts // using k colors static long countWays(int n, int k) { // There are k ways to color first post long total = k; int mod = 1000000007; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) long same = 0, diff = k; // Fill for 2 posts onwards for (int i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = total * (k - 1); diff = diff % mod; // Total choices till i. total = (same + diff) % mod; } return total; } // Driver code static void Main() { int n = 3, k = 2; Console.Write(countWays(n, k)); }} // This code is contributed by DrRoot_ <?php// PHP program for Painting Fence Algorithm // Returns count of ways to color k// posts using k colorsfunction countWays($n, $k){ // There are k ways to color first post $total = $k; $mod = 1000000007; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) $same = 0; $diff = $k; // Fill for 2 posts onwards for ($i = 2; $i <= $n; $i++) { // Current same is same as previous diff $same = $diff; // We always have k-1 choices for next post $diff = $total * ($k - 1); $diff = $diff % $mod; // Total choices till i. $total = ($same + $diff) % $mod; } return $total;} // Driver code$n = 3;$k = 2;echo countWays($n, $k) . "\n"; // This code is contributed by ita_c?> <script> // JavaScript program for Painting Fence Algorithm // Returns count of ways to color k posts // using k colors function countWays(n, k) { // There are k ways to color first post let total = k; let mod = 1000000007; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) let same = 0, diff = k; // Fill for 2 posts onwards for (let i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = total * (k - 1); diff = diff % mod; // Total choices till i. total = (same + diff) % mod; } return total; } let n = 3, k = 2; document.write(countWays(n, k)); </script> Output: 6 This article is contributed by Aditi Sharma. 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. Sagar Pant 1 ankthon DrRoot_ Code_Mech ukasp Rajput-Ji yashjaiswal10 SHUBHAMSINGH10 kevinmartin2428 aditosh007 avanitrachhadiya2155 nikheelindanoor123 divyeshrabadiya07 suresh07 Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Largest Sum Contiguous Subarray Program for Fibonacci numbers Longest Palindromic Substring | Set 1 Longest Increasing Subsequence | DP-3 Sieve of Eratosthenes
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jun, 2021" }, { "code": null, "e": 261, "s": 52, "text": "Given a fence with n posts and k colors, find out the number of ways of painting the fence such that at most 2 adjacent posts have the same color. Since answer can be large return it modulo 10^9 + 7.Examples:" }, { "code": null, "e": 492, "s": 261, "text": "Input : n = 2 k = 4\nOutput : 16\nWe have 4 colors and 2 posts.\nWays when both posts have same color : 4 \nWays when both posts have diff color :\n4(choices for 1st post) * 3(choices for \n2nd post) = 12\n\nInput : n = 3 k = 2\nOutput : 6" }, { "code": null, "e": 571, "s": 492, "text": "Following image depicts the 6 possible ways of painting 3 posts with 2 colors:" }, { "code": null, "e": 671, "s": 571, "text": "Consider the following image in which c, c’ and c” are respective colors of posts i, i-1, and i -2." }, { "code": null, "e": 680, "s": 671, "text": "Chapters" }, { "code": null, "e": 707, "s": 680, "text": "descriptions off, selected" }, { "code": null, "e": 757, "s": 707, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 780, "s": 757, "text": "captions off, selected" }, { "code": null, "e": 788, "s": 780, "text": "English" }, { "code": null, "e": 812, "s": 788, "text": "This is a modal window." }, { "code": null, "e": 881, "s": 812, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 903, "s": 881, "text": "End of dialog window." }, { "code": null, "e": 1094, "s": 903, "text": "According to the constraint of the problem, c = c’ = c” is not possible simultaneously, so either c’ != c or c” != c or both. There are k – 1 possibilities for c’ != c and k – 1 for c” != c." }, { "code": null, "e": 1983, "s": 1094, "text": " diff = no of ways when color of last\n two posts is different\n same = no of ways when color of last \n two posts is same\n total ways = diff + sum\n\nfor n = 1\n diff = k, same = 0\n total = k\n\nfor n = 2\n diff = k * (k-1) //k choices for\n first post, k-1 for next\n same = k //k choices for common \n color of two posts\n total = k + k * (k-1)\n\nfor n = 3\n diff = k * (k-1)* (k-1) \n //(k-1) choices for the first place \n // k choices for the second place\n //(k-1) choices for the third place\n same = k * (k-1) * 2\n // 2 is multiplied because consider two color R and B\n // R R B or B R R \n // B B R or R B B \n c'' != c, (k-1) choices for it\n\nHence we deduce that,\ntotal[i] = same[i] + diff[i]\nsame[i] = diff[i-1]\ndiff[i] = (diff[i-1] + diff[i-2]) * (k-1)\n = total[i-1] * (k-1)" }, { "code": null, "e": 2027, "s": 1983, "text": "Below is the implementation of the problem:" }, { "code": null, "e": 2031, "s": 2027, "text": "C++" }, { "code": null, "e": 2036, "s": 2031, "text": "Java" }, { "code": null, "e": 2044, "s": 2036, "text": "Python3" }, { "code": null, "e": 2047, "s": 2044, "text": "C#" }, { "code": null, "e": 2058, "s": 2047, "text": "Javascript" }, { "code": "// C++ program for Painting Fence Algorithm// optimised version #include <bits/stdc++.h>using namespace std; // Returns count of ways to color k postslong countWays(int n, int k){ long dp[n + 1]; memset(dp, 0, sizeof(dp)); long long mod = 1000000007; dp[1] = k; dp[2] = k * k; for (int i = 3; i <= n; i++) { dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])) % mod; } return dp[n];} // Driver codeint main(){ int n = 3, k = 2; cout << countWays(n, k) << endl; return 0;}", "e": 2565, "s": 2058, "text": null }, { "code": "// Java program for Painting Fence Algorithmimport java.util.*; class GfG { // Returns count of ways to color k posts // using k colors static long countWays(int n, int k) { // To store results for subproblems long dp[] = new long[n + 1]; Arrays.fill(dp, 0); int mod = 1000000007; // There are k ways to color first post dp[1] = k; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) int same = 0, diff = k; // Fill for 2 posts onwards for (int i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = (int)(dp[i - 1] * (k - 1)); diff = diff % mod; // Total choices till i. dp[i] = (same + diff) % mod; } return dp[n]; } // Driver code public static void main(String[] args) { int n = 3, k = 2; System.out.println(countWays(n, k)); }} // This code contributed by Rajput-Ji", "e": 3690, "s": 2565, "text": null }, { "code": "# Python3 program for Painting Fence Algorithm# optimised version # Returns count of ways to color k postsdef countWays(n, k): dp = [0] * (n + 1) total = k mod = 1000000007 dp[1] = k dp[2] = k * k for i in range(3,n+1): dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])) % mod return dp[n] # Driver coden = 3k = 2print(countWays(n, k)) # This code is contributed by shubhamsingh10", "e": 4122, "s": 3690, "text": null }, { "code": "// C# program for Painting Fence Algorithmusing System;public class GFG{ // Returns count of ways to color k posts // using k colors static long countWays(int n, int k) { // To store results for subproblems long[] dp = new long[n + 1]; Array.Fill(dp, 0); int mod = 1000000007; // There are k ways to color first post dp[1] = k; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) int same = 0, diff = k; // Fill for 2 posts onwards for (int i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = (int)(dp[i - 1] * (k - 1)); diff = diff % mod; // Total choices till i. dp[i] = (same + diff) % mod; } return dp[n]; } // Driver code static public void Main () { int n = 3, k = 2; Console.WriteLine(countWays(n, k)); }} // This code is contributed by avanitrachhadiya2155", "e": 5125, "s": 4122, "text": null }, { "code": "<script> // Javascript program for Painting Fence Algorithm // Returns count of ways to color k posts // using k colors function countWays(n, k) { // To store results for subproblems let dp = new Array(n + 1); dp.fill(0); let mod = 1000000007; // There are k ways to color first post dp[1] = k; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) let same = 0, diff = k; // Fill for 2 posts onwards for (let i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = (dp[i - 1] * (k - 1)); diff = diff % mod; // Total choices till i. dp[i] = (same + diff) % mod; } return dp[n]; } let n = 3, k = 2; document.write(countWays(n, k)); // This code is contributed by divyeshrabadiya07.</script>", "e": 6116, "s": 5125, "text": null }, { "code": null, "e": 6124, "s": 6116, "text": "Output:" }, { "code": null, "e": 6126, "s": 6124, "text": "6" }, { "code": null, "e": 6265, "s": 6126, "text": "Space optimization : We can optimize the above solution to use one variable instead of a table.Below is the implementation of the problem:" }, { "code": null, "e": 6269, "s": 6265, "text": "C++" }, { "code": null, "e": 6274, "s": 6269, "text": "Java" }, { "code": null, "e": 6282, "s": 6274, "text": "Python3" }, { "code": null, "e": 6285, "s": 6282, "text": "C#" }, { "code": null, "e": 6289, "s": 6285, "text": "PHP" }, { "code": null, "e": 6300, "s": 6289, "text": "Javascript" }, { "code": "// C++ program for Painting Fence Algorithm#include <bits/stdc++.h>using namespace std; // Returns count of ways to color k posts// using k colorslong countWays(int n, int k){ // There are k ways to color first post long total = k; int mod = 1000000007; // There are 0 ways for single post to // violate (same color) and k ways to // not violate (different color) int same = 0, diff = k; // Fill for 2 posts onwards for (int i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = total * (k - 1); diff = diff % mod; // Total choices till i. total = (same + diff) % mod; } return total;} // Driver codeint main(){ int n = 3, k = 2; cout << countWays(n, k) << endl; return 0;}", "e": 7143, "s": 6300, "text": null }, { "code": "// Java program for Painting Fence Algorithmclass GFG { // Returns count of ways to color k posts // using k colors static long countWays(int n, int k) { // There are k ways to color first post long total = k; int mod = 1000000007; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) int same = 0, diff = k; // Fill for 2 posts onwards for (int i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = (int)total * (k - 1); diff = diff % mod; // Total choices till i. total = (same + diff) % mod; } return total; } // Driver code public static void main(String[] args) { int n = 3, k = 2; System.out.println(countWays(n, k)); }} // This code is contributed by Mukul Singh", "e": 8144, "s": 7143, "text": null }, { "code": "# Python3 program for Painting# Fence Algorithm # Returns count of ways to color# k posts using k colorsdef countWays(n, k) : # There are k ways to color first post total = k mod = 1000000007 # There are 0 ways for single post to # violate (same color_ and k ways to # not violate (different color) same, diff = 0, k # Fill for 2 posts onwards for i in range(2, n + 1) : # Current same is same as # previous diff same = diff # We always have k-1 choices # for next post diff = total * (k - 1) diff = diff % mod # Total choices till i. total = (same + diff) % mod return total # Driver codeif __name__ == \"__main__\" : n, k = 3, 2 print(countWays(n, k)) # This code is contributed by Ryuga", "e": 8951, "s": 8144, "text": null }, { "code": "// C# program for Painting Fence Algorithmusing System; class GFG { // Returns count of ways to color k posts // using k colors static long countWays(int n, int k) { // There are k ways to color first post long total = k; int mod = 1000000007; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) long same = 0, diff = k; // Fill for 2 posts onwards for (int i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = total * (k - 1); diff = diff % mod; // Total choices till i. total = (same + diff) % mod; } return total; } // Driver code static void Main() { int n = 3, k = 2; Console.Write(countWays(n, k)); }} // This code is contributed by DrRoot_", "e": 9931, "s": 8951, "text": null }, { "code": "<?php// PHP program for Painting Fence Algorithm // Returns count of ways to color k// posts using k colorsfunction countWays($n, $k){ // There are k ways to color first post $total = $k; $mod = 1000000007; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) $same = 0; $diff = $k; // Fill for 2 posts onwards for ($i = 2; $i <= $n; $i++) { // Current same is same as previous diff $same = $diff; // We always have k-1 choices for next post $diff = $total * ($k - 1); $diff = $diff % $mod; // Total choices till i. $total = ($same + $diff) % $mod; } return $total;} // Driver code$n = 3;$k = 2;echo countWays($n, $k) . \"\\n\"; // This code is contributed by ita_c?>", "e": 10746, "s": 9931, "text": null }, { "code": "<script> // JavaScript program for Painting Fence Algorithm // Returns count of ways to color k posts // using k colors function countWays(n, k) { // There are k ways to color first post let total = k; let mod = 1000000007; // There are 0 ways for single post to // violate (same color_ and k ways to // not violate (different color) let same = 0, diff = k; // Fill for 2 posts onwards for (let i = 2; i <= n; i++) { // Current same is same as previous diff same = diff; // We always have k-1 choices for next post diff = total * (k - 1); diff = diff % mod; // Total choices till i. total = (same + diff) % mod; } return total; } let n = 3, k = 2; document.write(countWays(n, k)); </script>", "e": 11646, "s": 10746, "text": null }, { "code": null, "e": 11654, "s": 11646, "text": "Output:" }, { "code": null, "e": 11656, "s": 11654, "text": "6" }, { "code": null, "e": 12077, "s": 11656, "text": "This article is contributed by Aditi Sharma. 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": 12090, "s": 12077, "text": "Sagar Pant 1" }, { "code": null, "e": 12098, "s": 12090, "text": "ankthon" }, { "code": null, "e": 12106, "s": 12098, "text": "DrRoot_" }, { "code": null, "e": 12116, "s": 12106, "text": "Code_Mech" }, { "code": null, "e": 12122, "s": 12116, "text": "ukasp" }, { "code": null, "e": 12132, "s": 12122, "text": "Rajput-Ji" }, { "code": null, "e": 12146, "s": 12132, "text": "yashjaiswal10" }, { "code": null, "e": 12161, "s": 12146, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 12177, "s": 12161, "text": "kevinmartin2428" }, { "code": null, "e": 12188, "s": 12177, "text": "aditosh007" }, { "code": null, "e": 12209, "s": 12188, "text": "avanitrachhadiya2155" }, { "code": null, "e": 12228, "s": 12209, "text": "nikheelindanoor123" }, { "code": null, "e": 12246, "s": 12228, "text": "divyeshrabadiya07" }, { "code": null, "e": 12255, "s": 12246, "text": "suresh07" }, { "code": null, "e": 12262, "s": 12255, "text": "Arrays" }, { "code": null, "e": 12282, "s": 12262, "text": "Dynamic Programming" }, { "code": null, "e": 12289, "s": 12282, "text": "Arrays" }, { "code": null, "e": 12309, "s": 12289, "text": "Dynamic Programming" }, { "code": null, "e": 12407, "s": 12309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12422, "s": 12407, "text": "Arrays in Java" }, { "code": null, "e": 12468, "s": 12422, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 12536, "s": 12468, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 12580, "s": 12536, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 12612, "s": 12580, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 12644, "s": 12612, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 12674, "s": 12644, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 12712, "s": 12674, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 12750, "s": 12712, "text": "Longest Increasing Subsequence | DP-3" } ]
How to Rename and Move a File in Golang?
02 Apr, 2020 In the Go language, you are allowed to rename and move the existing file to a new path with the help of the Rename() method. This method is used to rename and move a file from the old path to the new path. If the given new path already exists and it is not in a directory, then this method will replace it. But OS-specific restrictions may apply when the given old path and the new path are in different directories. If the given path is incorrect, then it will throw an error of type *LinkError. It is defined under the os package so, you have to import os package in your program for accessing Remove() function. Syntax: func Rename(old_path, new_path string) error Example 1: // Go program to illustrate how to rename// and move a file in default directorypackage main import ( "log" "os") func main() { // Rename and Remove a file // Using Rename() function Original_Path := "GeeksforGeeks.txt" New_Path := "gfg.txt" e := os.Rename(Original_Path, New_Path) if e != nil { log.Fatal(e) } } Output: Before: After: Example 2: // Go program to illustrate how to rename // and remove a file in the new directorypackage main import ( "log" "os") func main() { // Rename and Remove a file // Using Rename() function Original_Path := "/Users/anki/Documents/new_folder/GeeksforGeeks.txt" New_Path := "/Users/anki/Documents/new_folder/myfolder/gfg.txt" e := os.Rename(Original_Path, New_Path) if e != nil { log.Fatal(e) }} Output: Before: After: Golang-File-Handling Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Apr, 2020" }, { "code": null, "e": 234, "s": 28, "text": "In the Go language, you are allowed to rename and move the existing file to a new path with the help of the Rename() method. This method is used to rename and move a file from the old path to the new path." }, { "code": null, "e": 445, "s": 234, "text": "If the given new path already exists and it is not in a directory, then this method will replace it. But OS-specific restrictions may apply when the given old path and the new path are in different directories." }, { "code": null, "e": 525, "s": 445, "text": "If the given path is incorrect, then it will throw an error of type *LinkError." }, { "code": null, "e": 643, "s": 525, "text": "It is defined under the os package so, you have to import os package in your program for accessing Remove() function." }, { "code": null, "e": 651, "s": 643, "text": "Syntax:" }, { "code": null, "e": 696, "s": 651, "text": "func Rename(old_path, new_path string) error" }, { "code": null, "e": 707, "s": 696, "text": "Example 1:" }, { "code": "// Go program to illustrate how to rename// and move a file in default directorypackage main import ( \"log\" \"os\") func main() { // Rename and Remove a file // Using Rename() function Original_Path := \"GeeksforGeeks.txt\" New_Path := \"gfg.txt\" e := os.Rename(Original_Path, New_Path) if e != nil { log.Fatal(e) } }", "e": 1068, "s": 707, "text": null }, { "code": null, "e": 1076, "s": 1068, "text": "Output:" }, { "code": null, "e": 1084, "s": 1076, "text": "Before:" }, { "code": null, "e": 1091, "s": 1084, "text": "After:" }, { "code": null, "e": 1102, "s": 1091, "text": "Example 2:" }, { "code": "// Go program to illustrate how to rename // and remove a file in the new directorypackage main import ( \"log\" \"os\") func main() { // Rename and Remove a file // Using Rename() function Original_Path := \"/Users/anki/Documents/new_folder/GeeksforGeeks.txt\" New_Path := \"/Users/anki/Documents/new_folder/myfolder/gfg.txt\" e := os.Rename(Original_Path, New_Path) if e != nil { log.Fatal(e) }}", "e": 1535, "s": 1102, "text": null }, { "code": null, "e": 1543, "s": 1535, "text": "Output:" }, { "code": null, "e": 1551, "s": 1543, "text": "Before:" }, { "code": null, "e": 1558, "s": 1551, "text": "After:" }, { "code": null, "e": 1579, "s": 1558, "text": "Golang-File-Handling" }, { "code": null, "e": 1591, "s": 1579, "text": "Go Language" } ]
HTML5 | <details> tag
06 Jun, 2022 The <details> tag is used for the content/information which is initially hidden but could be displayed if the user wishes to see it. This tag is used to create an interactive widget that the user can open or close. The content of the details tag is visible when open the set attributes. The summary tag is used with the details tag for specifying visible heading. This tag is new in HTML5. Syntax: <details> <summary> Text content </summary> <div> Content . . . > </details> Attributes: details open: The detail tag has an attribute called open which is used to display the hidden information by default. Example: The below code explains the details tag. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <!-- details tag starts here --> <details> <summary>GeeksforGeeks</summary> <p>A computer science portal for geeks</p> <div>It is a computer science portal where you can learn programming.</div> <!-- details tag ends here --> </details> </body></html> Output: Syntax: <details open> <summary> Text content </summary> <div> Content . . . > </details> Example: The below code explains the details open tag in details tag. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <!-- details open tag starts here --> <details open> <summary>GeeksforGeeks</summary> <p>A computer science portal for geeks</p> <div>It is a computer science portal where you can learn programming.</div> <!-- details open tag ends here --> </details> </body></html> Output: Supported Browsers: Google Chrome 12.0 and above Firefox 49.0 and above Opera 15.0 and above Safari 6.0 and above shubham_singh shubhamyadav4 avtarkumar719 hritikbhatnagar2182 HTML5 Picked CSS HTML Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Jun, 2022" }, { "code": null, "e": 418, "s": 53, "text": "The <details> tag is used for the content/information which is initially hidden but could be displayed if the user wishes to see it. This tag is used to create an interactive widget that the user can open or close. The content of the details tag is visible when open the set attributes. The summary tag is used with the details tag for specifying visible heading. " }, { "code": null, "e": 445, "s": 418, "text": "This tag is new in HTML5. " }, { "code": null, "e": 454, "s": 445, "text": "Syntax: " }, { "code": null, "e": 541, "s": 454, "text": "<details>\n <summary> Text content </summary>\n <div> Content . . . >\n</details>" }, { "code": null, "e": 553, "s": 541, "text": "Attributes:" }, { "code": null, "e": 722, "s": 553, "text": "details open: The detail tag has an attribute called open which is used to display the hidden information by default. Example: The below code explains the details tag." }, { "code": null, "e": 727, "s": 722, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <!-- details tag starts here --> <details> <summary>GeeksforGeeks</summary> <p>A computer science portal for geeks</p> <div>It is a computer science portal where you can learn programming.</div> <!-- details tag ends here --> </details> </body></html>", "e": 1123, "s": 727, "text": null }, { "code": null, "e": 1133, "s": 1123, "text": "Output: " }, { "code": null, "e": 1142, "s": 1133, "text": "Syntax: " }, { "code": null, "e": 1234, "s": 1142, "text": "<details open>\n <summary> Text content </summary>\n <div> Content . . . >\n</details>" }, { "code": null, "e": 1304, "s": 1234, "text": "Example: The below code explains the details open tag in details tag." }, { "code": null, "e": 1309, "s": 1304, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <!-- details open tag starts here --> <details open> <summary>GeeksforGeeks</summary> <p>A computer science portal for geeks</p> <div>It is a computer science portal where you can learn programming.</div> <!-- details open tag ends here --> </details> </body></html> ", "e": 1739, "s": 1309, "text": null }, { "code": null, "e": 1749, "s": 1739, "text": "Output: " }, { "code": null, "e": 1770, "s": 1749, "text": "Supported Browsers: " }, { "code": null, "e": 1799, "s": 1770, "text": "Google Chrome 12.0 and above" }, { "code": null, "e": 1822, "s": 1799, "text": "Firefox 49.0 and above" }, { "code": null, "e": 1843, "s": 1822, "text": "Opera 15.0 and above" }, { "code": null, "e": 1864, "s": 1843, "text": "Safari 6.0 and above" }, { "code": null, "e": 1878, "s": 1864, "text": "shubham_singh" }, { "code": null, "e": 1892, "s": 1878, "text": "shubhamyadav4" }, { "code": null, "e": 1906, "s": 1892, "text": "avtarkumar719" }, { "code": null, "e": 1926, "s": 1906, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1932, "s": 1926, "text": "HTML5" }, { "code": null, "e": 1939, "s": 1932, "text": "Picked" }, { "code": null, "e": 1943, "s": 1939, "text": "CSS" }, { "code": null, "e": 1948, "s": 1943, "text": "HTML" }, { "code": null, "e": 1975, "s": 1948, "text": "Web technologies Questions" }, { "code": null, "e": 1980, "s": 1975, "text": "HTML" }, { "code": null, "e": 2078, "s": 1980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2126, "s": 2078, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2188, "s": 2126, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2238, "s": 2188, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2296, "s": 2238, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 2346, "s": 2296, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2394, "s": 2346, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2456, "s": 2394, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2506, "s": 2456, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2530, "s": 2506, "text": "REST API (Introduction)" } ]
Data Reduction in Data Mining
15 Dec, 2021 Prerequisite – Data Mining The method of data reduction may achieve a condensed description of the original data which is much smaller in quantity but keeps the quality of the original data. Methods of data reduction: These are explained as following below. 1. Data Cube Aggregation: This technique is used to aggregate data in a simpler form. For example, imagine that information you gathered for your analysis for the years 2012 to 2014, that data includes the revenue of your company every three months. They involve you in the annual sales, rather than the quarterly average, So we can summarize the data in such a way that the resulting data summarizes the total sales per year instead of per quarter. It summarizes the data. 2. Dimension reduction: Whenever we come across any data which is weakly important, then we use the attribute required for our analysis. It reduces data size as it eliminates outdated or redundant features. Step-wise Forward Selection – The selection begins with an empty set of attributes later on we decide best of the original attributes on the set based on their relevance to other attributes. We know it as a p-value in statistics. Suppose there are the following attributes in the data set in which few attributes are redundant. Suppose there are the following attributes in the data set in which few attributes are redundant. Initial attribute Set: {X1, X2, X3, X4, X5, X6} Initial reduced attribute set: { } Step-1: {X1} Step-2: {X1, X2} Step-3: {X1, X2, X5} Final reduced attribute set: {X1, X2, X5} Step-wise Backward Selection – This selection starts with a set of complete attributes in the original data and at each point, it eliminates the worst remaining attribute in the set. Suppose there are the following attributes in the data set in which few attributes are redundant. Suppose there are the following attributes in the data set in which few attributes are redundant. Initial attribute Set: {X1, X2, X3, X4, X5, X6} Initial reduced attribute set: {X1, X2, X3, X4, X5, X6 } Step-1: {X1, X2, X3, X4, X5} Step-2: {X1, X2, X3, X5} Step-3: {X1, X2, X5} Final reduced attribute set: {X1, X2, X5} Combination of forwarding and Backward Selection – It allows us to remove the worst and select best attributes, saving time and making the process faster. 3. Data Compression: The data compression technique reduces the size of the files using different encoding mechanisms (Huffman Encoding & run-length Encoding). We can divide it into two types based on their compression techniques. Lossless Compression – Encoding techniques (Run Length Encoding) allows a simple and minimal data size reduction. Lossless data compression uses algorithms to restore the precise original data from the compressed data. Lossy Compression – Methods such as Discrete Wavelet transform technique, PCA (principal component analysis) are examples of this compression. For e.g., JPEG image format is a lossy compression, but we can find the meaning equivalent to the original the image. In lossy-data compression, the decompressed data may differ to the original data but are useful enough to retrieve information from them. 4. Numerosity Reduction: In this reduction technique the actual data is replaced with mathematical models or smaller representation of the data instead of actual data, it is important to only store the model parameter. Or non-parametric method such as clustering, histogram, sampling. For More Information on Numerosity Reduction Visit the link below: 5. Discretization & Concept Hierarchy Operation: Techniques of data discretization are used to divide the attributes of the continuous nature into data with intervals. We replace many constant values of the attributes by labels of small intervals. This means that mining results are shown in a concise, and easily understandable way. Top-down discretization – If you first consider one or a couple of points (so-called breakpoints or split points) to divide the whole set of attributes and repeat of this method up to the end, then the process is known as top-down discretization also known as splitting. Bottom-up discretization – If you first consider all the constant values as split-points, some are discarded through a combination of the neighbourhood values in the interval, that process is called bottom-up discretization. Concept Hierarchies: It reduces the data size by collecting and then replacing the low-level concepts (such as 43 for age) to high-level concepts (categorical variables such as middle age or Senior). For numeric data following techniques can be followed: Binning – Binning is the process of changing numerical variables into categorical counterparts. The number of categorical counterparts depends on the number of bins specified by the user. Histogram analysis – Like the process of binning, the histogram is used to partition the value for the attribute X, into disjoint ranges called brackets. There are several partitioning rules: Equal Frequency partitioning: Partitioning the values based on their number of occurrences in the data set. Equal Width Partitioning: Partitioning the values in a fixed gap based on the number of bins i.e. a set of values ranging from 0-20. Clustering: Grouping the similar data together. Equal Frequency partitioning: Partitioning the values based on their number of occurrences in the data set. Equal Width Partitioning: Partitioning the values in a fixed gap based on the number of bins i.e. a set of values ranging from 0-20. Clustering: Grouping the similar data together. Equal Frequency partitioning: Partitioning the values based on their number of occurrences in the data set. Equal Width Partitioning: Partitioning the values in a fixed gap based on the number of bins i.e. a set of values ranging from 0-20. Clustering: Grouping the similar data together. anikaseth98 simmytarika5 data mining DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Dec, 2021" }, { "code": null, "e": 220, "s": 28, "text": "Prerequisite – Data Mining The method of data reduction may achieve a condensed description of the original data which is much smaller in quantity but keeps the quality of the original data. " }, { "code": null, "e": 288, "s": 220, "text": "Methods of data reduction: These are explained as following below. " }, { "code": null, "e": 764, "s": 288, "text": "1. Data Cube Aggregation: This technique is used to aggregate data in a simpler form. For example, imagine that information you gathered for your analysis for the years 2012 to 2014, that data includes the revenue of your company every three months. They involve you in the annual sales, rather than the quarterly average, So we can summarize the data in such a way that the resulting data summarizes the total sales per year instead of per quarter. It summarizes the data. " }, { "code": null, "e": 972, "s": 764, "text": "2. Dimension reduction: Whenever we come across any data which is weakly important, then we use the attribute required for our analysis. It reduces data size as it eliminates outdated or redundant features. " }, { "code": null, "e": 1301, "s": 972, "text": "Step-wise Forward Selection – The selection begins with an empty set of attributes later on we decide best of the original attributes on the set based on their relevance to other attributes. We know it as a p-value in statistics. Suppose there are the following attributes in the data set in which few attributes are redundant. " }, { "code": null, "e": 1400, "s": 1301, "text": "Suppose there are the following attributes in the data set in which few attributes are redundant. " }, { "code": null, "e": 1580, "s": 1400, "text": "Initial attribute Set: {X1, X2, X3, X4, X5, X6}\nInitial reduced attribute set: { }\n\nStep-1: {X1}\nStep-2: {X1, X2}\nStep-3: {X1, X2, X5}\n\nFinal reduced attribute set: {X1, X2, X5} " }, { "code": null, "e": 1862, "s": 1580, "text": "Step-wise Backward Selection – This selection starts with a set of complete attributes in the original data and at each point, it eliminates the worst remaining attribute in the set. Suppose there are the following attributes in the data set in which few attributes are redundant. " }, { "code": null, "e": 1961, "s": 1862, "text": "Suppose there are the following attributes in the data set in which few attributes are redundant. " }, { "code": null, "e": 2187, "s": 1961, "text": "Initial attribute Set: {X1, X2, X3, X4, X5, X6}\nInitial reduced attribute set: {X1, X2, X3, X4, X5, X6 }\n\nStep-1: {X1, X2, X3, X4, X5}\nStep-2: {X1, X2, X3, X5}\nStep-3: {X1, X2, X5}\n\nFinal reduced attribute set: {X1, X2, X5} " }, { "code": null, "e": 2343, "s": 2187, "text": "Combination of forwarding and Backward Selection – It allows us to remove the worst and select best attributes, saving time and making the process faster. " }, { "code": null, "e": 2575, "s": 2343, "text": "3. Data Compression: The data compression technique reduces the size of the files using different encoding mechanisms (Huffman Encoding & run-length Encoding). We can divide it into two types based on their compression techniques. " }, { "code": null, "e": 2796, "s": 2575, "text": "Lossless Compression – Encoding techniques (Run Length Encoding) allows a simple and minimal data size reduction. Lossless data compression uses algorithms to restore the precise original data from the compressed data. " }, { "code": null, "e": 3196, "s": 2796, "text": "Lossy Compression – Methods such as Discrete Wavelet transform technique, PCA (principal component analysis) are examples of this compression. For e.g., JPEG image format is a lossy compression, but we can find the meaning equivalent to the original the image. In lossy-data compression, the decompressed data may differ to the original data but are useful enough to retrieve information from them. " }, { "code": null, "e": 3549, "s": 3196, "text": "4. Numerosity Reduction: In this reduction technique the actual data is replaced with mathematical models or smaller representation of the data instead of actual data, it is important to only store the model parameter. Or non-parametric method such as clustering, histogram, sampling. For More Information on Numerosity Reduction Visit the link below: " }, { "code": null, "e": 3884, "s": 3549, "text": "5. Discretization & Concept Hierarchy Operation: Techniques of data discretization are used to divide the attributes of the continuous nature into data with intervals. We replace many constant values of the attributes by labels of small intervals. This means that mining results are shown in a concise, and easily understandable way. " }, { "code": null, "e": 4156, "s": 3884, "text": "Top-down discretization – If you first consider one or a couple of points (so-called breakpoints or split points) to divide the whole set of attributes and repeat of this method up to the end, then the process is known as top-down discretization also known as splitting. " }, { "code": null, "e": 4382, "s": 4156, "text": "Bottom-up discretization – If you first consider all the constant values as split-points, some are discarded through a combination of the neighbourhood values in the interval, that process is called bottom-up discretization. " }, { "code": null, "e": 4583, "s": 4382, "text": "Concept Hierarchies: It reduces the data size by collecting and then replacing the low-level concepts (such as 43 for age) to high-level concepts (categorical variables such as middle age or Senior). " }, { "code": null, "e": 4639, "s": 4583, "text": "For numeric data following techniques can be followed: " }, { "code": null, "e": 4828, "s": 4639, "text": "Binning – Binning is the process of changing numerical variables into categorical counterparts. The number of categorical counterparts depends on the number of bins specified by the user. " }, { "code": null, "e": 5311, "s": 4828, "text": "Histogram analysis – Like the process of binning, the histogram is used to partition the value for the attribute X, into disjoint ranges called brackets. There are several partitioning rules: Equal Frequency partitioning: Partitioning the values based on their number of occurrences in the data set. Equal Width Partitioning: Partitioning the values in a fixed gap based on the number of bins i.e. a set of values ranging from 0-20. Clustering: Grouping the similar data together. " }, { "code": null, "e": 5602, "s": 5311, "text": "Equal Frequency partitioning: Partitioning the values based on their number of occurrences in the data set. Equal Width Partitioning: Partitioning the values in a fixed gap based on the number of bins i.e. a set of values ranging from 0-20. Clustering: Grouping the similar data together. " }, { "code": null, "e": 5711, "s": 5602, "text": "Equal Frequency partitioning: Partitioning the values based on their number of occurrences in the data set. " }, { "code": null, "e": 5845, "s": 5711, "text": "Equal Width Partitioning: Partitioning the values in a fixed gap based on the number of bins i.e. a set of values ranging from 0-20. " }, { "code": null, "e": 5895, "s": 5845, "text": "Clustering: Grouping the similar data together. " }, { "code": null, "e": 5909, "s": 5897, "text": "anikaseth98" }, { "code": null, "e": 5922, "s": 5909, "text": "simmytarika5" }, { "code": null, "e": 5934, "s": 5922, "text": "data mining" }, { "code": null, "e": 5939, "s": 5934, "text": "DBMS" }, { "code": null, "e": 5944, "s": 5939, "text": "DBMS" } ]
How To Dynamically Resize Button Text in Tkinter?
16 Oct, 2021 Prerequisite: Python GUI – tkinter, Dynamically Resize Buttons When Resizing a Window using Tkinter In this article, we will see how to make the button text size dynamic. Dynamic means whenever button size will change, the button text size will also change. In Tkinter there is no in-built function, that will change the button text size dynamically. Approach: Create button and set sticky to all direction Set bind, what bind will do, whenever button size change it will call resize function that we will create later. Inside the resize function, we will have a different condition, depends on the main window geometry/size. Set row and column configure Let’s understand with step-by-step implementation: Step 1: Creates a normal Tkinter window. Python3 # Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Execute tkinterroot.mainloop() Output: Step 2: Create a button inside the main window. Python3 # Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Create Buttonsbutton_1 = Button(root , text = "Button 1") # Set gridbutton_1.grid(row = 0,column = 0) # Execute tkinterroot.mainloop() Output: Step 3: Resizing the button text size Inside the resize function, the “e” value will tell the main window width and height. Python3 # resize button text sizedef resize(e): # get window width size = e.width/10 # define text size on different condition # if window height is greater # than 300 and less than 400 (set font size 40) if e.height <= 400 and e.height > 300: button_1.config(font = ("Helvetica", 40)) # if window height is greater than # 200 and less than 300 (set font size 30) elif e.height < 300 and e.height > 200: button_1.config(font = ("Helvetica", 30)) # if window height is less than 200 (set font size 40) elif e.height < 200: button_1.config(font = ("Helvetica", 40)) Below is the full implementation: Python3 # Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Specify GridGrid.columnconfigure(root, index = 0, weight = 1) Grid.rowconfigure(root, 0, weight = 1) # Create Buttonsbutton_1 = Button(root, text = "Button 1") # Set gridbutton_1.grid(row = 0, column = 0, sticky = "NSEW") # resize button text sizedef resize(e): # get window width size = e.width/10 # define text size on different condition # if window height is greater # than 300 and less than 400 (set font size 40) if e.height <= 400 and e.height > 300: button_1.config(font = ("Helvetica", 40)) # if window height is greater than # 200 and less than 300 (set font size 30) elif e.height < 300 and e.height > 200: button_1.config(font = ("Helvetica", 30)) # if window height is less # than 200 (set font size 40) elif e.height < 200: button_1.config(font = ("Helvetica", 40)) # it will call resize function# when window size will changeroot.bind('<Configure>', resize) # Execute tkinterroot.mainloop() Output: ruhelaa48 Python-tkinter 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? Enumerate() in Python Python Dictionary Python OOPs Concepts Different ways to create Pandas Dataframe Python Classes and Objects Introduction To PYTHON Stack in Python Queue in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Oct, 2021" }, { "code": null, "e": 128, "s": 28, "text": "Prerequisite: Python GUI – tkinter, Dynamically Resize Buttons When Resizing a Window using Tkinter" }, { "code": null, "e": 379, "s": 128, "text": "In this article, we will see how to make the button text size dynamic. Dynamic means whenever button size will change, the button text size will also change. In Tkinter there is no in-built function, that will change the button text size dynamically." }, { "code": null, "e": 389, "s": 379, "text": "Approach:" }, { "code": null, "e": 435, "s": 389, "text": "Create button and set sticky to all direction" }, { "code": null, "e": 548, "s": 435, "text": "Set bind, what bind will do, whenever button size change it will call resize function that we will create later." }, { "code": null, "e": 654, "s": 548, "text": "Inside the resize function, we will have a different condition, depends on the main window geometry/size." }, { "code": null, "e": 683, "s": 654, "text": "Set row and column configure" }, { "code": null, "e": 734, "s": 683, "text": "Let’s understand with step-by-step implementation:" }, { "code": null, "e": 775, "s": 734, "text": "Step 1: Creates a normal Tkinter window." }, { "code": null, "e": 783, "s": 775, "text": "Python3" }, { "code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # Execute tkinterroot.mainloop()", "e": 924, "s": 783, "text": null }, { "code": null, "e": 932, "s": 924, "text": "Output:" }, { "code": null, "e": 980, "s": 932, "text": "Step 2: Create a button inside the main window." }, { "code": null, "e": 988, "s": 980, "text": "Python3" }, { "code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # Create Buttonsbutton_1 = Button(root , text = \"Button 1\") # Set gridbutton_1.grid(row = 0,column = 0) # Execute tkinterroot.mainloop()", "e": 1227, "s": 988, "text": null }, { "code": null, "e": 1235, "s": 1227, "text": "Output:" }, { "code": null, "e": 1273, "s": 1235, "text": "Step 3: Resizing the button text size" }, { "code": null, "e": 1359, "s": 1273, "text": "Inside the resize function, the “e” value will tell the main window width and height." }, { "code": null, "e": 1367, "s": 1359, "text": "Python3" }, { "code": "# resize button text sizedef resize(e): # get window width size = e.width/10 # define text size on different condition # if window height is greater # than 300 and less than 400 (set font size 40) if e.height <= 400 and e.height > 300: button_1.config(font = (\"Helvetica\", 40)) # if window height is greater than # 200 and less than 300 (set font size 30) elif e.height < 300 and e.height > 200: button_1.config(font = (\"Helvetica\", 30)) # if window height is less than 200 (set font size 40) elif e.height < 200: button_1.config(font = (\"Helvetica\", 40))", "e": 1986, "s": 1367, "text": null }, { "code": null, "e": 2020, "s": 1986, "text": "Below is the full implementation:" }, { "code": null, "e": 2028, "s": 2020, "text": "Python3" }, { "code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # Specify GridGrid.columnconfigure(root, index = 0, weight = 1) Grid.rowconfigure(root, 0, weight = 1) # Create Buttonsbutton_1 = Button(root, text = \"Button 1\") # Set gridbutton_1.grid(row = 0, column = 0, sticky = \"NSEW\") # resize button text sizedef resize(e): # get window width size = e.width/10 # define text size on different condition # if window height is greater # than 300 and less than 400 (set font size 40) if e.height <= 400 and e.height > 300: button_1.config(font = (\"Helvetica\", 40)) # if window height is greater than # 200 and less than 300 (set font size 30) elif e.height < 300 and e.height > 200: button_1.config(font = (\"Helvetica\", 30)) # if window height is less # than 200 (set font size 40) elif e.height < 200: button_1.config(font = (\"Helvetica\", 40)) # it will call resize function# when window size will changeroot.bind('<Configure>', resize) # Execute tkinterroot.mainloop()", "e": 3154, "s": 2028, "text": null }, { "code": null, "e": 3162, "s": 3154, "text": "Output:" }, { "code": null, "e": 3172, "s": 3162, "text": "ruhelaa48" }, { "code": null, "e": 3187, "s": 3172, "text": "Python-tkinter" }, { "code": null, "e": 3194, "s": 3187, "text": "Python" }, { "code": null, "e": 3292, "s": 3194, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3322, "s": 3292, "text": "Iterate over a list in Python" }, { "code": null, "e": 3367, "s": 3322, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 3389, "s": 3367, "text": "Enumerate() in Python" }, { "code": null, "e": 3407, "s": 3389, "text": "Python Dictionary" }, { "code": null, "e": 3428, "s": 3407, "text": "Python OOPs Concepts" }, { "code": null, "e": 3470, "s": 3428, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3497, "s": 3470, "text": "Python Classes and Objects" }, { "code": null, "e": 3520, "s": 3497, "text": "Introduction To PYTHON" }, { "code": null, "e": 3536, "s": 3520, "text": "Stack in Python" } ]
Image Processing in Java – Colored to Red Green Blue Image Conversion
14 Nov, 2021 Prerequisites: 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 In this set, we will be converting a colored image to an image with either red effect, green effect, or blue effect. Colored Image – The colored image or RGB color model is an additive mixing model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. The basic idea is to get the pixel value for each coordinate and then keep the desired resultant color pixel value to be the same and set the other two as zero. Get the RGB value of the pixel.Set the RGB values as follows: R: NO CHANGEG: Set to 0B: Set to 0Replace the R, G, and B values of the pixel with the values calculated in step 2.Repeat Step 1 to Step 3 for each pixel of the image. Get the RGB value of the pixel. Set the RGB values as follows: R: NO CHANGEG: Set to 0B: Set to 0 R: NO CHANGE G: Set to 0 B: Set to 0 Replace the R, G, and B values of the pixel with the values calculated in step 2. Repeat Step 1 to Step 3 for each pixel of the image. Java // Java program to demonstrate colored// to red colored image conversion import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class RedImage { public static void main(String args[]) throws IOException { BufferedImage img = null; File f = null; // read image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png"); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // get width and height int width = img.getWidth(); int height = img.getHeight(); // convert to red image for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int p = img.getRGB(x, y); int a = (p >> 24) & 0xff; int r = (p >> 16) & 0xff; // set new RGB keeping the r // value same as in original image // and setting g and b as 0. p = (a << 24) | (r << 16) | (0 << 8) | 0; img.setRGB(x, y, p); } } // write image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/GFG.png"); ImageIO.write(img, "png", f); } catch (IOException e) { System.out.println(e); } }} Note: This code will not run on an online IDE as it needs an image on a disk. Get the RGB value of the pixel.Set the RGB values as follows: R: Set to 0G: NO CHANGEB: Set to 0Replace the R, G, and B values of the pixel with the values calculated in step 2.Repeat Step 1 to Step 3 for each pixel of the image. Get the RGB value of the pixel. Set the RGB values as follows: R: Set to 0G: NO CHANGEB: Set to 0 R: Set to 0 G: NO CHANGE B: Set to 0 Replace the R, G, and B values of the pixel with the values calculated in step 2. Repeat Step 1 to Step 3 for each pixel of the image. Java // Java program to demonstrate colored// to green coloured image conversion import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class GreenImage { public static void main(String args[]) throws IOException { BufferedImage img = null; File f = null; // read image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png"); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // get width and height int width = img.getWidth(); int height = img.getHeight(); // convert to green image for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int p = img.getRGB(x, y); int a = (p >> 24) & 0xff; int g = (p >> 8) & 0xff; // set new RGB // keeping the g value same as in original // image and setting r and b as 0. p = (a << 24) | (0 << 16) | (g << 8) | 0; img.setRGB(x, y, p); } } // write image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/GFG.png"); ImageIO.write(img, "png", f); } catch (IOException e) { System.out.println(e); } }} Note: This code will not run on an online IDE as it needs an image on a disk. Get the RGB value of the pixel.Set the RGB values as follows: R: Set to 0G: Set to 0B: NO CHANGEReplace the R, G, and B values of the pixel with the values calculated in step 2.Repeat Step 1 to Step 3 for each pixel of the image. Get the RGB value of the pixel. Set the RGB values as follows: R: Set to 0G: Set to 0B: NO CHANGE R: Set to 0 G: Set to 0 B: NO CHANGE Replace the R, G, and B values of the pixel with the values calculated in step 2. Repeat Step 1 to Step 3 for each pixel of the image. Java // Java program to demonstrate colored// to blue coloured image conversion import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class BlueImage { public static void main(String args[]) throws IOException { BufferedImage img = null; File f = null; // read image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png"); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // get width and height int width = img.getWidth(); int height = img.getHeight(); // convert to blue image for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int p = img.getRGB(x, y); int a = (p >> 24) & 0xff; int b = p & 0xff; // set new RGB // keeping the b value same as in original // image and setting r and g as 0. p = (a << 24) | (0 << 16) | (0 << 8) | b; img.setRGB(x, y, p); } } // write image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/GFG.png"); ImageIO.write(img, "png", f); } catch (IOException e) { System.out.println(e); } }} Note: This code will not run on an online IDE as it needs an image on a disk. 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. ruhelaa48 nishkarshgandhi Image-Processing Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Nov, 2021" }, { "code": null, "e": 70, "s": 54, "text": "Prerequisites: " }, { "code": null, "e": 112, "s": 70, "text": "Image Processing in Java – Read and Write" }, { "code": null, "e": 158, "s": 112, "text": "Image Processing In Java – Get and Set Pixels" }, { "code": null, "e": 229, "s": 158, "text": "Image Processing in Java – Colored Image to Grayscale Image Conversion" }, { "code": null, "e": 299, "s": 229, "text": "Image Processing in Java – Colored Image to Negative Image Conversion" }, { "code": null, "e": 416, "s": 299, "text": "In this set, we will be converting a colored image to an image with either red effect, green effect, or blue effect." }, { "code": null, "e": 607, "s": 416, "text": "Colored Image – The colored image or RGB color model is an additive mixing model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. " }, { "code": null, "e": 768, "s": 607, "text": "The basic idea is to get the pixel value for each coordinate and then keep the desired resultant color pixel value to be the same and set the other two as zero." }, { "code": null, "e": 998, "s": 768, "text": "Get the RGB value of the pixel.Set the RGB values as follows: R: NO CHANGEG: Set to 0B: Set to 0Replace the R, G, and B values of the pixel with the values calculated in step 2.Repeat Step 1 to Step 3 for each pixel of the image." }, { "code": null, "e": 1030, "s": 998, "text": "Get the RGB value of the pixel." }, { "code": null, "e": 1096, "s": 1030, "text": "Set the RGB values as follows: R: NO CHANGEG: Set to 0B: Set to 0" }, { "code": null, "e": 1109, "s": 1096, "text": "R: NO CHANGE" }, { "code": null, "e": 1121, "s": 1109, "text": "G: Set to 0" }, { "code": null, "e": 1133, "s": 1121, "text": "B: Set to 0" }, { "code": null, "e": 1215, "s": 1133, "text": "Replace the R, G, and B values of the pixel with the values calculated in step 2." }, { "code": null, "e": 1268, "s": 1215, "text": "Repeat Step 1 to Step 3 for each pixel of the image." }, { "code": null, "e": 1273, "s": 1268, "text": "Java" }, { "code": "// Java program to demonstrate colored// to red colored image conversion import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class RedImage { public static void main(String args[]) throws IOException { BufferedImage img = null; File f = null; // read image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png\"); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // get width and height int width = img.getWidth(); int height = img.getHeight(); // convert to red image for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int p = img.getRGB(x, y); int a = (p >> 24) & 0xff; int r = (p >> 16) & 0xff; // set new RGB keeping the r // value same as in original image // and setting g and b as 0. p = (a << 24) | (r << 16) | (0 << 8) | 0; img.setRGB(x, y, p); } } // write image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/GFG.png\"); ImageIO.write(img, \"png\", f); } catch (IOException e) { System.out.println(e); } }}", "e": 2739, "s": 1273, "text": null }, { "code": null, "e": 2818, "s": 2739, "text": "Note: This code will not run on an online IDE as it needs an image on a disk. " }, { "code": null, "e": 3048, "s": 2818, "text": "Get the RGB value of the pixel.Set the RGB values as follows: R: Set to 0G: NO CHANGEB: Set to 0Replace the R, G, and B values of the pixel with the values calculated in step 2.Repeat Step 1 to Step 3 for each pixel of the image." }, { "code": null, "e": 3080, "s": 3048, "text": "Get the RGB value of the pixel." }, { "code": null, "e": 3146, "s": 3080, "text": "Set the RGB values as follows: R: Set to 0G: NO CHANGEB: Set to 0" }, { "code": null, "e": 3158, "s": 3146, "text": "R: Set to 0" }, { "code": null, "e": 3171, "s": 3158, "text": "G: NO CHANGE" }, { "code": null, "e": 3183, "s": 3171, "text": "B: Set to 0" }, { "code": null, "e": 3265, "s": 3183, "text": "Replace the R, G, and B values of the pixel with the values calculated in step 2." }, { "code": null, "e": 3318, "s": 3265, "text": "Repeat Step 1 to Step 3 for each pixel of the image." }, { "code": null, "e": 3323, "s": 3318, "text": "Java" }, { "code": "// Java program to demonstrate colored// to green coloured image conversion import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class GreenImage { public static void main(String args[]) throws IOException { BufferedImage img = null; File f = null; // read image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png\"); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // get width and height int width = img.getWidth(); int height = img.getHeight(); // convert to green image for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int p = img.getRGB(x, y); int a = (p >> 24) & 0xff; int g = (p >> 8) & 0xff; // set new RGB // keeping the g value same as in original // image and setting r and b as 0. p = (a << 24) | (0 << 16) | (g << 8) | 0; img.setRGB(x, y, p); } } // write image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/GFG.png\"); ImageIO.write(img, \"png\", f); } catch (IOException e) { System.out.println(e); } }}", "e": 4795, "s": 3323, "text": null }, { "code": null, "e": 4874, "s": 4795, "text": "Note: This code will not run on an online IDE as it needs an image on a disk. " }, { "code": null, "e": 5104, "s": 4874, "text": "Get the RGB value of the pixel.Set the RGB values as follows: R: Set to 0G: Set to 0B: NO CHANGEReplace the R, G, and B values of the pixel with the values calculated in step 2.Repeat Step 1 to Step 3 for each pixel of the image." }, { "code": null, "e": 5136, "s": 5104, "text": "Get the RGB value of the pixel." }, { "code": null, "e": 5202, "s": 5136, "text": "Set the RGB values as follows: R: Set to 0G: Set to 0B: NO CHANGE" }, { "code": null, "e": 5214, "s": 5202, "text": "R: Set to 0" }, { "code": null, "e": 5226, "s": 5214, "text": "G: Set to 0" }, { "code": null, "e": 5239, "s": 5226, "text": "B: NO CHANGE" }, { "code": null, "e": 5321, "s": 5239, "text": "Replace the R, G, and B values of the pixel with the values calculated in step 2." }, { "code": null, "e": 5374, "s": 5321, "text": "Repeat Step 1 to Step 3 for each pixel of the image." }, { "code": null, "e": 5379, "s": 5374, "text": "Java" }, { "code": "// Java program to demonstrate colored// to blue coloured image conversion import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class BlueImage { public static void main(String args[]) throws IOException { BufferedImage img = null; File f = null; // read image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png\"); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // get width and height int width = img.getWidth(); int height = img.getHeight(); // convert to blue image for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int p = img.getRGB(x, y); int a = (p >> 24) & 0xff; int b = p & 0xff; // set new RGB // keeping the b value same as in original // image and setting r and g as 0. p = (a << 24) | (0 << 16) | (0 << 8) | b; img.setRGB(x, y, p); } } // write image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/GFG.png\"); ImageIO.write(img, \"png\", f); } catch (IOException e) { System.out.println(e); } }}", "e": 6841, "s": 5379, "text": null }, { "code": null, "e": 6920, "s": 6841, "text": "Note: This code will not run on an online IDE as it needs an image on a disk. " }, { "code": null, "e": 7343, "s": 6920, "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": 7353, "s": 7343, "text": "ruhelaa48" }, { "code": null, "e": 7369, "s": 7353, "text": "nishkarshgandhi" }, { "code": null, "e": 7386, "s": 7369, "text": "Image-Processing" }, { "code": null, "e": 7391, "s": 7386, "text": "Java" }, { "code": null, "e": 7396, "s": 7391, "text": "Java" } ]
Popup Menu in Android With Example
26 Nov, 2020 In android, Menu is an important part of the UI component which is used to provide some common functionality around the application. With the help of the menu, users can experience smooth and consistent experiences throughout the application. In android, we have three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are the following: Android Options Menu: Android Options Menu is a primary collection of menu items in an android application and useful for actions that have a global impact on the searching application. Android Context Menu: Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and useful for elements that affect the selected content or context frame. Android Popup Menu: Android Popup Menu displays a list of items in a vertical list which presents to the view that invoked the menu and useful to provide an overflow of actions that related to specific content. So in this article, we are going to discuss the Popup Menu. A PopupMenu displays a Menu in a popup window anchored to a View. The popup will be shown below the anchored View if there is room(space) otherwise above the View. If any IME(Input Method Editor) is visible the popup will not overlap it until the View(to which the popup is anchored) is touched. Touching outside the popup window will dismiss it. In this example, we are going to make a popup menu anchored to a Button and on click, the popup menu will appear, and on a touch of the popup menu item, a Toast message will be shown. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file In this step, we will add a button to the layout file and give it an id as clickBtn to it. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/clickBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#0F9D58" android:text="Click Me" android:textColor="#ffffff" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. XML <resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color></resources> Step 3: Creating menu directory and menu file First, we will create a menu director which will contain the menu file. Go to app > res > right-click > New > Android Resource Directory and give Directory name and Resource type as menu. Now, we will create a popup_menu file inside that menu resource directory. Go to app > res > menu > right-click > New > Menu Resource File and create a menu resource file and name it as popup_menu. In the popup_menu file, we will add menu items. Below is the code snippet for the popup_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/java" android:title="Java" /> <item android:id="@+id/kotlin" android:title="Kotlin" /> <item android:id="@+id/android" android:title="Android" /> <item android:id="@+id/react_native" android:title="React Native" /> </menu> Step 4: Working with the MainActivity.java file In the MainActivity.java file, we will get the reference of the Button and initialize it. Add onClick behavior to the button and inflate the popup menu to it. Below is the code snippet for the MainActivity.java file. Java import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.PopupMenu;import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Referencing and Initializing the button button = (Button) findViewById(R.id.clickBtn); // Setting onClick behavior to the button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Initializing the popup menu and giving the reference as current context PopupMenu popupMenu = new PopupMenu(MainActivity.this, button); // Inflating popup menu from popup_menu.xml file popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { // Toast message on menu item clicked Toast.makeText(MainActivity.this, "You Clicked " + menuItem.getTitle(), Toast.LENGTH_SHORT).show(); return true; } }); // Showing the popup menu popupMenu.show(); } }); }} android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Nov, 2020" }, { "code": null, "e": 467, "s": 52, "text": "In android, Menu is an important part of the UI component which is used to provide some common functionality around the application. With the help of the menu, users can experience smooth and consistent experiences throughout the application. In android, we have three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are the following:" }, { "code": null, "e": 653, "s": 467, "text": "Android Options Menu: Android Options Menu is a primary collection of menu items in an android application and useful for actions that have a global impact on the searching application." }, { "code": null, "e": 859, "s": 653, "text": "Android Context Menu: Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and useful for elements that affect the selected content or context frame." }, { "code": null, "e": 1070, "s": 859, "text": "Android Popup Menu: Android Popup Menu displays a list of items in a vertical list which presents to the view that invoked the menu and useful to provide an overflow of actions that related to specific content." }, { "code": null, "e": 1477, "s": 1070, "text": "So in this article, we are going to discuss the Popup Menu. A PopupMenu displays a Menu in a popup window anchored to a View. The popup will be shown below the anchored View if there is room(space) otherwise above the View. If any IME(Input Method Editor) is visible the popup will not overlap it until the View(to which the popup is anchored) is touched. Touching outside the popup window will dismiss it." }, { "code": null, "e": 1826, "s": 1477, "text": "In this example, we are going to make a popup menu anchored to a Button and on click, the popup menu will appear, and on a touch of the popup menu item, a Toast message will be shown. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 1855, "s": 1826, "text": "Step 1: Create a New Project" }, { "code": null, "e": 2017, "s": 1855, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 2065, "s": 2017, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 2156, "s": 2065, "text": "In this step, we will add a button to the layout file and give it an id as clickBtn to it." }, { "code": null, "e": 2160, "s": 2156, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/clickBtn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#0F9D58\" android:text=\"Click Me\" android:textColor=\"#ffffff\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 3031, "s": 2160, "text": null }, { "code": null, "e": 3197, "s": 3031, "text": "Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. " }, { "code": null, "e": 3201, "s": 3197, "text": "XML" }, { "code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color></resources>", "e": 3366, "s": 3201, "text": null }, { "code": null, "e": 3412, "s": 3366, "text": "Step 3: Creating menu directory and menu file" }, { "code": null, "e": 3600, "s": 3412, "text": "First, we will create a menu director which will contain the menu file. Go to app > res > right-click > New > Android Resource Directory and give Directory name and Resource type as menu." }, { "code": null, "e": 3901, "s": 3600, "text": "Now, we will create a popup_menu file inside that menu resource directory. Go to app > res > menu > right-click > New > Menu Resource File and create a menu resource file and name it as popup_menu. In the popup_menu file, we will add menu items. Below is the code snippet for the popup_menu.xml file." }, { "code": null, "e": 3905, "s": 3901, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:id=\"@+id/java\" android:title=\"Java\" /> <item android:id=\"@+id/kotlin\" android:title=\"Kotlin\" /> <item android:id=\"@+id/android\" android:title=\"Android\" /> <item android:id=\"@+id/react_native\" android:title=\"React Native\" /> </menu>", "e": 4332, "s": 3905, "text": null }, { "code": null, "e": 4380, "s": 4332, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 4597, "s": 4380, "text": "In the MainActivity.java file, we will get the reference of the Button and initialize it. Add onClick behavior to the button and inflate the popup menu to it. Below is the code snippet for the MainActivity.java file." }, { "code": null, "e": 4602, "s": 4597, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.PopupMenu;import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Referencing and Initializing the button button = (Button) findViewById(R.id.clickBtn); // Setting onClick behavior to the button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Initializing the popup menu and giving the reference as current context PopupMenu popupMenu = new PopupMenu(MainActivity.this, button); // Inflating popup menu from popup_menu.xml file popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { // Toast message on menu item clicked Toast.makeText(MainActivity.this, \"You Clicked \" + menuItem.getTitle(), Toast.LENGTH_SHORT).show(); return true; } }); // Showing the popup menu popupMenu.show(); } }); }}", "e": 6252, "s": 4602, "text": null }, { "code": null, "e": 6260, "s": 6252, "text": "android" }, { "code": null, "e": 6284, "s": 6260, "text": "Technical Scripter 2020" }, { "code": null, "e": 6292, "s": 6284, "text": "Android" }, { "code": null, "e": 6297, "s": 6292, "text": "Java" }, { "code": null, "e": 6316, "s": 6297, "text": "Technical Scripter" }, { "code": null, "e": 6321, "s": 6316, "text": "Java" }, { "code": null, "e": 6329, "s": 6321, "text": "Android" } ]
Substring in Java
07 Jul, 2021 There are two variants of the substring() method. This article depicts all of them, as follows : 1. String substring(): This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. And index of substring starts from 1 and not from 0. Syntax : public String substring(int begIndex) Parameters : begIndex : the begin index, inclusive. Return Value : The specified substring. Java // Java code to demonstrate the// working of substring(int begIndex)public class Substr1 { public static void main(String args[]) { // Initializing String String Str = new String("Welcome to geeksforgeeks"); // using substring() to extract substring // returns (whiteSpace)geeksforgeeks System.out.print("The extracted substring is : "); System.out.println(Str.substring(10)); }} Output: The extracted substring is : geeksforgeeks 2. String substring(begIndex, endIndex): This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1 if the second argument is given. Syntax : public String substring(int begIndex, int endIndex) Parameters : beginIndex : the begin index, inclusive. endIndex : the end index, exclusive. Return Value : The specified substring. Java // Java code to demonstrate the// working of substring(int begIndex, int endIndex)public class Substr2 { public static void main(String args[]) { // Initializing String String Str = new String("Welcome to geeksforgeeks"); // using substring() to extract substring // returns geeks System.out.print("The extracted substring is : "); System.out.println(Str.substring(10, 16)); }} Output: The extracted substring is : geeks Possible application: The substring extraction finds its use in many applications including prefix and suffix extraction. For example to extract a Lastname from the name or extract only denomination from a string containing both amount and currency symbol. The latter one is explained below. Java // Java code to demonstrate the// application of substring()public class Appli { public static void main(String args[]) { // Initializing String String Str = new String("Rs 1000"); // Printing original string System.out.print("The original string is : "); System.out.println(Str); // using substring() to extract substring // returns 1000 System.out.print("The extracted substring is : "); System.out.println(Str.substring(3)); }} Output : The original string is : Rs 1000 The extracted substring is : 1000 This article is contributed by Astha Tyagi. 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. yash_nagayach Java-Functions Java-lang package Java-String-Programs Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java Collections in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stack Class in Java Stream In Java Queue Interface In Java Constructors in Java Introduction to Java
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jul, 2021" }, { "code": null, "e": 151, "s": 53, "text": "There are two variants of the substring() method. This article depicts all of them, as follows : " }, { "code": null, "e": 419, "s": 151, "text": "1. String substring(): This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. And index of substring starts from 1 and not from 0." }, { "code": null, "e": 561, "s": 419, "text": "Syntax : \npublic String substring(int begIndex)\nParameters : \nbegIndex : the begin index, inclusive.\nReturn Value : \nThe specified substring." }, { "code": null, "e": 566, "s": 561, "text": "Java" }, { "code": "// Java code to demonstrate the// working of substring(int begIndex)public class Substr1 { public static void main(String args[]) { // Initializing String String Str = new String(\"Welcome to geeksforgeeks\"); // using substring() to extract substring // returns (whiteSpace)geeksforgeeks System.out.print(\"The extracted substring is : \"); System.out.println(Str.substring(10)); }}", "e": 1006, "s": 566, "text": null }, { "code": null, "e": 1015, "s": 1006, "text": "Output: " }, { "code": null, "e": 1059, "s": 1015, "text": "The extracted substring is : geeksforgeeks" }, { "code": null, "e": 1347, "s": 1059, "text": "2. String substring(begIndex, endIndex): This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1 if the second argument is given. " }, { "code": null, "e": 1544, "s": 1347, "text": "Syntax : \npublic String substring(int begIndex, int endIndex)\nParameters : \nbeginIndex : the begin index, inclusive.\nendIndex : the end index, exclusive.\nReturn Value : \nThe specified substring." }, { "code": null, "e": 1549, "s": 1544, "text": "Java" }, { "code": "// Java code to demonstrate the// working of substring(int begIndex, int endIndex)public class Substr2 { public static void main(String args[]) { // Initializing String String Str = new String(\"Welcome to geeksforgeeks\"); // using substring() to extract substring // returns geeks System.out.print(\"The extracted substring is : \"); System.out.println(Str.substring(10, 16)); }}", "e": 1981, "s": 1549, "text": null }, { "code": null, "e": 1990, "s": 1981, "text": "Output: " }, { "code": null, "e": 2027, "s": 1990, "text": "The extracted substring is : geeks" }, { "code": null, "e": 2321, "s": 2027, "text": "Possible application: The substring extraction finds its use in many applications including prefix and suffix extraction. For example to extract a Lastname from the name or extract only denomination from a string containing both amount and currency symbol. The latter one is explained below. " }, { "code": null, "e": 2326, "s": 2321, "text": "Java" }, { "code": "// Java code to demonstrate the// application of substring()public class Appli { public static void main(String args[]) { // Initializing String String Str = new String(\"Rs 1000\"); // Printing original string System.out.print(\"The original string is : \"); System.out.println(Str); // using substring() to extract substring // returns 1000 System.out.print(\"The extracted substring is : \"); System.out.println(Str.substring(3)); }}", "e": 2834, "s": 2326, "text": null }, { "code": null, "e": 2844, "s": 2834, "text": "Output : " }, { "code": null, "e": 2913, "s": 2844, "text": "The original string is : Rs 1000\nThe extracted substring is : 1000" }, { "code": null, "e": 3334, "s": 2913, "text": "This article is contributed by Astha Tyagi. 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": 3348, "s": 3334, "text": "yash_nagayach" }, { "code": null, "e": 3363, "s": 3348, "text": "Java-Functions" }, { "code": null, "e": 3381, "s": 3363, "text": "Java-lang package" }, { "code": null, "e": 3402, "s": 3381, "text": "Java-String-Programs" }, { "code": null, "e": 3415, "s": 3402, "text": "Java-Strings" }, { "code": null, "e": 3420, "s": 3415, "text": "Java" }, { "code": null, "e": 3433, "s": 3420, "text": "Java-Strings" }, { "code": null, "e": 3438, "s": 3433, "text": "Java" }, { "code": null, "e": 3536, "s": 3438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3587, "s": 3536, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3607, "s": 3587, "text": "Collections in Java" }, { "code": null, "e": 3626, "s": 3607, "text": "Interfaces in Java" }, { "code": null, "e": 3656, "s": 3626, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3674, "s": 3656, "text": "ArrayList in Java" }, { "code": null, "e": 3694, "s": 3674, "text": "Stack Class in Java" }, { "code": null, "e": 3709, "s": 3694, "text": "Stream In Java" }, { "code": null, "e": 3733, "s": 3709, "text": "Queue Interface In Java" }, { "code": null, "e": 3754, "s": 3733, "text": "Constructors in Java" } ]
LINQ | How to find maximum value of the given sequence?
21 May, 2019 In LINQ, you can find the maximum element of the given sequence by using Max() function. This method provides the maximum element of the given set of values. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#. It returns null if all the elements present in the collection are null. It returns any type of data type means you can also use Max with the collection of a custom type(does not contain numeric value), but for this, you have to implement the IComparable interface. It can work with nullable, non-nullable decimal, double, floats, int, etc. values. Example 1: // C# program to find maximum // value from the given arrayusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Data source int[] sequence = {20, 45, 50, 79, 90, 79, 89, 100, 567, 29}; // Display the sequence Console.WriteLine("The sequence is:"); foreach(int s in sequence) { Console.WriteLine(s); } // Finding the maximum element // from the given sequence // Using Max function int result = sequence.Max(); Console.WriteLine("Maximum Value: {0}", result); }} The sequence is: 20 45 50 79 90 79 89 100 567 29 Maximum Value: 567 Example 2: // C# program to find the Maximum// salary of the employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000 }, new Employee() { emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000 }, new Employee() { emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000 }, new Employee() { emp_id = 212, emp_name = "Supriya", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 40000 }, new Employee() { emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 40000 }, new Employee() { emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000 }, }; // Find the Maximum salary of the // employee Using Max() method var res = emp.Max(a => a.emp_salary); Console.WriteLine("Maximum Salary of the Employee: {0}", res); }} Maximum Salary of the Employee: 50000 CSharp LINQ C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework C# | Data Types C# | Method Overriding C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object C# | Constructors
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2019" }, { "code": null, "e": 665, "s": 28, "text": "In LINQ, you can find the maximum element of the given sequence by using Max() function. This method provides the maximum element of the given set of values. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#. It returns null if all the elements present in the collection are null. It returns any type of data type means you can also use Max with the collection of a custom type(does not contain numeric value), but for this, you have to implement the IComparable interface. It can work with nullable, non-nullable decimal, double, floats, int, etc. values." }, { "code": null, "e": 676, "s": 665, "text": "Example 1:" }, { "code": "// C# program to find maximum // value from the given arrayusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Data source int[] sequence = {20, 45, 50, 79, 90, 79, 89, 100, 567, 29}; // Display the sequence Console.WriteLine(\"The sequence is:\"); foreach(int s in sequence) { Console.WriteLine(s); } // Finding the maximum element // from the given sequence // Using Max function int result = sequence.Max(); Console.WriteLine(\"Maximum Value: {0}\", result); }}", "e": 1313, "s": 676, "text": null }, { "code": null, "e": 1382, "s": 1313, "text": "The sequence is:\n20\n45\n50\n79\n90\n79\n89\n100\n567\n29\nMaximum Value: 567\n" }, { "code": null, "e": 1393, "s": 1382, "text": "Example 2:" }, { "code": "// C# program to find the Maximum// salary of the employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000 }, new Employee() { emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000 }, new Employee() { emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000 }, new Employee() { emp_id = 212, emp_name = \"Supriya\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 40000 }, new Employee() { emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 40000 }, new Employee() { emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000 }, }; // Find the Maximum salary of the // employee Using Max() method var res = emp.Max(a => a.emp_salary); Console.WriteLine(\"Maximum Salary of the Employee: {0}\", res); }}", "e": 3027, "s": 1393, "text": null }, { "code": null, "e": 3066, "s": 3027, "text": "Maximum Salary of the Employee: 50000\n" }, { "code": null, "e": 3078, "s": 3066, "text": "CSharp LINQ" }, { "code": null, "e": 3081, "s": 3078, "text": "C#" }, { "code": null, "e": 3179, "s": 3081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3207, "s": 3179, "text": "C# Dictionary with examples" }, { "code": null, "e": 3250, "s": 3207, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3281, "s": 3250, "text": "Introduction to .NET Framework" }, { "code": null, "e": 3296, "s": 3281, "text": "C# | Delegates" }, { "code": null, "e": 3345, "s": 3296, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3361, "s": 3345, "text": "C# | Data Types" }, { "code": null, "e": 3384, "s": 3361, "text": "C# | Method Overriding" }, { "code": null, "e": 3424, "s": 3384, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 3446, "s": 3424, "text": "C# | Class and Object" } ]
Default Methods In Java 8
17 Feb, 2020 Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface. // A simple program to Test Interface default// methods in javainterface TestInterface{ // abstract method public void square(int a); // default method default void show() { System.out.println("Default Method Executed"); }} class TestClass implements TestInterface{ // implementation of square abstract method public void square(int a) { System.out.println(a*a); } public static void main(String args[]) { TestClass d = new TestClass(); d.square(4); // default method executed d.show(); }} Output: 16 Default Method Executed The default methods were introduced to provide backward compatibility so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class. Default methods are also known as defender methods or virtual extension methods. Static Methods:The interfaces can have static methods as well which is similar to static method of classes. // A simple Java program to TestClassnstrate static// methods in javainterface TestInterface{ // abstract method public void square (int a); // static method static void show() { System.out.println("Static Method Executed"); }} class TestClass implements TestInterface{ // Implementation of square abstract method public void square (int a) { System.out.println(a*a); } public static void main(String args[]) { TestClass d = new TestClass(); d.square(4); // Static method executed TestInterface.show(); }} Output: 16 Static Method Executed Default Methods and Multiple InheritanceIn case both the implemented interfaces contain default methods with same method signature, the implementing class should explicitly specify which default method is to be used or it should override the default method. // A simple Java program to demonstrate multiple// inheritance through default methods.interface TestInterface1{ // default method default void show() { System.out.println("Default TestInterface1"); }} interface TestInterface2{ // Default method default void show() { System.out.println("Default TestInterface2"); }} // Implementation class codeclass TestClass implements TestInterface1, TestInterface2{ // Overriding default show method public void show() { // use super keyword to call the show // method of TestInterface1 interface TestInterface1.super.show(); // use super keyword to call the show // method of TestInterface2 interface TestInterface2.super.show(); } public static void main(String args[]) { TestClass d = new TestClass(); d.show(); }} Output: Default TestInterface1 Default TestInterface2 Important Points: Interfaces can have default methods with implementation in Java 8 on later.Interfaces can have static methods as well, similar to static methods in classes.Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code. Interfaces can have default methods with implementation in Java 8 on later. Interfaces can have static methods as well, similar to static methods in classes. Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code. This article is contributed by Akash Ojha. 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. SyedAtamishAli gwatts Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Feb, 2020" }, { "code": null, "e": 534, "s": 52, "text": "Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface." }, { "code": "// A simple program to Test Interface default// methods in javainterface TestInterface{ // abstract method public void square(int a); // default method default void show() { System.out.println(\"Default Method Executed\"); }} class TestClass implements TestInterface{ // implementation of square abstract method public void square(int a) { System.out.println(a*a); } public static void main(String args[]) { TestClass d = new TestClass(); d.square(4); // default method executed d.show(); }}", "e": 1110, "s": 534, "text": null }, { "code": null, "e": 1118, "s": 1110, "text": "Output:" }, { "code": null, "e": 1148, "s": 1118, "text": " 16\n Default Method Executed\n" }, { "code": null, "e": 1420, "s": 1148, "text": "The default methods were introduced to provide backward compatibility so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class. Default methods are also known as defender methods or virtual extension methods." }, { "code": null, "e": 1528, "s": 1420, "text": "Static Methods:The interfaces can have static methods as well which is similar to static method of classes." }, { "code": "// A simple Java program to TestClassnstrate static// methods in javainterface TestInterface{ // abstract method public void square (int a); // static method static void show() { System.out.println(\"Static Method Executed\"); }} class TestClass implements TestInterface{ // Implementation of square abstract method public void square (int a) { System.out.println(a*a); } public static void main(String args[]) { TestClass d = new TestClass(); d.square(4); // Static method executed TestInterface.show(); }}", "e": 2122, "s": 1528, "text": null }, { "code": null, "e": 2130, "s": 2122, "text": "Output:" }, { "code": null, "e": 2158, "s": 2130, "text": " 16\n Static Method Executed" }, { "code": null, "e": 2416, "s": 2158, "text": "Default Methods and Multiple InheritanceIn case both the implemented interfaces contain default methods with same method signature, the implementing class should explicitly specify which default method is to be used or it should override the default method." }, { "code": "// A simple Java program to demonstrate multiple// inheritance through default methods.interface TestInterface1{ // default method default void show() { System.out.println(\"Default TestInterface1\"); }} interface TestInterface2{ // Default method default void show() { System.out.println(\"Default TestInterface2\"); }} // Implementation class codeclass TestClass implements TestInterface1, TestInterface2{ // Overriding default show method public void show() { // use super keyword to call the show // method of TestInterface1 interface TestInterface1.super.show(); // use super keyword to call the show // method of TestInterface2 interface TestInterface2.super.show(); } public static void main(String args[]) { TestClass d = new TestClass(); d.show(); }}", "e": 3293, "s": 2416, "text": null }, { "code": null, "e": 3301, "s": 3293, "text": "Output:" }, { "code": null, "e": 3347, "s": 3301, "text": "Default TestInterface1\nDefault TestInterface2" }, { "code": null, "e": 3365, "s": 3347, "text": "Important Points:" }, { "code": null, "e": 3673, "s": 3365, "text": "Interfaces can have default methods with implementation in Java 8 on later.Interfaces can have static methods as well, similar to static methods in classes.Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code." }, { "code": null, "e": 3749, "s": 3673, "text": "Interfaces can have default methods with implementation in Java 8 on later." }, { "code": null, "e": 3831, "s": 3749, "text": "Interfaces can have static methods as well, similar to static methods in classes." }, { "code": null, "e": 3983, "s": 3831, "text": "Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code." }, { "code": null, "e": 4281, "s": 3983, "text": "This article is contributed by Akash Ojha. 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": 4406, "s": 4281, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4421, "s": 4406, "text": "SyedAtamishAli" }, { "code": null, "e": 4428, "s": 4421, "text": "gwatts" }, { "code": null, "e": 4433, "s": 4428, "text": "Java" }, { "code": null, "e": 4438, "s": 4433, "text": "Java" } ]
Storage Classes in C++ with Examples
28 Jun, 2021 Storage Classes are used to describe the features of a variable/function. These features basically include the scope, visibility and life-time which help us to trace the existence of a particular variable during the runtime of a program. To specify the storage class for a variable, the following syntax is to be followed: Syntax: storage_class var_data_type var_name; C++ uses 5 storage classes, namely: autoregisterexternstaticmutable auto register extern static mutable Below is the detailed explanation of each storage class: auto: The auto keyword provides type inference capabilities, using which automatic deduction of the data type of an expression in a programming language can be done. This consumes less time having to write out things the compiler already knows. As all the types are deduced in compiler phase only, the time for compilation increases slightly but it does not affect the run time of the program. This feature also extends to functions and non-type template parameters. Since C++14 for functions, the return type will be deduced from its return statements. Since C++17, for non-type template parameters, the type will be deduced from the argument. Example: C++ #include <iostream>using namespace std; void autoStorageClass(){ cout << "Demonstrating auto class\n"; // Declaring an auto variable // No data-type declaration needed auto a = 32; auto b = 3.2; auto c = "GeeksforGeeks"; auto d = 'G'; // printing the auto variables cout << a << " \n"; cout << b << " \n"; cout << c << " \n"; cout << d << " \n";} int main(){ // To demonstrate auto Storage Class autoStorageClass(); return 0;} Demonstrating auto class 32 3.2 GeeksforGeeks G extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. For more information on how extern variables work, have a look at this link. Example: C++ #include <iostream>using namespace std; // declaring the variable which is to// be made extern an initial value can// also be initialized to xint x;void externStorageClass(){ cout << "Demonstrating extern class\n"; // telling the compiler that the variable // x is an extern variable and has been // defined elsewhere (above the main // function) extern int x; // printing the extern variables 'x' cout << "Value of the variable 'x'" << "declared, as extern: " << x << "\n"; // value of extern variable x modified x = 2; // printing the modified values of // extern variables 'x' cout << "Modified value of the variable 'x'" << " declared as extern: \n" << x;} int main(){ // To demonstrate extern Storage Class externStorageClass(); return 0;} Demonstrating extern class Value of the variable 'x'declared, as extern: 0 Modified value of the variable 'x' declared as extern: 2 static: This storage class is used to declare static variables which are popularly used while writing programs in C++ language. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist until the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler. C++ #include <iostream>using namespace std; // Function containing static variables// memory is retained during executionint staticFun(){ cout << "For static variables: "; static int count = 0; count++; return count;} // Function containing non-static variables// memory is destroyedint nonStaticFun(){ cout << "For Non-Static variables: "; int count = 0; count++; return count;} int main(){ // Calling the static parts cout << staticFun() << "\n"; cout << staticFun() << "\n"; ; // Calling the non-static parts cout << nonStaticFun() << "\n"; ; cout << nonStaticFun() << "\n"; ; return 0;} For static variables: 1 For static variables: 2 For Non-Static variables: 1 For Non-Static variables: 1 register: This storage class declares register variables which have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free register is not available, these are then stored in the memory only. Usually, a few variables which are to be accessed very frequently in a program are declared with the register keyword which improves the running time of the program. An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers. Example: C++ #include <iostream>using namespace std; void registerStorageClass(){ cout << "Demonstrating register class\n"; // declaring a register variable register char b = 'G'; // printing the register variable 'b' cout << "Value of the variable 'b'" << " declared as register: " << b;}int main(){ // To demonstrate register Storage Class registerStorageClass(); return 0;} Demonstrating register class Value of the variable 'b' declared as register: G mutable: Sometimes there is a requirement to modify one or more data members of class/struct through const function even though you don’t want the function to update other members of class/struct. This task can be easily performed by using the mutable keyword. The keyword mutable is mainly used to allow a particular data member of const object to be modified. When we declare a function as const, this pointer passed to function becomes const. Adding mutable to a variable allows a const pointer to change members. Example: C++ #include <iostream>using std::cout; class Test {public: int x; // defining mutable variable y // now this can be modified mutable int y; Test() { x = 4; y = 10; }}; int main(){ // t1 is set to constant const Test t1; // trying to change the value t1.y = 20; cout << t1.y; // Uncommenting below lines // will throw error // t1.x = 8; // cout << t1.x; return 0;} 20 wengmat simranarora5sos Storage Classes and Type Qualifiers C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 375, "s": 52, "text": "Storage Classes are used to describe the features of a variable/function. These features basically include the scope, visibility and life-time which help us to trace the existence of a particular variable during the runtime of a program. To specify the storage class for a variable, the following syntax is to be followed:" }, { "code": null, "e": 384, "s": 375, "text": "Syntax: " }, { "code": null, "e": 423, "s": 384, "text": "storage_class var_data_type var_name; " }, { "code": null, "e": 460, "s": 423, "text": "C++ uses 5 storage classes, namely: " }, { "code": null, "e": 492, "s": 460, "text": "autoregisterexternstaticmutable" }, { "code": null, "e": 497, "s": 492, "text": "auto" }, { "code": null, "e": 506, "s": 497, "text": "register" }, { "code": null, "e": 513, "s": 506, "text": "extern" }, { "code": null, "e": 520, "s": 513, "text": "static" }, { "code": null, "e": 528, "s": 520, "text": "mutable" }, { "code": null, "e": 586, "s": 528, "text": "Below is the detailed explanation of each storage class: " }, { "code": null, "e": 1231, "s": 586, "text": "auto: The auto keyword provides type inference capabilities, using which automatic deduction of the data type of an expression in a programming language can be done. This consumes less time having to write out things the compiler already knows. As all the types are deduced in compiler phase only, the time for compilation increases slightly but it does not affect the run time of the program. This feature also extends to functions and non-type template parameters. Since C++14 for functions, the return type will be deduced from its return statements. Since C++17, for non-type template parameters, the type will be deduced from the argument." }, { "code": null, "e": 1241, "s": 1231, "text": "Example: " }, { "code": null, "e": 1245, "s": 1241, "text": "C++" }, { "code": "#include <iostream>using namespace std; void autoStorageClass(){ cout << \"Demonstrating auto class\\n\"; // Declaring an auto variable // No data-type declaration needed auto a = 32; auto b = 3.2; auto c = \"GeeksforGeeks\"; auto d = 'G'; // printing the auto variables cout << a << \" \\n\"; cout << b << \" \\n\"; cout << c << \" \\n\"; cout << d << \" \\n\";} int main(){ // To demonstrate auto Storage Class autoStorageClass(); return 0;}", "e": 1722, "s": 1245, "text": null }, { "code": null, "e": 1773, "s": 1722, "text": "Demonstrating auto class\n32 \n3.2 \nGeeksforGeeks \nG" }, { "code": null, "e": 2706, "s": 1775, "text": "extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. For more information on how extern variables work, have a look at this link." }, { "code": null, "e": 2716, "s": 2706, "text": "Example: " }, { "code": null, "e": 2720, "s": 2716, "text": "C++" }, { "code": "#include <iostream>using namespace std; // declaring the variable which is to// be made extern an initial value can// also be initialized to xint x;void externStorageClass(){ cout << \"Demonstrating extern class\\n\"; // telling the compiler that the variable // x is an extern variable and has been // defined elsewhere (above the main // function) extern int x; // printing the extern variables 'x' cout << \"Value of the variable 'x'\" << \"declared, as extern: \" << x << \"\\n\"; // value of extern variable x modified x = 2; // printing the modified values of // extern variables 'x' cout << \"Modified value of the variable 'x'\" << \" declared as extern: \\n\" << x;} int main(){ // To demonstrate extern Storage Class externStorageClass(); return 0;}", "e": 3549, "s": 2720, "text": null }, { "code": null, "e": 3682, "s": 3549, "text": "Demonstrating extern class\nValue of the variable 'x'declared, as extern: 0\nModified value of the variable 'x' declared as extern: \n2" }, { "code": null, "e": 4342, "s": 3684, "text": "static: This storage class is used to declare static variables which are popularly used while writing programs in C++ language. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist until the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler." }, { "code": null, "e": 4346, "s": 4342, "text": "C++" }, { "code": "#include <iostream>using namespace std; // Function containing static variables// memory is retained during executionint staticFun(){ cout << \"For static variables: \"; static int count = 0; count++; return count;} // Function containing non-static variables// memory is destroyedint nonStaticFun(){ cout << \"For Non-Static variables: \"; int count = 0; count++; return count;} int main(){ // Calling the static parts cout << staticFun() << \"\\n\"; cout << staticFun() << \"\\n\"; ; // Calling the non-static parts cout << nonStaticFun() << \"\\n\"; ; cout << nonStaticFun() << \"\\n\"; ; return 0;}", "e": 4991, "s": 4346, "text": null }, { "code": null, "e": 5095, "s": 4991, "text": "For static variables: 1\nFor static variables: 2\nFor Non-Static variables: 1\nFor Non-Static variables: 1" }, { "code": null, "e": 5877, "s": 5097, "text": "register: This storage class declares register variables which have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free register is not available, these are then stored in the memory only. Usually, a few variables which are to be accessed very frequently in a program are declared with the register keyword which improves the running time of the program. An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers." }, { "code": null, "e": 5887, "s": 5877, "text": "Example: " }, { "code": null, "e": 5891, "s": 5887, "text": "C++" }, { "code": "#include <iostream>using namespace std; void registerStorageClass(){ cout << \"Demonstrating register class\\n\"; // declaring a register variable register char b = 'G'; // printing the register variable 'b' cout << \"Value of the variable 'b'\" << \" declared as register: \" << b;}int main(){ // To demonstrate register Storage Class registerStorageClass(); return 0;}", "e": 6291, "s": 5891, "text": null }, { "code": null, "e": 6370, "s": 6291, "text": "Demonstrating register class\nValue of the variable 'b' declared as register: G" }, { "code": null, "e": 6889, "s": 6372, "text": "mutable: Sometimes there is a requirement to modify one or more data members of class/struct through const function even though you don’t want the function to update other members of class/struct. This task can be easily performed by using the mutable keyword. The keyword mutable is mainly used to allow a particular data member of const object to be modified. When we declare a function as const, this pointer passed to function becomes const. Adding mutable to a variable allows a const pointer to change members." }, { "code": null, "e": 6899, "s": 6889, "text": "Example: " }, { "code": null, "e": 6903, "s": 6899, "text": "C++" }, { "code": "#include <iostream>using std::cout; class Test {public: int x; // defining mutable variable y // now this can be modified mutable int y; Test() { x = 4; y = 10; }}; int main(){ // t1 is set to constant const Test t1; // trying to change the value t1.y = 20; cout << t1.y; // Uncommenting below lines // will throw error // t1.x = 8; // cout << t1.x; return 0;}", "e": 7333, "s": 6903, "text": null }, { "code": null, "e": 7336, "s": 7333, "text": "20" }, { "code": null, "e": 7346, "s": 7338, "text": "wengmat" }, { "code": null, "e": 7362, "s": 7346, "text": "simranarora5sos" }, { "code": null, "e": 7398, "s": 7362, "text": "Storage Classes and Type Qualifiers" }, { "code": null, "e": 7402, "s": 7398, "text": "C++" }, { "code": null, "e": 7406, "s": 7402, "text": "CPP" }, { "code": null, "e": 7504, "s": 7406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7528, "s": 7504, "text": "Sorting a vector in C++" }, { "code": null, "e": 7548, "s": 7528, "text": "Polymorphism in C++" }, { "code": null, "e": 7581, "s": 7548, "text": "Friend class and function in C++" }, { "code": null, "e": 7606, "s": 7581, "text": "std::string class in C++" }, { "code": null, "e": 7650, "s": 7606, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 7695, "s": 7650, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 7743, "s": 7695, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 7787, "s": 7743, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 7804, "s": 7787, "text": "std::find in C++" } ]
Parsero – Tool for reading the Robots.txt file in Kali Linux
18 Jul, 2021 Parsero is a free and open-source tool available on GitHub. Parsero is used to reading Robots.txt files of websites and web apps. This tool can be used to get information about our target(domain). We can target any domain using Parsero. It has an interactive console that provides a number of helpful features, such as command completion and contextual help. This tool is written in python, so you must have python installed in your Kali Linux to use this tool. It is a python script that is used to read Robots.txt file on a live web server in the disallowed entries. When the tool starts working, these disallowed entries tell the search engines what HTML files or static directories must or must not be indexed. Google spiders and crawlers play important roles in indexing a website according to the number of visitors. It is the responsibility of the administrator that they don’t share private and sensitive information with the search engines. But sometimes these developers mistakenly allow search engines to access Robots.txt file. Parsero helps in such situations by checking whether the Robots.txt file is visible or not. Step 1: Use the following command to install the Parsero tool. apt install parsero Step 2: The tool has been downloaded and installed successfully. Now, run the tool using the following command. parsero -h The tool is running successfully. Now we will see an example to use the tool. Example: Use the parsero tool to scan any website. parsero -u <domain> This is how you can search for your target. This tool is very useful for security researchers in the initial phases of Pentesting. You can target any domain of your choice. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples chmod command in Linux with examples nohup Command in Linux with Examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 491, "s": 28, "text": "Parsero is a free and open-source tool available on GitHub. Parsero is used to reading Robots.txt files of websites and web apps. This tool can be used to get information about our target(domain). We can target any domain using Parsero. It has an interactive console that provides a number of helpful features, such as command completion and contextual help. This tool is written in python, so you must have python installed in your Kali Linux to use this tool." }, { "code": null, "e": 1162, "s": 491, "text": " It is a python script that is used to read Robots.txt file on a live web server in the disallowed entries. When the tool starts working, these disallowed entries tell the search engines what HTML files or static directories must or must not be indexed. Google spiders and crawlers play important roles in indexing a website according to the number of visitors. It is the responsibility of the administrator that they don’t share private and sensitive information with the search engines. But sometimes these developers mistakenly allow search engines to access Robots.txt file. Parsero helps in such situations by checking whether the Robots.txt file is visible or not." }, { "code": null, "e": 1225, "s": 1162, "text": "Step 1: Use the following command to install the Parsero tool." }, { "code": null, "e": 1245, "s": 1225, "text": "apt install parsero" }, { "code": null, "e": 1357, "s": 1245, "text": "Step 2: The tool has been downloaded and installed successfully. Now, run the tool using the following command." }, { "code": null, "e": 1368, "s": 1357, "text": "parsero -h" }, { "code": null, "e": 1446, "s": 1368, "text": "The tool is running successfully. Now we will see an example to use the tool." }, { "code": null, "e": 1497, "s": 1446, "text": "Example: Use the parsero tool to scan any website." }, { "code": null, "e": 1517, "s": 1497, "text": "parsero -u <domain>" }, { "code": null, "e": 1690, "s": 1517, "text": "This is how you can search for your target. This tool is very useful for security researchers in the initial phases of Pentesting. You can target any domain of your choice." }, { "code": null, "e": 1701, "s": 1690, "text": "Kali-Linux" }, { "code": null, "e": 1713, "s": 1701, "text": "Linux-Tools" }, { "code": null, "e": 1724, "s": 1713, "text": "Linux-Unix" }, { "code": null, "e": 1822, "s": 1724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1848, "s": 1822, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1883, "s": 1848, "text": "scp command in Linux with Examples" }, { "code": null, "e": 1920, "s": 1883, "text": "chown command in Linux with Examples" }, { "code": null, "e": 1949, "s": 1920, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 1983, "s": 1949, "text": "mv command in Linux with examples" }, { "code": null, "e": 2020, "s": 1983, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2057, "s": 2020, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2096, "s": 2057, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 2136, "s": 2096, "text": "Array Basics in Shell Scripting | Set 1" } ]
Nth root of a number using log
08 Apr, 2021 Given two integers N and K, the task is to find the Nth root of the K. Examples: Input: N = 3, K = 8 Output: 2.00 Explanation: Cube root of 8 is 2. i.e. 23 = 8 Input: N = 2, K = 16 Output: 4.00 Explanation: Square root of 16 is 4, i.e. 42 = 16 Approach: The idea is to use logarithmic function to find the Nth root of K. Let D be our Nth root of the K, Then, Apply logK on both the sides – => => => Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// Kth root of a number using log #include <bits/stdc++.h> // Function to find the Kth root// of the number using log functiondouble kthRoot(double n, int k){ return pow(k, (1.0 / k) * (log(n) / log(k)));} // Driver Codeint main(void){ double n = 81; int k = 4; printf("%lf ", kthRoot(n, k)); return 0;} // Java implementation to find the// Kth root of a number using logimport java.util.*; class GFG { // Function to find the Kth root// of the number using log functionstatic double kthRoot(double n, int k){ return Math.pow(k, ((1.0 / k) * (Math.log(n) / Math.log(k))));} // Driver Codepublic static void main(String args[]){ double n = 81; int k = 4; System.out.printf("%.6f", kthRoot(n, k));}} // This code is contributed by rutvik_56 # Python3 implementation to find the# Kth root of a number using log import numpy as np # Function to find the Kth root# of the number using log functiondef kthRoot(n, k): return pow(k, ((1.0 / k) * (np.log(n) / np.log(k)))) # Driver Coden = 81k = 4 print("%.6f" % kthRoot(n, k)) # This code is contributed by PratikBasu // C# implementation to find the// Kth root of a number using logusing System; class GFG { // Function to find the Kth root// of the number using log functionstatic double kthRoot(double n, int k){ return Math.Pow(k, ((1.0 / k) * (Math.Log(n) / Math.Log(k))));} // Driver Codepublic static void Main(String []args){ double n = 81; int k = 4; Console.Write("{0:F6}", kthRoot(n, k));}} // This code is contributed by AbhiThakur <script> // Javascript implementation to find the// Kth root of a number using log // Function to find the Kth root// of the number using log functionfunction kthRoot(n, k){ return Math.pow(k, ((1.0 / k) * (Math.log(n) / Math.log(k))));} // Driver Codevar n = 81;var k = 4;var x = kthRoot(n, k) document.write(x.toFixed(6)); // This code is contributed by Ankita saini </script> 3.000000 PratikBasu rutvik_56 abhaysingh290895 ankita_saini root Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Merge two sorted arrays with O(1) extra space Segment Tree | Set 1 (Sum of given range) Fizz Buzz Implementation Check if a number is Palindrome Count ways to reach the n'th stair Product of Array except itself Find Union and Intersection of two unsorted arrays Median of two sorted arrays of same size
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Apr, 2021" }, { "code": null, "e": 100, "s": 28, "text": "Given two integers N and K, the task is to find the Nth root of the K. " }, { "code": null, "e": 111, "s": 100, "text": "Examples: " }, { "code": null, "e": 190, "s": 111, "text": "Input: N = 3, K = 8 Output: 2.00 Explanation: Cube root of 8 is 2. i.e. 23 = 8" }, { "code": null, "e": 276, "s": 190, "text": "Input: N = 2, K = 16 Output: 4.00 Explanation: Square root of 16 is 4, i.e. 42 = 16 " }, { "code": null, "e": 353, "s": 276, "text": "Approach: The idea is to use logarithmic function to find the Nth root of K." }, { "code": null, "e": 433, "s": 353, "text": "Let D be our Nth root of the K, Then, Apply logK on both the sides – => => => " }, { "code": null, "e": 486, "s": 433, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 490, "s": 486, "text": "C++" }, { "code": null, "e": 495, "s": 490, "text": "Java" }, { "code": null, "e": 503, "s": 495, "text": "Python3" }, { "code": null, "e": 506, "s": 503, "text": "C#" }, { "code": null, "e": 517, "s": 506, "text": "Javascript" }, { "code": "// C++ implementation to find the// Kth root of a number using log #include <bits/stdc++.h> // Function to find the Kth root// of the number using log functiondouble kthRoot(double n, int k){ return pow(k, (1.0 / k) * (log(n) / log(k)));} // Driver Codeint main(void){ double n = 81; int k = 4; printf(\"%lf \", kthRoot(n, k)); return 0;}", "e": 922, "s": 517, "text": null }, { "code": "// Java implementation to find the// Kth root of a number using logimport java.util.*; class GFG { // Function to find the Kth root// of the number using log functionstatic double kthRoot(double n, int k){ return Math.pow(k, ((1.0 / k) * (Math.log(n) / Math.log(k))));} // Driver Codepublic static void main(String args[]){ double n = 81; int k = 4; System.out.printf(\"%.6f\", kthRoot(n, k));}} // This code is contributed by rutvik_56", "e": 1419, "s": 922, "text": null }, { "code": "# Python3 implementation to find the# Kth root of a number using log import numpy as np # Function to find the Kth root# of the number using log functiondef kthRoot(n, k): return pow(k, ((1.0 / k) * (np.log(n) / np.log(k)))) # Driver Coden = 81k = 4 print(\"%.6f\" % kthRoot(n, k)) # This code is contributed by PratikBasu ", "e": 1805, "s": 1419, "text": null }, { "code": "// C# implementation to find the// Kth root of a number using logusing System; class GFG { // Function to find the Kth root// of the number using log functionstatic double kthRoot(double n, int k){ return Math.Pow(k, ((1.0 / k) * (Math.Log(n) / Math.Log(k))));} // Driver Codepublic static void Main(String []args){ double n = 81; int k = 4; Console.Write(\"{0:F6}\", kthRoot(n, k));}} // This code is contributed by AbhiThakur", "e": 2300, "s": 1805, "text": null }, { "code": "<script> // Javascript implementation to find the// Kth root of a number using log // Function to find the Kth root// of the number using log functionfunction kthRoot(n, k){ return Math.pow(k, ((1.0 / k) * (Math.log(n) / Math.log(k))));} // Driver Codevar n = 81;var k = 4;var x = kthRoot(n, k) document.write(x.toFixed(6)); // This code is contributed by Ankita saini </script>", "e": 2747, "s": 2300, "text": null }, { "code": null, "e": 2756, "s": 2747, "text": "3.000000" }, { "code": null, "e": 2769, "s": 2758, "text": "PratikBasu" }, { "code": null, "e": 2779, "s": 2769, "text": "rutvik_56" }, { "code": null, "e": 2796, "s": 2779, "text": "abhaysingh290895" }, { "code": null, "e": 2809, "s": 2796, "text": "ankita_saini" }, { "code": null, "e": 2814, "s": 2809, "text": "root" }, { "code": null, "e": 2827, "s": 2814, "text": "Mathematical" }, { "code": null, "e": 2840, "s": 2827, "text": "Mathematical" }, { "code": null, "e": 2938, "s": 2840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2970, "s": 2938, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 3014, "s": 2970, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 3060, "s": 3014, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 3102, "s": 3060, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 3127, "s": 3102, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 3159, "s": 3127, "text": "Check if a number is Palindrome" }, { "code": null, "e": 3194, "s": 3159, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 3225, "s": 3194, "text": "Product of Array except itself" }, { "code": null, "e": 3276, "s": 3225, "text": "Find Union and Intersection of two unsorted arrays" } ]
SAP ABAP - Operators
ABAP provides a rich set of operators to manipulate variables. All ABAP operators are classified into four categories − Arithmetic Operators Comparison Operators Bitwise Operators Character String Operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following list describes arithmetic operators. Assume integer variable A holds 20 and variable B holds 40. + (Addition) Adds values on either side of the operator. Example: A + B will give 60. − (Subtraction) Subtracts right hand operand from left hand operand. Example: A − B will give -20. * (Multiplication) Multiplies values on either side of the operator. Example: A * B will give 800. / (Division) Divides left hand operand by right hand operand. Example: B / A will give 2. MOD (Modulus) Divides left hand operand by right hand operand and returns the remainder. Example: B MOD A will give 0. REPORT YS_SEP_08. DATA: A TYPE I VALUE 150, B TYPE I VALUE 50, Result TYPE I. Result = A / B. WRITE / Result. The above code produces the following output − 3 Let’s discuss the various types of comparison operators for different operands. = (equality test). Alternate form is EQ. Checks if the values of two operands are equal or not, if yes then condition becomes true. Example (A = B) is not true. <> (Inequality test). Alternate form is NE. Checks if the values of two operands are equal or not. If the values are not equal then the condition becomes true. Example (A <> B) is true. > (Greater than test). Alternate form is GT. Checks if the value of left operand is greater than the value of right operand. If yes then condition becomes true. Example (A > B) is not true. < (Less than test). Alternate form is LT. Checks if the value of left operand is less than the value of right operand. If yes, then condition becomes true. Example (A < B) is true. >= (Greater than or equals) Alternate form is GE. Checks if the value of left operand is greater than or equal to the value of right Operand. If yes, then condition becomes true. Example (A >= B) is not true. <= (Less than or equals test). Alternate form is LE. Checks if the value of left operand is less than or equal to the value of right operand. If yes, then condition becomes true. Example (A <= B) is true. a1 BETWEEN a2 AND a3 (Interval test) Checks whether a1 lies in between a2 and a3 (inclusive). If yes, then the condition becomes true. Example (A BETWEEN B AND C) is true. IS INITIAL The condition becomes true if the contents of the variable have not changed and it has been automatically assigned its initial value. Example (A IS INITIAL) is not true IS NOT INITIAL The condition becomes true if the contents of the variable have changed. Example (A IS NOT INITIAL) is true. Note − If the data type or length of the variables does not match then automatic conversion is performed. Automatic type adjustment is performed for either one or both of the values while comparing two values of different data types. The conversion type is decided by the data type and the preference order of the data type. Following is the order of preference − If one field is of type I, then the other is converted to type I. If one field is of type I, then the other is converted to type I. If one field is of type P, then the other is converted to type P. If one field is of type P, then the other is converted to type P. If one field is of type D, then the other is converted to type D. But C and N types are not converted and they are compared directly. Similar is the case with type T. If one field is of type D, then the other is converted to type D. But C and N types are not converted and they are compared directly. Similar is the case with type T. If one field is of type N and the other is of type C or X, both the fields are converted to type P. If one field is of type N and the other is of type C or X, both the fields are converted to type P. If one field is of type C and the other is of type X, the X type is converted to type C. If one field is of type C and the other is of type X, the X type is converted to type C. REPORT YS_SEP_08. DATA: A TYPE I VALUE 115, B TYPE I VALUE 119. IF A LT B. WRITE: / 'A is less than B'. ENDIF The above code produces the following output − A is less than B REPORT YS_SEP_08. DATA: A TYPE I. IF A IS INITIAL. WRITE: / 'A is assigned'. ENDIF. The above code produces the following output − A is assigned. ABAP also provides a series of bitwise logical operators that can be used to build Boolean algebraic expressions. The bitwise operators can be combined in complex expressions using parentheses and so on. BIT-NOT Unary operator that flips all the bits in a hexadecimal number to the opposite value. For instance, applying this operator to a hexadecimal number having the bit level value 10101010 (e.g. 'AA') would give 01010101. BIT-AND This binary operator compares each field bit by bit using the Boolean AND operator. BIT-XOR Binary operator that compares each field bit by bit using the Boolean XOR (exclusive OR) operator. BIT-OR Binary operator that compares each field bit by bit using the Boolean OR operator. For example, following is the truth table that shows the values generated when applying the Boolean AND, OR, or XOR operators against the two bit values contained in field A and field B. Following is a list of character string operators − CO (Contains Only) Checks whether A is solely composed of the characters in B. CN (Not Contains ONLY) Checks whether A contains characters that are not in B. CA (Contains ANY) Checks whether A contains at least one character of B. NA (NOT Contains Any) Checks whether A does not contain any character of B. CS (Contains a String) Checks whether A contains the character string B. NS (NOT Contains a String) Checks whether A does not contain the character string B. CP (Contains a Pattern) It checks whether A contains the pattern in B. NP (NOT Contains a Pattern) It checks whether A does not contain the pattern in B. REPORT YS_SEP_08. DATA: P(10) TYPE C VALUE 'APPLE', Q(10) TYPE C VALUE 'CHAIR'. IF P CA Q. WRITE: / 'P contains at least one character of Q'. ENDIF. The above code produces the following output − P contains at least one character of Q.
[ { "code": null, "e": 3152, "s": 3032, "text": "ABAP provides a rich set of operators to manipulate variables. All ABAP operators are classified into four categories −" }, { "code": null, "e": 3173, "s": 3152, "text": "Arithmetic Operators" }, { "code": null, "e": 3194, "s": 3173, "text": "Comparison Operators" }, { "code": null, "e": 3212, "s": 3194, "text": "Bitwise Operators" }, { "code": null, "e": 3239, "s": 3212, "text": "Character String Operators" }, { "code": null, "e": 3455, "s": 3239, "text": "Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following list describes arithmetic operators. Assume integer variable A holds 20 and variable B holds 40." }, { "code": null, "e": 3468, "s": 3455, "text": "+ (Addition)" }, { "code": null, "e": 3541, "s": 3468, "text": "Adds values on either side of the operator. Example: A + B will give 60." }, { "code": null, "e": 3557, "s": 3541, "text": "− (Subtraction)" }, { "code": null, "e": 3640, "s": 3557, "text": "Subtracts right hand operand from left hand operand. Example: A − B will give -20." }, { "code": null, "e": 3659, "s": 3640, "text": "* (Multiplication)" }, { "code": null, "e": 3739, "s": 3659, "text": "Multiplies values on either side of the operator. Example: A * B will give 800." }, { "code": null, "e": 3752, "s": 3739, "text": "/ (Division)" }, { "code": null, "e": 3829, "s": 3752, "text": "Divides left hand operand by right hand operand. Example: B / A will give 2." }, { "code": null, "e": 3843, "s": 3829, "text": "MOD (Modulus)" }, { "code": null, "e": 3948, "s": 3843, "text": "Divides left hand operand by right hand operand and returns the remainder. Example: B MOD A will give 0." }, { "code": null, "e": 4064, "s": 3948, "text": "REPORT YS_SEP_08. \nDATA: A TYPE I VALUE 150, \nB TYPE I VALUE 50, \nResult TYPE I. \nResult = A / B. \nWRITE / Result." }, { "code": null, "e": 4111, "s": 4064, "text": "The above code produces the following output −" }, { "code": null, "e": 4114, "s": 4111, "text": "3\n" }, { "code": null, "e": 4194, "s": 4114, "text": "Let’s discuss the various types of comparison operators for different operands." }, { "code": null, "e": 4236, "s": 4194, "text": "= (equality test). Alternate form is EQ." }, { "code": null, "e": 4356, "s": 4236, "text": "Checks if the values of two operands are equal or not, if yes then condition becomes true. Example (A = B) is not true." }, { "code": null, "e": 4401, "s": 4356, "text": "<> (Inequality test). Alternate form is NE." }, { "code": null, "e": 4543, "s": 4401, "text": "Checks if the values of two operands are equal or not. If the values are not equal then the condition becomes true. Example (A <> B) is true." }, { "code": null, "e": 4588, "s": 4543, "text": "> (Greater than test). Alternate form is GT." }, { "code": null, "e": 4733, "s": 4588, "text": "Checks if the value of left operand is greater than the value of right operand. If yes then condition becomes true. Example (A > B) is not true." }, { "code": null, "e": 4775, "s": 4733, "text": "< (Less than test). Alternate form is LT." }, { "code": null, "e": 4914, "s": 4775, "text": "Checks if the value of left operand is less than the value of right operand. If yes, then condition becomes true. Example (A < B) is true." }, { "code": null, "e": 4964, "s": 4914, "text": ">= (Greater than or equals) Alternate form is GE." }, { "code": null, "e": 5123, "s": 4964, "text": "Checks if the value of left operand is greater than or equal to the value of right Operand. If yes, then condition becomes true. Example (A >= B) is not true." }, { "code": null, "e": 5176, "s": 5123, "text": "<= (Less than or equals test). Alternate form is LE." }, { "code": null, "e": 5328, "s": 5176, "text": "Checks if the value of left operand is less than or equal to the value of right operand. If yes, then condition becomes true. Example (A <= B) is true." }, { "code": null, "e": 5366, "s": 5328, "text": "a1 BETWEEN a2 AND a3 (Interval test)" }, { "code": null, "e": 5501, "s": 5366, "text": "Checks whether a1 lies in between a2 and a3 (inclusive). If yes, then the condition becomes true. Example (A BETWEEN B AND C) is true." }, { "code": null, "e": 5512, "s": 5501, "text": "IS INITIAL" }, { "code": null, "e": 5681, "s": 5512, "text": "The condition becomes true if the contents of the variable have not changed and it has been automatically assigned its initial value. Example (A IS INITIAL) is not true" }, { "code": null, "e": 5696, "s": 5681, "text": "IS NOT INITIAL" }, { "code": null, "e": 5805, "s": 5696, "text": "The condition becomes true if the contents of the variable have changed. Example (A IS NOT INITIAL) is true." }, { "code": null, "e": 6130, "s": 5805, "text": "Note − If the data type or length of the variables does not match then automatic conversion is performed. Automatic type adjustment is performed for either one or both of the values while comparing two values of different data types. The conversion type is decided by the data type and the preference order of the data type." }, { "code": null, "e": 6169, "s": 6130, "text": "Following is the order of preference −" }, { "code": null, "e": 6235, "s": 6169, "text": "If one field is of type I, then the other is converted to type I." }, { "code": null, "e": 6301, "s": 6235, "text": "If one field is of type I, then the other is converted to type I." }, { "code": null, "e": 6367, "s": 6301, "text": "If one field is of type P, then the other is converted to type P." }, { "code": null, "e": 6433, "s": 6367, "text": "If one field is of type P, then the other is converted to type P." }, { "code": null, "e": 6600, "s": 6433, "text": "If one field is of type D, then the other is converted to type D. But C and N types are not converted and they are compared directly. Similar is the case with type T." }, { "code": null, "e": 6767, "s": 6600, "text": "If one field is of type D, then the other is converted to type D. But C and N types are not converted and they are compared directly. Similar is the case with type T." }, { "code": null, "e": 6867, "s": 6767, "text": "If one field is of type N and the other is of type C or X, both the fields are converted to type P." }, { "code": null, "e": 6967, "s": 6867, "text": "If one field is of type N and the other is of type C or X, both the fields are converted to type P." }, { "code": null, "e": 7056, "s": 6967, "text": "If one field is of type C and the other is of type X, the X type is converted to type C." }, { "code": null, "e": 7145, "s": 7056, "text": "If one field is of type C and the other is of type X, the X type is converted to type C." }, { "code": null, "e": 7281, "s": 7145, "text": "REPORT YS_SEP_08. \n\nDATA: A TYPE I VALUE 115,\n B TYPE I VALUE 119.\n IF A LT B.\n WRITE: / 'A is less than B'.\n ENDIF" }, { "code": null, "e": 7328, "s": 7281, "text": "The above code produces the following output −" }, { "code": null, "e": 7347, "s": 7328, "text": "A is less than B \n" }, { "code": null, "e": 7451, "s": 7347, "text": "REPORT YS_SEP_08. \n\nDATA: A TYPE I.\n IF A IS INITIAL.\n WRITE: / 'A is assigned'.\n ENDIF." }, { "code": null, "e": 7498, "s": 7451, "text": "The above code produces the following output −" }, { "code": null, "e": 7514, "s": 7498, "text": "A is assigned.\n" }, { "code": null, "e": 7718, "s": 7514, "text": "ABAP also provides a series of bitwise logical operators that can be used to build Boolean algebraic expressions. The bitwise operators can be combined in complex expressions using parentheses and so on." }, { "code": null, "e": 7726, "s": 7718, "text": "BIT-NOT" }, { "code": null, "e": 7942, "s": 7726, "text": "Unary operator that flips all the bits in a hexadecimal number to the opposite value. For instance, applying this operator to a hexadecimal number having the bit level value 10101010 (e.g. 'AA') would give 01010101." }, { "code": null, "e": 7950, "s": 7942, "text": "BIT-AND" }, { "code": null, "e": 8034, "s": 7950, "text": "This binary operator compares each field bit by bit using the Boolean AND operator." }, { "code": null, "e": 8042, "s": 8034, "text": "BIT-XOR" }, { "code": null, "e": 8141, "s": 8042, "text": "Binary operator that compares each field bit by bit using the Boolean XOR (exclusive OR) operator." }, { "code": null, "e": 8148, "s": 8141, "text": "BIT-OR" }, { "code": null, "e": 8231, "s": 8148, "text": "Binary operator that compares each field bit by bit using the Boolean OR operator." }, { "code": null, "e": 8418, "s": 8231, "text": "For example, following is the truth table that shows the values generated when applying the Boolean AND, OR, or XOR operators against the two bit values contained in field A and field B." }, { "code": null, "e": 8470, "s": 8418, "text": "Following is a list of character string operators −" }, { "code": null, "e": 8489, "s": 8470, "text": "CO (Contains Only)" }, { "code": null, "e": 8549, "s": 8489, "text": "Checks whether A is solely composed of the characters in B." }, { "code": null, "e": 8572, "s": 8549, "text": "CN (Not Contains ONLY)" }, { "code": null, "e": 8628, "s": 8572, "text": "Checks whether A contains characters that are not in B." }, { "code": null, "e": 8646, "s": 8628, "text": "CA (Contains ANY)" }, { "code": null, "e": 8701, "s": 8646, "text": "Checks whether A contains at least one character of B." }, { "code": null, "e": 8723, "s": 8701, "text": "NA (NOT Contains Any)" }, { "code": null, "e": 8777, "s": 8723, "text": "Checks whether A does not contain any character of B." }, { "code": null, "e": 8800, "s": 8777, "text": "CS (Contains a String)" }, { "code": null, "e": 8850, "s": 8800, "text": "Checks whether A contains the character string B." }, { "code": null, "e": 8877, "s": 8850, "text": "NS (NOT Contains a String)" }, { "code": null, "e": 8935, "s": 8877, "text": "Checks whether A does not contain the character string B." }, { "code": null, "e": 8959, "s": 8935, "text": "CP (Contains a Pattern)" }, { "code": null, "e": 9006, "s": 8959, "text": "It checks whether A contains the pattern in B." }, { "code": null, "e": 9034, "s": 9006, "text": "NP (NOT Contains a Pattern)" }, { "code": null, "e": 9089, "s": 9034, "text": "It checks whether A does not contain the pattern in B." }, { "code": null, "e": 9265, "s": 9089, "text": "REPORT YS_SEP_08. \nDATA: P(10) TYPE C VALUE 'APPLE',\n Q(10) TYPE C VALUE 'CHAIR'.\n IF P CA Q.\n\t\n WRITE: / 'P contains at least one character of Q'.\n ENDIF." }, { "code": null, "e": 9312, "s": 9265, "text": "The above code produces the following output −" } ]
FLOOR() AND CEIL() Function in MySQL
28 Sep, 2020 1. FLOOR() Function :FLOOR() function in MySQL is used to return the largest integer value which will be either equal to or less than from a given input number. Syntax : FLOOR(X) Parameter : Required.X : A number whose floor value we want to calculate.Returns : It returns the closest integer which is <=X. So, if X is integer than it will return X. Otherwise, largest integer which is lesser than X. Example-1 :Applying FLOOR() function to a +ve integer. SELECT FLOOR(4) AS Floor_Value; Output : Example-2 :Applying FLOOR() function to a -ve integer. SELECT FLOOR(-6) AS Floor_Value; Output : Example-3 :Applying FLOOR() function to a +ve floating number. SELECT FLOOR(1.5) AS Floor_Value; Output : Example-4 :Applying FLOOR() function to a -ve floating number. SELECT FLOOR(-1.5) AS Floor_Value; Output : Example-5 :FLOOR value of a numeric column in a table. Table – Number SELECT X, FLOOR(X) AS X_Floor FROM Number; Output : 2. CEIL() Function :CEIL() function in MySQL is used to return the smallest integer value which is either greater than or equal to the given input number. Syntax : CEIL(X) Parameter : Required.X : A number whose ceiling value we want to calculate.Returns : It returns the closest integer which is >=X. So, if X is integer than it will return X. Otherwise, next integer which is greater than X. Example-1 :Applying CEIL() function to a +ve integer. SELECT CEIL(5) AS Ceil_Value; Output : Example-2 :Applying CEIL() function to a -ve integer. SELECT CEIL(-8) AS Ceil_Value; Output : Example-3 :Applying CEIL() function to a +ve floating number. SELECT CEIL(1.5) AS Ceil_Value; Output : Example-4 :Applying CEIL() function to a -ve floating number. SELECT CEIL(-1.5) AS Ceil_Value; Output : Example-5 :CEIL value of a numeric column in a table. Table – Number SELECT X, CEIL(X) AS X_Ceil FROM Number; Output : DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE Window functions in SQL MySQL | Group_CONCAT() Function SQL | GROUP BY Difference between DDL and DML in DBMS Difference between DELETE and TRUNCATE SQL Correlated Subqueries
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Sep, 2020" }, { "code": null, "e": 189, "s": 28, "text": "1. FLOOR() Function :FLOOR() function in MySQL is used to return the largest integer value which will be either equal to or less than from a given input number." }, { "code": null, "e": 198, "s": 189, "text": "Syntax :" }, { "code": null, "e": 207, "s": 198, "text": "FLOOR(X)" }, { "code": null, "e": 429, "s": 207, "text": "Parameter : Required.X : A number whose floor value we want to calculate.Returns : It returns the closest integer which is <=X. So, if X is integer than it will return X. Otherwise, largest integer which is lesser than X." }, { "code": null, "e": 484, "s": 429, "text": "Example-1 :Applying FLOOR() function to a +ve integer." }, { "code": null, "e": 516, "s": 484, "text": "SELECT FLOOR(4) AS Floor_Value;" }, { "code": null, "e": 525, "s": 516, "text": "Output :" }, { "code": null, "e": 580, "s": 525, "text": "Example-2 :Applying FLOOR() function to a -ve integer." }, { "code": null, "e": 613, "s": 580, "text": "SELECT FLOOR(-6) AS Floor_Value;" }, { "code": null, "e": 622, "s": 613, "text": "Output :" }, { "code": null, "e": 685, "s": 622, "text": "Example-3 :Applying FLOOR() function to a +ve floating number." }, { "code": null, "e": 719, "s": 685, "text": "SELECT FLOOR(1.5) AS Floor_Value;" }, { "code": null, "e": 728, "s": 719, "text": "Output :" }, { "code": null, "e": 791, "s": 728, "text": "Example-4 :Applying FLOOR() function to a -ve floating number." }, { "code": null, "e": 826, "s": 791, "text": "SELECT FLOOR(-1.5) AS Floor_Value;" }, { "code": null, "e": 835, "s": 826, "text": "Output :" }, { "code": null, "e": 890, "s": 835, "text": "Example-5 :FLOOR value of a numeric column in a table." }, { "code": null, "e": 905, "s": 890, "text": "Table – Number" }, { "code": null, "e": 948, "s": 905, "text": "SELECT X, FLOOR(X) AS X_Floor FROM Number;" }, { "code": null, "e": 957, "s": 948, "text": "Output :" }, { "code": null, "e": 1112, "s": 957, "text": "2. CEIL() Function :CEIL() function in MySQL is used to return the smallest integer value which is either greater than or equal to the given input number." }, { "code": null, "e": 1121, "s": 1112, "text": "Syntax :" }, { "code": null, "e": 1129, "s": 1121, "text": "CEIL(X)" }, { "code": null, "e": 1351, "s": 1129, "text": "Parameter : Required.X : A number whose ceiling value we want to calculate.Returns : It returns the closest integer which is >=X. So, if X is integer than it will return X. Otherwise, next integer which is greater than X." }, { "code": null, "e": 1405, "s": 1351, "text": "Example-1 :Applying CEIL() function to a +ve integer." }, { "code": null, "e": 1435, "s": 1405, "text": "SELECT CEIL(5) AS Ceil_Value;" }, { "code": null, "e": 1444, "s": 1435, "text": "Output :" }, { "code": null, "e": 1498, "s": 1444, "text": "Example-2 :Applying CEIL() function to a -ve integer." }, { "code": null, "e": 1529, "s": 1498, "text": "SELECT CEIL(-8) AS Ceil_Value;" }, { "code": null, "e": 1538, "s": 1529, "text": "Output :" }, { "code": null, "e": 1600, "s": 1538, "text": "Example-3 :Applying CEIL() function to a +ve floating number." }, { "code": null, "e": 1632, "s": 1600, "text": "SELECT CEIL(1.5) AS Ceil_Value;" }, { "code": null, "e": 1641, "s": 1632, "text": "Output :" }, { "code": null, "e": 1703, "s": 1641, "text": "Example-4 :Applying CEIL() function to a -ve floating number." }, { "code": null, "e": 1736, "s": 1703, "text": "SELECT CEIL(-1.5) AS Ceil_Value;" }, { "code": null, "e": 1745, "s": 1736, "text": "Output :" }, { "code": null, "e": 1799, "s": 1745, "text": "Example-5 :CEIL value of a numeric column in a table." }, { "code": null, "e": 1814, "s": 1799, "text": "Table – Number" }, { "code": null, "e": 1855, "s": 1814, "text": "SELECT X, CEIL(X) AS X_Ceil FROM Number;" }, { "code": null, "e": 1864, "s": 1855, "text": "Output :" }, { "code": null, "e": 1873, "s": 1864, "text": "DBMS-SQL" }, { "code": null, "e": 1879, "s": 1873, "text": "mysql" }, { "code": null, "e": 1883, "s": 1879, "text": "SQL" }, { "code": null, "e": 1887, "s": 1883, "text": "SQL" }, { "code": null, "e": 1985, "s": 1887, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2051, "s": 1985, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2075, "s": 2051, "text": "SQL Interview Questions" }, { "code": null, "e": 2087, "s": 2075, "text": "SQL | Views" }, { "code": null, "e": 2132, "s": 2087, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 2156, "s": 2132, "text": "Window functions in SQL" }, { "code": null, "e": 2188, "s": 2156, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 2203, "s": 2188, "text": "SQL | GROUP BY" }, { "code": null, "e": 2242, "s": 2203, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 2281, "s": 2242, "text": "Difference between DELETE and TRUNCATE" } ]
PyQt5 – How to set text to progress bar ?
22 Apr, 2020 In this article we will see how to set text to progress bar. When we create a progress bar only progress percentage text is visible but we can also set some text on it. Below is how normal progress bar vs progress bar with text looks like. In order to do this we will use setFormat method, although it is used to set the format i.e percentage indicator but if we pass normal text to it it will display it in process bar. # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 150, 200, 30) # set value to progress bar bar.setValue(70) # setting text bar.setFormat('This is progress bar') # setting alignment to centre bar.setAlignment(Qt.AlignCenter) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method 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": "\n22 Apr, 2020" }, { "code": null, "e": 197, "s": 28, "text": "In this article we will see how to set text to progress bar. When we create a progress bar only progress percentage text is visible but we can also set some text on it." }, { "code": null, "e": 269, "s": 197, "text": "Below is how normal progress bar vs progress bar with text looks like. " }, { "code": null, "e": 450, "s": 269, "text": "In order to do this we will use setFormat method, although it is used to set the format i.e percentage indicator but if we pass normal text to it it will display it in process bar." }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 150, 200, 30) # set value to progress bar bar.setValue(70) # setting text bar.setFormat('This is progress bar') # setting alignment to centre bar.setAlignment(Qt.AlignCenter) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1476, "s": 450, "text": null }, { "code": null, "e": 1485, "s": 1476, "text": "Output :" }, { "code": null, "e": 1496, "s": 1485, "text": "Python-gui" }, { "code": null, "e": 1508, "s": 1496, "text": "Python-PyQt" }, { "code": null, "e": 1515, "s": 1508, "text": "Python" }, { "code": null, "e": 1613, "s": 1515, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1645, "s": 1613, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1672, "s": 1645, "text": "Python Classes and Objects" }, { "code": null, "e": 1693, "s": 1672, "text": "Python OOPs Concepts" }, { "code": null, "e": 1716, "s": 1693, "text": "Introduction To PYTHON" }, { "code": null, "e": 1772, "s": 1716, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1803, "s": 1772, "text": "Python | os.path.join() method" }, { "code": null, "e": 1845, "s": 1803, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1887, "s": 1845, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1926, "s": 1887, "text": "Python | datetime.timedelta() function" } ]
Use of print() and say() in Perl
18 Jun, 2019 Perl uses statements and expressions to evaluate the input provided by the user or given as Hardcoded Input in the code. This evaluated expression will not be shown to the programmer as it’s been evaluated in the compiler. To display this evaluated expression, Perl uses print() function and say() function. These functions can display anything passed to them as arguments. print operator in Perl is used to print the values of the expressions in a List passed to it as an argument. Print operator prints whatever is passed to it as an argument whether it be a string, a number, a variable or anything. Double-quotes(“”) is used as a delimiter to this operator. Syntax: print ""; Example: #!/usr/bin/perl -w # Defining a string $string1 = "Geeks For Geeks"; $string2 = "Welcomes you all"; print "$string1";print "$string2"; Geeks For GeeksWelcomes you all Above example, prints both the strings with the help of print function but both the strings are printed in the same line. To avoid this and print them in different lines, we need to use a ‘\n’ operator that changes the line whenever used. Example: #!/usr/bin/perl -w # Defining a string $string1 = "Geeks For Geeks"; $string2 = "Welcomes you all"; print "$string1\n";print "$string2"; Geeks For Geeks Welcomes you all If we use Single Quotes instead of double quotes, then the print() function will not print the value of the variables or the escape characters used in the statement like ‘\n’, etc. These characters will be printed as it is and will not be evaluated. Example: #!/usr/bin/perl -w # Defining a string $string1 = 'Geeks For Geeks'; $string2 = 'Welcomes you all'; print '$string1\n';print '$string2'; $string1\n$string2 say() function in Perl works similar to the print() function but there’s a slight difference, say() function automatically adds a new line at the end of the statement, there is no need to add a newline character ‘\n’ for changing the line. Example: #!/usr/bin/perl -w use 5.010; # Defining a string $string1 = "Geeks For Geeks"; $string2 = "Welcomes you all"; # say() function to printsay("$string1");say("$string2"); Geeks For Geeks Welcomes you all Here, we have used ‘use 5.010‘ to use the say() function because newer versions of Perl don’t support some functions of the older versions and hence, the older version is to be called to execute the say() function. perl-basics Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Regular Expressions Perl | Polymorphism in OOPs Perl Tutorial - Learn Perl With Examples Perl | Boolean Values Perl | length() Function Perl | Subroutines or Functions Perl | Basic Syntax of a Perl Program Introduction to Perl Hello World Program in Perl Perl | substitution Operator
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Jun, 2019" }, { "code": null, "e": 428, "s": 54, "text": "Perl uses statements and expressions to evaluate the input provided by the user or given as Hardcoded Input in the code. This evaluated expression will not be shown to the programmer as it’s been evaluated in the compiler. To display this evaluated expression, Perl uses print() function and say() function. These functions can display anything passed to them as arguments." }, { "code": null, "e": 716, "s": 428, "text": "print operator in Perl is used to print the values of the expressions in a List passed to it as an argument. Print operator prints whatever is passed to it as an argument whether it be a string, a number, a variable or anything. Double-quotes(“”) is used as a delimiter to this operator." }, { "code": null, "e": 724, "s": 716, "text": "Syntax:" }, { "code": null, "e": 734, "s": 724, "text": "print \"\";" }, { "code": null, "e": 743, "s": 734, "text": "Example:" }, { "code": "#!/usr/bin/perl -w # Defining a string $string1 = \"Geeks For Geeks\"; $string2 = \"Welcomes you all\"; print \"$string1\";print \"$string2\";", "e": 883, "s": 743, "text": null }, { "code": null, "e": 916, "s": 883, "text": "Geeks For GeeksWelcomes you all\n" }, { "code": null, "e": 1155, "s": 916, "text": "Above example, prints both the strings with the help of print function but both the strings are printed in the same line. To avoid this and print them in different lines, we need to use a ‘\\n’ operator that changes the line whenever used." }, { "code": null, "e": 1164, "s": 1155, "text": "Example:" }, { "code": "#!/usr/bin/perl -w # Defining a string $string1 = \"Geeks For Geeks\"; $string2 = \"Welcomes you all\"; print \"$string1\\n\";print \"$string2\";", "e": 1306, "s": 1164, "text": null }, { "code": null, "e": 1340, "s": 1306, "text": "Geeks For Geeks\nWelcomes you all\n" }, { "code": null, "e": 1590, "s": 1340, "text": "If we use Single Quotes instead of double quotes, then the print() function will not print the value of the variables or the escape characters used in the statement like ‘\\n’, etc. These characters will be printed as it is and will not be evaluated." }, { "code": null, "e": 1599, "s": 1590, "text": "Example:" }, { "code": "#!/usr/bin/perl -w # Defining a string $string1 = 'Geeks For Geeks'; $string2 = 'Welcomes you all'; print '$string1\\n';print '$string2';", "e": 1741, "s": 1599, "text": null }, { "code": null, "e": 1761, "s": 1741, "text": "$string1\\n$string2\n" }, { "code": null, "e": 2001, "s": 1761, "text": "say() function in Perl works similar to the print() function but there’s a slight difference, say() function automatically adds a new line at the end of the statement, there is no need to add a newline character ‘\\n’ for changing the line." }, { "code": null, "e": 2010, "s": 2001, "text": "Example:" }, { "code": "#!/usr/bin/perl -w use 5.010; # Defining a string $string1 = \"Geeks For Geeks\"; $string2 = \"Welcomes you all\"; # say() function to printsay(\"$string1\");say(\"$string2\");", "e": 2181, "s": 2010, "text": null }, { "code": null, "e": 2215, "s": 2181, "text": "Geeks For Geeks\nWelcomes you all\n" }, { "code": null, "e": 2430, "s": 2215, "text": "Here, we have used ‘use 5.010‘ to use the say() function because newer versions of Perl don’t support some functions of the older versions and hence, the older version is to be called to execute the say() function." }, { "code": null, "e": 2442, "s": 2430, "text": "perl-basics" }, { "code": null, "e": 2447, "s": 2442, "text": "Perl" }, { "code": null, "e": 2452, "s": 2447, "text": "Perl" }, { "code": null, "e": 2550, "s": 2452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2577, "s": 2550, "text": "Perl | Regular Expressions" }, { "code": null, "e": 2605, "s": 2577, "text": "Perl | Polymorphism in OOPs" }, { "code": null, "e": 2646, "s": 2605, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 2668, "s": 2646, "text": "Perl | Boolean Values" }, { "code": null, "e": 2693, "s": 2668, "text": "Perl | length() Function" }, { "code": null, "e": 2725, "s": 2693, "text": "Perl | Subroutines or Functions" }, { "code": null, "e": 2763, "s": 2725, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 2784, "s": 2763, "text": "Introduction to Perl" }, { "code": null, "e": 2812, "s": 2784, "text": "Hello World Program in Perl" } ]
Python program to count upper and lower case characters without using inbuilt functions
24 Nov, 2020 Given a string that contains both upper and lower case characters in it. The task is to count number of upper and lower case characters in it without using in-built functions. Counting the upper and lower case characters of a string can be easily done using isupper() and islower() functions, refer this. But doing the same without help of any inbuilt function is quite exciting. Let’s see how this can be done : Examples : Input : Introduction to Python Output : Lower Case characters : 18 Upper case characters : 2 Input : Welcome to GeeksforGeeks Output : Lower Case characters : 19 Upper case characters: 3 Below is the implementation of above idea : # Python3 program to count upper and# lower case characters without using# inbuilt functionsdef upperlower(string): upper = 0 lower = 0 for i in range(len(string)): # For lower letters if (ord(string[i]) >= 97 and ord(string[i]) <= 122): lower += 1 # For upper letters elif (ord(string[i]) >= 65 and ord(string[i]) <= 90): upper += 1 print('Lower case characters = %s' %lower, 'Upper case characters = %s' %upper) # Driver Codestring = 'GeeksforGeeks is a portal for Geeks'upperlower(string) Lower case characters = 27 Upper case characters = 3 Alternative Method:- s = "The Geek King"l,u = 0,0for i in s: if (i>='a'and i<='z'): # counting lower case l=l+1 if (i>='A'and i<='Z'): #counting upper case u=u+1 print('Lower case characters: ',l)print('Upper case characters: ',u) Lower case characters: 8 Upper case characters: 3 Divyu_Pandey Python string-programs python-string Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Create a Pandas DataFrame from Lists
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Nov, 2020" }, { "code": null, "e": 229, "s": 53, "text": "Given a string that contains both upper and lower case characters in it. The task is to count number of upper and lower case characters in it without using in-built functions." }, { "code": null, "e": 466, "s": 229, "text": "Counting the upper and lower case characters of a string can be easily done using isupper() and islower() functions, refer this. But doing the same without help of any inbuilt function is quite exciting. Let’s see how this can be done :" }, { "code": null, "e": 477, "s": 466, "text": "Examples :" }, { "code": null, "e": 668, "s": 477, "text": "Input : Introduction to Python\nOutput : Lower Case characters : 18 Upper case characters : 2\n\nInput : Welcome to GeeksforGeeks\nOutput : Lower Case characters : 19 Upper case characters: 3\n" }, { "code": null, "e": 713, "s": 668, "text": " Below is the implementation of above idea :" }, { "code": "# Python3 program to count upper and# lower case characters without using# inbuilt functionsdef upperlower(string): upper = 0 lower = 0 for i in range(len(string)): # For lower letters if (ord(string[i]) >= 97 and ord(string[i]) <= 122): lower += 1 # For upper letters elif (ord(string[i]) >= 65 and ord(string[i]) <= 90): upper += 1 print('Lower case characters = %s' %lower, 'Upper case characters = %s' %upper) # Driver Codestring = 'GeeksforGeeks is a portal for Geeks'upperlower(string)", "e": 1319, "s": 713, "text": null }, { "code": null, "e": 1373, "s": 1319, "text": "Lower case characters = 27 Upper case characters = 3\n" }, { "code": null, "e": 1394, "s": 1373, "text": "Alternative Method:-" }, { "code": "s = \"The Geek King\"l,u = 0,0for i in s: if (i>='a'and i<='z'): # counting lower case l=l+1 if (i>='A'and i<='Z'): #counting upper case u=u+1 print('Lower case characters: ',l)print('Upper case characters: ',u)", "e": 1687, "s": 1394, "text": null }, { "code": null, "e": 1740, "s": 1687, "text": "Lower case characters: 8\nUpper case characters: 3\n" }, { "code": null, "e": 1753, "s": 1740, "text": "Divyu_Pandey" }, { "code": null, "e": 1776, "s": 1753, "text": "Python string-programs" }, { "code": null, "e": 1790, "s": 1776, "text": "python-string" }, { "code": null, "e": 1797, "s": 1790, "text": "Python" }, { "code": null, "e": 1816, "s": 1797, "text": "Technical Scripter" }, { "code": null, "e": 1914, "s": 1816, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1932, "s": 1914, "text": "Python Dictionary" }, { "code": null, "e": 1974, "s": 1932, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1996, "s": 1974, "text": "Enumerate() in Python" }, { "code": null, "e": 2022, "s": 1996, "text": "Python String | replace()" }, { "code": null, "e": 2054, "s": 2022, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2083, "s": 2054, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2110, "s": 2083, "text": "Python Classes and Objects" }, { "code": null, "e": 2146, "s": 2110, "text": "Convert integer to string in Python" }, { "code": null, "e": 2177, "s": 2146, "text": "Python | os.path.join() method" } ]
JavaScript | Object Constructors
31 May, 2019 Object: Object is the collection of related data or functionality in the form of key. This functionalities are usually consists of several functions and variables. All JavaScript values are objects except primitives. Example: var GFG = { subject : "programming", language : "JavaScript", } Here, subject and language are the keys and programming and JavaScript are the values. Class: In JavaScript, a class is a kind of function. This classes are similar to normal java classes. The classes are declared with the class keyword like another OOP languages. The class syntax has two components: class declarations and class expressions. Class declarations:class GFG { constructor(A, B, C) { this.g = A; this.f = B; this.gg = C; } }Here class name is GFG. class GFG { constructor(A, B, C) { this.g = A; this.f = B; this.gg = C; } } Here class name is GFG. Class expressions:<script>class GFG { constructor(A, B) { // "this" refers to the address // of the keys "g" and "f" this.g = A; this.f = B; } print() { document.write(this.g +"<br>"+this.f); }} let gg = new GFG("JavaScript", "Java"); gg.print(); </script>Output:JavaScript Java <script>class GFG { constructor(A, B) { // "this" refers to the address // of the keys "g" and "f" this.g = A; this.f = B; } print() { document.write(this.g +"<br>"+this.f); }} let gg = new GFG("JavaScript", "Java"); gg.print(); </script> Output: JavaScript Java this keyword: The this keyword refers to the object it belongs to, like OOPs languages C++, C#, JAVA etc. this keyword is used in different ways in different areas. While executing a function in JavaScript that has a reference to its current execution context, that is the reference by which the function or data member is called. See the previous example. Adding property to an object: The property can be added to the object by using dot(.) operator or square bracket., var GFG = { articles: 'computer science', quantity: 3000, }; The GFG has two properties “articles” and “quantity”. Now we wish to add one more property name called subject. Using dot (.) operatorGFG.subject: 'JavaScript'; GFG.subject: 'JavaScript'; Using square bracket:GFG['subject']: 'JavaScript'; GFG['subject']: 'JavaScript'; Here, subject is the property and ‘JavaScript’ is the value of the property. Adding a property to Constructor: We cannot add a property to an existing constructor like adding a property to an object (see previous point), for adding a property we need to declare under the constructor. function GFG(a, b, c) { this.A = a; this.B = b; this.C = c; this.G = "GEEK"; } Here, we add a property name G with value “GEEK”, in this case the value “GEEK” is not passed as an argument. Adding a Method to an Object: We can add a new method to an existing object. GFG.n = function () { return this.A + this.B; }; Here, the object is GFG. Adding a Method to Constructor: function GFG(a, b, c) { this.A = a; this.B = b; this.C = c; this.n = function () { return this.A + this.B; } } Here, in the last line a method is added to an object. Constructor: A constructor is a function that initializes an object. In JavaScript the constructors are more similar to normal java constructor. Object constructor: In JavaScript, there is a special constructor function known as Object() is used to create and initialize an object. The return value of the Object() constructor is assigned to a variable. The variable contains a reference to the new object. We need an object constructor to create an object “type” that can be used multiple times without redefining the object every time. Example: function GFG(A, B, C) { this.g = A; this.f = B; this.gg = C; } Here, GFG is the constructor name and A, B, C are the arguments of the constructor. Instantiating an object constructor: There are two ways to instantiate object constructor, 1. var object_name = new Object(); or var object_name = new Object("java", "JavaScript", "C#"); 2. var object_name = { }; In 1st method, the object is created by using new keyword like normal OOP languages, and “Java”, “JavaScript”, “C#” are the arguments, that are passed when the constructor is invoked.In 2nd method, the object is created by using curly braces “{ }”. Assigning properties to the objects: There are two ways to assigning properties to the objects. Using dot (.) operatorobject_name . properties = value; object_name . properties = value; Using third bracket:object_name [ 'properties'] = value; object_name [ 'properties'] = value; Example 1: This example shows object creation by using new keyword and assigning properties to the object using dot(.) operator. <script> // creating object using "new" keyword var gfg = new Object(); // Assigning properties to the object // by using dot (.) operator gfg.a = "JavaScript"; gfg.b = "GeeksforGeeks"; document.write("Subject: " + gfg.a + "<br>"); document.write("Author: " + gfg.b );</script> Output: Subject: JavaScript Author: GeeksforGeeks Example 2: This example shows object creation using curly braces and assigning properties to the object using third bracket “[]” operator. <script> // Creating an object using "{ }" bracket var gfg = { }; // Assigning properties to the object // by using third bracket gfg['a'] = "JavaScript"; gfg['b']= "GeeksforGeeks"; document.write("Subject: " + gfg.a + "<br>"); document.write("Author: " + gfg.b );</script> Output: Subject: JavaScript Author: GeeksforGeeks Example 3: This example shows how to use function() with object constructor. <script> // Creating object var gfg = new Object(); // Assigning properties to the object gfg.a = "JavaScript"; gfg.b = "GeeksforGeeks"; // Use function() gfg.c = function () { return (gfg.a +" "+ gfg.b); }; document.write("Subject: " + gfg.a + "<br>"); document.write("Author: " + gfg.b + "<br>"); // Call function with object constructor document.write("Adding the strings: "+ gfg.c() ); </script> Output: Subject: JavaScript Author: GeeksforGeeks Adding the strings: JavaScript GeeksforGeeks Example: Another way to create a function using function name. <script> // Creating object using "{ }" bracket var gfg = { }; // Assigning properties to the object gfg.a = "JavaScript"; gfg.b = "GeeksforGeeks"; // Use function() gfg.c = add; // Declare function add() function add() { return (gfg.a +" "+ gfg.b); }; document.write("Subject: " + gfg.a + "<br>"); document.write("Author: " + gfg.b + "<br>"); // Call function with object constructor document.write("Adding the strings: "+ gfg.c()); </script> Output : Subject: JavaScript Author: GeeksforGeeks Adding the strings: JavaScript GeeksforGeeks javascript-oop Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n31 May, 2019" }, { "code": null, "e": 270, "s": 53, "text": "Object: Object is the collection of related data or functionality in the form of key. This functionalities are usually consists of several functions and variables. All JavaScript values are objects except primitives." }, { "code": null, "e": 279, "s": 270, "text": "Example:" }, { "code": null, "e": 351, "s": 279, "text": "var GFG = {\n subject : \"programming\",\n language : \"JavaScript\",\n}" }, { "code": null, "e": 438, "s": 351, "text": "Here, subject and language are the keys and programming and JavaScript are the values." }, { "code": null, "e": 695, "s": 438, "text": "Class: In JavaScript, a class is a kind of function. This classes are similar to normal java classes. The classes are declared with the class keyword like another OOP languages. The class syntax has two components: class declarations and class expressions." }, { "code": null, "e": 845, "s": 695, "text": "Class declarations:class GFG {\n constructor(A, B, C) {\n this.g = A;\n this.f = B;\n this.gg = C;\n }\n}Here class name is GFG." }, { "code": null, "e": 953, "s": 845, "text": "class GFG {\n constructor(A, B, C) {\n this.g = A;\n this.f = B;\n this.gg = C;\n }\n}" }, { "code": null, "e": 977, "s": 953, "text": "Here class name is GFG." }, { "code": null, "e": 1308, "s": 977, "text": "Class expressions:<script>class GFG { constructor(A, B) { // \"this\" refers to the address // of the keys \"g\" and \"f\" this.g = A; this.f = B; } print() { document.write(this.g +\"<br>\"+this.f); }} let gg = new GFG(\"JavaScript\", \"Java\"); gg.print(); </script>Output:JavaScript\nJava" }, { "code": "<script>class GFG { constructor(A, B) { // \"this\" refers to the address // of the keys \"g\" and \"f\" this.g = A; this.f = B; } print() { document.write(this.g +\"<br>\"+this.f); }} let gg = new GFG(\"JavaScript\", \"Java\"); gg.print(); </script>", "e": 1599, "s": 1308, "text": null }, { "code": null, "e": 1607, "s": 1599, "text": "Output:" }, { "code": null, "e": 1623, "s": 1607, "text": "JavaScript\nJava" }, { "code": null, "e": 1980, "s": 1623, "text": "this keyword: The this keyword refers to the object it belongs to, like OOPs languages C++, C#, JAVA etc. this keyword is used in different ways in different areas. While executing a function in JavaScript that has a reference to its current execution context, that is the reference by which the function or data member is called. See the previous example." }, { "code": null, "e": 2095, "s": 1980, "text": "Adding property to an object: The property can be added to the object by using dot(.) operator or square bracket.," }, { "code": null, "e": 2164, "s": 2095, "text": "var GFG = {\n articles: 'computer science',\n quantity: 3000,\n};" }, { "code": null, "e": 2276, "s": 2164, "text": "The GFG has two properties “articles” and “quantity”. Now we wish to add one more property name called subject." }, { "code": null, "e": 2325, "s": 2276, "text": "Using dot (.) operatorGFG.subject: 'JavaScript';" }, { "code": null, "e": 2352, "s": 2325, "text": "GFG.subject: 'JavaScript';" }, { "code": null, "e": 2403, "s": 2352, "text": "Using square bracket:GFG['subject']: 'JavaScript';" }, { "code": null, "e": 2433, "s": 2403, "text": "GFG['subject']: 'JavaScript';" }, { "code": null, "e": 2510, "s": 2433, "text": "Here, subject is the property and ‘JavaScript’ is the value of the property." }, { "code": null, "e": 2718, "s": 2510, "text": "Adding a property to Constructor: We cannot add a property to an existing constructor like adding a property to an object (see previous point), for adding a property we need to declare under the constructor." }, { "code": null, "e": 2813, "s": 2718, "text": "function GFG(a, b, c) {\n this.A = a;\n this.B = b;\n this.C = c;\n this.G = \"GEEK\";\n}" }, { "code": null, "e": 2923, "s": 2813, "text": "Here, we add a property name G with value “GEEK”, in this case the value “GEEK” is not passed as an argument." }, { "code": null, "e": 3000, "s": 2923, "text": "Adding a Method to an Object: We can add a new method to an existing object." }, { "code": null, "e": 3053, "s": 3000, "text": "GFG.n = function () {\n return this.A + this.B;\n};" }, { "code": null, "e": 3078, "s": 3053, "text": "Here, the object is GFG." }, { "code": null, "e": 3110, "s": 3078, "text": "Adding a Method to Constructor:" }, { "code": null, "e": 3249, "s": 3110, "text": "function GFG(a, b, c) {\n this.A = a;\n this.B = b;\n this.C = c;\n this.n = function () {\n return this.A + this.B;\n }\n}" }, { "code": null, "e": 3304, "s": 3249, "text": "Here, in the last line a method is added to an object." }, { "code": null, "e": 3449, "s": 3304, "text": "Constructor: A constructor is a function that initializes an object. In JavaScript the constructors are more similar to normal java constructor." }, { "code": null, "e": 3842, "s": 3449, "text": "Object constructor: In JavaScript, there is a special constructor function known as Object() is used to create and initialize an object. The return value of the Object() constructor is assigned to a variable. The variable contains a reference to the new object. We need an object constructor to create an object “type” that can be used multiple times without redefining the object every time." }, { "code": null, "e": 3851, "s": 3842, "text": "Example:" }, { "code": null, "e": 3926, "s": 3851, "text": "function GFG(A, B, C) {\n this.g = A;\n this.f = B;\n this.gg = C;\n}" }, { "code": null, "e": 4010, "s": 3926, "text": "Here, GFG is the constructor name and A, B, C are the arguments of the constructor." }, { "code": null, "e": 4101, "s": 4010, "text": "Instantiating an object constructor: There are two ways to instantiate object constructor," }, { "code": null, "e": 4228, "s": 4101, "text": "1. var object_name = new Object(); or \n var object_name = new Object(\"java\", \"JavaScript\", \"C#\");\n2. var object_name = { };" }, { "code": null, "e": 4477, "s": 4228, "text": "In 1st method, the object is created by using new keyword like normal OOP languages, and “Java”, “JavaScript”, “C#” are the arguments, that are passed when the constructor is invoked.In 2nd method, the object is created by using curly braces “{ }”." }, { "code": null, "e": 4573, "s": 4477, "text": "Assigning properties to the objects: There are two ways to assigning properties to the objects." }, { "code": null, "e": 4629, "s": 4573, "text": "Using dot (.) operatorobject_name . properties = value;" }, { "code": null, "e": 4663, "s": 4629, "text": "object_name . properties = value;" }, { "code": null, "e": 4720, "s": 4663, "text": "Using third bracket:object_name [ 'properties'] = value;" }, { "code": null, "e": 4757, "s": 4720, "text": "object_name [ 'properties'] = value;" }, { "code": null, "e": 4886, "s": 4757, "text": "Example 1: This example shows object creation by using new keyword and assigning properties to the object using dot(.) operator." }, { "code": "<script> // creating object using \"new\" keyword var gfg = new Object(); // Assigning properties to the object // by using dot (.) operator gfg.a = \"JavaScript\"; gfg.b = \"GeeksforGeeks\"; document.write(\"Subject: \" + gfg.a + \"<br>\"); document.write(\"Author: \" + gfg.b );</script> ", "e": 5231, "s": 4886, "text": null }, { "code": null, "e": 5239, "s": 5231, "text": "Output:" }, { "code": null, "e": 5281, "s": 5239, "text": "Subject: JavaScript\nAuthor: GeeksforGeeks" }, { "code": null, "e": 5420, "s": 5281, "text": "Example 2: This example shows object creation using curly braces and assigning properties to the object using third bracket “[]” operator." }, { "code": " <script> // Creating an object using \"{ }\" bracket var gfg = { }; // Assigning properties to the object // by using third bracket gfg['a'] = \"JavaScript\"; gfg['b']= \"GeeksforGeeks\"; document.write(\"Subject: \" + gfg.a + \"<br>\"); document.write(\"Author: \" + gfg.b );</script>", "e": 5735, "s": 5420, "text": null }, { "code": null, "e": 5743, "s": 5735, "text": "Output:" }, { "code": null, "e": 5785, "s": 5743, "text": "Subject: JavaScript\nAuthor: GeeksforGeeks" }, { "code": null, "e": 5862, "s": 5785, "text": "Example 3: This example shows how to use function() with object constructor." }, { "code": "<script> // Creating object var gfg = new Object(); // Assigning properties to the object gfg.a = \"JavaScript\"; gfg.b = \"GeeksforGeeks\"; // Use function() gfg.c = function () { return (gfg.a +\" \"+ gfg.b); }; document.write(\"Subject: \" + gfg.a + \"<br>\"); document.write(\"Author: \" + gfg.b + \"<br>\"); // Call function with object constructor document.write(\"Adding the strings: \"+ gfg.c() ); </script> ", "e": 6366, "s": 5862, "text": null }, { "code": null, "e": 6374, "s": 6366, "text": "Output:" }, { "code": null, "e": 6462, "s": 6374, "text": "Subject: JavaScript\nAuthor: GeeksforGeeks\nAdding the strings: JavaScript GeeksforGeeks\n" }, { "code": null, "e": 6525, "s": 6462, "text": "Example: Another way to create a function using function name." }, { "code": "<script> // Creating object using \"{ }\" bracket var gfg = { }; // Assigning properties to the object gfg.a = \"JavaScript\"; gfg.b = \"GeeksforGeeks\"; // Use function() gfg.c = add; // Declare function add() function add() { return (gfg.a +\" \"+ gfg.b); }; document.write(\"Subject: \" + gfg.a + \"<br>\"); document.write(\"Author: \" + gfg.b + \"<br>\"); // Call function with object constructor document.write(\"Adding the strings: \"+ gfg.c()); </script> ", "e": 7075, "s": 6525, "text": null }, { "code": null, "e": 7084, "s": 7075, "text": "Output :" }, { "code": null, "e": 7172, "s": 7084, "text": "Subject: JavaScript\nAuthor: GeeksforGeeks\nAdding the strings: JavaScript GeeksforGeeks\n" }, { "code": null, "e": 7187, "s": 7172, "text": "javascript-oop" }, { "code": null, "e": 7194, "s": 7187, "text": "Picked" }, { "code": null, "e": 7205, "s": 7194, "text": "JavaScript" }, { "code": null, "e": 7222, "s": 7205, "text": "Web Technologies" } ]
Find minimum weight cycle in an undirected graph
07 Jul, 2022 Given a positive weighted undirected graph, find the minimum weight cycle in it. Examples: Minimum weighted cycle is : Minimum weighed cycle : 7 + 1 + 6 = 14 or 2 + 6 + 2 + 4 = 14 The idea is to use shortest path algorithm. We one by one remove every edge from the graph, then we find the shortest path between two corner vertices of it. We add an edge back before we process the next edge. 1). create an empty vector 'edge' of size 'E' ( E total number of edge). Every element of this vector is used to store information of all the edge in graph info 2) Traverse every edge edge[i] one - by - one a). First remove 'edge[i]' from graph 'G' b). get current edge vertices which we just removed from graph c). Find the shortest path between them "Using Dijkstra’s shortest path algorithm " d). To make a cycle we add the weight of the removed edge to the shortest path. e). update min_weight_cycle if needed 3). return minimum weighted cycle Below is the implementation of the above idea C++ Python3 // c++ program to find shortest weighted// cycle in undirected graph#include<bits/stdc++.h>using namespace std;# define INF 0x3f3f3f3fstruct Edge{ int u; int v; int weight;}; // weighted undirected Graphclass Graph{ int V ; list < pair <int, int > >*adj; // used to store all edge information vector < Edge > edge; public : Graph( int V ) { this->V = V ; adj = new list < pair <int, int > >[V]; } void addEdge ( int u, int v, int w ); void removeEdge( int u, int v, int w ); int ShortestPath (int u, int v ); void RemoveEdge( int u, int v ); int FindMinimumCycle (); }; //function add edge to graphvoid Graph :: addEdge ( int u, int v, int w ){ adj[u].push_back( make_pair( v, w )); adj[v].push_back( make_pair( u, w )); // add Edge to edge list Edge e { u, v, w }; edge.push_back ( e );} // function remove edge from undirected graphvoid Graph :: removeEdge ( int u, int v, int w ){ adj[u].remove(make_pair( v, w )); adj[v].remove(make_pair(u, w ));} // find the shortest path from source to sink using// Dijkstra’s shortest path algorithm [ Time complexity// O(E logV )]int Graph :: ShortestPath ( int u, int v ){ // Create a set to store vertices that are being // preprocessed set< pair<int, int> > setds; // Create a vector for distances and initialize all // distances as infinite (INF) vector<int> dist(V, INF); // Insert source itself in Set and initialize its // distance as 0. setds.insert(make_pair(0, u)); dist[u] = 0; /* Looping till all shortest distance are finalized then setds will become empty */ while (!setds.empty()) { // The first vertex in Set is the minimum distance // vertex, extract it from set. pair<int, int> tmp = *(setds.begin()); setds.erase(setds.begin()); // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted distance (distance must be first item // in pair) int u = tmp.second; // 'i' is used to get all adjacent vertices of // a vertex list< pair<int, int> >::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // Get vertex label and weight of current adjacent // of u. int v = (*i).first; int weight = (*i).second; // If there is shorter path to v through u. if (dist[v] > dist[u] + weight) { /* If the distance of v is not INF then it must be in our set, so removing it and inserting again with updated less distance. Note : We extract only those vertices from Set for which distance is finalized. So for them, we would never reach here. */ if (dist[v] != INF) setds.erase(setds.find(make_pair(dist[v], v))); // Updating distance of v dist[v] = dist[u] + weight; setds.insert(make_pair(dist[v], v)); } } } // return shortest path from current source to sink return dist[v] ;} // function return minimum weighted cycleint Graph :: FindMinimumCycle ( ){ int min_cycle = INT_MAX; int E = edge.size(); for ( int i = 0 ; i < E ; i++ ) { // current Edge information Edge e = edge[i]; // get current edge vertices which we currently // remove from graph and then find shortest path // between these two vertex using Dijkstra’s // shortest path algorithm . removeEdge( e.u, e.v, e.weight ) ; // minimum distance between these two vertices int distance = ShortestPath( e.u, e.v ); // to make a cycle we have to add weight of // currently removed edge if this is the shortest // cycle then update min_cycle min_cycle = min( min_cycle, distance + e.weight ); // add current edge back to the graph addEdge( e.u, e.v, e.weight ); } // return shortest cycle return min_cycle ;} // driver program to test above functionint main(){ int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); cout << g.FindMinimumCycle() << endl; return 0;} # Python3 program to find shortest weighted# cycle in undirected graphfrom sys import maxsize INF = int(0x3f3f3f3f) class Edge: def __init__(self, u: int, v: int, weight: int) -> None: self.u = u self.v = v self.weight = weight # Weighted undirected Graphclass Graph: def __init__(self, V: int) -> None: self.V = V self.adj = [[] for _ in range(V)] # Used to store all edge information self.edge = [] # Function add edge to graph def addEdge(self, u: int, v: int, w: int) -> None: self.adj[u].append((v, w)) self.adj[v].append((u, w)) # Add Edge to edge list e = Edge(u, v, w) self.edge.append(e) # Function remove edge from undirected graph def removeEdge(self, u: int, v: int, w: int) -> None: self.adj[u].remove((v, w)) self.adj[v].remove((u, w)) # Find the shortest path from source # to sink using Dijkstra’s shortest # path algorithm [ Time complexity # O(E logV )] def ShortestPath(self, u: int, v: int) -> int: # Create a set to store vertices that # are being preprocessed setds = set() # Create a vector for distances and # initialize all distances as infinite (INF) dist = [INF] * self.V # Insert source itself in Set and # initialize its distance as 0. setds.add((0, u)) dist[u] = 0 # Looping till all shortest distance are # finalized then setds will become empty while (setds): # The first vertex in Set is the minimum # distance vertex, extract it from set. tmp = setds.pop() # Vertex label is stored in second of # pair (it has to be done this way to # keep the vertices sorted distance # (distance must be first item in pair) uu = tmp[1] # 'i' is used to get all adjacent # vertices of a vertex for i in self.adj[uu]: # Get vertex label and weight of # current adjacent of u. vv = i[0] weight = i[1] # If there is shorter path to v through u. if (dist[vv] > dist[uu] + weight): # If the distance of v is not INF then # it must be in our set, so removing it # and inserting again with updated less # distance. Note : We extract only those # vertices from Set for which distance # is finalized. So for them, we would # never reach here. if (dist[vv] != INF): if ((dist[vv], vv) in setds): setds.remove((dist[vv], vv)) # Updating distance of v dist[vv] = dist[uu] + weight setds.add((dist[vv], vv)) # Return shortest path from # current source to sink return dist[v] # Function return minimum weighted cycle def FindMinimumCycle(self) -> int: min_cycle = maxsize E = len(self.edge) for i in range(E): # Current Edge information e = self.edge[i] # Get current edge vertices which we currently # remove from graph and then find shortest path # between these two vertex using Dijkstra’s # shortest path algorithm . self.removeEdge(e.u, e.v, e.weight) # Minimum distance between these two vertices distance = self.ShortestPath(e.u, e.v) # To make a cycle we have to add weight of # currently removed edge if this is the # shortest cycle then update min_cycle min_cycle = min(min_cycle, distance + e.weight) # Add current edge back to the graph self.addEdge(e.u, e.v, e.weight) # Return shortest cycle return min_cycle # Driver Codeif __name__ == "__main__": V = 9 g = Graph(V) # Making above shown graph g.addEdge(0, 1, 4) g.addEdge(0, 7, 8) g.addEdge(1, 2, 8) g.addEdge(1, 7, 11) g.addEdge(2, 3, 7) g.addEdge(2, 8, 2) g.addEdge(2, 5, 4) g.addEdge(3, 4, 9) g.addEdge(3, 5, 14) g.addEdge(4, 5, 10) g.addEdge(5, 6, 2) g.addEdge(6, 7, 1) g.addEdge(6, 8, 6) g.addEdge(7, 8, 7) print(g.FindMinimumCycle()) # This code is contributed by sanjeev2552 14 Time Complexity: O( E ( E log V ) ) For every edge, we run Dijkstra’s shortest path algorithm so over all time complexity E2logV. In set 2 | we will discuss optimize the algorithm to find a minimum weight cycle in undirected graph. This article is contributed by Nishant Singh . 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. Saksham Bhardwaj sanjeev2552 hardikkoriintern Dijkstra graph-cycle Shortest Path Graph Graph Shortest Path Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Dijkstra's shortest path algorithm | Greedy Algo-7 Find if there is a path between two vertices in a directed graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Detect Cycle in a Directed Graph Introduction to Data Structures Find if there is a path between two vertices in an undirected graph What is Data Structure: Types, Classifications and Applications Bellman–Ford Algorithm | DP-23 Minimum number of swaps required to sort an array m Coloring Problem | Backtracking-5
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 133, "s": 52, "text": "Given a positive weighted undirected graph, find the minimum weight cycle in it." }, { "code": null, "e": 145, "s": 133, "text": "Examples: " }, { "code": null, "e": 173, "s": 145, "text": "Minimum weighted cycle is :" }, { "code": null, "e": 260, "s": 173, "text": "Minimum weighed cycle : 7 + 1 + 6 = 14 or \n 2 + 6 + 2 + 4 = 14 " }, { "code": null, "e": 472, "s": 260, "text": "The idea is to use shortest path algorithm. We one by one remove every edge from the graph, then we find the shortest path between two corner vertices of it. We add an edge back before we process the next edge. " }, { "code": null, "e": 1085, "s": 472, "text": "1). create an empty vector 'edge' of size 'E'\n ( E total number of edge). Every element of \n this vector is used to store information of \n all the edge in graph info \n\n2) Traverse every edge edge[i] one - by - one \n a). First remove 'edge[i]' from graph 'G'\n b). get current edge vertices which we just \n removed from graph \n c). Find the shortest path between them \n \"Using Dijkstra’s shortest path algorithm \"\n d). To make a cycle we add the weight of the \n removed edge to the shortest path.\n e). update min_weight_cycle if needed \n3). return minimum weighted cycle" }, { "code": null, "e": 1132, "s": 1085, "text": "Below is the implementation of the above idea " }, { "code": null, "e": 1136, "s": 1132, "text": "C++" }, { "code": null, "e": 1144, "s": 1136, "text": "Python3" }, { "code": "// c++ program to find shortest weighted// cycle in undirected graph#include<bits/stdc++.h>using namespace std;# define INF 0x3f3f3f3fstruct Edge{ int u; int v; int weight;}; // weighted undirected Graphclass Graph{ int V ; list < pair <int, int > >*adj; // used to store all edge information vector < Edge > edge; public : Graph( int V ) { this->V = V ; adj = new list < pair <int, int > >[V]; } void addEdge ( int u, int v, int w ); void removeEdge( int u, int v, int w ); int ShortestPath (int u, int v ); void RemoveEdge( int u, int v ); int FindMinimumCycle (); }; //function add edge to graphvoid Graph :: addEdge ( int u, int v, int w ){ adj[u].push_back( make_pair( v, w )); adj[v].push_back( make_pair( u, w )); // add Edge to edge list Edge e { u, v, w }; edge.push_back ( e );} // function remove edge from undirected graphvoid Graph :: removeEdge ( int u, int v, int w ){ adj[u].remove(make_pair( v, w )); adj[v].remove(make_pair(u, w ));} // find the shortest path from source to sink using// Dijkstra’s shortest path algorithm [ Time complexity// O(E logV )]int Graph :: ShortestPath ( int u, int v ){ // Create a set to store vertices that are being // preprocessed set< pair<int, int> > setds; // Create a vector for distances and initialize all // distances as infinite (INF) vector<int> dist(V, INF); // Insert source itself in Set and initialize its // distance as 0. setds.insert(make_pair(0, u)); dist[u] = 0; /* Looping till all shortest distance are finalized then setds will become empty */ while (!setds.empty()) { // The first vertex in Set is the minimum distance // vertex, extract it from set. pair<int, int> tmp = *(setds.begin()); setds.erase(setds.begin()); // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted distance (distance must be first item // in pair) int u = tmp.second; // 'i' is used to get all adjacent vertices of // a vertex list< pair<int, int> >::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // Get vertex label and weight of current adjacent // of u. int v = (*i).first; int weight = (*i).second; // If there is shorter path to v through u. if (dist[v] > dist[u] + weight) { /* If the distance of v is not INF then it must be in our set, so removing it and inserting again with updated less distance. Note : We extract only those vertices from Set for which distance is finalized. So for them, we would never reach here. */ if (dist[v] != INF) setds.erase(setds.find(make_pair(dist[v], v))); // Updating distance of v dist[v] = dist[u] + weight; setds.insert(make_pair(dist[v], v)); } } } // return shortest path from current source to sink return dist[v] ;} // function return minimum weighted cycleint Graph :: FindMinimumCycle ( ){ int min_cycle = INT_MAX; int E = edge.size(); for ( int i = 0 ; i < E ; i++ ) { // current Edge information Edge e = edge[i]; // get current edge vertices which we currently // remove from graph and then find shortest path // between these two vertex using Dijkstra’s // shortest path algorithm . removeEdge( e.u, e.v, e.weight ) ; // minimum distance between these two vertices int distance = ShortestPath( e.u, e.v ); // to make a cycle we have to add weight of // currently removed edge if this is the shortest // cycle then update min_cycle min_cycle = min( min_cycle, distance + e.weight ); // add current edge back to the graph addEdge( e.u, e.v, e.weight ); } // return shortest cycle return min_cycle ;} // driver program to test above functionint main(){ int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); cout << g.FindMinimumCycle() << endl; return 0;}", "e": 5761, "s": 1144, "text": null }, { "code": "# Python3 program to find shortest weighted# cycle in undirected graphfrom sys import maxsize INF = int(0x3f3f3f3f) class Edge: def __init__(self, u: int, v: int, weight: int) -> None: self.u = u self.v = v self.weight = weight # Weighted undirected Graphclass Graph: def __init__(self, V: int) -> None: self.V = V self.adj = [[] for _ in range(V)] # Used to store all edge information self.edge = [] # Function add edge to graph def addEdge(self, u: int, v: int, w: int) -> None: self.adj[u].append((v, w)) self.adj[v].append((u, w)) # Add Edge to edge list e = Edge(u, v, w) self.edge.append(e) # Function remove edge from undirected graph def removeEdge(self, u: int, v: int, w: int) -> None: self.adj[u].remove((v, w)) self.adj[v].remove((u, w)) # Find the shortest path from source # to sink using Dijkstra’s shortest # path algorithm [ Time complexity # O(E logV )] def ShortestPath(self, u: int, v: int) -> int: # Create a set to store vertices that # are being preprocessed setds = set() # Create a vector for distances and # initialize all distances as infinite (INF) dist = [INF] * self.V # Insert source itself in Set and # initialize its distance as 0. setds.add((0, u)) dist[u] = 0 # Looping till all shortest distance are # finalized then setds will become empty while (setds): # The first vertex in Set is the minimum # distance vertex, extract it from set. tmp = setds.pop() # Vertex label is stored in second of # pair (it has to be done this way to # keep the vertices sorted distance # (distance must be first item in pair) uu = tmp[1] # 'i' is used to get all adjacent # vertices of a vertex for i in self.adj[uu]: # Get vertex label and weight of # current adjacent of u. vv = i[0] weight = i[1] # If there is shorter path to v through u. if (dist[vv] > dist[uu] + weight): # If the distance of v is not INF then # it must be in our set, so removing it # and inserting again with updated less # distance. Note : We extract only those # vertices from Set for which distance # is finalized. So for them, we would # never reach here. if (dist[vv] != INF): if ((dist[vv], vv) in setds): setds.remove((dist[vv], vv)) # Updating distance of v dist[vv] = dist[uu] + weight setds.add((dist[vv], vv)) # Return shortest path from # current source to sink return dist[v] # Function return minimum weighted cycle def FindMinimumCycle(self) -> int: min_cycle = maxsize E = len(self.edge) for i in range(E): # Current Edge information e = self.edge[i] # Get current edge vertices which we currently # remove from graph and then find shortest path # between these two vertex using Dijkstra’s # shortest path algorithm . self.removeEdge(e.u, e.v, e.weight) # Minimum distance between these two vertices distance = self.ShortestPath(e.u, e.v) # To make a cycle we have to add weight of # currently removed edge if this is the # shortest cycle then update min_cycle min_cycle = min(min_cycle, distance + e.weight) # Add current edge back to the graph self.addEdge(e.u, e.v, e.weight) # Return shortest cycle return min_cycle # Driver Codeif __name__ == \"__main__\": V = 9 g = Graph(V) # Making above shown graph g.addEdge(0, 1, 4) g.addEdge(0, 7, 8) g.addEdge(1, 2, 8) g.addEdge(1, 7, 11) g.addEdge(2, 3, 7) g.addEdge(2, 8, 2) g.addEdge(2, 5, 4) g.addEdge(3, 4, 9) g.addEdge(3, 5, 14) g.addEdge(4, 5, 10) g.addEdge(5, 6, 2) g.addEdge(6, 7, 1) g.addEdge(6, 8, 6) g.addEdge(7, 8, 7) print(g.FindMinimumCycle()) # This code is contributed by sanjeev2552", "e": 10493, "s": 5761, "text": null }, { "code": null, "e": 10497, "s": 10493, "text": "14\n" }, { "code": null, "e": 10534, "s": 10497, "text": "Time Complexity: O( E ( E log V ) ) " }, { "code": null, "e": 10731, "s": 10534, "text": "For every edge, we run Dijkstra’s shortest path algorithm so over all time complexity E2logV. In set 2 | we will discuss optimize the algorithm to find a minimum weight cycle in undirected graph. " }, { "code": null, "e": 11030, "s": 10731, "text": "This article is contributed by Nishant Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 11047, "s": 11030, "text": "Saksham Bhardwaj" }, { "code": null, "e": 11059, "s": 11047, "text": "sanjeev2552" }, { "code": null, "e": 11076, "s": 11059, "text": "hardikkoriintern" }, { "code": null, "e": 11085, "s": 11076, "text": "Dijkstra" }, { "code": null, "e": 11097, "s": 11085, "text": "graph-cycle" }, { "code": null, "e": 11111, "s": 11097, "text": "Shortest Path" }, { "code": null, "e": 11117, "s": 11111, "text": "Graph" }, { "code": null, "e": 11123, "s": 11117, "text": "Graph" }, { "code": null, "e": 11137, "s": 11123, "text": "Shortest Path" }, { "code": null, "e": 11235, "s": 11137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11286, "s": 11235, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 11351, "s": 11286, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 11409, "s": 11351, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 11442, "s": 11409, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 11474, "s": 11442, "text": "Introduction to Data Structures" }, { "code": null, "e": 11542, "s": 11474, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 11606, "s": 11542, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 11637, "s": 11606, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 11687, "s": 11637, "text": "Minimum number of swaps required to sort an array" } ]
Count Number of List Elements in R
05 Apr, 2021 In this article, we are going to count the elements in a list and elements in a nested list in R Programming Language. So we are going to use length() and lengths() to find the elements count in a list. Steps – Create a list with vectors/list/range operator Find the count of elements using the length and lengths function. Syntax: list(value1,value2,...,value) values can be range operator or vector. Let’s create a list using the range, vector, and list. R # range from 10 to 50values = 10:50 # vector elements of character typenames = c("sravan", "bobby", "ojaswi", "gnanu") # data1 with list of elementsdata1 = list(1, 2, 3, 4, 5) # give input to the data which is a listdata = list(values, names, data1) # displayprint(data) Output: Example 1: Using length() function. Length function is used to count the elements in the list Syntax: length(listname) return value: integer Below is the implementation: R # range from 10 to 50values = 10:50 # vector elements of character typenames = c("sravan", "bobby", "ojaswi", "gnanu") # data1 with list of elementsdata1 = list(1, 2, 3, 4, 5) # give input to the data which is a listdata = list(values, names, data1) # displayprint(data) # count elements using length functionprint(length(data)) Output: Example 2: For finding the length of each data in a list (nested list) we will use lengths() function Syntax: lengths(list_name) Below is the implementation: R # range from 10 to 50values = 10:50 # vector elements of character typenames = c("sravan", "bobby", "ojaswi", "gnanu") # data1 with list of elementsdata1 = list(1, 2, 3, 4, 5) # give input to the data which is a listdata = list(a1 = values, a2 = names, a3 = data1) # displayprint(data) # count elements in each nested using lengths functionprint(lengths(data)) Output: Example 3: R program count elements in a nested list R # data1 with list of elementsdata1 = list(1, 2, 3, 4, 5) # data2 with list of elementsdata2 = list("a", 'b', 'c') # give input to the data which is a listdata = list(a1 = data1, a2 = data2) # displayprint(data) # count elements in each nested using length functionprint(length(data))print("-----") # count elements in each nested using lengths functionprint(lengths(data)) Output: Picked R List-Programs R-List R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Apr, 2021" }, { "code": null, "e": 231, "s": 28, "text": "In this article, we are going to count the elements in a list and elements in a nested list in R Programming Language. So we are going to use length() and lengths() to find the elements count in a list." }, { "code": null, "e": 239, "s": 231, "text": "Steps –" }, { "code": null, "e": 286, "s": 239, "text": "Create a list with vectors/list/range operator" }, { "code": null, "e": 352, "s": 286, "text": "Find the count of elements using the length and lengths function." }, { "code": null, "e": 390, "s": 352, "text": "Syntax: list(value1,value2,...,value)" }, { "code": null, "e": 430, "s": 390, "text": "values can be range operator or vector." }, { "code": null, "e": 485, "s": 430, "text": "Let’s create a list using the range, vector, and list." }, { "code": null, "e": 487, "s": 485, "text": "R" }, { "code": "# range from 10 to 50values = 10:50 # vector elements of character typenames = c(\"sravan\", \"bobby\", \"ojaswi\", \"gnanu\") # data1 with list of elementsdata1 = list(1, 2, 3, 4, 5) # give input to the data which is a listdata = list(values, names, data1) # displayprint(data)", "e": 762, "s": 487, "text": null }, { "code": null, "e": 770, "s": 762, "text": "Output:" }, { "code": null, "e": 806, "s": 770, "text": "Example 1: Using length() function." }, { "code": null, "e": 864, "s": 806, "text": "Length function is used to count the elements in the list" }, { "code": null, "e": 889, "s": 864, "text": "Syntax: length(listname)" }, { "code": null, "e": 911, "s": 889, "text": "return value: integer" }, { "code": null, "e": 940, "s": 911, "text": "Below is the implementation:" }, { "code": null, "e": 942, "s": 940, "text": "R" }, { "code": "# range from 10 to 50values = 10:50 # vector elements of character typenames = c(\"sravan\", \"bobby\", \"ojaswi\", \"gnanu\") # data1 with list of elementsdata1 = list(1, 2, 3, 4, 5) # give input to the data which is a listdata = list(values, names, data1) # displayprint(data) # count elements using length functionprint(length(data))", "e": 1276, "s": 942, "text": null }, { "code": null, "e": 1284, "s": 1276, "text": "Output:" }, { "code": null, "e": 1386, "s": 1284, "text": "Example 2: For finding the length of each data in a list (nested list) we will use lengths() function" }, { "code": null, "e": 1413, "s": 1386, "text": "Syntax: lengths(list_name)" }, { "code": null, "e": 1442, "s": 1413, "text": "Below is the implementation:" }, { "code": null, "e": 1444, "s": 1442, "text": "R" }, { "code": "# range from 10 to 50values = 10:50 # vector elements of character typenames = c(\"sravan\", \"bobby\", \"ojaswi\", \"gnanu\") # data1 with list of elementsdata1 = list(1, 2, 3, 4, 5) # give input to the data which is a listdata = list(a1 = values, a2 = names, a3 = data1) # displayprint(data) # count elements in each nested using lengths functionprint(lengths(data))", "e": 1811, "s": 1444, "text": null }, { "code": null, "e": 1819, "s": 1811, "text": "Output:" }, { "code": null, "e": 1872, "s": 1819, "text": "Example 3: R program count elements in a nested list" }, { "code": null, "e": 1874, "s": 1872, "text": "R" }, { "code": "# data1 with list of elementsdata1 = list(1, 2, 3, 4, 5) # data2 with list of elementsdata2 = list(\"a\", 'b', 'c') # give input to the data which is a listdata = list(a1 = data1, a2 = data2) # displayprint(data) # count elements in each nested using length functionprint(length(data))print(\"-----\") # count elements in each nested using lengths functionprint(lengths(data))", "e": 2254, "s": 1874, "text": null }, { "code": null, "e": 2262, "s": 2254, "text": "Output:" }, { "code": null, "e": 2269, "s": 2262, "text": "Picked" }, { "code": null, "e": 2285, "s": 2269, "text": "R List-Programs" }, { "code": null, "e": 2292, "s": 2285, "text": "R-List" }, { "code": null, "e": 2303, "s": 2292, "text": "R Language" }, { "code": null, "e": 2314, "s": 2303, "text": "R Programs" }, { "code": null, "e": 2412, "s": 2314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2464, "s": 2412, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2522, "s": 2464, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2557, "s": 2522, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2595, "s": 2557, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2644, "s": 2595, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2702, "s": 2644, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2751, "s": 2702, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2794, "s": 2751, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2832, "s": 2794, "text": "Merge DataFrames by Column Names in R" } ]
Python – Remove dictionary from a list of dictionaries if a particular value is not present
When it is required to remove dictionary from a list of dictionaries if a particular value is not present, a simple iteration and the ‘del’ operator is used. Below is a demonstration of the same − my_list = [{"id" : 1, "data" : "Python"}, {"id" : 2, "data" : "Code"}, {"id" : 3, "data" : "Learn"}] print("The list is :") print(my_list) for index in range(len(my_list)): if my_list[index]['id'] == 2: del my_list[index] break print("The result is :") print(my_list) The list is : [{'id': 1, 'data': 'Python'}, {'id': 2, 'data': 'Code'}, {'id': 3, 'data': 'Learn'}] The result is : [{'id': 1, 'data': 'Python'}, {'id': 3, 'data': 'Learn'}] A list of dictionary elements is defined and is displayed on the console. A list of dictionary elements is defined and is displayed on the console. The list of dictionary is iterated over, and the ‘value’ associated with every key is checked to equivalent to 2. The list of dictionary is iterated over, and the ‘value’ associated with every key is checked to equivalent to 2. If yes, that specific element is deleted. If yes, that specific element is deleted. The control breaks out of the loop. The control breaks out of the loop. In the end, this list of dictionary is displayed as output on the console. In the end, this list of dictionary is displayed as output on the console.
[ { "code": null, "e": 1220, "s": 1062, "text": "When it is required to remove dictionary from a list of dictionaries if a particular value is not present, a simple iteration and the ‘del’ operator is used." }, { "code": null, "e": 1259, "s": 1220, "text": "Below is a demonstration of the same −" }, { "code": null, "e": 1551, "s": 1259, "text": "my_list = [{\"id\" : 1, \"data\" : \"Python\"},\n {\"id\" : 2, \"data\" : \"Code\"},\n {\"id\" : 3, \"data\" : \"Learn\"}]\n\nprint(\"The list is :\")\nprint(my_list)\n\nfor index in range(len(my_list)):\n if my_list[index]['id'] == 2:\n del my_list[index]\n break\n\nprint(\"The result is :\")\nprint(my_list)" }, { "code": null, "e": 1724, "s": 1551, "text": "The list is :\n[{'id': 1, 'data': 'Python'}, {'id': 2, 'data': 'Code'}, {'id': 3, 'data': 'Learn'}]\nThe result is :\n[{'id': 1, 'data': 'Python'}, {'id': 3, 'data': 'Learn'}]" }, { "code": null, "e": 1798, "s": 1724, "text": "A list of dictionary elements is defined and is displayed on the console." }, { "code": null, "e": 1872, "s": 1798, "text": "A list of dictionary elements is defined and is displayed on the console." }, { "code": null, "e": 1986, "s": 1872, "text": "The list of dictionary is iterated over, and the ‘value’ associated with every key is checked to equivalent to 2." }, { "code": null, "e": 2100, "s": 1986, "text": "The list of dictionary is iterated over, and the ‘value’ associated with every key is checked to equivalent to 2." }, { "code": null, "e": 2142, "s": 2100, "text": "If yes, that specific element is deleted." }, { "code": null, "e": 2184, "s": 2142, "text": "If yes, that specific element is deleted." }, { "code": null, "e": 2220, "s": 2184, "text": "The control breaks out of the loop." }, { "code": null, "e": 2256, "s": 2220, "text": "The control breaks out of the loop." }, { "code": null, "e": 2331, "s": 2256, "text": "In the end, this list of dictionary is displayed as output on the console." }, { "code": null, "e": 2406, "s": 2331, "text": "In the end, this list of dictionary is displayed as output on the console." } ]
How to Solve java.lang.IllegalStateException in Java main Thread? - GeeksforGeeks
03 Mar, 2022 An unexpected, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally. There are mainly two types of exception in java as follows: 1. Checked Exception: The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exception then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get compile-time error. Examples of checked exceptions are ClassNotFoundException, IOException, SQLException, etc. 2. Unchecked Exception: The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException etc. Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time. IllegalStateException is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise explicitly by programmer or by the API developer to indicate that a method has been invoked at the wrong time. Generally, this method is used to indicate a method is called at an illegal or inappropriate time. Example: After starting a thread we are not allowed to restart the same thread once again otherwise we will get Runtime Exception saying IllegalStateException. Example 1: We call start() method when it’s already executing the run() method. Java // Java program to show the occurrence of// IllegalStateException. // Import required packages import java.io.*;import java.util.*; // Creating a thread in our myThread class by extending the// Thread class// class 1// Helper class class myThread extends Thread { // Method in helper class // declaring run method public void run() { for (int i = 0; i < 5; i++) { // Display message System.out.println("GeeksForGeeks"); } }} // class 2// Main classclass Thread1 { // Main driver method public static void main(String[] args) { // creating a thread object in the main() method // of our helper class above myThread t = new myThread(); // Starting the above created thread // using the start() method t.start(); // Display Message System.out.println("Main Thread"); // starting the thread again when it is already // running and hence it cause an exception t.start(); }} Example 2: We call start() method on a thread when it has finished executing run() method. Java // Java program to show the occurrence of// IllegalStateException. // Import required packagesimport java.io.*;import java.util.*; // Creating a thread in our myThread class by extending the// Thread class// class 1// Helper classclass myThread extends Thread { // Method in helper class // declaring run method public void run() { for (int i = 0; i < 5; i++) { // Display message System.out.println("GeeksForGeeks"); } }} // class 2// Main classclass Thread1 { // Main driver method public static void main(String[] args) { // creating a thread object in the main() method // of our helper class above myThread t = new myThread(); // Starting the above created thread // using the start() method t.start(); try { System.out.println("Main Thread is going to sleep"); // making main thread sleep for 2000ms t.sleep(2000); System.out.println("Main Thread awaken"); } catch (Exception e) { System.out.println(e); } // Display Message System.out.println("Main Thread"); // calling start( ) method on a dead thread // which causes exception t.start(); }} How to solve this error? In order to avoid java.lang.IllegalStateException in Java main Thread we must ensure that any method in our code cannot be called at an illegal or an inappropriate time. In the above example if we call start() method only once on thread t then we will not get any java.lang.IllegalStateException because we are not calling the start() method after the starting of thread (i.e we are not calling the start() method at an illegal or an inappropriate time.) Java // Java program to demonstrate that the error// does not occur in this program // Import required packagesimport java.io.*;import java.util.*; // Creating a thread in our myThread class by extending the// Thread class// class 1// Helper classclass myThread extends Thread { // Method in helper class // declaring run method public void run() { for (int i = 0; i < 5; i++) { // Display message System.out.println("GeeksForGeeks"); } }} // class 2// Main classclass Thread1 { // Main driver method public static void main(String[] args) { // creating a thread object in the main() method // of our helper class above myThread t = new myThread(); // Starting the above created thread // using the start() method t.start(); try { System.out.println("Main Thread is going to sleep"); // making main thread sleep for 2000ms t.sleep(2000); System.out.println("Main Thread awaken"); } catch (Exception e) { System.out.println(e); } // Display Message System.out.println("Main Thread"); }} saurabh1990aror arorakashish0911 avtarkumar719 Java-Exceptions Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24418, "s": 24390, "text": "\n03 Mar, 2022" }, { "code": null, "e": 24513, "s": 24418, "text": "An unexpected, unwanted event that disturbed the normal flow of a program is called Exception." }, { "code": null, "e": 24927, "s": 24513, "text": "Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally." }, { "code": null, "e": 24988, "s": 24927, "text": "There are mainly two types of exception in java as follows:" }, { "code": null, "e": 25010, "s": 24988, "text": "1. Checked Exception:" }, { "code": null, "e": 25342, "s": 25010, "text": "The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exception then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get compile-time error." }, { "code": null, "e": 25433, "s": 25342, "text": "Examples of checked exceptions are ClassNotFoundException, IOException, SQLException, etc." }, { "code": null, "e": 25457, "s": 25433, "text": "2. Unchecked Exception:" }, { "code": null, "e": 25604, "s": 25457, "text": "The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception." }, { "code": null, "e": 25687, "s": 25604, "text": "Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException etc." }, { "code": null, "e": 25839, "s": 25687, "text": "Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time." }, { "code": null, "e": 26173, "s": 25839, "text": "IllegalStateException is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise explicitly by programmer or by the API developer to indicate that a method has been invoked at the wrong time. Generally, this method is used to indicate a method is called at an illegal or inappropriate time." }, { "code": null, "e": 26333, "s": 26173, "text": "Example: After starting a thread we are not allowed to restart the same thread once again otherwise we will get Runtime Exception saying IllegalStateException." }, { "code": null, "e": 26413, "s": 26333, "text": "Example 1: We call start() method when it’s already executing the run() method." }, { "code": null, "e": 26418, "s": 26413, "text": "Java" }, { "code": "// Java program to show the occurrence of// IllegalStateException. // Import required packages import java.io.*;import java.util.*; // Creating a thread in our myThread class by extending the// Thread class// class 1// Helper class class myThread extends Thread { // Method in helper class // declaring run method public void run() { for (int i = 0; i < 5; i++) { // Display message System.out.println(\"GeeksForGeeks\"); } }} // class 2// Main classclass Thread1 { // Main driver method public static void main(String[] args) { // creating a thread object in the main() method // of our helper class above myThread t = new myThread(); // Starting the above created thread // using the start() method t.start(); // Display Message System.out.println(\"Main Thread\"); // starting the thread again when it is already // running and hence it cause an exception t.start(); }}", "e": 27467, "s": 26418, "text": null }, { "code": null, "e": 27559, "s": 27467, "text": "Example 2: We call start() method on a thread when it has finished executing run() method. " }, { "code": null, "e": 27564, "s": 27559, "text": "Java" }, { "code": "// Java program to show the occurrence of// IllegalStateException. // Import required packagesimport java.io.*;import java.util.*; // Creating a thread in our myThread class by extending the// Thread class// class 1// Helper classclass myThread extends Thread { // Method in helper class // declaring run method public void run() { for (int i = 0; i < 5; i++) { // Display message System.out.println(\"GeeksForGeeks\"); } }} // class 2// Main classclass Thread1 { // Main driver method public static void main(String[] args) { // creating a thread object in the main() method // of our helper class above myThread t = new myThread(); // Starting the above created thread // using the start() method t.start(); try { System.out.println(\"Main Thread is going to sleep\"); // making main thread sleep for 2000ms t.sleep(2000); System.out.println(\"Main Thread awaken\"); } catch (Exception e) { System.out.println(e); } // Display Message System.out.println(\"Main Thread\"); // calling start( ) method on a dead thread // which causes exception t.start(); }}", "e": 28889, "s": 27564, "text": null }, { "code": null, "e": 28915, "s": 28889, "text": " How to solve this error?" }, { "code": null, "e": 29085, "s": 28915, "text": "In order to avoid java.lang.IllegalStateException in Java main Thread we must ensure that any method in our code cannot be called at an illegal or an inappropriate time." }, { "code": null, "e": 29371, "s": 29085, "text": "In the above example if we call start() method only once on thread t then we will not get any java.lang.IllegalStateException because we are not calling the start() method after the starting of thread (i.e we are not calling the start() method at an illegal or an inappropriate time.) " }, { "code": null, "e": 29376, "s": 29371, "text": "Java" }, { "code": "// Java program to demonstrate that the error// does not occur in this program // Import required packagesimport java.io.*;import java.util.*; // Creating a thread in our myThread class by extending the// Thread class// class 1// Helper classclass myThread extends Thread { // Method in helper class // declaring run method public void run() { for (int i = 0; i < 5; i++) { // Display message System.out.println(\"GeeksForGeeks\"); } }} // class 2// Main classclass Thread1 { // Main driver method public static void main(String[] args) { // creating a thread object in the main() method // of our helper class above myThread t = new myThread(); // Starting the above created thread // using the start() method t.start(); try { System.out.println(\"Main Thread is going to sleep\"); // making main thread sleep for 2000ms t.sleep(2000); System.out.println(\"Main Thread awaken\"); } catch (Exception e) { System.out.println(e); } // Display Message System.out.println(\"Main Thread\"); }}", "e": 30615, "s": 29376, "text": null }, { "code": null, "e": 30633, "s": 30617, "text": "saurabh1990aror" }, { "code": null, "e": 30650, "s": 30633, "text": "arorakashish0911" }, { "code": null, "e": 30664, "s": 30650, "text": "avtarkumar719" }, { "code": null, "e": 30680, "s": 30664, "text": "Java-Exceptions" }, { "code": null, "e": 30687, "s": 30680, "text": "Picked" }, { "code": null, "e": 30711, "s": 30687, "text": "Technical Scripter 2020" }, { "code": null, "e": 30716, "s": 30711, "text": "Java" }, { "code": null, "e": 30730, "s": 30716, "text": "Java Programs" }, { "code": null, "e": 30749, "s": 30730, "text": "Technical Scripter" }, { "code": null, "e": 30754, "s": 30749, "text": "Java" }, { "code": null, "e": 30852, "s": 30754, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30884, "s": 30852, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 30935, "s": 30884, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30965, "s": 30935, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30984, "s": 30965, "text": "Interfaces in Java" }, { "code": null, "e": 31002, "s": 30984, "text": "ArrayList in Java" }, { "code": null, "e": 31046, "s": 31002, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 31074, "s": 31046, "text": "Initializing a List in Java" }, { "code": null, "e": 31100, "s": 31074, "text": "Java Programming Examples" }, { "code": null, "e": 31134, "s": 31100, "text": "Convert Double to Integer in Java" } ]
wxPython - Environment
Prebuilt binaries for Windows OS (both 32 bit and 64 bit) are available on http://www.wxpython.org/download.php page. Latest versions of installers available are − wxPython3.0-win32-3.0.2.0-py27.exe for 32-bit Python 2.7 wxPython3.0-win64-3.0.2.0-py27.exe for 64-bit Python 2.7 wxPython demo, samples and wxWidgets documentation is also available for download on the same page. wxPython3.0-win32-docs-demos.exe wxPython binaries for many Linux distros can be found in their respective repositories. Corresponding package managers will have to be used to download and install. For instance on Debian Linux, following command should be able to install wxPython. sudo apt-get install python-wxgtk3.0 Prebuilt binaries for MacOS in the form of disk images are available on the download page of the official website. Print Add Notes Bookmark this page
[ { "code": null, "e": 2160, "s": 1882, "text": "Prebuilt binaries for Windows OS (both 32 bit and 64 bit) are available on http://www.wxpython.org/download.php page. Latest versions of installers available are − wxPython3.0-win32-3.0.2.0-py27.exe for 32-bit Python 2.7 wxPython3.0-win64-3.0.2.0-py27.exe for 64-bit Python 2.7" }, { "code": null, "e": 2260, "s": 2160, "text": "wxPython demo, samples and wxWidgets documentation is also available for download on the same page." }, { "code": null, "e": 2293, "s": 2260, "text": "wxPython3.0-win32-docs-demos.exe" }, { "code": null, "e": 2542, "s": 2293, "text": "wxPython binaries for many Linux distros can be found in their respective repositories. Corresponding package managers will have to be used to download and install. For instance on Debian Linux, following command should be able to install wxPython." }, { "code": null, "e": 2580, "s": 2542, "text": "sudo apt-get install python-wxgtk3.0\n" }, { "code": null, "e": 2695, "s": 2580, "text": "Prebuilt binaries for MacOS in the form of disk images are available on the download page of the official website." }, { "code": null, "e": 2702, "s": 2695, "text": " Print" }, { "code": null, "e": 2713, "s": 2702, "text": " Add Notes" } ]
Java - The TreeSet Class
TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in a sorted and ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. Following is the list of the constructors supported by the TreeSet class. TreeSet( ) This constructor constructs an empty tree set that will be sorted in an ascending order according to the natural order of its elements. TreeSet(Collection c) This constructor builds a tree set that contains the elements of the collection c. TreeSet(Comparator comp) This constructor constructs an empty tree set that will be sorted according to the given comparator. TreeSet(SortedSet ss) This constructor builds a TreeSet that contains the elements of the given SortedSet. Apart from the methods inherited from its parent classes, TreeSet defines the following methods − void add(Object o) Adds the specified element to this set if it is not already present. boolean addAll(Collection c) Adds all of the elements in the specified collection to this set. void clear() Removes all of the elements from this set. Object clone() Returns a shallow copy of this TreeSet instance. Comparator comparator() Returns the comparator used to order this sorted set, or null if this tree set uses its elements natural ordering. boolean contains(Object o) Returns true if this set contains the specified element. Object first() Returns the first (lowest) element currently in this sorted set. SortedSet headSet(Object toElement) Returns a view of the portion of this set whose elements are strictly less than toElement. boolean isEmpty() Returns true if this set contains no elements. Iterator iterator() Returns an iterator over the elements in this set. Object last() Returns the last (highest) element currently in this sorted set. boolean remove(Object o) Removes the specified element from this set if it is present. int size() Returns the number of elements in this set (its cardinality). SortedSet subSet(Object fromElement, Object toElement) Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. SortedSet tailSet(Object fromElement) Returns a view of the portion of this set whose elements are greater than or equal to fromElement. The following program illustrates several of the methods supported by this collection − import java.util.*; public class TreeSetDemo { public static void main(String args[]) { // Create a tree set TreeSet ts = new TreeSet(); // Add elements to the tree set ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); System.out.println(ts); } } This will produce the following result − [A, B, C, D, E, F] 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": 2515, "s": 2377, "text": "TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in a sorted and ascending order." }, { "code": null, "e": 2675, "s": 2515, "text": "Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly." }, { "code": null, "e": 2749, "s": 2675, "text": "Following is the list of the constructors supported by the TreeSet class." }, { "code": null, "e": 2760, "s": 2749, "text": "TreeSet( )" }, { "code": null, "e": 2896, "s": 2760, "text": "This constructor constructs an empty tree set that will be sorted in an ascending order according to the natural order of its elements." }, { "code": null, "e": 2918, "s": 2896, "text": "TreeSet(Collection c)" }, { "code": null, "e": 3001, "s": 2918, "text": "This constructor builds a tree set that contains the elements of the collection c." }, { "code": null, "e": 3027, "s": 3001, "text": "TreeSet(Comparator comp) " }, { "code": null, "e": 3128, "s": 3027, "text": "This constructor constructs an empty tree set that will be sorted according to the given comparator." }, { "code": null, "e": 3150, "s": 3128, "text": "TreeSet(SortedSet ss)" }, { "code": null, "e": 3235, "s": 3150, "text": "This constructor builds a TreeSet that contains the elements of the given SortedSet." }, { "code": null, "e": 3333, "s": 3235, "text": "Apart from the methods inherited from its parent classes, TreeSet defines the following methods −" }, { "code": null, "e": 3352, "s": 3333, "text": "void add(Object o)" }, { "code": null, "e": 3421, "s": 3352, "text": "Adds the specified element to this set if it is not already present." }, { "code": null, "e": 3450, "s": 3421, "text": "boolean addAll(Collection c)" }, { "code": null, "e": 3516, "s": 3450, "text": "Adds all of the elements in the specified collection to this set." }, { "code": null, "e": 3529, "s": 3516, "text": "void clear()" }, { "code": null, "e": 3572, "s": 3529, "text": "Removes all of the elements from this set." }, { "code": null, "e": 3587, "s": 3572, "text": "Object clone()" }, { "code": null, "e": 3636, "s": 3587, "text": "Returns a shallow copy of this TreeSet instance." }, { "code": null, "e": 3660, "s": 3636, "text": "Comparator comparator()" }, { "code": null, "e": 3775, "s": 3660, "text": "Returns the comparator used to order this sorted set, or null if this tree set uses its elements natural ordering." }, { "code": null, "e": 3802, "s": 3775, "text": "boolean contains(Object o)" }, { "code": null, "e": 3859, "s": 3802, "text": "Returns true if this set contains the specified element." }, { "code": null, "e": 3874, "s": 3859, "text": "Object first()" }, { "code": null, "e": 3939, "s": 3874, "text": "Returns the first (lowest) element currently in this sorted set." }, { "code": null, "e": 3975, "s": 3939, "text": "SortedSet headSet(Object toElement)" }, { "code": null, "e": 4066, "s": 3975, "text": "Returns a view of the portion of this set whose elements are strictly less than toElement." }, { "code": null, "e": 4084, "s": 4066, "text": "boolean isEmpty()" }, { "code": null, "e": 4131, "s": 4084, "text": "Returns true if this set contains no elements." }, { "code": null, "e": 4151, "s": 4131, "text": "Iterator iterator()" }, { "code": null, "e": 4202, "s": 4151, "text": "Returns an iterator over the elements in this set." }, { "code": null, "e": 4216, "s": 4202, "text": "Object last()" }, { "code": null, "e": 4281, "s": 4216, "text": "Returns the last (highest) element currently in this sorted set." }, { "code": null, "e": 4306, "s": 4281, "text": "boolean remove(Object o)" }, { "code": null, "e": 4368, "s": 4306, "text": "Removes the specified element from this set if it is present." }, { "code": null, "e": 4379, "s": 4368, "text": "int size()" }, { "code": null, "e": 4441, "s": 4379, "text": "Returns the number of elements in this set (its cardinality)." }, { "code": null, "e": 4496, "s": 4441, "text": "SortedSet subSet(Object fromElement, Object toElement)" }, { "code": null, "e": 4613, "s": 4496, "text": "Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive." }, { "code": null, "e": 4651, "s": 4613, "text": "SortedSet tailSet(Object fromElement)" }, { "code": null, "e": 4750, "s": 4651, "text": "Returns a view of the portion of this set whose elements are greater than or equal to fromElement." }, { "code": null, "e": 4838, "s": 4750, "text": "The following program illustrates several of the methods supported by this collection −" }, { "code": null, "e": 5186, "s": 4838, "text": "import java.util.*;\npublic class TreeSetDemo {\n\n public static void main(String args[]) {\n // Create a tree set\n TreeSet ts = new TreeSet();\n \n // Add elements to the tree set\n ts.add(\"C\");\n ts.add(\"A\");\n ts.add(\"B\");\n ts.add(\"E\");\n ts.add(\"F\");\n ts.add(\"D\");\n System.out.println(ts);\n }\n}" }, { "code": null, "e": 5227, "s": 5186, "text": "This will produce the following result −" }, { "code": null, "e": 5247, "s": 5227, "text": "[A, B, C, D, E, F]\n" }, { "code": null, "e": 5280, "s": 5247, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5296, "s": 5280, "text": " Malhar Lathkar" }, { "code": null, "e": 5329, "s": 5296, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5345, "s": 5329, "text": " Malhar Lathkar" }, { "code": null, "e": 5380, "s": 5345, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5394, "s": 5380, "text": " Anadi Sharma" }, { "code": null, "e": 5428, "s": 5394, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5442, "s": 5428, "text": " Tushar Kale" }, { "code": null, "e": 5479, "s": 5442, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5494, "s": 5479, "text": " Monica Mittal" }, { "code": null, "e": 5527, "s": 5494, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5546, "s": 5527, "text": " Arnab Chakraborty" }, { "code": null, "e": 5553, "s": 5546, "text": " Print" }, { "code": null, "e": 5564, "s": 5553, "text": " Add Notes" } ]
A Simple Song Recommender System in Python (Tutorial) | by Jack Bandy | Towards Data Science
This material is based on content from a workshop I taught in April 2020. Most of us now use AI-based recommender systems every day: looking for a show on Netflix, scrolling through social media feeds, watching “up next” videos on YouTube, and listening to “Discover Weekly” playlists on Spotify. So how do these recommenders work? They have become really good, and in some cases, creepily good. Many of us have received recommendations and advertisements that make us ask: “were they recording me?” Generally speaking, companies do not make recommendations by hacking your microphone and recording your conversations. Instead, they make a model of you, or as Tristan Harris called it, “a little voodoo doll, avatar-like version of you,” and then make predictions about that doll. I’ll refer to this doll as a mathematical model of your tastes. The methods in this tutorial are nowhere near as sophisticated as what Google, Facebook, and Spotify are using, and they will not produce any creepily good recommendations. Still, most recommendations principally work the same, and are bound up in three steps: Companies make a mathematical model of you and everyone elseThey use those models to find people who are similar to youThey find what those similar people liked, and recommend it to you Companies make a mathematical model of you and everyone else They use those models to find people who are similar to you They find what those similar people liked, and recommend it to you I’ll go over these three steps twice, first in a simple visual example, and then in a larger code-based example. Let’s start by considering three people (Jack, Nick, and Trevor) and how they rated three songs (One Dance, Lean On, and Sunflower) on a scale of 1 to 5. Here they are in a simple table: We now have a simple mathematical model of musical taste. In the real world, Spotify uses other signals, such as how many times you listen to a song, to determine this rating. Regardless, the principle is to translate your tastes into a list of numbers, which is also called a vector, a matrix, or an array. Whatever you call them, it’s helpful to visualize these numbers on a graph. Below, we put the rating for “One Dance” on the x-axis, and the rating for “Lean On” on the y-axis: We now have a list of numbers that capture your musical tastes, so we can go to the next step: finding people with similar tastes. Let’s go back to the graph: In the visual representation, similar people are just nearby people. So figuring out who is “most similar” to Jack is just a matter of figuring out who is closest to Jack. And we can measure this distance using the old Pythagorean theorem from middle school geometry: Cool! We’re almost there. We can already see that Jack is most similar to Nick and not Trevor, but let’s make it official: The maths confirm: in this tiny universe of song tastes, Jack is 3.2 units away from Trevor, but only 1.4 units away from Nick. Now that we know Jack and Nick have similar taste, we can predict whether Jack will like “Sunflower” based on whether Nick liked sunflower. It’s just a matter of looking it up in the table: Nick gave “Sunflower” a 5/5 rating, so we can predict that Jack will probably like the song, too. Obviously, the scale of this tiny universe is a lot smaller than Spotify’s universe. We looked at three songs and three people, while Spotify purportedly has over 50 million tracks and over 271 million active users. So now, we’ll scale up. To make a bigger dataset, we will load in a larger table. Here is one with 25 songs and 8 people: In Python, you can use Pandas to load this data with the following command: from pandas import read_csvdata_url = 'https://gist.githubusercontent.com/jackbandy/5cd988ab5c3d95b79219364dce7ee5ae/raw/731ecdbecc7b33030f23cd919e6067dfbaf42feb/song-ratings.csv'ratings = read_csv(data_url,index_col=0) Now, let’s try to predict whether I (still Jack) will like the song “7 Rings.” As in the visual example, we will find the person closest to me. Using the Pythagorean theorem, the distance function in two dimensions was just distance=sqrt(a^2 + b^2) , which we could write like this: def distance(person1,person2): a_squared = (person1[0] - person2[0])**2 b_squared = (person1[1] - person2[1])**2 c = sqrt(a_squared+b_squared) return c But this time, there are 25 dimensions, not just two. How do we find the closest person when we have 25 dimensions instead of just an x-axis and a y-axis? It turns out the trusty Pythagorean theorem generalizes pretty well. (Most recommenders use other distance metrics like cosine distance, but we’ll ignore that for this tutorial). If there are three dimensions, we can call them a , b , and c , and then just add it under the square root:distance=sqrt(a^2 + b^2 + c^2) . And we can actually do this with any number of dimensions: distance=sqrt(a^2 + b^2 + c^2 + d^2 + ... + n^2) . The scipy library has written a function to do exactly what we need: calculate Euclidean distance in any number of dimensions. Let’s use it: from scipy.spatial.distance import euclideandef distance(person1,person2): distance = euclidean(person1,person2) return distance Now, we can use that distance function to look at the similarity between any two people. The only catch is that we need to fill in blanks with “0,” using fillna . The following block does that, and then retrieves the rows of data for the three people: ratings=ratings.fillna(0)jack=ratings.loc['Jack']nick=ratings.loc['Nick']trevor=ratings.loc['Trevor'] Then, we can look at the distance between Jack and the other two people: print("Distance between Jack and Nick:")print(distance(jack,nick))# 10.63014581273465print("Distance between Jack and Trevor:")print(distance(jack,trevor))# 13.490737563232042 Just like in the tiny universe, Jack is closer to Nick (10.63 units away) than to Trevor (13.49 units away). But really, we want to look at the distance between Jack and every other person. Here’s a function that uses a “for loop” to do just that: def most_similar_to(name): person = ratings.loc[name] closest_distance=float('inf') closest_person='' for other_person in ratings.itertuples(): if other_person.Index==name: # don't compare a person to themself continue distance_to_other_person = distance(person,ratings.loc[other_person.Index]) if distance_to_other_person < best_similarity: # new high score! save it closest_distance = distance_to_other_person closest_person = other_person.Index return closest_person It starts by saying: “the closest person so far is infinitely far away.” Then, it loops through to look at each person and asks “is this person closer than the closest person so far?” It’s not very helpful to answer “the person most similar to Jack is Jack,” which is why the loops skips (i.e., continue ) if the names are the same. Now, we can just call most_similar_to to see who is closest to any person. Let’s try it for me (Jack): print("Jack is most similar to:")person_most_similar_to_jack = most_similar_to('Jack')print(person_most_similar_to_jack)print(distance)# Meg# 8.660254037844387 At last, we can predict whether I will like “7 Rings” by looking at the user who is most similar to me. At the time, the data said this was Meg, so let’s see how Meg rated the song: print(ratings.at['Meg', '7 Rings (Ariana Grande)'])# 3.0 Meg rated the song at 3/5, so I will probably not be too crazy about it. A Google Colab notebook with all the code is available here. If you really wanted to do what Spotify is doing, you would make predictions using musical tastes of every person, not just the closest person. For example, maybe if I knew that Trevor and I consistently had very different tastes, recognizing that Trevor liked “7 Rings” might tell me that I would dislike the song. I may cover this in a future tutorial, so let me know if you are interested!
[ { "code": null, "e": 245, "s": 171, "text": "This material is based on content from a workshop I taught in April 2020." }, { "code": null, "e": 468, "s": 245, "text": "Most of us now use AI-based recommender systems every day: looking for a show on Netflix, scrolling through social media feeds, watching “up next” videos on YouTube, and listening to “Discover Weekly” playlists on Spotify." }, { "code": null, "e": 503, "s": 468, "text": "So how do these recommenders work?" }, { "code": null, "e": 1016, "s": 503, "text": "They have become really good, and in some cases, creepily good. Many of us have received recommendations and advertisements that make us ask: “were they recording me?” Generally speaking, companies do not make recommendations by hacking your microphone and recording your conversations. Instead, they make a model of you, or as Tristan Harris called it, “a little voodoo doll, avatar-like version of you,” and then make predictions about that doll. I’ll refer to this doll as a mathematical model of your tastes." }, { "code": null, "e": 1277, "s": 1016, "text": "The methods in this tutorial are nowhere near as sophisticated as what Google, Facebook, and Spotify are using, and they will not produce any creepily good recommendations. Still, most recommendations principally work the same, and are bound up in three steps:" }, { "code": null, "e": 1463, "s": 1277, "text": "Companies make a mathematical model of you and everyone elseThey use those models to find people who are similar to youThey find what those similar people liked, and recommend it to you" }, { "code": null, "e": 1524, "s": 1463, "text": "Companies make a mathematical model of you and everyone else" }, { "code": null, "e": 1584, "s": 1524, "text": "They use those models to find people who are similar to you" }, { "code": null, "e": 1651, "s": 1584, "text": "They find what those similar people liked, and recommend it to you" }, { "code": null, "e": 1764, "s": 1651, "text": "I’ll go over these three steps twice, first in a simple visual example, and then in a larger code-based example." }, { "code": null, "e": 1951, "s": 1764, "text": "Let’s start by considering three people (Jack, Nick, and Trevor) and how they rated three songs (One Dance, Lean On, and Sunflower) on a scale of 1 to 5. Here they are in a simple table:" }, { "code": null, "e": 2435, "s": 1951, "text": "We now have a simple mathematical model of musical taste. In the real world, Spotify uses other signals, such as how many times you listen to a song, to determine this rating. Regardless, the principle is to translate your tastes into a list of numbers, which is also called a vector, a matrix, or an array. Whatever you call them, it’s helpful to visualize these numbers on a graph. Below, we put the rating for “One Dance” on the x-axis, and the rating for “Lean On” on the y-axis:" }, { "code": null, "e": 2594, "s": 2435, "text": "We now have a list of numbers that capture your musical tastes, so we can go to the next step: finding people with similar tastes. Let’s go back to the graph:" }, { "code": null, "e": 2862, "s": 2594, "text": "In the visual representation, similar people are just nearby people. So figuring out who is “most similar” to Jack is just a matter of figuring out who is closest to Jack. And we can measure this distance using the old Pythagorean theorem from middle school geometry:" }, { "code": null, "e": 2985, "s": 2862, "text": "Cool! We’re almost there. We can already see that Jack is most similar to Nick and not Trevor, but let’s make it official:" }, { "code": null, "e": 3113, "s": 2985, "text": "The maths confirm: in this tiny universe of song tastes, Jack is 3.2 units away from Trevor, but only 1.4 units away from Nick." }, { "code": null, "e": 3303, "s": 3113, "text": "Now that we know Jack and Nick have similar taste, we can predict whether Jack will like “Sunflower” based on whether Nick liked sunflower. It’s just a matter of looking it up in the table:" }, { "code": null, "e": 3401, "s": 3303, "text": "Nick gave “Sunflower” a 5/5 rating, so we can predict that Jack will probably like the song, too." }, { "code": null, "e": 3641, "s": 3401, "text": "Obviously, the scale of this tiny universe is a lot smaller than Spotify’s universe. We looked at three songs and three people, while Spotify purportedly has over 50 million tracks and over 271 million active users. So now, we’ll scale up." }, { "code": null, "e": 3739, "s": 3641, "text": "To make a bigger dataset, we will load in a larger table. Here is one with 25 songs and 8 people:" }, { "code": null, "e": 3815, "s": 3739, "text": "In Python, you can use Pandas to load this data with the following command:" }, { "code": null, "e": 4035, "s": 3815, "text": "from pandas import read_csvdata_url = 'https://gist.githubusercontent.com/jackbandy/5cd988ab5c3d95b79219364dce7ee5ae/raw/731ecdbecc7b33030f23cd919e6067dfbaf42feb/song-ratings.csv'ratings = read_csv(data_url,index_col=0)" }, { "code": null, "e": 4318, "s": 4035, "text": "Now, let’s try to predict whether I (still Jack) will like the song “7 Rings.” As in the visual example, we will find the person closest to me. Using the Pythagorean theorem, the distance function in two dimensions was just distance=sqrt(a^2 + b^2) , which we could write like this:" }, { "code": null, "e": 4474, "s": 4318, "text": "def distance(person1,person2): a_squared = (person1[0] - person2[0])**2 b_squared = (person1[1] - person2[1])**2 c = sqrt(a_squared+b_squared) return c" }, { "code": null, "e": 4629, "s": 4474, "text": "But this time, there are 25 dimensions, not just two. How do we find the closest person when we have 25 dimensions instead of just an x-axis and a y-axis?" }, { "code": null, "e": 5058, "s": 4629, "text": "It turns out the trusty Pythagorean theorem generalizes pretty well. (Most recommenders use other distance metrics like cosine distance, but we’ll ignore that for this tutorial). If there are three dimensions, we can call them a , b , and c , and then just add it under the square root:distance=sqrt(a^2 + b^2 + c^2) . And we can actually do this with any number of dimensions: distance=sqrt(a^2 + b^2 + c^2 + d^2 + ... + n^2) ." }, { "code": null, "e": 5199, "s": 5058, "text": "The scipy library has written a function to do exactly what we need: calculate Euclidean distance in any number of dimensions. Let’s use it:" }, { "code": null, "e": 5330, "s": 5199, "text": "from scipy.spatial.distance import euclideandef distance(person1,person2): distance = euclidean(person1,person2) return distance" }, { "code": null, "e": 5582, "s": 5330, "text": "Now, we can use that distance function to look at the similarity between any two people. The only catch is that we need to fill in blanks with “0,” using fillna . The following block does that, and then retrieves the rows of data for the three people:" }, { "code": null, "e": 5684, "s": 5582, "text": "ratings=ratings.fillna(0)jack=ratings.loc['Jack']nick=ratings.loc['Nick']trevor=ratings.loc['Trevor']" }, { "code": null, "e": 5757, "s": 5684, "text": "Then, we can look at the distance between Jack and the other two people:" }, { "code": null, "e": 5933, "s": 5757, "text": "print(\"Distance between Jack and Nick:\")print(distance(jack,nick))# 10.63014581273465print(\"Distance between Jack and Trevor:\")print(distance(jack,trevor))# 13.490737563232042" }, { "code": null, "e": 6181, "s": 5933, "text": "Just like in the tiny universe, Jack is closer to Nick (10.63 units away) than to Trevor (13.49 units away). But really, we want to look at the distance between Jack and every other person. Here’s a function that uses a “for loop” to do just that:" }, { "code": null, "e": 6688, "s": 6181, "text": "def most_similar_to(name): person = ratings.loc[name] closest_distance=float('inf') closest_person='' for other_person in ratings.itertuples(): if other_person.Index==name: # don't compare a person to themself continue distance_to_other_person = distance(person,ratings.loc[other_person.Index]) if distance_to_other_person < best_similarity: # new high score! save it closest_distance = distance_to_other_person closest_person = other_person.Index return closest_person" }, { "code": null, "e": 7021, "s": 6688, "text": "It starts by saying: “the closest person so far is infinitely far away.” Then, it loops through to look at each person and asks “is this person closer than the closest person so far?” It’s not very helpful to answer “the person most similar to Jack is Jack,” which is why the loops skips (i.e., continue ) if the names are the same." }, { "code": null, "e": 7124, "s": 7021, "text": "Now, we can just call most_similar_to to see who is closest to any person. Let’s try it for me (Jack):" }, { "code": null, "e": 7284, "s": 7124, "text": "print(\"Jack is most similar to:\")person_most_similar_to_jack = most_similar_to('Jack')print(person_most_similar_to_jack)print(distance)# Meg# 8.660254037844387" }, { "code": null, "e": 7466, "s": 7284, "text": "At last, we can predict whether I will like “7 Rings” by looking at the user who is most similar to me. At the time, the data said this was Meg, so let’s see how Meg rated the song:" }, { "code": null, "e": 7523, "s": 7466, "text": "print(ratings.at['Meg', '7 Rings (Ariana Grande)'])# 3.0" }, { "code": null, "e": 7596, "s": 7523, "text": "Meg rated the song at 3/5, so I will probably not be too crazy about it." }, { "code": null, "e": 7657, "s": 7596, "text": "A Google Colab notebook with all the code is available here." } ]
Detecting Malaria with Deep Learning | by Dipanjan (DJ) Sarkar | Towards Data Science
The content for this article has been adapted from my own article published previously in opensource.com Welcome to the AI for Social Good Series, where we will be focusing on different aspects of how Artificial Intelligence (AI) coupled with popular open-source tools, technologies and frameworks are being used for development and betterment of our society. “Health is Wealth” is perhaps a cliched quote yet very true! In this particular article, we will look at how AI can be leveraged for detecting malaria, a deadly disease and the promise of building a low-cost, yet effective and accurate open-source solution. The intent of the article is two-fold — understanding the motivation and importance of the deadly disease malaria and the effectiveness of deep learning in detecting malaria. We will be covering the following major topics in this article. Motivation for this project Methods for Malaria Detection Deep Learning for Malaria Detection Convolutional Neural Networks (CNNs) trained from scratch Transfer Learning with Pre-trained Models Now before we begin, I’d like to point out that I am neither a doctor nor a healthcare researcher and I’m nowhere near to being as qualified as they are. I do have interests though in applying AI for healthcare research. The intent of this article is not to dive into the hype that AI would be replacing jobs and taking over the world, but to showcase how AI can be useful in assisting with malaria detection, diagnosis and reducing manual labor with low-cost effective and accurate open-source solutions. Thanks to the power of Python and deep learning frameworks like TensorFlow, we can build robust, scalable and effective deep learning solutions. The added benefit of these tools being open-source and free, enable us to build solutions which can be really cost effective and be adopted and used by everyone easily. Let’s get started! Malaria is a deadly, infectious mosquito-borne disease caused by Plasmodium parasites. These parasites are transmitted by the bites of infected female Anopheles mosquitoes. While we won’t get into details about the disease, there are five main types of malaria. Let’s now look at the significance of how deadly this disease can be in the following plot. It is pretty clear that malaria is prevalent across the globe especially in tropical regions. The motivation for this project is however based on the nature and fatality of this disease. Initially if an infected mosquito bites you, parasites carried by the mosquito will get in your blood and start destroying oxygen-carrying RBCs (red blood cells). Typically the first symptoms of malaria are similar to the flu or a virus when you usually start feeling sick within a few days or weeks after the mosquito bite. However these deadly parasites can live in your body for over a year without any problems! Thus, a delay in the right treatment can lead to complications and even death. Hence early and effective testing and detection of malaria can save lives. The World Health Organization (WHO) has released several crucial facts on malaria which you can check out here. In short, nearly half the world’s population is at risk from malaria and there are over 200 million malaria cases and approximately 400,000 deaths due to malaria every year. This gives us all the more motivation to make malaria detection and diagnosis fast, easy and effective. There are several methods and tests which can be used for malaria detection and diagnosis. The original paper on which our data and analysis is based on, ‘ Pre-trained convolutional neural networks as feature extractors toward improved Malaria parasite detection in thin blood smear images’ by S Rajaraman et. al. introduces us briefly to some of these methods. These include but are not limited to, thick and thin blood smear examinations, polymerase chain reaction (PCR) and rapid diagnostic tests (RDT). While we won’t cover all the methods here in detail, an important point to remember is that the latter two tests are alternative methods typically used an an alternative particularly where good quality microscopy services cannot be readily provided. We will discuss briefly about a standard malaria diagnosis, based on a typical blood-smear workflow, thanks to this wonderful article by Carlos Ariza on Insight Data Science, which I got to know from Adrian Rosebrock’s excellent article on malaria detection on pyimagesearch, so my heartfelt thanks to both of them for such excellent resources, giving me more perspective in this domain. Based on the guidelines from the WHO protocol, this procedure involves intensive examination of the blood smear at a 100X magnification, where people manually count red blood cells that contain parasites out of 5000 cells. In fact the paper by Rajaraman et. al. which we mentioned previously, talks about the exact same thing and I quote the following exerpt from the paper to make things clearer. Thick blood smears assist in detecting the presence of parasites while thin blood smears assist in identifying the species of the parasite causing the infection (Centers for Disease Control and Prevention, 2012). The diagnostic accuracy heavily depends on human expertise and can be adversely impacted by the inter-observer variability and the liability imposed by large-scale diagnoses in disease-endemic/resource-constrained regions (Mitiku, Mengistu & Gelaw, 2003). Alternative techniques such as polymerase chain reaction (PCR) and rapid diagnostic tests (RDT) are used; however, PCR analysis is limited in its performance (Hommelsheim et al., 2014) and RDTs are less cost-effective in disease-endemic regions (Hawkes, Katsuva & Masumbuko, 2009). Thus, malaria detection is definitely an intensive manual process which can perhaps be automated using deep learning which forms the basis of this article. With regular manual diagnosis of blood smears, it is an intensive manual process requiring proper expertise in classifying and counting the parasitized and uninfected cells. Typically this may not scale well and might cause problems if we do not have the right expertise in specific regions around the world. Some advancements have been made in leveraging state-of-the-art (SOTA) image processing and analysis techniques to extract hand-engineered features and build machine learning based classification models. However these models are not scalable with more data being available for training and given the fact that hand-engineered features take a lot of time. Deep Learning models, or to be more specific, Convolutional Neural Networks (CNNs) have proven to be really effective in a wide variety of computer vision tasks. While we assume that you have some knowledge on CNNs, in case you don’t, feel free to dive deeper into them by checking out this article here. Briefly, The key layers in a CNN model include convolution and pooling layers as depicted in the following figure. Convolution layers learn spatial hierarchical patterns from the data, which are also translation invariant. Thus they are able to learn different aspects of images. For example, the first convolution layer will learn small and local patterns such as edges and corners, a second convolution layer will learn larger patterns based on the features from the first layers, and so on. This allows CNNs to automate feature engineering and learn effective features which generalize well on new data points. Pooling layers help with downsampling and dimension reduction. Thus, CNNs help us with automated and scalable feature engineering. Also, plugging in dense layers at the end of our model enables us to perform tasks like image classification. Automated malaria detection using deep learning models like CNNs could be very effective, cheap and scalable especially with the advent of transfer learning and pre-trained models which work quite well even with constraints like less data. The paper by Rajaraman et al. , ‘Pre-trained convolutional neural networks as feature extractors toward improved parasite detection in thin blood smear images’ leverages a total of six pre-trained models on the data mentioned in their paper to obtain an impressive accuracy of 95.9% in detecting malaria vs. non-infected samples. Our focus would be to try out some simple CNN models from scratch and a couple of pre-trained models using transfer learning to see the kind of results we get on the same dataset! We will be using open-source tools and frameworks which include Python and TensorFlow to build our models. Let’s talk about the dataset we would be using in our analysis. We are lucky to have researchers at the Lister Hill National Center for Biomedical Communications (LHNCBC), part of National Library of Medicine (NLM) who have carefully collected and annotated this dataset of healthy and infected blood smear images. You can download these images from the official website. In fact they have developed a mobile application that runs on a standard Android smartphone attached to a conventional light microscope (Poostchi et al., 2018). Giemsa-stained thin blood smear slides from 150 P. falciparum-infected and 50 healthy patients were collected and photographed at Chittagong Medical College Hospital, Bangladesh. The smartphone’s built-in camera acquired images of slides for each microscopic field of view. The images were manually annotated by an expert slide reader at the Mahidol-Oxford Tropical Medicine Research Unit in Bangkok, Thailand. Let’s briefly check out our dataset structure. We install some basic dependencies first based on the OS being used. I am using a Debian based system on the cloud having a GPU so I can run my models faster! Install the tree dependency in case you don’t have it so we can view our directory structure (sudo apt install tree). Looks like we have two folders which contain images of cells which are infected and healthy. We can get further detail of the total number of images using the following code. Looks like we have a balanced dataset of 13779 malaria and non-malaria (uninfected) cell images. Let’s build a dataframe from this which will be of use to us shortly as we start building our datasets. To build deep learning models we need training data but we also need to test the model’s performance on unseen data. We will use a 60:10:30 split for train, validatation and test datasets respectively. We will leverage the train and validation datasets during training and check the performance of the model on the test dataset. Now obviously the images will not be of equal dimensions given blood smears and cell images will vary based on the human, the test method and the orientation in which the photo was taken. Let’s get some summary statistics of our training dataset to decide optimal image dimensions (remember we don’t touch the test dataset at all!). We apply parallel processing to speed up the image read operations and based on the summary statistics, we have decided to resize each image to 125x125 pixels. Let’s load up all our images and resize them to these fixed dimensions. We leverage parallel processing again to speed up computations pertaining to image load and resizing. Finally we get our image tensors of desired dimensions as depicted in the preceding output. We can now view some sample cell images to get an idea of how our data looks like. Based on the sample images above, we can notice some subtle differences between malaria and healthy cell images. We will basically make our deep learning models try and learn these patterns during model training. We setup some basic configuration settings before we start training our models. We fix our image dimensions, batch size, epochs and encode our categorical class labels. The alpha version of TensorFlow 2.0 was released on March, 2019 just a couple of weeks before this article was written and it gives us a perfect excuse to try it out! In the model training phase, we will build several deep learning models and train them on our training data and compare their performance on the validation data. We will then save these models and use them later on again in the model evaluation phase. Our first malaria detection model will be building and training a basic convolutional neural network (CNN) from scratch. First let’s define our model architecture. Based on the architecture in the preceding code, our CNN model has three convolution and pooling layers followed by two dense layers and dropout for regularization. Let’s train our model now! We get a validation accuracy of 95.6% which is pretty good, though our model looks to be overfitting slightly looking at our training accuracy which is 99.9%. We can get a clear perspective on this by plotting the training and validation accuracy and loss curves. Thus we can see after the fifth epoch, things don’t seem to improve a whole lot overall. Let’s save this model for future evaluation. model.save('basic_cnn.h5') Just like humans have an inherent capability of being able to transfer knowledge across tasks, transfer learning enables us to utilize knowledge from previously learned tasks and apply them to newer, related ones even in the context of machine learning or deep learning. A comprehensive coverage of transfer learning is available in my article and my book for readers interested in doing a deep-dive. For the purpose of this article, the idea is, can we leverage a pre-trained deep learning model (which was trained on a large dataset — like ImageNet) to solve the problem of malaria detection by applying and transferring its knowledge in the context of our problem? We will apply the two most popular strategies for deep transfer learning. Pre-trained Model as a Feature Extractor Pre-trained Model with Fine-tuning We will be using the pre-trained VGG-19 deep learning model, developed by the Visual Geometry Group (VGG) at the University of Oxford, for our experiments. A pre-trained model like the VGG-19 is an already pre-trained model on a huge dataset (ImageNet) with a lot of diverse image categories. Considering this fact, the model should have learned a robust hierarchy of features, which are spatial, rotation, and translation invariant with regard to features learned by CNN models. Hence, the model, having learned a good representation of features for over a million images, can act as a good feature extractor for new images suitable for computer vision problems just like malaria detection! Let’s briefly discuss the VGG-19 model architecture before unleashing the power of transfer learning on our problem. The VGG-19 model is a 19-layer (convolution and fully connected) deep learning network built on the ImageNet database, which is built for the purpose of image recognition and classification. This model was built by Karen Simonyan and Andrew Zisserman and is mentioned in their paper titled ‘Very Deep Convolutional Networks for Large-Scale Image Recognition’. I recommend all interested readers to go and read up on the excellent literature in this paper. The architecture of the VGG-19 model is depicted in the following figure. You can clearly see that we have a total of 16 convolution layers using 3 x 3convolution filters along with max pooling layers for downsampling and a total of two fully connected hidden layers of 4096 units in each layer followed by a dense layer of 1000 units, where each unit represents one of the image categories in the ImageNet database. We do not need the last three layers since we will be using our own fully connected dense layers to predict malaria. We are more concerned with the first five blocks, so that we can leverage the VGG model as an effective feature extractor. For one of the models, we will use it as a simple feature extractor by freezing all the five convolution blocks to make sure their weights don’t get updated after each epoch. For the last model, we will apply fine-tuning to the VGG model, where we will unfreeze the last two blocks (Block 4 and Block 5) so that their weights get updated in each iteration (per batch of data) as we train our own model. For building this model, we will leverage TensorFlow to load up the VGG-19 model, and freeze the convolution blocks so that we can use it as an image feature extractor. We will plugin our own dense layers at the end for performing the classification task. Thus it is quite evident from the preceding output that we have a lot of layers in our model and we will be using the frozen layers of the VGG-19 model as feature extractors only. You can use the following code to verify how many layers in our model are indeed trainable and how many total layers are present in our network. We will now train our model using similar configurations and callbacks which we used in our previous model. Refer to my GitHub repository for the complete code to train the model. We observe the following plots showing the model’s accuracy and loss. This shows us that our model is not overfitting as much as our basic CNN model but the performance is not really better and in fact is sligtly lesser than our basic CNN model. Let’s save this model now for future evaluation. model.save('vgg_frozen.h5') In our final model, we will fine-tune the weights of the layers present in the last two blocks of our pre-trained VGG-19 model. Besides that, we will also introduce the concept of image augmentation. The idea behind image augmentation is exactly as the name sounds. We load in existing images from our training dataset and apply some image transformation operations to them, such as rotation, shearing, translation, zooming, and so on, to produce new, altered versions of existing images. Due to these random transformations, we don’t get the same images each time. We will leverage an excellent utility called ImageDataGenerator in tf.keras that can help us build image augmentors. We do not apply any transformations on our validation dataset except scaling the images (which is mandatory), since we will be using it to evaluate our model performance per epoch. For detailed explanation of image augmentation in the context of transfer learning feel free to check out my article if needed. Let's take a look at some sample results from a batch of image augmentation transforms. You can clearly see the slight variations of our images in the preceding output. We will now build our deep learning model making sure the last two blocks of the VGG-19 model is trainable. We reduce the learning rate in our model since we don’t want to make to large weight updates to the pre-trained layers when fine-tuning. The training process of this model will be slightly different since we are using data generators and hence we will be leveraging the fit_generator(...) function. This looks to be our best model yet giving us a validation accuracy of almost 96.5% and based on the training accuracy, it doesn’t look like our model is overfitting as much as our first model. This can be verified with the following learning curves. Let’s save this model now so that we can use it for model evaluation on our test dataset shortly. model.save('vgg_finetuned.h5') This completes our model training phase and we are now ready to test the performance of our models on the actual test dataset! We will now evaluate the three different models that we just built in the training phase by making predictions with them on the data from our test dataset, because just validation is not enough! We have also built a nifty utility module called model_evaluation_utils, which we will be using to evaluate the performance of our deep learning models with relevant classification metrics. The first step here is to obviously scale our test data. The next step involves loading up our saved deep learning models and making predictions on the test data. The final step is to leverage our model_evaluation_utils module and check the performance of each model with relevant classification metrics. Looks like our third model performs the best out of all our three models on the test dataset giving a model accuracy as well as f1-score of 96% which is pretty good and quite comparable to the more complex models mentioned in the research paper and articles we mentioned earlier! We looked at an interesting real-world medical imaging case study of malaria detection in this article. Malaria detection by itself is not an easy procedure and the availability of the right personnel across the globe is also a serious concern. We looked at easy to build open-source techniques leveraging AI which can give us state-of-the-art accuracy in detecting malaria thus enabling AI for social good. I encourage everyone to check out the articles and research papers mentioned in this article, without which it would have been impossible for me to conceptualize and write this article. Let’s hope for more adoption of open-source AI capabilities across healthcare making it cheaper and accessible for everyone across the world! This article has been adapted from my own article published previously in opensource.com If you are interested in running or adopting all the code used in this article, it is available on my GitHub repository. Remember to download the data from the official website.
[ { "code": null, "e": 277, "s": 172, "text": "The content for this article has been adapted from my own article published previously in opensource.com" }, { "code": null, "e": 1029, "s": 277, "text": "Welcome to the AI for Social Good Series, where we will be focusing on different aspects of how Artificial Intelligence (AI) coupled with popular open-source tools, technologies and frameworks are being used for development and betterment of our society. “Health is Wealth” is perhaps a cliched quote yet very true! In this particular article, we will look at how AI can be leveraged for detecting malaria, a deadly disease and the promise of building a low-cost, yet effective and accurate open-source solution. The intent of the article is two-fold — understanding the motivation and importance of the deadly disease malaria and the effectiveness of deep learning in detecting malaria. We will be covering the following major topics in this article." }, { "code": null, "e": 1057, "s": 1029, "text": "Motivation for this project" }, { "code": null, "e": 1087, "s": 1057, "text": "Methods for Malaria Detection" }, { "code": null, "e": 1123, "s": 1087, "text": "Deep Learning for Malaria Detection" }, { "code": null, "e": 1181, "s": 1123, "text": "Convolutional Neural Networks (CNNs) trained from scratch" }, { "code": null, "e": 1223, "s": 1181, "text": "Transfer Learning with Pre-trained Models" }, { "code": null, "e": 1729, "s": 1223, "text": "Now before we begin, I’d like to point out that I am neither a doctor nor a healthcare researcher and I’m nowhere near to being as qualified as they are. I do have interests though in applying AI for healthcare research. The intent of this article is not to dive into the hype that AI would be replacing jobs and taking over the world, but to showcase how AI can be useful in assisting with malaria detection, diagnosis and reducing manual labor with low-cost effective and accurate open-source solutions." }, { "code": null, "e": 2062, "s": 1729, "text": "Thanks to the power of Python and deep learning frameworks like TensorFlow, we can build robust, scalable and effective deep learning solutions. The added benefit of these tools being open-source and free, enable us to build solutions which can be really cost effective and be adopted and used by everyone easily. Let’s get started!" }, { "code": null, "e": 2416, "s": 2062, "text": "Malaria is a deadly, infectious mosquito-borne disease caused by Plasmodium parasites. These parasites are transmitted by the bites of infected female Anopheles mosquitoes. While we won’t get into details about the disease, there are five main types of malaria. Let’s now look at the significance of how deadly this disease can be in the following plot." }, { "code": null, "e": 3173, "s": 2416, "text": "It is pretty clear that malaria is prevalent across the globe especially in tropical regions. The motivation for this project is however based on the nature and fatality of this disease. Initially if an infected mosquito bites you, parasites carried by the mosquito will get in your blood and start destroying oxygen-carrying RBCs (red blood cells). Typically the first symptoms of malaria are similar to the flu or a virus when you usually start feeling sick within a few days or weeks after the mosquito bite. However these deadly parasites can live in your body for over a year without any problems! Thus, a delay in the right treatment can lead to complications and even death. Hence early and effective testing and detection of malaria can save lives." }, { "code": null, "e": 3563, "s": 3173, "text": "The World Health Organization (WHO) has released several crucial facts on malaria which you can check out here. In short, nearly half the world’s population is at risk from malaria and there are over 200 million malaria cases and approximately 400,000 deaths due to malaria every year. This gives us all the more motivation to make malaria detection and diagnosis fast, easy and effective." }, { "code": null, "e": 4320, "s": 3563, "text": "There are several methods and tests which can be used for malaria detection and diagnosis. The original paper on which our data and analysis is based on, ‘ Pre-trained convolutional neural networks as feature extractors toward improved Malaria parasite detection in thin blood smear images’ by S Rajaraman et. al. introduces us briefly to some of these methods. These include but are not limited to, thick and thin blood smear examinations, polymerase chain reaction (PCR) and rapid diagnostic tests (RDT). While we won’t cover all the methods here in detail, an important point to remember is that the latter two tests are alternative methods typically used an an alternative particularly where good quality microscopy services cannot be readily provided." }, { "code": null, "e": 4708, "s": 4320, "text": "We will discuss briefly about a standard malaria diagnosis, based on a typical blood-smear workflow, thanks to this wonderful article by Carlos Ariza on Insight Data Science, which I got to know from Adrian Rosebrock’s excellent article on malaria detection on pyimagesearch, so my heartfelt thanks to both of them for such excellent resources, giving me more perspective in this domain." }, { "code": null, "e": 5106, "s": 4708, "text": "Based on the guidelines from the WHO protocol, this procedure involves intensive examination of the blood smear at a 100X magnification, where people manually count red blood cells that contain parasites out of 5000 cells. In fact the paper by Rajaraman et. al. which we mentioned previously, talks about the exact same thing and I quote the following exerpt from the paper to make things clearer." }, { "code": null, "e": 5857, "s": 5106, "text": "Thick blood smears assist in detecting the presence of parasites while thin blood smears assist in identifying the species of the parasite causing the infection (Centers for Disease Control and Prevention, 2012). The diagnostic accuracy heavily depends on human expertise and can be adversely impacted by the inter-observer variability and the liability imposed by large-scale diagnoses in disease-endemic/resource-constrained regions (Mitiku, Mengistu & Gelaw, 2003). Alternative techniques such as polymerase chain reaction (PCR) and rapid diagnostic tests (RDT) are used; however, PCR analysis is limited in its performance (Hommelsheim et al., 2014) and RDTs are less cost-effective in disease-endemic regions (Hawkes, Katsuva & Masumbuko, 2009)." }, { "code": null, "e": 6013, "s": 5857, "text": "Thus, malaria detection is definitely an intensive manual process which can perhaps be automated using deep learning which forms the basis of this article." }, { "code": null, "e": 6677, "s": 6013, "text": "With regular manual diagnosis of blood smears, it is an intensive manual process requiring proper expertise in classifying and counting the parasitized and uninfected cells. Typically this may not scale well and might cause problems if we do not have the right expertise in specific regions around the world. Some advancements have been made in leveraging state-of-the-art (SOTA) image processing and analysis techniques to extract hand-engineered features and build machine learning based classification models. However these models are not scalable with more data being available for training and given the fact that hand-engineered features take a lot of time." }, { "code": null, "e": 7097, "s": 6677, "text": "Deep Learning models, or to be more specific, Convolutional Neural Networks (CNNs) have proven to be really effective in a wide variety of computer vision tasks. While we assume that you have some knowledge on CNNs, in case you don’t, feel free to dive deeper into them by checking out this article here. Briefly, The key layers in a CNN model include convolution and pooling layers as depicted in the following figure." }, { "code": null, "e": 7659, "s": 7097, "text": "Convolution layers learn spatial hierarchical patterns from the data, which are also translation invariant. Thus they are able to learn different aspects of images. For example, the first convolution layer will learn small and local patterns such as edges and corners, a second convolution layer will learn larger patterns based on the features from the first layers, and so on. This allows CNNs to automate feature engineering and learn effective features which generalize well on new data points. Pooling layers help with downsampling and dimension reduction." }, { "code": null, "e": 8077, "s": 7659, "text": "Thus, CNNs help us with automated and scalable feature engineering. Also, plugging in dense layers at the end of our model enables us to perform tasks like image classification. Automated malaria detection using deep learning models like CNNs could be very effective, cheap and scalable especially with the advent of transfer learning and pre-trained models which work quite well even with constraints like less data." }, { "code": null, "e": 8694, "s": 8077, "text": "The paper by Rajaraman et al. , ‘Pre-trained convolutional neural networks as feature extractors toward improved parasite detection in thin blood smear images’ leverages a total of six pre-trained models on the data mentioned in their paper to obtain an impressive accuracy of 95.9% in detecting malaria vs. non-infected samples. Our focus would be to try out some simple CNN models from scratch and a couple of pre-trained models using transfer learning to see the kind of results we get on the same dataset! We will be using open-source tools and frameworks which include Python and TensorFlow to build our models." }, { "code": null, "e": 9066, "s": 8694, "text": "Let’s talk about the dataset we would be using in our analysis. We are lucky to have researchers at the Lister Hill National Center for Biomedical Communications (LHNCBC), part of National Library of Medicine (NLM) who have carefully collected and annotated this dataset of healthy and infected blood smear images. You can download these images from the official website." }, { "code": null, "e": 9754, "s": 9066, "text": "In fact they have developed a mobile application that runs on a standard Android smartphone attached to a conventional light microscope (Poostchi et al., 2018). Giemsa-stained thin blood smear slides from 150 P. falciparum-infected and 50 healthy patients were collected and photographed at Chittagong Medical College Hospital, Bangladesh. The smartphone’s built-in camera acquired images of slides for each microscopic field of view. The images were manually annotated by an expert slide reader at the Mahidol-Oxford Tropical Medicine Research Unit in Bangkok, Thailand. Let’s briefly check out our dataset structure. We install some basic dependencies first based on the OS being used." }, { "code": null, "e": 9962, "s": 9754, "text": "I am using a Debian based system on the cloud having a GPU so I can run my models faster! Install the tree dependency in case you don’t have it so we can view our directory structure (sudo apt install tree)." }, { "code": null, "e": 10137, "s": 9962, "text": "Looks like we have two folders which contain images of cells which are infected and healthy. We can get further detail of the total number of images using the following code." }, { "code": null, "e": 10338, "s": 10137, "text": "Looks like we have a balanced dataset of 13779 malaria and non-malaria (uninfected) cell images. Let’s build a dataframe from this which will be of use to us shortly as we start building our datasets." }, { "code": null, "e": 10667, "s": 10338, "text": "To build deep learning models we need training data but we also need to test the model’s performance on unseen data. We will use a 60:10:30 split for train, validatation and test datasets respectively. We will leverage the train and validation datasets during training and check the performance of the model on the test dataset." }, { "code": null, "e": 11000, "s": 10667, "text": "Now obviously the images will not be of equal dimensions given blood smears and cell images will vary based on the human, the test method and the orientation in which the photo was taken. Let’s get some summary statistics of our training dataset to decide optimal image dimensions (remember we don’t touch the test dataset at all!)." }, { "code": null, "e": 11232, "s": 11000, "text": "We apply parallel processing to speed up the image read operations and based on the summary statistics, we have decided to resize each image to 125x125 pixels. Let’s load up all our images and resize them to these fixed dimensions." }, { "code": null, "e": 11509, "s": 11232, "text": "We leverage parallel processing again to speed up computations pertaining to image load and resizing. Finally we get our image tensors of desired dimensions as depicted in the preceding output. We can now view some sample cell images to get an idea of how our data looks like." }, { "code": null, "e": 11802, "s": 11509, "text": "Based on the sample images above, we can notice some subtle differences between malaria and healthy cell images. We will basically make our deep learning models try and learn these patterns during model training. We setup some basic configuration settings before we start training our models." }, { "code": null, "e": 12058, "s": 11802, "text": "We fix our image dimensions, batch size, epochs and encode our categorical class labels. The alpha version of TensorFlow 2.0 was released on March, 2019 just a couple of weeks before this article was written and it gives us a perfect excuse to try it out!" }, { "code": null, "e": 12310, "s": 12058, "text": "In the model training phase, we will build several deep learning models and train them on our training data and compare their performance on the validation data. We will then save these models and use them later on again in the model evaluation phase." }, { "code": null, "e": 12474, "s": 12310, "text": "Our first malaria detection model will be building and training a basic convolutional neural network (CNN) from scratch. First let’s define our model architecture." }, { "code": null, "e": 12666, "s": 12474, "text": "Based on the architecture in the preceding code, our CNN model has three convolution and pooling layers followed by two dense layers and dropout for regularization. Let’s train our model now!" }, { "code": null, "e": 12930, "s": 12666, "text": "We get a validation accuracy of 95.6% which is pretty good, though our model looks to be overfitting slightly looking at our training accuracy which is 99.9%. We can get a clear perspective on this by plotting the training and validation accuracy and loss curves." }, { "code": null, "e": 13064, "s": 12930, "text": "Thus we can see after the fifth epoch, things don’t seem to improve a whole lot overall. Let’s save this model for future evaluation." }, { "code": null, "e": 13091, "s": 13064, "text": "model.save('basic_cnn.h5')" }, { "code": null, "e": 13492, "s": 13091, "text": "Just like humans have an inherent capability of being able to transfer knowledge across tasks, transfer learning enables us to utilize knowledge from previously learned tasks and apply them to newer, related ones even in the context of machine learning or deep learning. A comprehensive coverage of transfer learning is available in my article and my book for readers interested in doing a deep-dive." }, { "code": null, "e": 13759, "s": 13492, "text": "For the purpose of this article, the idea is, can we leverage a pre-trained deep learning model (which was trained on a large dataset — like ImageNet) to solve the problem of malaria detection by applying and transferring its knowledge in the context of our problem?" }, { "code": null, "e": 13833, "s": 13759, "text": "We will apply the two most popular strategies for deep transfer learning." }, { "code": null, "e": 13874, "s": 13833, "text": "Pre-trained Model as a Feature Extractor" }, { "code": null, "e": 13909, "s": 13874, "text": "Pre-trained Model with Fine-tuning" }, { "code": null, "e": 14718, "s": 13909, "text": "We will be using the pre-trained VGG-19 deep learning model, developed by the Visual Geometry Group (VGG) at the University of Oxford, for our experiments. A pre-trained model like the VGG-19 is an already pre-trained model on a huge dataset (ImageNet) with a lot of diverse image categories. Considering this fact, the model should have learned a robust hierarchy of features, which are spatial, rotation, and translation invariant with regard to features learned by CNN models. Hence, the model, having learned a good representation of features for over a million images, can act as a good feature extractor for new images suitable for computer vision problems just like malaria detection! Let’s briefly discuss the VGG-19 model architecture before unleashing the power of transfer learning on our problem." }, { "code": null, "e": 15248, "s": 14718, "text": "The VGG-19 model is a 19-layer (convolution and fully connected) deep learning network built on the ImageNet database, which is built for the purpose of image recognition and classification. This model was built by Karen Simonyan and Andrew Zisserman and is mentioned in their paper titled ‘Very Deep Convolutional Networks for Large-Scale Image Recognition’. I recommend all interested readers to go and read up on the excellent literature in this paper. The architecture of the VGG-19 model is depicted in the following figure." }, { "code": null, "e": 15831, "s": 15248, "text": "You can clearly see that we have a total of 16 convolution layers using 3 x 3convolution filters along with max pooling layers for downsampling and a total of two fully connected hidden layers of 4096 units in each layer followed by a dense layer of 1000 units, where each unit represents one of the image categories in the ImageNet database. We do not need the last three layers since we will be using our own fully connected dense layers to predict malaria. We are more concerned with the first five blocks, so that we can leverage the VGG model as an effective feature extractor." }, { "code": null, "e": 16234, "s": 15831, "text": "For one of the models, we will use it as a simple feature extractor by freezing all the five convolution blocks to make sure their weights don’t get updated after each epoch. For the last model, we will apply fine-tuning to the VGG model, where we will unfreeze the last two blocks (Block 4 and Block 5) so that their weights get updated in each iteration (per batch of data) as we train our own model." }, { "code": null, "e": 16490, "s": 16234, "text": "For building this model, we will leverage TensorFlow to load up the VGG-19 model, and freeze the convolution blocks so that we can use it as an image feature extractor. We will plugin our own dense layers at the end for performing the classification task." }, { "code": null, "e": 16815, "s": 16490, "text": "Thus it is quite evident from the preceding output that we have a lot of layers in our model and we will be using the frozen layers of the VGG-19 model as feature extractors only. You can use the following code to verify how many layers in our model are indeed trainable and how many total layers are present in our network." }, { "code": null, "e": 17065, "s": 16815, "text": "We will now train our model using similar configurations and callbacks which we used in our previous model. Refer to my GitHub repository for the complete code to train the model. We observe the following plots showing the model’s accuracy and loss." }, { "code": null, "e": 17290, "s": 17065, "text": "This shows us that our model is not overfitting as much as our basic CNN model but the performance is not really better and in fact is sligtly lesser than our basic CNN model. Let’s save this model now for future evaluation." }, { "code": null, "e": 17318, "s": 17290, "text": "model.save('vgg_frozen.h5')" }, { "code": null, "e": 18001, "s": 17318, "text": "In our final model, we will fine-tune the weights of the layers present in the last two blocks of our pre-trained VGG-19 model. Besides that, we will also introduce the concept of image augmentation. The idea behind image augmentation is exactly as the name sounds. We load in existing images from our training dataset and apply some image transformation operations to them, such as rotation, shearing, translation, zooming, and so on, to produce new, altered versions of existing images. Due to these random transformations, we don’t get the same images each time. We will leverage an excellent utility called ImageDataGenerator in tf.keras that can help us build image augmentors." }, { "code": null, "e": 18398, "s": 18001, "text": "We do not apply any transformations on our validation dataset except scaling the images (which is mandatory), since we will be using it to evaluate our model performance per epoch. For detailed explanation of image augmentation in the context of transfer learning feel free to check out my article if needed. Let's take a look at some sample results from a batch of image augmentation transforms." }, { "code": null, "e": 18587, "s": 18398, "text": "You can clearly see the slight variations of our images in the preceding output. We will now build our deep learning model making sure the last two blocks of the VGG-19 model is trainable." }, { "code": null, "e": 18886, "s": 18587, "text": "We reduce the learning rate in our model since we don’t want to make to large weight updates to the pre-trained layers when fine-tuning. The training process of this model will be slightly different since we are using data generators and hence we will be leveraging the fit_generator(...) function." }, { "code": null, "e": 19137, "s": 18886, "text": "This looks to be our best model yet giving us a validation accuracy of almost 96.5% and based on the training accuracy, it doesn’t look like our model is overfitting as much as our first model. This can be verified with the following learning curves." }, { "code": null, "e": 19235, "s": 19137, "text": "Let’s save this model now so that we can use it for model evaluation on our test dataset shortly." }, { "code": null, "e": 19266, "s": 19235, "text": "model.save('vgg_finetuned.h5')" }, { "code": null, "e": 19393, "s": 19266, "text": "This completes our model training phase and we are now ready to test the performance of our models on the actual test dataset!" }, { "code": null, "e": 19835, "s": 19393, "text": "We will now evaluate the three different models that we just built in the training phase by making predictions with them on the data from our test dataset, because just validation is not enough! We have also built a nifty utility module called model_evaluation_utils, which we will be using to evaluate the performance of our deep learning models with relevant classification metrics. The first step here is to obviously scale our test data." }, { "code": null, "e": 19941, "s": 19835, "text": "The next step involves loading up our saved deep learning models and making predictions on the test data." }, { "code": null, "e": 20083, "s": 19941, "text": "The final step is to leverage our model_evaluation_utils module and check the performance of each model with relevant classification metrics." }, { "code": null, "e": 20363, "s": 20083, "text": "Looks like our third model performs the best out of all our three models on the test dataset giving a model accuracy as well as f1-score of 96% which is pretty good and quite comparable to the more complex models mentioned in the research paper and articles we mentioned earlier!" }, { "code": null, "e": 21099, "s": 20363, "text": "We looked at an interesting real-world medical imaging case study of malaria detection in this article. Malaria detection by itself is not an easy procedure and the availability of the right personnel across the globe is also a serious concern. We looked at easy to build open-source techniques leveraging AI which can give us state-of-the-art accuracy in detecting malaria thus enabling AI for social good. I encourage everyone to check out the articles and research papers mentioned in this article, without which it would have been impossible for me to conceptualize and write this article. Let’s hope for more adoption of open-source AI capabilities across healthcare making it cheaper and accessible for everyone across the world!" }, { "code": null, "e": 21188, "s": 21099, "text": "This article has been adapted from my own article published previously in opensource.com" }, { "code": null, "e": 21309, "s": 21188, "text": "If you are interested in running or adopting all the code used in this article, it is available on my GitHub repository." } ]
R - Data Reshaping
Data Reshaping in R is about changing the way data is organized into rows and columns. Most of the time data processing in R is done by taking the input data as a data frame. It is easy to extract data from the rows and columns of a data frame but there are situations when we need the data frame in a format that is different from format in which we received it. R has many functions to split, merge and change the rows to columns and vice-versa in a data frame. We can join multiple vectors to create a data frame using the cbind()function. Also we can merge two data frames using rbind() function. # Create vector objects. city <- c("Tampa","Seattle","Hartford","Denver") state <- c("FL","WA","CT","CO") zipcode <- c(33602,98104,06161,80294) # Combine above three vectors into one data frame. addresses <- cbind(city,state,zipcode) # Print a header. cat("# # # # The First data frame\n") # Print the data frame. print(addresses) # Create another data frame with similar columns new.address <- data.frame( city = c("Lowry","Charlotte"), state = c("CO","FL"), zipcode = c("80230","33949"), stringsAsFactors = FALSE ) # Print a header. cat("# # # The Second data frame\n") # Print the data frame. print(new.address) # Combine rows form both the data frames. all.addresses <- rbind(addresses,new.address) # Print a header. cat("# # # The combined data frame\n") # Print the result. print(all.addresses) When we execute the above code, it produces the following result − # # # # The First data frame city state zipcode [1,] "Tampa" "FL" "33602" [2,] "Seattle" "WA" "98104" [3,] "Hartford" "CT" "6161" [4,] "Denver" "CO" "80294" # # # The Second data frame city state zipcode 1 Lowry CO 80230 2 Charlotte FL 33949 # # # The combined data frame city state zipcode 1 Tampa FL 33602 2 Seattle WA 98104 3 Hartford CT 6161 4 Denver CO 80294 5 Lowry CO 80230 6 Charlotte FL 33949 We can merge two data frames by using the merge() function. The data frames must have same column names on which the merging happens. In the example below, we consider the data sets about Diabetes in Pima Indian Women available in the library names "MASS". we merge the two data sets based on the values of blood pressure("bp") and body mass index("bmi"). On choosing these two columns for merging, the records where values of these two variables match in both data sets are combined together to form a single data frame. library(MASS) merged.Pima <- merge(x = Pima.te, y = Pima.tr, by.x = c("bp", "bmi"), by.y = c("bp", "bmi") ) print(merged.Pima) nrow(merged.Pima) When we execute the above code, it produces the following result − bp bmi npreg.x glu.x skin.x ped.x age.x type.x npreg.y glu.y skin.y ped.y 1 60 33.8 1 117 23 0.466 27 No 2 125 20 0.088 2 64 29.7 2 75 24 0.370 33 No 2 100 23 0.368 3 64 31.2 5 189 33 0.583 29 Yes 3 158 13 0.295 4 64 33.2 4 117 27 0.230 24 No 1 96 27 0.289 5 66 38.1 3 115 39 0.150 28 No 1 114 36 0.289 6 68 38.5 2 100 25 0.324 26 No 7 129 49 0.439 7 70 27.4 1 116 28 0.204 21 No 0 124 20 0.254 8 70 33.1 4 91 32 0.446 22 No 9 123 44 0.374 9 70 35.4 9 124 33 0.282 34 No 6 134 23 0.542 10 72 25.6 1 157 21 0.123 24 No 4 99 17 0.294 11 72 37.7 5 95 33 0.370 27 No 6 103 32 0.324 12 74 25.9 9 134 33 0.460 81 No 8 126 38 0.162 13 74 25.9 1 95 21 0.673 36 No 8 126 38 0.162 14 78 27.6 5 88 30 0.258 37 No 6 125 31 0.565 15 78 27.6 10 122 31 0.512 45 No 6 125 31 0.565 16 78 39.4 2 112 50 0.175 24 No 4 112 40 0.236 17 88 34.5 1 117 24 0.403 40 Yes 4 127 11 0.598 age.y type.y 1 31 No 2 21 No 3 24 No 4 21 No 5 21 No 6 43 Yes 7 36 Yes 8 40 No 9 29 Yes 10 28 No 11 55 No 12 39 No 13 39 No 14 49 Yes 15 49 Yes 16 38 No 17 28 No [1] 17 One of the most interesting aspects of R programming is about changing the shape of the data in multiple steps to get a desired shape. The functions used to do this are called melt() and cast(). We consider the dataset called ships present in the library called "MASS". library(MASS) print(ships) When we execute the above code, it produces the following result − type year period service incidents 1 A 60 60 127 0 2 A 60 75 63 0 3 A 65 60 1095 3 4 A 65 75 1095 4 5 A 70 60 1512 6 ............. ............. 8 A 75 75 2244 11 9 B 60 60 44882 39 10 B 60 75 17176 29 11 B 65 60 28609 58 ............ ............ 17 C 60 60 1179 1 18 C 60 75 552 1 19 C 65 60 781 0 ............ ............ Now we melt the data to organize it, converting all columns other than type and year into multiple rows. molten.ships <- melt(ships, id = c("type","year")) print(molten.ships) When we execute the above code, it produces the following result − type year variable value 1 A 60 period 60 2 A 60 period 75 3 A 65 period 60 4 A 65 period 75 ............ ............ 9 B 60 period 60 10 B 60 period 75 11 B 65 period 60 12 B 65 period 75 13 B 70 period 60 ........... ........... 41 A 60 service 127 42 A 60 service 63 43 A 65 service 1095 ........... ........... 70 D 70 service 1208 71 D 75 service 0 72 D 75 service 2051 73 E 60 service 45 74 E 60 service 0 75 E 65 service 789 ........... ........... 101 C 70 incidents 6 102 C 70 incidents 2 103 C 75 incidents 0 104 C 75 incidents 1 105 D 60 incidents 0 106 D 60 incidents 0 ........... ........... We can cast the molten data into a new form where the aggregate of each type of ship for each year is created. It is done using the cast() function. recasted.ship <- cast(molten.ships, type+year~variable,sum) print(recasted.ship) When we execute the above code, it produces the following result − type year period service incidents 1 A 60 135 190 0 2 A 65 135 2190 7 3 A 70 135 4865 24 4 A 75 135 2244 11 5 B 60 135 62058 68 6 B 65 135 48979 111 7 B 70 135 20163 56 8 B 75 135 7117 18 9 C 60 135 1731 2 10 C 65 135 1457 1 11 C 70 135 2731 8 12 C 75 135 274 1 13 D 60 135 356 0 14 D 65 135 480 0 15 D 70 135 1557 13 16 D 75 135 2051 4 17 E 60 135 45 0 18 E 65 135 1226 14 19 E 70 135 3318 17 20 E 75 135 542 1 12 Lectures 2 hours Nishant Malik 10 Lectures 1.5 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 20 Lectures 2 hours Asif Hussain 10 Lectures 1.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2866, "s": 2402, "text": "Data Reshaping in R is about changing the way data is organized into rows and columns. Most of the time data processing in R is done by taking the input data as a data frame. It is easy to extract data from the rows and columns of a data frame but there are situations when we need the data frame in a format that is different from format in which we received it. R has many functions to split, merge and change the rows to columns and vice-versa in a data frame." }, { "code": null, "e": 3003, "s": 2866, "text": "We can join multiple vectors to create a data frame using the cbind()function. Also we can merge two data frames using rbind() function." }, { "code": null, "e": 3828, "s": 3003, "text": "# Create vector objects.\ncity <- c(\"Tampa\",\"Seattle\",\"Hartford\",\"Denver\")\nstate <- c(\"FL\",\"WA\",\"CT\",\"CO\")\nzipcode <- c(33602,98104,06161,80294)\n\n# Combine above three vectors into one data frame.\naddresses <- cbind(city,state,zipcode)\n\n# Print a header.\ncat(\"# # # # The First data frame\\n\") \n\n# Print the data frame.\nprint(addresses)\n\n# Create another data frame with similar columns\nnew.address <- data.frame(\n city = c(\"Lowry\",\"Charlotte\"),\n state = c(\"CO\",\"FL\"),\n zipcode = c(\"80230\",\"33949\"),\n stringsAsFactors = FALSE\n)\n\n# Print a header.\ncat(\"# # # The Second data frame\\n\") \n\n# Print the data frame.\nprint(new.address)\n\n# Combine rows form both the data frames.\nall.addresses <- rbind(addresses,new.address)\n\n# Print a header.\ncat(\"# # # The combined data frame\\n\") \n\n# Print the result.\nprint(all.addresses)" }, { "code": null, "e": 3895, "s": 3828, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 4439, "s": 3895, "text": "# # # # The First data frame\n city state zipcode\n[1,] \"Tampa\" \"FL\" \"33602\"\n[2,] \"Seattle\" \"WA\" \"98104\"\n[3,] \"Hartford\" \"CT\" \"6161\" \n[4,] \"Denver\" \"CO\" \"80294\"\n\n# # # The Second data frame\n city state zipcode\n1 Lowry CO 80230\n2 Charlotte FL 33949\n\n# # # The combined data frame\n city state zipcode\n1 Tampa FL 33602\n2 Seattle WA 98104\n3 Hartford CT 6161\n4 Denver CO 80294\n5 Lowry CO 80230\n6 Charlotte FL 33949\n" }, { "code": null, "e": 4573, "s": 4439, "text": "We can merge two data frames by using the merge() function. The data frames must have same column names on which the merging happens." }, { "code": null, "e": 4961, "s": 4573, "text": "In the example below, we consider the data sets about Diabetes in Pima Indian Women available in the library names \"MASS\". we merge the two data sets based on the values of blood pressure(\"bp\") and body mass index(\"bmi\"). On choosing these two columns for merging, the records where values of these two variables match in both data sets are combined together to form a single data frame." }, { "code": null, "e": 5112, "s": 4961, "text": "library(MASS)\nmerged.Pima <- merge(x = Pima.te, y = Pima.tr,\n by.x = c(\"bp\", \"bmi\"),\n by.y = c(\"bp\", \"bmi\")\n)\nprint(merged.Pima)\nnrow(merged.Pima)" }, { "code": null, "e": 5179, "s": 5112, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 6879, "s": 5179, "text": " bp bmi npreg.x glu.x skin.x ped.x age.x type.x npreg.y glu.y skin.y ped.y\n1 60 33.8 1 117 23 0.466 27 No 2 125 20 0.088\n2 64 29.7 2 75 24 0.370 33 No 2 100 23 0.368\n3 64 31.2 5 189 33 0.583 29 Yes 3 158 13 0.295\n4 64 33.2 4 117 27 0.230 24 No 1 96 27 0.289\n5 66 38.1 3 115 39 0.150 28 No 1 114 36 0.289\n6 68 38.5 2 100 25 0.324 26 No 7 129 49 0.439\n7 70 27.4 1 116 28 0.204 21 No 0 124 20 0.254\n8 70 33.1 4 91 32 0.446 22 No 9 123 44 0.374\n9 70 35.4 9 124 33 0.282 34 No 6 134 23 0.542\n10 72 25.6 1 157 21 0.123 24 No 4 99 17 0.294\n11 72 37.7 5 95 33 0.370 27 No 6 103 32 0.324\n12 74 25.9 9 134 33 0.460 81 No 8 126 38 0.162\n13 74 25.9 1 95 21 0.673 36 No 8 126 38 0.162\n14 78 27.6 5 88 30 0.258 37 No 6 125 31 0.565\n15 78 27.6 10 122 31 0.512 45 No 6 125 31 0.565\n16 78 39.4 2 112 50 0.175 24 No 4 112 40 0.236\n17 88 34.5 1 117 24 0.403 40 Yes 4 127 11 0.598\n age.y type.y\n1 31 No\n2 21 No\n3 24 No\n4 21 No\n5 21 No\n6 43 Yes\n7 36 Yes\n8 40 No\n9 29 Yes\n10 28 No\n11 55 No\n12 39 No\n13 39 No\n14 49 Yes\n15 49 Yes\n16 38 No\n17 28 No\n[1] 17\n" }, { "code": null, "e": 7074, "s": 6879, "text": "One of the most interesting aspects of R programming is about changing the shape of the data in multiple steps to get a desired shape. The functions used to do this are called melt() and cast()." }, { "code": null, "e": 7149, "s": 7074, "text": "We consider the dataset called ships present in the library called \"MASS\"." }, { "code": null, "e": 7176, "s": 7149, "text": "library(MASS)\nprint(ships)" }, { "code": null, "e": 7243, "s": 7176, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 7866, "s": 7243, "text": " type year period service incidents\n1 A 60 60 127 0\n2 A 60 75 63 0\n3 A 65 60 1095 3\n4 A 65 75 1095 4\n5 A 70 60 1512 6\n.............\n.............\n8 A 75 75 2244 11\n9 B 60 60 44882 39\n10 B 60 75 17176 29\n11 B 65 60 28609 58\n............\n............\n17 C 60 60 1179 1\n18 C 60 75 552 1\n19 C 65 60 781 0\n............\n............\n" }, { "code": null, "e": 7971, "s": 7866, "text": "Now we melt the data to organize it, converting all columns other than type and year into multiple rows." }, { "code": null, "e": 8042, "s": 7971, "text": "molten.ships <- melt(ships, id = c(\"type\",\"year\"))\nprint(molten.ships)" }, { "code": null, "e": 8109, "s": 8042, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 9033, "s": 8109, "text": " type year variable value\n1 A 60 period 60\n2 A 60 period 75\n3 A 65 period 60\n4 A 65 period 75\n............\n............\n9 B 60 period 60\n10 B 60 period 75\n11 B 65 period 60\n12 B 65 period 75\n13 B 70 period 60\n...........\n...........\n41 A 60 service 127\n42 A 60 service 63\n43 A 65 service 1095\n...........\n...........\n70 D 70 service 1208\n71 D 75 service 0\n72 D 75 service 2051\n73 E 60 service 45\n74 E 60 service 0\n75 E 65 service 789\n...........\n...........\n101 C 70 incidents 6\n102 C 70 incidents 2\n103 C 75 incidents 0\n104 C 75 incidents 1\n105 D 60 incidents 0\n106 D 60 incidents 0\n...........\n...........\n" }, { "code": null, "e": 9182, "s": 9033, "text": "We can cast the molten data into a new form where the aggregate of each type of ship for each year is created. It is done using the cast() function." }, { "code": null, "e": 9263, "s": 9182, "text": "recasted.ship <- cast(molten.ships, type+year~variable,sum)\nprint(recasted.ship)" }, { "code": null, "e": 9330, "s": 9263, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 10114, "s": 9330, "text": " type year period service incidents\n1 A 60 135 190 0\n2 A 65 135 2190 7\n3 A 70 135 4865 24\n4 A 75 135 2244 11\n5 B 60 135 62058 68\n6 B 65 135 48979 111\n7 B 70 135 20163 56\n8 B 75 135 7117 18\n9 C 60 135 1731 2\n10 C 65 135 1457 1\n11 C 70 135 2731 8\n12 C 75 135 274 1\n13 D 60 135 356 0\n14 D 65 135 480 0\n15 D 70 135 1557 13\n16 D 75 135 2051 4\n17 E 60 135 45 0\n18 E 65 135 1226 14\n19 E 70 135 3318 17\n20 E 75 135 542 1\n" }, { "code": null, "e": 10147, "s": 10114, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 10162, "s": 10147, "text": " Nishant Malik" }, { "code": null, "e": 10197, "s": 10162, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10212, "s": 10197, "text": " Nishant Malik" }, { "code": null, "e": 10247, "s": 10212, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10262, "s": 10247, "text": " Nishant Malik" }, { "code": null, "e": 10295, "s": 10262, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 10309, "s": 10295, "text": " Asif Hussain" }, { "code": null, "e": 10344, "s": 10309, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10359, "s": 10344, "text": " Nishant Malik" }, { "code": null, "e": 10394, "s": 10359, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 10408, "s": 10394, "text": " Asif Hussain" }, { "code": null, "e": 10415, "s": 10408, "text": " Print" }, { "code": null, "e": 10426, "s": 10415, "text": " Add Notes" } ]
Batch Script - EXIT
This batch command exits the DOS console. Exit @echo off echo "Hello World" exit The batch file will terminate and the command prompt window will close. Print Add Notes Bookmark this page
[ { "code": null, "e": 2211, "s": 2169, "text": "This batch command exits the DOS console." }, { "code": null, "e": 2217, "s": 2211, "text": "Exit\n" }, { "code": null, "e": 2253, "s": 2217, "text": "@echo off \necho \"Hello World\" \nexit" }, { "code": null, "e": 2325, "s": 2253, "text": "The batch file will terminate and the command prompt window will close." }, { "code": null, "e": 2332, "s": 2325, "text": " Print" }, { "code": null, "e": 2343, "s": 2332, "text": " Add Notes" } ]
Data Augmentation and Handling Huge Datasets with Keras: A Simple Way | by Lucas Robinet | Towards Data Science
In today’s tutorial, we will see a well-known technique to reduce overfitting in computer vision and a simple way to implement it : Data Augmentation. We will be going over the following. A Definition of Data Augmentation The Keras’ ImageDataGeneratorClass How to handle Datasets that does not fit into memory In the Deep Learning field, the performance of a model often improves with the amount of data that has been used to train it. Data Augmentation artificially increases the size of the training set by generating new variant of each training instance. It is a very well known and widespread technique for all computer vision problems that allows the creation of new training instances belonging to the same class as the base instance. Data augmentation forces the model to be more tolerant and it increases its capacity to generalize. It encompasses a wide range of techniques to slightly and randomly disrupt the original data. The disturbances are mostly translations, distortions, horizontal and vertical flips, changes in brightness, scale, ZCA or PCA whitening... With this technique, the network trains on slightly different images in each epoch. This technique is only used during training and not during the test phase. Data Augmentation results in a reduction in overfitting and an improvement in accuracy. On datasets with little data such as 17-flowers for example, using data augmentation can quickly lead to significant improvements in accuracy. I will describe two methods of data augmentation right away. The first method is to simply increase the size of your training set. This method consists in loading an image into memory, modifying it, taking the transformed image and the original image, and saving them both in the training file. This method can be useful but does not really help our model to generalize. The most widespread method is the second method also called On The Fly Data Augmentation [1]. It is this method that the ImageDataGenerator class implements. In this case, the model does not train on the initial instance but only on the generated instance which changes at each epoch to allow the network to better generalize. Here we are going to talk about this Keras class, see the modifications on the image that we can perform, how to train a model using data augmentation and all the code that goes with it. For all our first experiments, we are going to use this very nice photo from Robert Woeger This ImageDataGenerator class allows to generate batches of tensor image data with real-time data augmentation. The data will be looped over (in batches). Since this class is a Python Generator, if you are not familiar with this, I invite you to look at the RealPython tutorial. Now let’s take a closer look at how it works [2] : Some arguments are self-explanatory but for others it may be interesting to look at their effects and this is what we will do right now. Let’s start doing Data Augmentation! To perform shifts, the width_shift_range and height_shift_range arguments must be adjusted and set. The value of this parameter is the percentage of shift along the chosen dimension. Let’s look at the code to perform 20% shifts augmentation. Let’s go through the code together. We start by importing the necessary packages, here the Keras functions to load an image and convert it into a numpy array format. Line 9: we extend the dimension of our image, our ImageDataGenerator class expects to receive data with the shape (None, height, width, depth). The flow() method is then used to generate real-time data augmentation.We also indicate the folder to store the image with the argument save_to_dir and the format for our new training instance (here jpg). The argument save_prefix is used to sign the necessary images by adding this term before the generic name created by the Keras class. Knowing that imGen is a Python generator, you can generate a new image by calling the next() method. Here we generate 6 new images. You can easily visualize these new images with the following code. And here is the result ! A rotation augmentation randomly rotates the image by ± the value in degrees set to the rotation_range parameter. For instance, for a ± 30 degrees rotation, the code looks quite similar This method allows an image to be augmented by either randomly darkening or brightening it. It is all controlled by the brightness_range argument. Values less than 1.0 darken the image while values larger than 1.0 brighten the image. You know what happens next. And the result ! It’s quite complicated to go through all the possibilities of this class. However, here are a few examples [3]: Vertical and horizontal image flipping: quite self-explanatory. Simply set horizontal_flip and vertical_flip arguments to True. Image zooming: quite self-explanatory also. The zoom_range argument allows our image to be zoomed by a factor randomly between [1-zoom_range, 1+zoom_range] Image shearing: controls the maximum angle (in radians) in the counterclockwise direction in which our image will be randomly sheared. Feature Standardization: this is an important notion that we have not studied yet because it didn’t make sense until now since we were working on a single image. However, it is possible to standardize each pixel across an entire dataset for each feature. To do this you just have to set the featurewise_center and featurewise_std_normalization arguments to True. ZCA whitening: a whitening transform allows better visualization and understanding of the structure and features of our data. Explaining the ZCA operation in detail is outside the scope of this tutorial. However, if you are interested, feel free to read Learning Multiple Layers of Features from Tiny Images by Alex Krizhevsky. Whether there is a magic set of arguments that would work in any case is a question you are entitled to ask yourself. Unfortunately, the answer is no, as you expected the Data Augmentation must be performed according to the dataset. So, for example to recognize cars, allowing vertical flip would make no sense since the algorithm will never see flipped cars (unless you are starring in Inception right now, but that’s unlikely). However, if the objective is to know if jellyfish are presents within an image, then vertical flip augmentation remains a useful tool. However, here is a simple example that you can set up to start your Data Augmentation. Now that we know how to manipulate the Keras’ ImageDataGenerator class and are familiar with most of the Data Augmentation possibilities, let’s look at how to train a network with real-time Data Augmentation and training instances that change at each epoch. For this part, I took the code from the Keras Documentation [2] which treats the CIFAR-10 dataset. First, we load the dataset into memory and encode our labels. Then we define our ImageDataGenerator object with the Data Augmentation we want to achieve. If you want to perform standardization or a ZCA whitening, you have to use the fit method on your generator (see Line 9). Finally, we use the fit() method of our model with the standard syntax in order to apply image augmentation. The generated images aren’t generated at the same time, they are generated in batches for flexibility (i.e 32 in our case).So at each batch, 32 images will be randomly generated. We also have to define the steps_per_epoch argument, it determines the number of iterations of training per epoch. We set it naturally to (dataset size/batch size) in this case so the network is trained on the same number of images, as there are initially in the dataset, at each epoch.Then the parameters are the same as for classic training. Sometimes, or rather all the time in modern problems, the dataset is too big to fit into memory. With the exponential advance in the Deep Learning field, datasets are quite enormous and this growth in GigaBytes results in a very important issue: memory management. Keras’ ImageDataGenerator class allows to implement a solution where images are loaded and augmented in batch as the training progresses. Let’s see how to use it on the Animals Dataset First, your directories must be organized as follows. datasets/ animals/ train/ dogs/ dogs_00001.jpg ... cats/ cats_00001.jpg ... panda/ panda_00001.jpg val/ dogs/ dogs_00801.jpg ... cats/ cats_00801.jpg ... panda/ panda_00801.jpg ... Now we will use the method flow_from_directory. The flow_from_directory method takes into account by default the depth of our images. So, in our TARGET_SIZE we put only width and height: the dimensions to which all images found will be resized. This piece of code prints us a message that matches the information on our dataset. Found 2400 images belonging to 3 classes.Found 600 images belonging to 3 classes. So, everything seems to be good, it’s normal, it’s good! N.B: For the Test Generator, no data augmentation is applied, we simply normalize the pixels to be consistent with the data that will be used to train the network. The training code is quite similar to the one in the previous section. And that’s it ! In this tutorial we have seen what Data Augmentation is, its usefulness, the main methods and how to implement it with the ImageDataGenerator class. I presented two types of Data Augmentation in the first part. There are of course others, such as the combination of the two methods (widely used in behavioral cloning in particular). Then, we implement a code to manage a dataset too big to fit into memory. This method is very simple and proves useful in many cases. However, there is a major problem with this method, each image on the disk requires an I/O operation which slows down the training. Adding I/O latency is the last thing you want when you are training a deep neural network that already takes a lot of time. To overcome this problem, we can for example choose to store our dataset in an HDF5 file and then generate data from this file. This method will be the subject of a future tutorial. In the meantime, thank you for reading this article, I hope you found it useful. [1] A. Rosebrock, Keras ImageDataGenerator and Data Augmentation (2019), pyimagesearch [2] Keras ImageDataGenerator class [3] Jason Brownlee, Image Augmentation for Deep Learning with Keras (2016), Machine Learning Mastery
[ { "code": null, "e": 360, "s": 172, "text": "In today’s tutorial, we will see a well-known technique to reduce overfitting in computer vision and a simple way to implement it : Data Augmentation. We will be going over the following." }, { "code": null, "e": 394, "s": 360, "text": "A Definition of Data Augmentation" }, { "code": null, "e": 429, "s": 394, "text": "The Keras’ ImageDataGeneratorClass" }, { "code": null, "e": 482, "s": 429, "text": "How to handle Datasets that does not fit into memory" }, { "code": null, "e": 1108, "s": 482, "text": "In the Deep Learning field, the performance of a model often improves with the amount of data that has been used to train it. Data Augmentation artificially increases the size of the training set by generating new variant of each training instance. It is a very well known and widespread technique for all computer vision problems that allows the creation of new training instances belonging to the same class as the base instance. Data augmentation forces the model to be more tolerant and it increases its capacity to generalize. It encompasses a wide range of techniques to slightly and randomly disrupt the original data." }, { "code": null, "e": 1248, "s": 1108, "text": "The disturbances are mostly translations, distortions, horizontal and vertical flips, changes in brightness, scale, ZCA or PCA whitening..." }, { "code": null, "e": 1407, "s": 1248, "text": "With this technique, the network trains on slightly different images in each epoch. This technique is only used during training and not during the test phase." }, { "code": null, "e": 1638, "s": 1407, "text": "Data Augmentation results in a reduction in overfitting and an improvement in accuracy. On datasets with little data such as 17-flowers for example, using data augmentation can quickly lead to significant improvements in accuracy." }, { "code": null, "e": 1699, "s": 1638, "text": "I will describe two methods of data augmentation right away." }, { "code": null, "e": 2009, "s": 1699, "text": "The first method is to simply increase the size of your training set. This method consists in loading an image into memory, modifying it, taking the transformed image and the original image, and saving them both in the training file. This method can be useful but does not really help our model to generalize." }, { "code": null, "e": 2336, "s": 2009, "text": "The most widespread method is the second method also called On The Fly Data Augmentation [1]. It is this method that the ImageDataGenerator class implements. In this case, the model does not train on the initial instance but only on the generated instance which changes at each epoch to allow the network to better generalize." }, { "code": null, "e": 2614, "s": 2336, "text": "Here we are going to talk about this Keras class, see the modifications on the image that we can perform, how to train a model using data augmentation and all the code that goes with it. For all our first experiments, we are going to use this very nice photo from Robert Woeger" }, { "code": null, "e": 2769, "s": 2614, "text": "This ImageDataGenerator class allows to generate batches of tensor image data with real-time data augmentation. The data will be looped over (in batches)." }, { "code": null, "e": 2944, "s": 2769, "text": "Since this class is a Python Generator, if you are not familiar with this, I invite you to look at the RealPython tutorial. Now let’s take a closer look at how it works [2] :" }, { "code": null, "e": 3118, "s": 2944, "text": "Some arguments are self-explanatory but for others it may be interesting to look at their effects and this is what we will do right now. Let’s start doing Data Augmentation!" }, { "code": null, "e": 3360, "s": 3118, "text": "To perform shifts, the width_shift_range and height_shift_range arguments must be adjusted and set. The value of this parameter is the percentage of shift along the chosen dimension. Let’s look at the code to perform 20% shifts augmentation." }, { "code": null, "e": 3396, "s": 3360, "text": "Let’s go through the code together." }, { "code": null, "e": 3526, "s": 3396, "text": "We start by importing the necessary packages, here the Keras functions to load an image and convert it into a numpy array format." }, { "code": null, "e": 3670, "s": 3526, "text": "Line 9: we extend the dimension of our image, our ImageDataGenerator class expects to receive data with the shape (None, height, width, depth)." }, { "code": null, "e": 4009, "s": 3670, "text": "The flow() method is then used to generate real-time data augmentation.We also indicate the folder to store the image with the argument save_to_dir and the format for our new training instance (here jpg). The argument save_prefix is used to sign the necessary images by adding this term before the generic name created by the Keras class." }, { "code": null, "e": 4141, "s": 4009, "text": "Knowing that imGen is a Python generator, you can generate a new image by calling the next() method. Here we generate 6 new images." }, { "code": null, "e": 4208, "s": 4141, "text": "You can easily visualize these new images with the following code." }, { "code": null, "e": 4233, "s": 4208, "text": "And here is the result !" }, { "code": null, "e": 4419, "s": 4233, "text": "A rotation augmentation randomly rotates the image by ± the value in degrees set to the rotation_range parameter. For instance, for a ± 30 degrees rotation, the code looks quite similar" }, { "code": null, "e": 4653, "s": 4419, "text": "This method allows an image to be augmented by either randomly darkening or brightening it. It is all controlled by the brightness_range argument. Values less than 1.0 darken the image while values larger than 1.0 brighten the image." }, { "code": null, "e": 4681, "s": 4653, "text": "You know what happens next." }, { "code": null, "e": 4698, "s": 4681, "text": "And the result !" }, { "code": null, "e": 4810, "s": 4698, "text": "It’s quite complicated to go through all the possibilities of this class. However, here are a few examples [3]:" }, { "code": null, "e": 4938, "s": 4810, "text": "Vertical and horizontal image flipping: quite self-explanatory. Simply set horizontal_flip and vertical_flip arguments to True." }, { "code": null, "e": 5094, "s": 4938, "text": "Image zooming: quite self-explanatory also. The zoom_range argument allows our image to be zoomed by a factor randomly between [1-zoom_range, 1+zoom_range]" }, { "code": null, "e": 5229, "s": 5094, "text": "Image shearing: controls the maximum angle (in radians) in the counterclockwise direction in which our image will be randomly sheared." }, { "code": null, "e": 5592, "s": 5229, "text": "Feature Standardization: this is an important notion that we have not studied yet because it didn’t make sense until now since we were working on a single image. However, it is possible to standardize each pixel across an entire dataset for each feature. To do this you just have to set the featurewise_center and featurewise_std_normalization arguments to True." }, { "code": null, "e": 5920, "s": 5592, "text": "ZCA whitening: a whitening transform allows better visualization and understanding of the structure and features of our data. Explaining the ZCA operation in detail is outside the scope of this tutorial. However, if you are interested, feel free to read Learning Multiple Layers of Features from Tiny Images by Alex Krizhevsky." }, { "code": null, "e": 6485, "s": 5920, "text": "Whether there is a magic set of arguments that would work in any case is a question you are entitled to ask yourself. Unfortunately, the answer is no, as you expected the Data Augmentation must be performed according to the dataset. So, for example to recognize cars, allowing vertical flip would make no sense since the algorithm will never see flipped cars (unless you are starring in Inception right now, but that’s unlikely). However, if the objective is to know if jellyfish are presents within an image, then vertical flip augmentation remains a useful tool." }, { "code": null, "e": 6572, "s": 6485, "text": "However, here is a simple example that you can set up to start your Data Augmentation." }, { "code": null, "e": 6929, "s": 6572, "text": "Now that we know how to manipulate the Keras’ ImageDataGenerator class and are familiar with most of the Data Augmentation possibilities, let’s look at how to train a network with real-time Data Augmentation and training instances that change at each epoch. For this part, I took the code from the Keras Documentation [2] which treats the CIFAR-10 dataset." }, { "code": null, "e": 7083, "s": 6929, "text": "First, we load the dataset into memory and encode our labels. Then we define our ImageDataGenerator object with the Data Augmentation we want to achieve." }, { "code": null, "e": 7205, "s": 7083, "text": "If you want to perform standardization or a ZCA whitening, you have to use the fit method on your generator (see Line 9)." }, { "code": null, "e": 7837, "s": 7205, "text": "Finally, we use the fit() method of our model with the standard syntax in order to apply image augmentation. The generated images aren’t generated at the same time, they are generated in batches for flexibility (i.e 32 in our case).So at each batch, 32 images will be randomly generated. We also have to define the steps_per_epoch argument, it determines the number of iterations of training per epoch. We set it naturally to (dataset size/batch size) in this case so the network is trained on the same number of images, as there are initially in the dataset, at each epoch.Then the parameters are the same as for classic training." }, { "code": null, "e": 7934, "s": 7837, "text": "Sometimes, or rather all the time in modern problems, the dataset is too big to fit into memory." }, { "code": null, "e": 8287, "s": 7934, "text": "With the exponential advance in the Deep Learning field, datasets are quite enormous and this growth in GigaBytes results in a very important issue: memory management. Keras’ ImageDataGenerator class allows to implement a solution where images are loaded and augmented in batch as the training progresses. Let’s see how to use it on the Animals Dataset" }, { "code": null, "e": 8341, "s": 8287, "text": "First, your directories must be organized as follows." }, { "code": null, "e": 8774, "s": 8341, "text": "datasets/ animals/ train/ dogs/ dogs_00001.jpg ... cats/ cats_00001.jpg ... panda/ panda_00001.jpg val/ dogs/ dogs_00801.jpg ... cats/ cats_00801.jpg ... panda/ panda_00801.jpg ..." }, { "code": null, "e": 8822, "s": 8774, "text": "Now we will use the method flow_from_directory." }, { "code": null, "e": 9103, "s": 8822, "text": "The flow_from_directory method takes into account by default the depth of our images. So, in our TARGET_SIZE we put only width and height: the dimensions to which all images found will be resized. This piece of code prints us a message that matches the information on our dataset." }, { "code": null, "e": 9185, "s": 9103, "text": "Found 2400 images belonging to 3 classes.Found 600 images belonging to 3 classes." }, { "code": null, "e": 9242, "s": 9185, "text": "So, everything seems to be good, it’s normal, it’s good!" }, { "code": null, "e": 9406, "s": 9242, "text": "N.B: For the Test Generator, no data augmentation is applied, we simply normalize the pixels to be consistent with the data that will be used to train the network." }, { "code": null, "e": 9477, "s": 9406, "text": "The training code is quite similar to the one in the previous section." }, { "code": null, "e": 9493, "s": 9477, "text": "And that’s it !" }, { "code": null, "e": 9826, "s": 9493, "text": "In this tutorial we have seen what Data Augmentation is, its usefulness, the main methods and how to implement it with the ImageDataGenerator class. I presented two types of Data Augmentation in the first part. There are of course others, such as the combination of the two methods (widely used in behavioral cloning in particular)." }, { "code": null, "e": 10216, "s": 9826, "text": "Then, we implement a code to manage a dataset too big to fit into memory. This method is very simple and proves useful in many cases. However, there is a major problem with this method, each image on the disk requires an I/O operation which slows down the training. Adding I/O latency is the last thing you want when you are training a deep neural network that already takes a lot of time." }, { "code": null, "e": 10398, "s": 10216, "text": "To overcome this problem, we can for example choose to store our dataset in an HDF5 file and then generate data from this file. This method will be the subject of a future tutorial." }, { "code": null, "e": 10479, "s": 10398, "text": "In the meantime, thank you for reading this article, I hope you found it useful." }, { "code": null, "e": 10566, "s": 10479, "text": "[1] A. Rosebrock, Keras ImageDataGenerator and Data Augmentation (2019), pyimagesearch" }, { "code": null, "e": 10601, "s": 10566, "text": "[2] Keras ImageDataGenerator class" } ]
Pneumonia Detection using Convolutional Neural Networks | by Nischal Madiraju | Towards Data Science
With the completion of my AIML course, I wanted to put my newfound knowledge to use and work on some side-projects which will both help me get some practical exposure in the field and either solve an interesting real-life problem or have some sort of practical usefulness to it. On this quest to find a project that fits my need I had finally decided that I will build a convolutional neural network that detects pneumonia by looking at chest X-ray images. Pneumonia is a form of an acute respiratory infection that affects the lungs. The lungs are made up of small sacs called alveoli, which fill with air when a healthy person breathes. When an individual has pneumonia, the alveoli are filled with pus and fluid, which makes breathing painful and limits oxygen intake. Pneumonia is the single largest infectious cause of death in children worldwide. Pneumonia killed 808 694 children under the age of 5 in 2017, accounting for 15% of all deaths of children under five years old. Pneumonia affects children and families everywhere but is most prevalent in South Asia and sub-Saharan Africa. With these facts serving as an inspiration I had started working on my project: To start off with I needed to figure out where I can build and run the code as my systems specs were not sufficient to handle the amount of computational power it takes to build a model so I used Google’s Colab. Colab allows you to write and execute Python in your browser, with Zero configuration required Free access to GPUs Easy sharing Whether you’re a student, a data scientist or an AI researcher, Colab can make your work easier. Note: Need API In the below code I have also mentioned how to access the dataset from Kaggle but the important things to note are: Have your API key file i.e. ‘kaggle.json’ readyWith this method, every time the runtime resets in google collab you will lose all your files and the generated model so once done always download your model file and after every reset remember to re-import the dataset Have your API key file i.e. ‘kaggle.json’ ready With this method, every time the runtime resets in google collab you will lose all your files and the generated model so once done always download your model file and after every reset remember to re-import the dataset When you submit an X-Ray Image of a 5-year-old kid’s chest, the algorithm should be able to predict with high accuracy, if the patient has Pneumonia. First, you have to upload your API key file on to your Jupyter notebook in Colab: Next, import the dataset from Kaggle and unzip it: from google.colab import filesfiles.upload()!pip install -q kaggle !mkdir -p ~/.kaggle !cp kaggle.json ~/.kaggle/ !kaggle datasets download -d paultimothymooney/chest-xray-pneumonia!unzip /content/chest-xray-pneumonia.zip I have used the Chest X-Ray Images (Pneumonia) dataset by Paul Mooney as the data was already conveniently split into the train, test, and val: Train -contains the training data/images for teaching our model. Val — contains images that we will use to validate our model. The purpose of this data set is to prevent our model from overfitting. Overfitting happens when a model learns the detail and noise in the training data to the extent that it negatively impacts the performance of the model on new data. This means that the noise or random fluctuations in the training data is picked up and learned as concepts by the model. The problem is that these concepts do not apply to new data and negatively impact the model’s ability to generalize. Test — this contains the data that we use to test the model once it has learned the relationships between the images and their label (Pneumonia/Not-Pneumonia) Now, let us start by importing all the required libraries: from keras.models import Sequentialfrom keras.layers import Conv2Dfrom keras.layers import MaxPooling2Dfrom keras.layers import Flattenfrom keras.layers import Densefrom keras.preprocessing.image import ImageDataGeneratorimport numpy as npfrom keras.preprocessing import imageimport osimport matplotlib.pyplot as pltimport cv2 The Keras Python library makes creating deep learning models fast and easy. The sequential API allows you to create models layer-by-layer for most problems. It is limited in that it does not allow you to create models that share layers or have multiple inputs or outputs.Keras Conv2D is a 2D Convolution Layer, this layer creates a convolution kernel that is wind with layers input which helps produce a tensor of outputs. (Note:- Kernel: In image processing kernel is a convolution matrix or masks which can be used for blurring, sharpening, embossing, edge detection and more by doing a convolution between a kernel and an image.)MaxPooling2D from keras.layers, which is used for pooling operation. For building this particular neural network, we are using a Maxpooling function, there exist different types of pooling operations like Min Pooling, Mean Pooling, etc. Here in MaxPooling we need the maximum value pixel from the respective region of interest.Flatten from keras.layers, which is used for Flattening. Flattening is the process of converting all the resultant 2-dimensional arrays into a single long continuous linear vector.Dense from keras.layers, which is used to perform the full connection of the neural networkImageDataGenerator, which Takes a batch of images and applies a series of random transformations to each image in the batch (including random rotation, resizing, shearing, etc.) and then Replacing the original batch with the new, randomly transformed batch for training the CNN. The Keras Python library makes creating deep learning models fast and easy. The sequential API allows you to create models layer-by-layer for most problems. It is limited in that it does not allow you to create models that share layers or have multiple inputs or outputs. Keras Conv2D is a 2D Convolution Layer, this layer creates a convolution kernel that is wind with layers input which helps produce a tensor of outputs. (Note:- Kernel: In image processing kernel is a convolution matrix or masks which can be used for blurring, sharpening, embossing, edge detection and more by doing a convolution between a kernel and an image.) MaxPooling2D from keras.layers, which is used for pooling operation. For building this particular neural network, we are using a Maxpooling function, there exist different types of pooling operations like Min Pooling, Mean Pooling, etc. Here in MaxPooling we need the maximum value pixel from the respective region of interest. Flatten from keras.layers, which is used for Flattening. Flattening is the process of converting all the resultant 2-dimensional arrays into a single long continuous linear vector. Dense from keras.layers, which is used to perform the full connection of the neural network ImageDataGenerator, which Takes a batch of images and applies a series of random transformations to each image in the batch (including random rotation, resizing, shearing, etc.) and then Replacing the original batch with the new, randomly transformed batch for training the CNN. I have first defined two variables that hold the values of image dimensions that I am going to use and the batch size I am going to use: img_dims = 64batch_size = 32 I have then created an object of the sequential class and have started with coding the convolutional step: classifier = Sequential()classifier.add(Conv2D(32, (3, 3), input_shape = (img_dims, img_dims, 3), activation = 'relu'))classifier.add(MaxPooling2D(pool_size = (2, 2)))classifier.add(Flatten())classifier.add(Dense(units = 128, activation = 'relu'))classifier.add(Dense(units = 1, activation = 'sigmoid')) I then took the classifier object and added a convolution layer by using the “Conv2D” function. The Conv2D function is taking 4 arguments: the first is filter this is a mandatory Conv2D parameter that defines the numbers of filters that convolutional layers will learn from i.e 32 here, filters are taken to slice through the image and map them one by one and learn different portions of an input image. Imagine a small filter sliding left to right across the image from top to bottom and that moving filter is looking for, say, a dark edge. Each time a match is found, it is mapped out onto an output image.the second argument is the shape each filter is going to be i.e 3x3 here,the third is the input shape and the type of image(RGB or Black and White)of each image i.e the input image our CNN is going to be taking is of a 64x64 resolution and “3” stands for RGB, which is a color imagethe fourth argument is the activation function we want to use, here ‘relu’ stands for a Rectified Linear Unit function. The activation function is a node that helps to decide if the neuron would fire or not. Relu sets all negative values in the matrix x to zero and all other values are kept constant. the first is filter this is a mandatory Conv2D parameter that defines the numbers of filters that convolutional layers will learn from i.e 32 here, filters are taken to slice through the image and map them one by one and learn different portions of an input image. Imagine a small filter sliding left to right across the image from top to bottom and that moving filter is looking for, say, a dark edge. Each time a match is found, it is mapped out onto an output image. the second argument is the shape each filter is going to be i.e 3x3 here, the third is the input shape and the type of image(RGB or Black and White)of each image i.e the input image our CNN is going to be taking is of a 64x64 resolution and “3” stands for RGB, which is a color image the fourth argument is the activation function we want to use, here ‘relu’ stands for a Rectified Linear Unit function. The activation function is a node that helps to decide if the neuron would fire or not. Relu sets all negative values in the matrix x to zero and all other values are kept constant. Now I perform pooling operation on the resultant feature maps I got after the convolution operation is done on an image. The primary aim of a pooling operation is to reduce the size of the images as much as possible. Next, I convert all the pooled images into a continuous vector through Flattening. Flattening is a very important step to understand. What we are basically doing here is taking the 2-D array, i.e pooled image pixels and converting them to a one-dimensional single vector. Now, to create a fully connected layer I have connected the set of nodes I got after the flattening step, these nodes will act as an input layer to these fully-connected layers. Dense is the function to add a fully connected layer, ‘units’ is where we define the number of nodes that should be present in this hidden layer. Then I have initialized the output layer which consists of a single node giving me the respective output Once building the CNN model is finished it is time for compiling it: classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) Here we have used the following parameters: Adam is an optimization algorithm that can be used instead of the classical stochastic gradient descent procedure to update network weights iterative based on training data.Cross-entropy loss, or log loss, measure the performance of a classification model whose output is a probability value between 0 and 1. Cross-entropy loss increases as the predicted probability diverge from the actual label.Finally, the metrics parameter is to choose the performance metric. Adam is an optimization algorithm that can be used instead of the classical stochastic gradient descent procedure to update network weights iterative based on training data. Cross-entropy loss, or log loss, measure the performance of a classification model whose output is a probability value between 0 and 1. Cross-entropy loss increases as the predicted probability diverge from the actual label. Finally, the metrics parameter is to choose the performance metric. Before we get into fitting our CNN to image dataset we need to pre-process the images to prevent overfitting: input_path = '/content/chest_xray/'train_datagen = ImageDataGenerator(rescale = 1./255,shear_range = 0.2,zoom_range = 0.2,horizontal_flip = True)test_datagen = ImageDataGenerator(rescale = 1./255)training_set = train_datagen.flow_from_directory(directory=input_path+'train',target_size = (img_dims, img_dims),batch_size = batch_size,class_mode = 'binary')test_set = test_datagen.flow_from_directory(directory=input_path+'test',target_size = (img_dims, img_dims),batch_size = batch_size,class_mode = 'binary') For this task we have used the ImageDataGenerator of Keras and have passed the following parameters:rescale: rescaling factor. Defaults to None. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (after applying all other transformations).shear_range: Float. Shear Intensity (Shear angle in the counter-clockwise direction in degrees). Shearing used to transform the orientation of the image.zoom_range: Float or [lower, upper]. The range for random zoom.horizontal_flip: Boolean. Randomly flip inputs horizontally.flow_from_directory: Takes the path to a directory, and generates batches of augmented/normalized data. For this task we have used the ImageDataGenerator of Keras and have passed the following parameters: rescale: rescaling factor. Defaults to None. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (after applying all other transformations). shear_range: Float. Shear Intensity (Shear angle in the counter-clockwise direction in degrees). Shearing used to transform the orientation of the image. zoom_range: Float or [lower, upper]. The range for random zoom. horizontal_flip: Boolean. Randomly flip inputs horizontally. flow_from_directory: Takes the path to a directory, and generates batches of augmented/normalized data. Now to fit the data to the CNN model: epochs = 10 hist = classifier.fit_generator( training_set, steps_per_epoch=training_set.samples // batch_size, epochs=epochs, validation_data=test_set, validation_steps= test_set.samples) In the above code, ‘steps_per_epoch’ holds the number of training images, i.e the number of images the training_set folder contains.And ‘epochs’, A single epoch is a single step in training a neural network; in other words, when a neural network is trained on every training samples only in one pass we say that one epoch is finished. So the training process should consist of more than one epoch. In the above code, ‘steps_per_epoch’ holds the number of training images, i.e the number of images the training_set folder contains. And ‘epochs’, A single epoch is a single step in training a neural network; in other words, when a neural network is trained on every training samples only in one pass we say that one epoch is finished. So the training process should consist of more than one epoch. Once you have finally built and trained your model you can pass images to classifier.predict()(i.e. [modelname].predict()) function and get the predictions. You can also save your model for future use by using the classifier.save()(i.e. [modelname].save()) If you are interested in the code, you can check out GitHub I was able to achieve: Higher accuracy can be achieved by changing the number of layers used in the network. Another way to improve the accuracy would be to change the hyperparameters accordingly. It is fairly easy for any developer with decent programming skills to create a Machine Learning models which could be useful to millions of people. Much better results have been achieved by professionals out there. As a beginner, I was able to achieve an accuracy of 89%, which is clearly not bad. But in order to be used in the real world, by millions of people, 89% accuracy means it will misdiagnose roughly 1,00,000 cases.
[ { "code": null, "e": 629, "s": 172, "text": "With the completion of my AIML course, I wanted to put my newfound knowledge to use and work on some side-projects which will both help me get some practical exposure in the field and either solve an interesting real-life problem or have some sort of practical usefulness to it. On this quest to find a project that fits my need I had finally decided that I will build a convolutional neural network that detects pneumonia by looking at chest X-ray images." }, { "code": null, "e": 944, "s": 629, "text": "Pneumonia is a form of an acute respiratory infection that affects the lungs. The lungs are made up of small sacs called alveoli, which fill with air when a healthy person breathes. When an individual has pneumonia, the alveoli are filled with pus and fluid, which makes breathing painful and limits oxygen intake." }, { "code": null, "e": 1265, "s": 944, "text": "Pneumonia is the single largest infectious cause of death in children worldwide. Pneumonia killed 808 694 children under the age of 5 in 2017, accounting for 15% of all deaths of children under five years old. Pneumonia affects children and families everywhere but is most prevalent in South Asia and sub-Saharan Africa." }, { "code": null, "e": 1345, "s": 1265, "text": "With these facts serving as an inspiration I had started working on my project:" }, { "code": null, "e": 1624, "s": 1345, "text": "To start off with I needed to figure out where I can build and run the code as my systems specs were not sufficient to handle the amount of computational power it takes to build a model so I used Google’s Colab. Colab allows you to write and execute Python in your browser, with" }, { "code": null, "e": 1652, "s": 1624, "text": "Zero configuration required" }, { "code": null, "e": 1672, "s": 1652, "text": "Free access to GPUs" }, { "code": null, "e": 1685, "s": 1672, "text": "Easy sharing" }, { "code": null, "e": 1782, "s": 1685, "text": "Whether you’re a student, a data scientist or an AI researcher, Colab can make your work easier." }, { "code": null, "e": 1797, "s": 1782, "text": "Note: Need API" }, { "code": null, "e": 1913, "s": 1797, "text": "In the below code I have also mentioned how to access the dataset from Kaggle but the important things to note are:" }, { "code": null, "e": 2179, "s": 1913, "text": "Have your API key file i.e. ‘kaggle.json’ readyWith this method, every time the runtime resets in google collab you will lose all your files and the generated model so once done always download your model file and after every reset remember to re-import the dataset" }, { "code": null, "e": 2227, "s": 2179, "text": "Have your API key file i.e. ‘kaggle.json’ ready" }, { "code": null, "e": 2446, "s": 2227, "text": "With this method, every time the runtime resets in google collab you will lose all your files and the generated model so once done always download your model file and after every reset remember to re-import the dataset" }, { "code": null, "e": 2596, "s": 2446, "text": "When you submit an X-Ray Image of a 5-year-old kid’s chest, the algorithm should be able to predict with high accuracy, if the patient has Pneumonia." }, { "code": null, "e": 2678, "s": 2596, "text": "First, you have to upload your API key file on to your Jupyter notebook in Colab:" }, { "code": null, "e": 2729, "s": 2678, "text": "Next, import the dataset from Kaggle and unzip it:" }, { "code": null, "e": 2951, "s": 2729, "text": "from google.colab import filesfiles.upload()!pip install -q kaggle !mkdir -p ~/.kaggle !cp kaggle.json ~/.kaggle/ !kaggle datasets download -d paultimothymooney/chest-xray-pneumonia!unzip /content/chest-xray-pneumonia.zip" }, { "code": null, "e": 3095, "s": 2951, "text": "I have used the Chest X-Ray Images (Pneumonia) dataset by Paul Mooney as the data was already conveniently split into the train, test, and val:" }, { "code": null, "e": 3160, "s": 3095, "text": "Train -contains the training data/images for teaching our model." }, { "code": null, "e": 3696, "s": 3160, "text": "Val — contains images that we will use to validate our model. The purpose of this data set is to prevent our model from overfitting. Overfitting happens when a model learns the detail and noise in the training data to the extent that it negatively impacts the performance of the model on new data. This means that the noise or random fluctuations in the training data is picked up and learned as concepts by the model. The problem is that these concepts do not apply to new data and negatively impact the model’s ability to generalize." }, { "code": null, "e": 3855, "s": 3696, "text": "Test — this contains the data that we use to test the model once it has learned the relationships between the images and their label (Pneumonia/Not-Pneumonia)" }, { "code": null, "e": 3914, "s": 3855, "text": "Now, let us start by importing all the required libraries:" }, { "code": null, "e": 4241, "s": 3914, "text": "from keras.models import Sequentialfrom keras.layers import Conv2Dfrom keras.layers import MaxPooling2Dfrom keras.layers import Flattenfrom keras.layers import Densefrom keras.preprocessing.image import ImageDataGeneratorimport numpy as npfrom keras.preprocessing import imageimport osimport matplotlib.pyplot as pltimport cv2" }, { "code": null, "e": 5750, "s": 4241, "text": "The Keras Python library makes creating deep learning models fast and easy. The sequential API allows you to create models layer-by-layer for most problems. It is limited in that it does not allow you to create models that share layers or have multiple inputs or outputs.Keras Conv2D is a 2D Convolution Layer, this layer creates a convolution kernel that is wind with layers input which helps produce a tensor of outputs. (Note:- Kernel: In image processing kernel is a convolution matrix or masks which can be used for blurring, sharpening, embossing, edge detection and more by doing a convolution between a kernel and an image.)MaxPooling2D from keras.layers, which is used for pooling operation. For building this particular neural network, we are using a Maxpooling function, there exist different types of pooling operations like Min Pooling, Mean Pooling, etc. Here in MaxPooling we need the maximum value pixel from the respective region of interest.Flatten from keras.layers, which is used for Flattening. Flattening is the process of converting all the resultant 2-dimensional arrays into a single long continuous linear vector.Dense from keras.layers, which is used to perform the full connection of the neural networkImageDataGenerator, which Takes a batch of images and applies a series of random transformations to each image in the batch (including random rotation, resizing, shearing, etc.) and then Replacing the original batch with the new, randomly transformed batch for training the CNN." }, { "code": null, "e": 6022, "s": 5750, "text": "The Keras Python library makes creating deep learning models fast and easy. The sequential API allows you to create models layer-by-layer for most problems. It is limited in that it does not allow you to create models that share layers or have multiple inputs or outputs." }, { "code": null, "e": 6384, "s": 6022, "text": "Keras Conv2D is a 2D Convolution Layer, this layer creates a convolution kernel that is wind with layers input which helps produce a tensor of outputs. (Note:- Kernel: In image processing kernel is a convolution matrix or masks which can be used for blurring, sharpening, embossing, edge detection and more by doing a convolution between a kernel and an image.)" }, { "code": null, "e": 6712, "s": 6384, "text": "MaxPooling2D from keras.layers, which is used for pooling operation. For building this particular neural network, we are using a Maxpooling function, there exist different types of pooling operations like Min Pooling, Mean Pooling, etc. Here in MaxPooling we need the maximum value pixel from the respective region of interest." }, { "code": null, "e": 6893, "s": 6712, "text": "Flatten from keras.layers, which is used for Flattening. Flattening is the process of converting all the resultant 2-dimensional arrays into a single long continuous linear vector." }, { "code": null, "e": 6985, "s": 6893, "text": "Dense from keras.layers, which is used to perform the full connection of the neural network" }, { "code": null, "e": 7264, "s": 6985, "text": "ImageDataGenerator, which Takes a batch of images and applies a series of random transformations to each image in the batch (including random rotation, resizing, shearing, etc.) and then Replacing the original batch with the new, randomly transformed batch for training the CNN." }, { "code": null, "e": 7401, "s": 7264, "text": "I have first defined two variables that hold the values of image dimensions that I am going to use and the batch size I am going to use:" }, { "code": null, "e": 7430, "s": 7401, "text": "img_dims = 64batch_size = 32" }, { "code": null, "e": 7537, "s": 7430, "text": "I have then created an object of the sequential class and have started with coding the convolutional step:" }, { "code": null, "e": 7841, "s": 7537, "text": "classifier = Sequential()classifier.add(Conv2D(32, (3, 3), input_shape = (img_dims, img_dims, 3), activation = 'relu'))classifier.add(MaxPooling2D(pool_size = (2, 2)))classifier.add(Flatten())classifier.add(Dense(units = 128, activation = 'relu'))classifier.add(Dense(units = 1, activation = 'sigmoid'))" }, { "code": null, "e": 7980, "s": 7841, "text": "I then took the classifier object and added a convolution layer by using the “Conv2D” function. The Conv2D function is taking 4 arguments:" }, { "code": null, "e": 9033, "s": 7980, "text": "the first is filter this is a mandatory Conv2D parameter that defines the numbers of filters that convolutional layers will learn from i.e 32 here, filters are taken to slice through the image and map them one by one and learn different portions of an input image. Imagine a small filter sliding left to right across the image from top to bottom and that moving filter is looking for, say, a dark edge. Each time a match is found, it is mapped out onto an output image.the second argument is the shape each filter is going to be i.e 3x3 here,the third is the input shape and the type of image(RGB or Black and White)of each image i.e the input image our CNN is going to be taking is of a 64x64 resolution and “3” stands for RGB, which is a color imagethe fourth argument is the activation function we want to use, here ‘relu’ stands for a Rectified Linear Unit function. The activation function is a node that helps to decide if the neuron would fire or not. Relu sets all negative values in the matrix x to zero and all other values are kept constant." }, { "code": null, "e": 9503, "s": 9033, "text": "the first is filter this is a mandatory Conv2D parameter that defines the numbers of filters that convolutional layers will learn from i.e 32 here, filters are taken to slice through the image and map them one by one and learn different portions of an input image. Imagine a small filter sliding left to right across the image from top to bottom and that moving filter is looking for, say, a dark edge. Each time a match is found, it is mapped out onto an output image." }, { "code": null, "e": 9577, "s": 9503, "text": "the second argument is the shape each filter is going to be i.e 3x3 here," }, { "code": null, "e": 9787, "s": 9577, "text": "the third is the input shape and the type of image(RGB or Black and White)of each image i.e the input image our CNN is going to be taking is of a 64x64 resolution and “3” stands for RGB, which is a color image" }, { "code": null, "e": 10089, "s": 9787, "text": "the fourth argument is the activation function we want to use, here ‘relu’ stands for a Rectified Linear Unit function. The activation function is a node that helps to decide if the neuron would fire or not. Relu sets all negative values in the matrix x to zero and all other values are kept constant." }, { "code": null, "e": 10306, "s": 10089, "text": "Now I perform pooling operation on the resultant feature maps I got after the convolution operation is done on an image. The primary aim of a pooling operation is to reduce the size of the images as much as possible." }, { "code": null, "e": 10578, "s": 10306, "text": "Next, I convert all the pooled images into a continuous vector through Flattening. Flattening is a very important step to understand. What we are basically doing here is taking the 2-D array, i.e pooled image pixels and converting them to a one-dimensional single vector." }, { "code": null, "e": 10902, "s": 10578, "text": "Now, to create a fully connected layer I have connected the set of nodes I got after the flattening step, these nodes will act as an input layer to these fully-connected layers. Dense is the function to add a fully connected layer, ‘units’ is where we define the number of nodes that should be present in this hidden layer." }, { "code": null, "e": 11007, "s": 10902, "text": "Then I have initialized the output layer which consists of a single node giving me the respective output" }, { "code": null, "e": 11076, "s": 11007, "text": "Once building the CNN model is finished it is time for compiling it:" }, { "code": null, "e": 11169, "s": 11076, "text": "classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])" }, { "code": null, "e": 11213, "s": 11169, "text": "Here we have used the following parameters:" }, { "code": null, "e": 11678, "s": 11213, "text": "Adam is an optimization algorithm that can be used instead of the classical stochastic gradient descent procedure to update network weights iterative based on training data.Cross-entropy loss, or log loss, measure the performance of a classification model whose output is a probability value between 0 and 1. Cross-entropy loss increases as the predicted probability diverge from the actual label.Finally, the metrics parameter is to choose the performance metric." }, { "code": null, "e": 11852, "s": 11678, "text": "Adam is an optimization algorithm that can be used instead of the classical stochastic gradient descent procedure to update network weights iterative based on training data." }, { "code": null, "e": 12077, "s": 11852, "text": "Cross-entropy loss, or log loss, measure the performance of a classification model whose output is a probability value between 0 and 1. Cross-entropy loss increases as the predicted probability diverge from the actual label." }, { "code": null, "e": 12145, "s": 12077, "text": "Finally, the metrics parameter is to choose the performance metric." }, { "code": null, "e": 12255, "s": 12145, "text": "Before we get into fitting our CNN to image dataset we need to pre-process the images to prevent overfitting:" }, { "code": null, "e": 12764, "s": 12255, "text": "input_path = '/content/chest_xray/'train_datagen = ImageDataGenerator(rescale = 1./255,shear_range = 0.2,zoom_range = 0.2,horizontal_flip = True)test_datagen = ImageDataGenerator(rescale = 1./255)training_set = train_datagen.flow_from_directory(directory=input_path+'train',target_size = (img_dims, img_dims),batch_size = batch_size,class_mode = 'binary')test_set = test_datagen.flow_from_directory(directory=input_path+'test',target_size = (img_dims, img_dims),batch_size = batch_size,class_mode = 'binary')" }, { "code": null, "e": 13424, "s": 12764, "text": "For this task we have used the ImageDataGenerator of Keras and have passed the following parameters:rescale: rescaling factor. Defaults to None. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (after applying all other transformations).shear_range: Float. Shear Intensity (Shear angle in the counter-clockwise direction in degrees). Shearing used to transform the orientation of the image.zoom_range: Float or [lower, upper]. The range for random zoom.horizontal_flip: Boolean. Randomly flip inputs horizontally.flow_from_directory: Takes the path to a directory, and generates batches of augmented/normalized data." }, { "code": null, "e": 13525, "s": 13424, "text": "For this task we have used the ImageDataGenerator of Keras and have passed the following parameters:" }, { "code": null, "e": 13706, "s": 13525, "text": "rescale: rescaling factor. Defaults to None. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (after applying all other transformations)." }, { "code": null, "e": 13860, "s": 13706, "text": "shear_range: Float. Shear Intensity (Shear angle in the counter-clockwise direction in degrees). Shearing used to transform the orientation of the image." }, { "code": null, "e": 13924, "s": 13860, "text": "zoom_range: Float or [lower, upper]. The range for random zoom." }, { "code": null, "e": 13985, "s": 13924, "text": "horizontal_flip: Boolean. Randomly flip inputs horizontally." }, { "code": null, "e": 14089, "s": 13985, "text": "flow_from_directory: Takes the path to a directory, and generates batches of augmented/normalized data." }, { "code": null, "e": 14127, "s": 14089, "text": "Now to fit the data to the CNN model:" }, { "code": null, "e": 14351, "s": 14127, "text": "epochs = 10 hist = classifier.fit_generator( training_set, steps_per_epoch=training_set.samples // batch_size, epochs=epochs, validation_data=test_set, validation_steps= test_set.samples)" }, { "code": null, "e": 14749, "s": 14351, "text": "In the above code, ‘steps_per_epoch’ holds the number of training images, i.e the number of images the training_set folder contains.And ‘epochs’, A single epoch is a single step in training a neural network; in other words, when a neural network is trained on every training samples only in one pass we say that one epoch is finished. So the training process should consist of more than one epoch." }, { "code": null, "e": 14882, "s": 14749, "text": "In the above code, ‘steps_per_epoch’ holds the number of training images, i.e the number of images the training_set folder contains." }, { "code": null, "e": 15148, "s": 14882, "text": "And ‘epochs’, A single epoch is a single step in training a neural network; in other words, when a neural network is trained on every training samples only in one pass we say that one epoch is finished. So the training process should consist of more than one epoch." }, { "code": null, "e": 15305, "s": 15148, "text": "Once you have finally built and trained your model you can pass images to classifier.predict()(i.e. [modelname].predict()) function and get the predictions." }, { "code": null, "e": 15405, "s": 15305, "text": "You can also save your model for future use by using the classifier.save()(i.e. [modelname].save())" }, { "code": null, "e": 15465, "s": 15405, "text": "If you are interested in the code, you can check out GitHub" }, { "code": null, "e": 15488, "s": 15465, "text": "I was able to achieve:" }, { "code": null, "e": 15662, "s": 15488, "text": "Higher accuracy can be achieved by changing the number of layers used in the network. Another way to improve the accuracy would be to change the hyperparameters accordingly." }, { "code": null, "e": 15810, "s": 15662, "text": "It is fairly easy for any developer with decent programming skills to create a Machine Learning models which could be useful to millions of people." } ]
C++ program to find the sum of the series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!
In this tutorial, we will be discussing a program to find the sum of the given series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!. For this, we will be given with the value of n and our task is to add up every term starting from the first one to find the sum of the given series. #include <iostream> using namespace std; //calculating the sum of the series double calc_sum(int n) { int i; double sum = 0, fact=1; for (i = 1; i <= n; i++) fact = fact * i; sum += i/fact; return sum; } int main() { int n = 6; double res = calc_sum(n); cout << res << endl; return 0; } 0.00972222
[ { "code": null, "e": 1190, "s": 1062, "text": "In this tutorial, we will be discussing a program to find the sum of the given series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!." }, { "code": null, "e": 1339, "s": 1190, "text": "For this, we will be given with the value of n and our task is to add up every term starting from the first one to find the sum of the given series." }, { "code": null, "e": 1656, "s": 1339, "text": "#include <iostream>\nusing namespace std;\n//calculating the sum of the series\ndouble calc_sum(int n) {\n int i;\n double sum = 0, fact=1;\n for (i = 1; i <= n; i++)\n fact = fact * i;\n sum += i/fact;\n return sum;\n}\nint main() {\n int n = 6;\n double res = calc_sum(n);\n cout << res << endl;\n return 0;\n}" }, { "code": null, "e": 1667, "s": 1656, "text": "0.00972222" } ]
Finding sum of digits of a number until sum becomes single digit - GeeksforGeeks
13 Feb, 2022 Given a number n, we need to find the sum of its digits such that: If n < 10 digSum(n) = n Else digSum(n) = Sum(digSum(n)) Examples : Input : 1234 Output : 1 Explanation : The sum of 1+2+3+4 = 10, digSum(x) == 10 Hence ans will be 1+0 = 1 Input : 5674 Output : 4 A brute force approach is to sum all the digits until the sum < 10. Flowchart: Below is the brute force program to find the sum. C++ Java Python C# PHP Javascript // C++ program to find sum of// digits of a number until// sum becomes single digit.#include<bits/stdc++.h> using namespace std; int digSum(int n){ int sum = 0; // Loop to do sum while // sum is not less than // or equal to 9 while(n > 0 || sum > 9) { if(n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } return sum;} // Driver program to test the above functionint main(){ int n = 1234; cout << digSum(n); return 0;} // Java program to find sum of// digits of a number until// sum becomes single digit.import java.util.*; public class GfG { static int digSum(int n) { int sum = 0; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } return sum; } // Driver code public static void main(String argc[]) { int n = 1234; System.out.println(digSum(n)); }} // This code is contributed by Gitanjali. # Python program to find sum of# digits of a number until# sum becomes single digit.import math # method to find sum of digits# of a number until sum becomes# single digitdef digSum( n): sum = 0 while(n > 0 or sum > 9): if(n == 0): n = sum sum = 0 sum += n % 10 n /= 10 return sum # Driver methodn = 1234print (digSum(n)) # This code is contributed by Gitanjali. // C# program to find sum of// digits of a number until// sum becomes single digit.using System; class GFG { static int digSum(int n) { int sum = 0; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } return sum; } // Driver code public static void Main() { int n = 1234; Console.Write(digSum(n)); }} // This code is contributed by nitin mittal <?php// PHP program to find sum of// digits of a number until// sum becomes single digit. function digSum( $n){ $sum = 0; // Loop to do sum while // sum is not less than // or equal to 9 while($n > 0 || $sum > 9) { if($n == 0) { $n = $sum; $sum = 0; } $sum += $n % 10; $n = (int)$n / 10; } return $sum;} // Driver Code$n = 1234;echo digSum($n); // This code is contributed// by aj_36?> <script>// Javascript program to find sum of// digits of a number until// sum becomes single digit. let n = 1234; //Function to get sum of digits function getSum(n) { let sum = 0; while (n > 0 || sum > 9) { if(n == 0) { n = sum; sum = 0; } sum = sum + n % 10; n = Math.floor(n / 10); } return sum; } //function call document.write(getSum(n)); //This code is contributed by Surbhi Tyagi</script> Output : 1 So, another challenge is “Could you do it without any loop/recursion in O(1) runtime?” YES!!There exists a simple and elegant O(1) solution for this too. The answer is given simply:- If n == 0 return 0; If n % 9 == 0 digSum(n) = 9 Else digSum(n) = n % 9 How does the above logic works? The logic behind this approach is : To check if a number is divisible by 9, add the digits of the number and check if the sum is divisible by 9 or not. If yes, is the case, the number is divisible by 9, otherwise, it’s not. let’s take 27 i.e (2+7 = 9) hence divisible by 9.If a number n is divisible by 9, then the sum of its digit until the sum becomes a single digit is always 9. For example, Let, n = 2880 Sum of digits = 2 + 8 + 8 = 18: 18 = 1 + 8 = 9 Therefore,A number can be of the form 9x or 9x + k. For the first case, the answer is always 9. For the second case, and is always k which is the remainder left. The problem is widely known as the digit root problem. You may find this Wikipedia article useful. -> https://en.wikipedia.org/wiki/Digital_root Below is the implementation of the above idea : C++ Java Python3 C# PHP Javascript #include<bits/stdc++.h>using namespace std; int digSum(int n){ if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9);} // Driver program to test the above functionint main(){ int n = 9999; cout<<digSum(n); return 0;} import java.io.*; class GFG { static int digSum(int n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Driver program to test the above function public static void main (String[] args) { int n = 9999; System.out.println(digSum(n)); }} // This code is contributed by anuj_67. def digSum(n): if (n == 0): return 0 if (n % 9 == 0): return 9 else: return (n % 9) # Driver program to test the above functionn = 9999print(digSum(n)) # This code is contributed by# Smitha Dinesh Semwal using System; class GFG{ static int digSum(int n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Driver Code public static void Main () { int n = 9999; Console.Write(digSum(n)); }} // This code is contributed by aj_36 <?php function digSum($n){ if ($n == 0) return 0; return ($n % 9 == 0) ? 9 : ($n % 9);} // Driver program to test the above function$n = 9999;echo digSum($n); //This code is contributed by anuj_67.?> <script> function digSum(n){ if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9);} // Driver coden = 9999;document.write(digSum(n)); // This code is contributed by code_hunt </script> Output: 9 Related Post : https://www.geeksforgeeks.org/digital-rootrepeated-digital-sum-given-integer/ This article is contributed by Ayush Khanduri. 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. NishuAggarwal nitin mittal vt_m jit_t ShubhamMaurya3 mv15 surbhityagi15 code_hunt hainguyen3 boopathiraaja srthkngm Amazon number-digits number-theory Mathematical Technical Scripter Amazon number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo Operator (%) in C/C++ with Examples Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ Euclidean algorithms (Basic and Extended) The Knight's tour problem | Backtracking-1 Efficient program to print all prime factors of a given number Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube
[ { "code": null, "e": 24962, "s": 24934, "text": "\n13 Feb, 2022" }, { "code": null, "e": 25030, "s": 24962, "text": "Given a number n, we need to find the sum of its digits such that: " }, { "code": null, "e": 25107, "s": 25030, "text": "If n < 10 \n digSum(n) = n\nElse \n digSum(n) = Sum(digSum(n))" }, { "code": null, "e": 25119, "s": 25107, "text": "Examples : " }, { "code": null, "e": 25279, "s": 25119, "text": "Input : 1234\nOutput : 1\nExplanation : The sum of 1+2+3+4 = 10, \n digSum(x) == 10\n Hence ans will be 1+0 = 1\n\nInput : 5674\nOutput : 4 " }, { "code": null, "e": 25359, "s": 25279, "text": "A brute force approach is to sum all the digits until the sum < 10. Flowchart: " }, { "code": null, "e": 25410, "s": 25359, "text": "Below is the brute force program to find the sum. " }, { "code": null, "e": 25414, "s": 25410, "text": "C++" }, { "code": null, "e": 25419, "s": 25414, "text": "Java" }, { "code": null, "e": 25426, "s": 25419, "text": "Python" }, { "code": null, "e": 25429, "s": 25426, "text": "C#" }, { "code": null, "e": 25433, "s": 25429, "text": "PHP" }, { "code": null, "e": 25444, "s": 25433, "text": "Javascript" }, { "code": "// C++ program to find sum of// digits of a number until// sum becomes single digit.#include<bits/stdc++.h> using namespace std; int digSum(int n){ int sum = 0; // Loop to do sum while // sum is not less than // or equal to 9 while(n > 0 || sum > 9) { if(n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } return sum;} // Driver program to test the above functionint main(){ int n = 1234; cout << digSum(n); return 0;}", "e": 25963, "s": 25444, "text": null }, { "code": "// Java program to find sum of// digits of a number until// sum becomes single digit.import java.util.*; public class GfG { static int digSum(int n) { int sum = 0; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } return sum; } // Driver code public static void main(String argc[]) { int n = 1234; System.out.println(digSum(n)); }} // This code is contributed by Gitanjali.", "e": 26615, "s": 25963, "text": null }, { "code": "# Python program to find sum of# digits of a number until# sum becomes single digit.import math # method to find sum of digits# of a number until sum becomes# single digitdef digSum( n): sum = 0 while(n > 0 or sum > 9): if(n == 0): n = sum sum = 0 sum += n % 10 n /= 10 return sum # Driver methodn = 1234print (digSum(n)) # This code is contributed by Gitanjali.", "e": 27054, "s": 26615, "text": null }, { "code": "// C# program to find sum of// digits of a number until// sum becomes single digit.using System; class GFG { static int digSum(int n) { int sum = 0; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } return sum; } // Driver code public static void Main() { int n = 1234; Console.Write(digSum(n)); }} // This code is contributed by nitin mittal", "e": 27686, "s": 27054, "text": null }, { "code": "<?php// PHP program to find sum of// digits of a number until// sum becomes single digit. function digSum( $n){ $sum = 0; // Loop to do sum while // sum is not less than // or equal to 9 while($n > 0 || $sum > 9) { if($n == 0) { $n = $sum; $sum = 0; } $sum += $n % 10; $n = (int)$n / 10; } return $sum;} // Driver Code$n = 1234;echo digSum($n); // This code is contributed// by aj_36?>", "e": 28158, "s": 27686, "text": null }, { "code": "<script>// Javascript program to find sum of// digits of a number until// sum becomes single digit. let n = 1234; //Function to get sum of digits function getSum(n) { let sum = 0; while (n > 0 || sum > 9) { if(n == 0) { n = sum; sum = 0; } sum = sum + n % 10; n = Math.floor(n / 10); } return sum; } //function call document.write(getSum(n)); //This code is contributed by Surbhi Tyagi</script>", "e": 28680, "s": 28158, "text": null }, { "code": null, "e": 28690, "s": 28680, "text": "Output : " }, { "code": null, "e": 28692, "s": 28690, "text": "1" }, { "code": null, "e": 28779, "s": 28692, "text": "So, another challenge is “Could you do it without any loop/recursion in O(1) runtime?”" }, { "code": null, "e": 28876, "s": 28779, "text": "YES!!There exists a simple and elegant O(1) solution for this too. The answer is given simply:- " }, { "code": null, "e": 28981, "s": 28876, "text": "If n == 0\n return 0;\n\nIf n % 9 == 0 \n digSum(n) = 9\nElse \n digSum(n) = n % 9 " }, { "code": null, "e": 29014, "s": 28981, "text": "How does the above logic works? " }, { "code": null, "e": 29050, "s": 29014, "text": "The logic behind this approach is :" }, { "code": null, "e": 29239, "s": 29050, "text": "To check if a number is divisible by 9, add the digits of the number and check if the sum is divisible by 9 or not. If yes, is the case, the number is divisible by 9, otherwise, it’s not." }, { "code": null, "e": 29472, "s": 29239, "text": "let’s take 27 i.e (2+7 = 9) hence divisible by 9.If a number n is divisible by 9, then the sum of its digit until the sum becomes a single digit is always 9. For example, Let, n = 2880 Sum of digits = 2 + 8 + 8 = 18: 18 = 1 + 8 = 9" }, { "code": null, "e": 29634, "s": 29472, "text": "Therefore,A number can be of the form 9x or 9x + k. For the first case, the answer is always 9. For the second case, and is always k which is the remainder left." }, { "code": null, "e": 29689, "s": 29634, "text": "The problem is widely known as the digit root problem." }, { "code": null, "e": 29779, "s": 29689, "text": "You may find this Wikipedia article useful. -> https://en.wikipedia.org/wiki/Digital_root" }, { "code": null, "e": 29828, "s": 29779, "text": "Below is the implementation of the above idea : " }, { "code": null, "e": 29832, "s": 29828, "text": "C++" }, { "code": null, "e": 29837, "s": 29832, "text": "Java" }, { "code": null, "e": 29845, "s": 29837, "text": "Python3" }, { "code": null, "e": 29848, "s": 29845, "text": "C#" }, { "code": null, "e": 29852, "s": 29848, "text": "PHP" }, { "code": null, "e": 29863, "s": 29852, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std; int digSum(int n){ if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9);} // Driver program to test the above functionint main(){ int n = 9999; cout<<digSum(n); return 0;}", "e": 30103, "s": 29863, "text": null }, { "code": "import java.io.*; class GFG { static int digSum(int n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Driver program to test the above function public static void main (String[] args) { int n = 9999; System.out.println(digSum(n)); }} // This code is contributed by anuj_67.", "e": 30456, "s": 30103, "text": null }, { "code": "def digSum(n): if (n == 0): return 0 if (n % 9 == 0): return 9 else: return (n % 9) # Driver program to test the above functionn = 9999print(digSum(n)) # This code is contributed by# Smitha Dinesh Semwal", "e": 30690, "s": 30456, "text": null }, { "code": "using System; class GFG{ static int digSum(int n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Driver Code public static void Main () { int n = 9999; Console.Write(digSum(n)); }} // This code is contributed by aj_36", "e": 30991, "s": 30690, "text": null }, { "code": "<?php function digSum($n){ if ($n == 0) return 0; return ($n % 9 == 0) ? 9 : ($n % 9);} // Driver program to test the above function$n = 9999;echo digSum($n); //This code is contributed by anuj_67.?>", "e": 31204, "s": 30991, "text": null }, { "code": "<script> function digSum(n){ if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9);} // Driver coden = 9999;document.write(digSum(n)); // This code is contributed by code_hunt </script>", "e": 31418, "s": 31204, "text": null }, { "code": null, "e": 31427, "s": 31418, "text": "Output: " }, { "code": null, "e": 31429, "s": 31427, "text": "9" }, { "code": null, "e": 31522, "s": 31429, "text": "Related Post : https://www.geeksforgeeks.org/digital-rootrepeated-digital-sum-given-integer/" }, { "code": null, "e": 31945, "s": 31522, "text": "This article is contributed by Ayush Khanduri. 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": 31959, "s": 31945, "text": "NishuAggarwal" }, { "code": null, "e": 31972, "s": 31959, "text": "nitin mittal" }, { "code": null, "e": 31977, "s": 31972, "text": "vt_m" }, { "code": null, "e": 31983, "s": 31977, "text": "jit_t" }, { "code": null, "e": 31998, "s": 31983, "text": "ShubhamMaurya3" }, { "code": null, "e": 32003, "s": 31998, "text": "mv15" }, { "code": null, "e": 32017, "s": 32003, "text": "surbhityagi15" }, { "code": null, "e": 32027, "s": 32017, "text": "code_hunt" }, { "code": null, "e": 32038, "s": 32027, "text": "hainguyen3" }, { "code": null, "e": 32052, "s": 32038, "text": "boopathiraaja" }, { "code": null, "e": 32061, "s": 32052, "text": "srthkngm" }, { "code": null, "e": 32068, "s": 32061, "text": "Amazon" }, { "code": null, "e": 32082, "s": 32068, "text": "number-digits" }, { "code": null, "e": 32096, "s": 32082, "text": "number-theory" }, { "code": null, "e": 32109, "s": 32096, "text": "Mathematical" }, { "code": null, "e": 32128, "s": 32109, "text": "Technical Scripter" }, { "code": null, "e": 32135, "s": 32128, "text": "Amazon" }, { "code": null, "e": 32149, "s": 32135, "text": "number-theory" }, { "code": null, "e": 32162, "s": 32149, "text": "Mathematical" }, { "code": null, "e": 32260, "s": 32162, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32303, "s": 32260, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32352, "s": 32303, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32386, "s": 32352, "text": "Program for factorial of a number" }, { "code": null, "e": 32407, "s": 32386, "text": "Operators in C / C++" }, { "code": null, "e": 32449, "s": 32407, "text": "Euclidean algorithms (Basic and Extended)" }, { "code": null, "e": 32492, "s": 32449, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 32555, "s": 32492, "text": "Efficient program to print all prime factors of a given number" }, { "code": null, "e": 32608, "s": 32555, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 32645, "s": 32608, "text": "Minimum number of jumps to reach end" } ]
Java Program to calculate area of a Tetrahedron
A Tetrahedron is a polyhedron composed of four triangular faces, six straight edges, and four vertex corners. Following is the Java program to calculate area of a Tetrahedron − Live Demo import java.io.*; public class Demo{ static double tetra_vol(int side){ double my_vol = (Math.pow(side, 3) / (6 * Math.sqrt(2))); return my_vol; } public static void main(String[] args){ int side = 4; double my_vol = tetra_vol(side); my_vol = (double)Math.round(my_vol * 100) / 100; System.out.println("The area of tetrahedron is"); System.out.println(my_vol); } } The area of tetrahedron is 7.54 A class named Demo contains a static function named 'tetra_vol' which takes 'side' as a parameter. The formula to calculate area of a tetrahedron is ‘side’ cube/(6v2). This is computed and the output is returned. In the main function, the value of size is defined, and the function is called on this value. The output is printed on the console.
[ { "code": null, "e": 1172, "s": 1062, "text": "A Tetrahedron is a polyhedron composed of four triangular faces, six straight edges, and four vertex corners." }, { "code": null, "e": 1239, "s": 1172, "text": "Following is the Java program to calculate area of a Tetrahedron −" }, { "code": null, "e": 1250, "s": 1239, "text": " Live Demo" }, { "code": null, "e": 1669, "s": 1250, "text": "import java.io.*;\npublic class Demo{\n static double tetra_vol(int side){\n double my_vol = (Math.pow(side, 3) / (6 * Math.sqrt(2)));\n return my_vol;\n }\n public static void main(String[] args){\n int side = 4;\n double my_vol = tetra_vol(side);\n my_vol = (double)Math.round(my_vol * 100) / 100;\n System.out.println(\"The area of tetrahedron is\");\n System.out.println(my_vol);\n }\n}" }, { "code": null, "e": 1701, "s": 1669, "text": "The area of tetrahedron is\n7.54" }, { "code": null, "e": 2046, "s": 1701, "text": "A class named Demo contains a static function named 'tetra_vol' which takes 'side' as a parameter. The formula to calculate area of a tetrahedron is ‘side’ cube/(6v2). This is computed and the output is returned. In the main function, the value of size is defined, and the function is called on this value. The output is printed on the console." } ]
Downloading & Uploading Images
In this chapter we are going to see how you can download an image from internet, perform some image processing techniques on the image, and then again upload the processed image to a server. In order to download an image from a website, we use java class named URL, which can be found under java.net package. Its syntax is given below − String website = "http://tutorialspoint.com"; URL url = new URL(website); Apart from the above method, there are other methods available in class URL as described briefly − public String getPath() It returns the path of the URL. public String getQuery() It returns the query part of the URL. public String getAuthority() It returns the authority of the URL. public int getPort() It returns the port of the URL. public int getDefaultPort() It returns the default port for the protocol of the URL. public String getProtocol() It returns the protocol of the URL. public String getHost() It returns the host of the URL. The following example demonstrates the use of java URL class to download an image from the internet − import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; public class Download { public static void main(String[] args) throws Exception { try{ String fileName = "digital_image_processing.jpg"; String website = "http://tutorialspoint.com/java_dip/images/"+fileName; System.out.println("Downloading File From: " + website); URL url = new URL(website); InputStream inputStream = url.openStream(); OutputStream outputStream = new FileOutputStream(fileName); byte[] buffer = new byte[2048]; int length = 0; while ((length = inputStream.read(buffer)) != -1) { System.out.println("Buffer Read of length: " + length); outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); } catch(Exception e) { System.out.println("Exception: " + e.getMessage()); } } } When you execute the given above, the following output is seen. It would download the following image from the server. Let us see how to upload an image to a webserver. We convert a BufferedImage to byte array in order to send it to server. We use Java class ByteArrayOutputStream, which can be found under java.io package. Its syntax is given below − ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", baos); In order to convert the image to byte array, we use toByteArray() method of ByteArrayOutputStream class. Its syntax is given below − byte[] bytes = baos.toByteArray(); Apart from the above method, there are other methods available in the ByteArrayOutputStream class as described briefly − public void reset() This method resets the number of valid bytes of the byte array output stream to zero, so that all the accumulated output in the stream is discarded. public byte[] toByteArray() This method creates a newly allocated Byte array. Its size would be the current size of the output stream and the contents of the buffer will be copied into it. It returns the current contents of the output stream as a byte array. public String toString() Converts the buffer content into a string. Translation will be done according to the default character encoding. It returns the String translated from the buffer's content. public void write(int w) It writes the specified array to the output stream. public void write(byte []b, int of, int len) It writes len number of bytes starting from offset off to the stream. public void writeTo(OutputStream outSt) It writes the entire content of this Stream to the specified stream argument. The following example demonstrates ByteArrayOutputStream to upload an image to the server − import javax.swing.*; import java.net.*; import java.awt.image.*; import javax.imageio.*; import java.io.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Client{ public static void main(String args[]) throws Exception{ Socket soc; BufferedImage img = null; soc=new Socket("localhost",4000); System.out.println("Client is running. "); try { System.out.println("Reading image from disk. "); img = ImageIO.read(new File("digital_image_processing.jpg")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(img, "jpg", baos); baos.flush(); byte[] bytes = baos.toByteArray(); baos.close(); System.out.println("Sending image to server. "); OutputStream out = soc.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); dos.writeInt(bytes.length); dos.write(bytes, 0, bytes.length); System.out.println("Image sent to server. "); dos.close(); out.close(); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); soc.close(); } soc.close(); } } import java.net.*; import java.io.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; class Server { public static void main(String args[]) throws Exception{ ServerSocket server=null; Socket socket; server = new ServerSocket(4000); System.out.println("Server Waiting for image"); socket = server.accept(); System.out.println("Client connected."); InputStream in = socket.getInputStream(); DataInputStream dis = new DataInputStream(in); int len = dis.readInt(); System.out.println("Image Size: " + len/1024 + "KB"); byte[] data = new byte[len]; dis.readFully(data); dis.close(); in.close(); InputStream ian = new ByteArrayInputStream(data); BufferedImage bImage = ImageIO.read(ian); JFrame f = new JFrame("Server"); ImageIcon icon = new ImageIcon(bImage); JLabel l = new JLabel(); l.setIcon(icon); f.add(l); f.pack(); f.setVisible(true); } } When you execute the client code, the following output appears on client side − When you execute the server code, the following ouptut appears on server side − After receiving the image, the server displays the image as shown below − 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": 2528, "s": 2337, "text": "In this chapter we are going to see how you can download an image from internet, perform some image processing techniques on the image, and then again upload the processed image to a server." }, { "code": null, "e": 2674, "s": 2528, "text": "In order to download an image from a website, we use java class named URL, which can be found under java.net package. Its syntax is given below −" }, { "code": null, "e": 2753, "s": 2674, "text": "String website = \"http://tutorialspoint.com\";\nURL url = new URL(website);\t\t\t\t\n" }, { "code": null, "e": 2852, "s": 2753, "text": "Apart from the above method, there are other methods available in class URL as\ndescribed briefly −" }, { "code": null, "e": 2876, "s": 2852, "text": "public String getPath()" }, { "code": null, "e": 2908, "s": 2876, "text": "It returns the path of the URL." }, { "code": null, "e": 2933, "s": 2908, "text": "public String getQuery()" }, { "code": null, "e": 2971, "s": 2933, "text": "It returns the query part of the URL." }, { "code": null, "e": 3000, "s": 2971, "text": "public String getAuthority()" }, { "code": null, "e": 3037, "s": 3000, "text": "It returns the authority of the URL." }, { "code": null, "e": 3058, "s": 3037, "text": "public int getPort()" }, { "code": null, "e": 3090, "s": 3058, "text": "It returns the port of the URL." }, { "code": null, "e": 3118, "s": 3090, "text": "public int getDefaultPort()" }, { "code": null, "e": 3175, "s": 3118, "text": "It returns the default port for the protocol of the URL." }, { "code": null, "e": 3203, "s": 3175, "text": "public String getProtocol()" }, { "code": null, "e": 3239, "s": 3203, "text": "It returns the protocol of the URL." }, { "code": null, "e": 3263, "s": 3239, "text": "public String getHost()" }, { "code": null, "e": 3295, "s": 3263, "text": "It returns the host of the URL." }, { "code": null, "e": 3397, "s": 3295, "text": "The following example demonstrates the use of java URL class to download an image from the internet −" }, { "code": null, "e": 4487, "s": 3397, "text": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\n\nimport java.net.URL;\n\npublic class Download {\n\n public static void main(String[] args) throws Exception {\n \n try{\n String fileName = \"digital_image_processing.jpg\";\n String website = \"http://tutorialspoint.com/java_dip/images/\"+fileName;\n \n System.out.println(\"Downloading File From: \" + website);\n \n URL url = new URL(website);\n InputStream inputStream = url.openStream();\n OutputStream outputStream = new FileOutputStream(fileName);\n byte[] buffer = new byte[2048];\n \n int length = 0;\n \n while ((length = inputStream.read(buffer)) != -1) {\n System.out.println(\"Buffer Read of length: \" + length);\n outputStream.write(buffer, 0, length);\n }\n \n inputStream.close();\n outputStream.close();\n \n } catch(Exception e) {\n System.out.println(\"Exception: \" + e.getMessage());\n }\n }\n}" }, { "code": null, "e": 4551, "s": 4487, "text": "When you execute the given above, the following output is seen." }, { "code": null, "e": 4606, "s": 4551, "text": "It would download the following image from the server." }, { "code": null, "e": 4728, "s": 4606, "text": "Let us see how to upload an image to a webserver. We convert a BufferedImage to byte array in order to send it to server." }, { "code": null, "e": 4839, "s": 4728, "text": "We use Java class ByteArrayOutputStream, which can be found under java.io package. Its syntax is given below −" }, { "code": null, "e": 4933, "s": 4839, "text": "ByteArrayOutputStream baos = new ByteArrayOutputStream();\nImageIO.write(image, \"jpg\", baos);\n" }, { "code": null, "e": 5066, "s": 4933, "text": "In order to convert the image to byte array, we use toByteArray() method of ByteArrayOutputStream class. Its syntax is given below −" }, { "code": null, "e": 5102, "s": 5066, "text": "byte[] bytes = baos.toByteArray();\n" }, { "code": null, "e": 5223, "s": 5102, "text": "Apart from the above method, there are other methods available in the ByteArrayOutputStream class as described briefly −" }, { "code": null, "e": 5243, "s": 5223, "text": "public void reset()" }, { "code": null, "e": 5392, "s": 5243, "text": "This method resets the number of valid bytes of the byte array output stream to zero, so that all the accumulated output in the stream is discarded." }, { "code": null, "e": 5420, "s": 5392, "text": "public byte[] toByteArray()" }, { "code": null, "e": 5651, "s": 5420, "text": "This method creates a newly allocated Byte array. Its size would be the current size of the output stream and the contents of the buffer will be copied into it. It returns the current contents of the output stream as a byte array." }, { "code": null, "e": 5676, "s": 5651, "text": "public String toString()" }, { "code": null, "e": 5849, "s": 5676, "text": "Converts the buffer content into a string. Translation will be done according to the default character encoding. It returns the String translated from the buffer's content." }, { "code": null, "e": 5874, "s": 5849, "text": "public void write(int w)" }, { "code": null, "e": 5926, "s": 5874, "text": "It writes the specified array to the output stream." }, { "code": null, "e": 5971, "s": 5926, "text": "public void write(byte []b, int of, int len)" }, { "code": null, "e": 6041, "s": 5971, "text": "It writes len number of bytes starting from offset off to the stream." }, { "code": null, "e": 6081, "s": 6041, "text": "public void writeTo(OutputStream outSt)" }, { "code": null, "e": 6159, "s": 6081, "text": "It writes the entire content of this Stream to the specified stream argument." }, { "code": null, "e": 6251, "s": 6159, "text": "The following example demonstrates ByteArrayOutputStream to upload an image to the server −" }, { "code": null, "e": 7655, "s": 6251, "text": "import javax.swing.*; \nimport java.net.*; \nimport java.awt.image.*;\nimport javax.imageio.*;\nimport java.io.*;\nimport java.awt.image.BufferedImage;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\n\npublic class Client{\n public static void main(String args[]) throws Exception{\n \n Socket soc;\n BufferedImage img = null;\n soc=new Socket(\"localhost\",4000);\n System.out.println(\"Client is running. \");\n \n try {\n System.out.println(\"Reading image from disk. \");\n img = ImageIO.read(new File(\"digital_image_processing.jpg\"));\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n \n ImageIO.write(img, \"jpg\", baos);\n baos.flush();\n \n byte[] bytes = baos.toByteArray();\n baos.close();\n \n System.out.println(\"Sending image to server. \");\n \n OutputStream out = soc.getOutputStream(); \n DataOutputStream dos = new DataOutputStream(out);\n \n dos.writeInt(bytes.length);\n dos.write(bytes, 0, bytes.length);\n \n System.out.println(\"Image sent to server. \");\n\n dos.close();\n out.close();\n \n } catch (Exception e) {\n System.out.println(\"Exception: \" + e.getMessage());\n soc.close();\n }\n soc.close();\n }\n}" }, { "code": null, "e": 8693, "s": 7655, "text": "import java.net.*;\nimport java.io.*;\nimport java.awt.image.*;\n\nimport javax.imageio.*; \nimport javax.swing.*; \n\nclass Server {\n public static void main(String args[]) throws Exception{\n ServerSocket server=null;\n Socket socket;\n server = new ServerSocket(4000);\n System.out.println(\"Server Waiting for image\");\n\n socket = server.accept();\n System.out.println(\"Client connected.\");\n \n InputStream in = socket.getInputStream();\n DataInputStream dis = new DataInputStream(in);\n\n int len = dis.readInt();\n System.out.println(\"Image Size: \" + len/1024 + \"KB\");\n \n byte[] data = new byte[len];\n dis.readFully(data);\n dis.close();\n in.close();\n\n InputStream ian = new ByteArrayInputStream(data);\n BufferedImage bImage = ImageIO.read(ian);\n \n JFrame f = new JFrame(\"Server\");\n ImageIcon icon = new ImageIcon(bImage);\n JLabel l = new JLabel();\n \n l.setIcon(icon);\n f.add(l);\n f.pack();\n f.setVisible(true);\n }\n}" }, { "code": null, "e": 8773, "s": 8693, "text": "When you execute the client code, the following output appears on client side −" }, { "code": null, "e": 8853, "s": 8773, "text": "When you execute the server code, the following ouptut appears on server side −" }, { "code": null, "e": 8927, "s": 8853, "text": "After receiving the image, the server displays the image as shown below −" }, { "code": null, "e": 8960, "s": 8927, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 8976, "s": 8960, "text": " Malhar Lathkar" }, { "code": null, "e": 9009, "s": 8976, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 9025, "s": 9009, "text": " Malhar Lathkar" }, { "code": null, "e": 9060, "s": 9025, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9074, "s": 9060, "text": " Anadi Sharma" }, { "code": null, "e": 9108, "s": 9074, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 9122, "s": 9108, "text": " Tushar Kale" }, { "code": null, "e": 9159, "s": 9122, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 9174, "s": 9159, "text": " Monica Mittal" }, { "code": null, "e": 9207, "s": 9174, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 9226, "s": 9207, "text": " Arnab Chakraborty" }, { "code": null, "e": 9233, "s": 9226, "text": " Print" }, { "code": null, "e": 9244, "s": 9233, "text": " Add Notes" } ]
Create ML: A GUI for training Neural Networks | by Dario Radečić | Towards Data Science
A couple of weeks ago I’ve bought a new laptop — a 2019 MacBook Pro and I’ve been loving it ever since. Naturally, I started experimenting with Swift and Xcode, mostly to create some dummy iOS apps. That’s where I discovered Create ML — a GUI tool for training custom neural networks. Here’s a quick statement directly from the official Apple’s documentation: Use Create ML with familiar tools like Swift and macOS playgrounds to create and train custom machine learning models on your Mac. You can train models to perform tasks like recognizing images, extracting meaning from text, or finding relationships between numerical values.[1] Nice. So you can see, it’s not only for image classification like we will do today. Just to make a note at the start, there will surely be a massive drawback to Create ML for most users — and that is the harsh requirement: you need to be on macOS. It’s not the end of the world if you don’t have a Mac since solutions like MacInCloud.com exist. I haven’t tested them personally, so I cannot guarantee you’ll have a perfectly smooth experience — but it must be better than nothing. So to recap, you’ll need to be running macOS if you want to follow along, and also install the latest version of Xcode. The article is structured as follows: Dataset download3 lines to train them allModel trainingModel evaluationModel savingConclusion and next steps Dataset download 3 lines to train them all Model training Model evaluation Model saving Conclusion and next steps Just to briefly mention, in the next article, we’ll create an iOS app and link our trained model to it. The GitHub repo already exists, so feel free to check it out. As mentioned earlier, we’ll be making a Dog vs Cat image classifier, and the dataset can be download from here. If you’ve downloaded and extracted it, inside the root folder you’ll have the following structure: ├── test│ ├── cat│ └── dog└── train ├── cat └── dog There are two things you must be aware of here: Subfolder names must be identical in both train and test foldersPredicted category names will be inferred from the subfolder names — ergo cat and dog here Subfolder names must be identical in both train and test folders Predicted category names will be inferred from the subfolder names — ergo cat and dog here Still following? Great, let’s proceed and prepare everything before we start with the training process. We can now open up Xcode and create a new Playground — a blank one for macOS: Name it as you wish and click on Next. We are now presented with the following screen: Great! In the left section, we’ll be writing our code and in the right one, we’ll be training our model. We can now delete this placeholder code and enter the following 3 lines: import CreateMLUIlet builder = MLImageClassifierBuilder()builder.showInLiveView() Your screen should look like this: Don’t worry about the deprecation warning as the code will work just fine. Now we can click on the blue play button below our code. After a couple of seconds you will be presented with this: And that’s it, we can begin training! Okay, literally the only thing you have to do now is to drag the train folder into this Drop Images To Begin Training section: The training process will begin instantly, and as we have more than 20K training images it will obviously take some time. So grab a cup of coffee, have a break, or just watch the model train. And now, sometime later (around half an hour on my machine) the model is trained: As we can see, it performed excellently on the train set, it only remains to see how will it perform on previously unseen data — ergo on the test set. Let’s explore just that in the next section. To evaluate the model on the test set, simply drag the test folder into Drop Images To Begin Testing section: The testing process will take significantly less time, as we only have 2500 images for testing purposes. Nevertheless, feel free to take another break until it’s finished. Okay, done yet? Cool. As we can see, accuracy on the test set is still impressive — 98%. Now we know that our model is ready for production, let’s explore how to export it in the next section. We’ll need to save this model so we can use it later in our iOS app. To do so, scroll up in the model training section and expand the dropdown: If you are satisfied with the auto-filled options click on Save. Remember, by default the model will be saved to the Documents folder — so let’s just verify quickly that it’ there: Awesome! Notice the .mlmodel extension? It is mandatory for any model you wish to deploy on iOS, so keep that in mind. We’re finished for today, so let’s make a brief conclusion. After all of this, you might be wondering how the heck the model performs so good? The official statement from Apple is as follows: Create ML leverages the machine learning infrastructure built in to Apple products like Photos and Siri. This means your image classification and natural language models are smaller and take much less time to train.[2] In a nutshell, it means that Apple has a lot of pre-trained models for which it only needs to adjust the output layer (also known as Transfer learning). If you’ve used ResNet or AlexNet before you know what I’m talking about. But there you have it, around 30 minutes to train the model and achieve 98% accuracy on the test set — pretty impressive for only 3 lines of code. Stay tuned for the following article, where we’ll incorporate this model into an iOS app. Thanks for reading. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 456, "s": 171, "text": "A couple of weeks ago I’ve bought a new laptop — a 2019 MacBook Pro and I’ve been loving it ever since. Naturally, I started experimenting with Swift and Xcode, mostly to create some dummy iOS apps. That’s where I discovered Create ML — a GUI tool for training custom neural networks." }, { "code": null, "e": 531, "s": 456, "text": "Here’s a quick statement directly from the official Apple’s documentation:" }, { "code": null, "e": 809, "s": 531, "text": "Use Create ML with familiar tools like Swift and macOS playgrounds to create and train custom machine learning models on your Mac. You can train models to perform tasks like recognizing images, extracting meaning from text, or finding relationships between numerical values.[1]" }, { "code": null, "e": 893, "s": 809, "text": "Nice. So you can see, it’s not only for image classification like we will do today." }, { "code": null, "e": 1057, "s": 893, "text": "Just to make a note at the start, there will surely be a massive drawback to Create ML for most users — and that is the harsh requirement: you need to be on macOS." }, { "code": null, "e": 1290, "s": 1057, "text": "It’s not the end of the world if you don’t have a Mac since solutions like MacInCloud.com exist. I haven’t tested them personally, so I cannot guarantee you’ll have a perfectly smooth experience — but it must be better than nothing." }, { "code": null, "e": 1410, "s": 1290, "text": "So to recap, you’ll need to be running macOS if you want to follow along, and also install the latest version of Xcode." }, { "code": null, "e": 1448, "s": 1410, "text": "The article is structured as follows:" }, { "code": null, "e": 1557, "s": 1448, "text": "Dataset download3 lines to train them allModel trainingModel evaluationModel savingConclusion and next steps" }, { "code": null, "e": 1574, "s": 1557, "text": "Dataset download" }, { "code": null, "e": 1600, "s": 1574, "text": "3 lines to train them all" }, { "code": null, "e": 1615, "s": 1600, "text": "Model training" }, { "code": null, "e": 1632, "s": 1615, "text": "Model evaluation" }, { "code": null, "e": 1645, "s": 1632, "text": "Model saving" }, { "code": null, "e": 1671, "s": 1645, "text": "Conclusion and next steps" }, { "code": null, "e": 1837, "s": 1671, "text": "Just to briefly mention, in the next article, we’ll create an iOS app and link our trained model to it. The GitHub repo already exists, so feel free to check it out." }, { "code": null, "e": 1949, "s": 1837, "text": "As mentioned earlier, we’ll be making a Dog vs Cat image classifier, and the dataset can be download from here." }, { "code": null, "e": 2048, "s": 1949, "text": "If you’ve downloaded and extracted it, inside the root folder you’ll have the following structure:" }, { "code": null, "e": 2110, "s": 2048, "text": "├── test│ ├── cat│ └── dog└── train ├── cat └── dog" }, { "code": null, "e": 2158, "s": 2110, "text": "There are two things you must be aware of here:" }, { "code": null, "e": 2313, "s": 2158, "text": "Subfolder names must be identical in both train and test foldersPredicted category names will be inferred from the subfolder names — ergo cat and dog here" }, { "code": null, "e": 2378, "s": 2313, "text": "Subfolder names must be identical in both train and test folders" }, { "code": null, "e": 2469, "s": 2378, "text": "Predicted category names will be inferred from the subfolder names — ergo cat and dog here" }, { "code": null, "e": 2573, "s": 2469, "text": "Still following? Great, let’s proceed and prepare everything before we start with the training process." }, { "code": null, "e": 2651, "s": 2573, "text": "We can now open up Xcode and create a new Playground — a blank one for macOS:" }, { "code": null, "e": 2738, "s": 2651, "text": "Name it as you wish and click on Next. We are now presented with the following screen:" }, { "code": null, "e": 2843, "s": 2738, "text": "Great! In the left section, we’ll be writing our code and in the right one, we’ll be training our model." }, { "code": null, "e": 2916, "s": 2843, "text": "We can now delete this placeholder code and enter the following 3 lines:" }, { "code": null, "e": 2998, "s": 2916, "text": "import CreateMLUIlet builder = MLImageClassifierBuilder()builder.showInLiveView()" }, { "code": null, "e": 3033, "s": 2998, "text": "Your screen should look like this:" }, { "code": null, "e": 3224, "s": 3033, "text": "Don’t worry about the deprecation warning as the code will work just fine. Now we can click on the blue play button below our code. After a couple of seconds you will be presented with this:" }, { "code": null, "e": 3262, "s": 3224, "text": "And that’s it, we can begin training!" }, { "code": null, "e": 3389, "s": 3262, "text": "Okay, literally the only thing you have to do now is to drag the train folder into this Drop Images To Begin Training section:" }, { "code": null, "e": 3581, "s": 3389, "text": "The training process will begin instantly, and as we have more than 20K training images it will obviously take some time. So grab a cup of coffee, have a break, or just watch the model train." }, { "code": null, "e": 3663, "s": 3581, "text": "And now, sometime later (around half an hour on my machine) the model is trained:" }, { "code": null, "e": 3859, "s": 3663, "text": "As we can see, it performed excellently on the train set, it only remains to see how will it perform on previously unseen data — ergo on the test set. Let’s explore just that in the next section." }, { "code": null, "e": 3969, "s": 3859, "text": "To evaluate the model on the test set, simply drag the test folder into Drop Images To Begin Testing section:" }, { "code": null, "e": 4141, "s": 3969, "text": "The testing process will take significantly less time, as we only have 2500 images for testing purposes. Nevertheless, feel free to take another break until it’s finished." }, { "code": null, "e": 4230, "s": 4141, "text": "Okay, done yet? Cool. As we can see, accuracy on the test set is still impressive — 98%." }, { "code": null, "e": 4334, "s": 4230, "text": "Now we know that our model is ready for production, let’s explore how to export it in the next section." }, { "code": null, "e": 4478, "s": 4334, "text": "We’ll need to save this model so we can use it later in our iOS app. To do so, scroll up in the model training section and expand the dropdown:" }, { "code": null, "e": 4659, "s": 4478, "text": "If you are satisfied with the auto-filled options click on Save. Remember, by default the model will be saved to the Documents folder — so let’s just verify quickly that it’ there:" }, { "code": null, "e": 4778, "s": 4659, "text": "Awesome! Notice the .mlmodel extension? It is mandatory for any model you wish to deploy on iOS, so keep that in mind." }, { "code": null, "e": 4838, "s": 4778, "text": "We’re finished for today, so let’s make a brief conclusion." }, { "code": null, "e": 4970, "s": 4838, "text": "After all of this, you might be wondering how the heck the model performs so good? The official statement from Apple is as follows:" }, { "code": null, "e": 5189, "s": 4970, "text": "Create ML leverages the machine learning infrastructure built in to Apple products like Photos and Siri. This means your image classification and natural language models are smaller and take much less time to train.[2]" }, { "code": null, "e": 5415, "s": 5189, "text": "In a nutshell, it means that Apple has a lot of pre-trained models for which it only needs to adjust the output layer (also known as Transfer learning). If you’ve used ResNet or AlexNet before you know what I’m talking about." }, { "code": null, "e": 5562, "s": 5415, "text": "But there you have it, around 30 minutes to train the model and achieve 98% accuracy on the test set — pretty impressive for only 3 lines of code." }, { "code": null, "e": 5652, "s": 5562, "text": "Stay tuned for the following article, where we’ll incorporate this model into an iOS app." }, { "code": null, "e": 5672, "s": 5652, "text": "Thanks for reading." } ]
Inverse Factorial in Python
Suppose we have a number a, we have to find n, such that factorial of n (n!) is same as a. As we know, the factorial n = n * (n - 1) * (n - 2) * ... * 1. If there is no such integer n then return -1. So, if the input is like a = 120, then the output will be 5. To solve this, we will follow these steps − i := 0, num := 1 L:= a new list while i < a, doi := factorial of numinsert i at the end of Lnum := num + 1 i := factorial of num insert i at the end of L num := num + 1 if a is in L, thenreturn the (index of a in L) +1 return the (index of a in L) +1 otherwise,return -1 return -1 Let us see the following implementation to get better understanding − Live Demo import math class Solution: def solve(self, a): i,num=0,1 L=[] while i < a : i=math.factorial(num) L.append(i) num+=1 if a in L : return L.index(a)+1 else : return -1 ob = Solution() print(ob.solve(120)) 120 5
[ { "code": null, "e": 1262, "s": 1062, "text": "Suppose we have a number a, we have to find n, such that factorial of n (n!) is same as a. As we\nknow, the factorial n = n * (n - 1) * (n - 2) * ... * 1. If there is no such integer n then return -1." }, { "code": null, "e": 1323, "s": 1262, "text": "So, if the input is like a = 120, then the output will be 5." }, { "code": null, "e": 1367, "s": 1323, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1384, "s": 1367, "text": "i := 0, num := 1" }, { "code": null, "e": 1399, "s": 1384, "text": "L:= a new list" }, { "code": null, "e": 1474, "s": 1399, "text": "while i < a, doi := factorial of numinsert i at the end of Lnum := num + 1" }, { "code": null, "e": 1496, "s": 1474, "text": "i := factorial of num" }, { "code": null, "e": 1521, "s": 1496, "text": "insert i at the end of L" }, { "code": null, "e": 1536, "s": 1521, "text": "num := num + 1" }, { "code": null, "e": 1586, "s": 1536, "text": "if a is in L, thenreturn the (index of a in L) +1" }, { "code": null, "e": 1618, "s": 1586, "text": "return the (index of a in L) +1" }, { "code": null, "e": 1638, "s": 1618, "text": "otherwise,return -1" }, { "code": null, "e": 1648, "s": 1638, "text": "return -1" }, { "code": null, "e": 1718, "s": 1648, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1729, "s": 1718, "text": " Live Demo" }, { "code": null, "e": 2023, "s": 1729, "text": "import math\nclass Solution:\n def solve(self, a):\n i,num=0,1\n L=[]\n while i < a :\n i=math.factorial(num)\n L.append(i)\n num+=1\n if a in L :\n return L.index(a)+1\n else :\n return -1\nob = Solution()\nprint(ob.solve(120))" }, { "code": null, "e": 2027, "s": 2023, "text": "120" }, { "code": null, "e": 2029, "s": 2027, "text": "5" } ]
Find a number in minimum steps - GeeksforGeeks
02 Jul, 2021 Given an infinite number line from -INFINITY to +INFINITY and we are on zero. We can move n steps either side at each n’th time. Approach 1 : Using Tree 1st time; we can move only 1 step to both ways, means -1 1; 2nd time we can move 2 steps from -1 and 1; -1 : -3 (-1-2) 1(-1+2) 1 : -1 ( 1-2) 3(1+2) 3rd time we can move 3 steps either way from -3, 1, -1, 3 -3: -6(-3-3) 0(-3+3) 1: -2(1-3) 4(1+3) -1: -4(-1-3) 2(-1+3) 3: 0(0-3) 6(3+3) Find the minimum number of steps to reach a given number n. Examples: Input : n = 10 Output : 4 We can reach 10 in 4 steps, 1, 3, 6, 10 Input : n = 13 Output : 5 We can reach 10 in 4 steps, -1, 2, 5, 9, 14 This problem can be modeled as tree. We put initial point 0 at root, 1 and -1 as children of root. Next level contains values at distance 2 and so on. 0 / \ -1 1 / \ / \ 1 -3 -1 3 / \ / \ / \ / \ The problem is now to find the closes node to root with value n. The idea is to do Level Order Traversal of tree to find the closest node. Note that using DFS for closest node is never a good idea (we may end up going down many unnecessary levels). Below is C++, Python implementation of above idea. C++ Java Python3 C# Javascript // C++ program to find a number in minimum steps#include <bits/stdc++.h>using namespace std;#define InF 99999 // To represent data of a node in treestruct number { int no; int level; public: number() {} number(int n, int l) : no(n), level(l) { }}; // Prints level of node nvoid findnthnumber(int n){ // Create a queue and insert root queue<number> q; struct number r(0, 1); q.push(r); // Do level order traversal while (!q.empty()) { // Remove a node from queue struct number temp = q.front(); q.pop(); // To avoid infinite loop if (temp.no >= InF || temp.no <= -InF) break; // Check if dequeued number is same as n if (temp.no == n) { cout << "Found number n at level " << temp.level - 1; break; } // Insert children of dequeued node to queue q.push(number(temp.no + temp.level, temp.level + 1)); q.push(number(temp.no - temp.level, temp.level + 1)); }} // Driver codeint main(){ findnthnumber(13); return 0;} // Java program to find a number in minimum stepsimport java.util.*;class GFG{ static final int InF = 99999; // To represent data of a node in tree static class number { int no; int level; number() {} number(int n, int l) { this.no = n; this.level = l; } }; // Prints level of node n static void findnthnumber(int n) { // Create a queue and insert root Queue<number> q = new LinkedList<>(); number r = new number(0, 1); q.add(r); // Do level order traversal while (!q.isEmpty()) { // Remove a node from queue number temp = q.peek(); q.remove(); // To astatic void infinite loop if (temp.no >= InF || temp.no <= -InF) break; // Check if dequeued number is same as n if (temp.no == n) { System.out.print("Found number n at level " + (temp.level - 1)); break; } // Insert children of dequeued node to queue q.add(new number(temp.no + temp.level, temp.level + 1)); q.add(new number(temp.no - temp.level, temp.level + 1)); } } // Driver code public static void main(String[] args) { findnthnumber(13); }} // This code is contributed by gauravrajput1 from collections import deque # Python program to find a number in minimum stepsInF = 99999 # To represent data of a node in treeclass number: def __init__(self,n,l): self.no = n self.level = l # Prints level of node ndef findnthnumber(n): # Create a queue and insert root q = deque() r = number(0, 1) q.append(r) # Do level order traversal while (len(q) > 0): # Remove a node from queue temp = q.popleft() # q.pop() # To avoid infinite loop if (temp.no >= InF or temp.no <= -InF): break # Check if dequeued number is same as n if (temp.no == n): print("Found number n at level", temp.level - 1) break # Insert children of dequeued node to queue q.append(number(temp.no + temp.level, temp.level + 1)) q.append(number(temp.no - temp.level, temp.level + 1)) # Driver codeif __name__ == '__main__': findnthnumber(13) # This code is contributed by mohit kumar 29 // C# program to find a number in minimum stepsusing System;using System.Collections.Generic;publicclass GFG{ static readonly int InF = 99999; // To represent data of a node in tree public class number { public int no; public int level; public number() {} public number(int n, int l) { this.no = n; this.level = l; } }; // Prints level of node n static void findnthnumber(int n) { // Create a queue and insert root Queue<number> q = new Queue<number>(); number r = new number(0, 1); q.Enqueue(r); // Do level order traversal while (q.Count != 0) { // Remove a node from queue number temp = q.Peek(); q.Dequeue(); // To astatic void infinite loop if (temp.no >= InF || temp.no <= -InF) break; // Check if dequeued number is same as n if (temp.no == n) { Console.Write("Found number n at level " + (temp.level - 1)); break; } // Insert children of dequeued node to queue q.Enqueue(new number(temp.no + temp.level, temp.level + 1)); q.Enqueue(new number(temp.no - temp.level, temp.level + 1)); } } // Driver code public static void Main(String[] args) { findnthnumber(13); }} // This code is contributed by gauravrajput1 <script> // JavaScript program to find a number in minimum steps var InF = 99999; // To represent data of a node in tree class number { constructor(n, l) { this.no = n; this.level = l; } }; // Prints level of node n function findnthnumber(n) { // Create a queue and insert root var q = []; var r = new number(0, 1); q.push(r); // Do level order traversal while (q.length != 0) { // Remove a node from queue var temp = q[0]; q.shift(); // To astatic void infinite loop if (temp.no >= InF || temp.no <= -InF) break; // Check if dequeued number is same as n if (temp.no == n) { document.write("Found number n at level " + (temp.level - 1)); break; } // Insert children of dequeued node to queue q.push(new number(temp.no + temp.level, temp.level + 1)); q.push(new number(temp.no - temp.level, temp.level + 1)); } } // Driver code findnthnumber(13); </script> Output: Found number n at level 5 The above solution is contributed by Mu Ven. Approach 2 : Using Vector The above solution uses binary tree for nth time instance i.e. -n and n. But as the level of tree increases this becomes inefficient. For values like abs(200) or more above program gives segmentation fault.Below solution does not make a tree and takes complexity equal to exact number of steps required. Also the steps required are printed in the array which equals the exact sum required. Main Idea: Distance between +n and -n is 2*n. So if you negate a number from +ve to -ve it will create difference of 2*n from previous sum. If a number lies between n(n+1)/2 and (n+1)(n+2)/2 for any n then we go to step (n+1)(n+2)/2 and try to decrease the sum to the difference using idea discussed above. If we go to n(n+1)/2 and then try to increase than it will ultimately lead you to same number of steps. And since you cannot negate any number (as sum is already less than required sum) from n(n+1)/2 this proves that it takes minimum number of steps. C++ Java Python3 C# Javascript // C++ program to Find a// number in minimum steps#include <bits/stdc++.h>using namespace std; vector<int> find(int n){ // Steps sequence vector<int> ans; // Current sum int sum = 0; int i; // Sign of the number int sign = (n >= 0 ? 1 : -1); n = abs(n); // Basic steps required to get // sum >= required value. for (i = 1; sum < n; i++) { ans.push_back(sign * i); sum += i; } // If we have reached ahead to destination. if (sum > sign * n) { /*If the last step was an odd number, then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum. */ if (i % 2) { sum -= n; if (sum % 2) { ans.push_back(sign * i); sum += i++; } ans[(sum / 2) - 1] *= -1; } else { /* If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there. */ sum -= n; if (sum % 2) { sum--; ans.push_back(sign * i); ans.push_back(sign * -1 * (i + 1)); } ans[(sum / 2) - 1] *= -1; } } return ans;} // Driver Programint main(){ int n = 20; if (n == 0) cout << "Minimum number of Steps: 0\nStep sequence:\n0"; else { vector<int> a = find(n); cout << "Minimum number of Steps: " << a.size() << "\nStep sequence:\n"; for (int i : a) cout << i << " "; } return 0;} // Java program to Find a// number in minimum stepsimport java.util.*;class GFG{ static Vector<Integer> find(int n) { // Steps sequence Vector<Integer> ans = new Vector<>(); // Current sum int sum = 0; int i = 1; // Sign of the number int sign = (n >= 0 ? 1 : -1); n = Math.abs(n); // Basic steps required to get // sum >= required value. for (; sum < n;) { ans.add(sign * i); sum += i; i++; } // If we have reached ahead to destination. if (sum > sign * n) { /*If the last step was an odd number, then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum. */ if (i % 2 != 0) { sum -= n; if (sum % 2 != 0) { ans.add(sign * i); sum += i; i++; } int a = ans.get((sum / 2) - 1); ans.remove((sum / 2) - 1); ans.add(((sum / 2) - 1), a*(-1)); } else { /* If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there. */ sum -= n; if (sum % 2 != 0) { sum--; ans.add(sign * i); ans.add(sign * -1 * (i + 1)); } ans.add((sum / 2) - 1, ans.get((sum / 2) - 1) * -1); } } return ans; } // Driver Program public static void main(String[] args) { int n = 20; if (n == 0) System.out.print("Minimum number of Steps: 0\nStep sequence:\n0"); else { Vector<Integer> a = find(n); System.out.print("Minimum number of Steps: " + a.size()+ "\nStep sequence:\n"); for (int i : a) System.out.print(i + " "); } }} // This code is contributed by aashish1995 # Python3 program to Find a# number in minimum stepsdef find(n): # Steps sequence ans = [] # Current sum Sum = 0 i = 0 # Sign of the number sign = 0 if (n >= 0): sign = 1 else: sign = -1 n = abs(n) i = 1 # Basic steps required to get # sum >= required value. while (Sum < n): ans.append(sign * i) Sum += i i += 1 # If we have reached ahead to destination. if (Sum > sign * n): # If the last step was an odd number, # then it has following mechanism for # negating a particular number and # decreasing the sum to required number # Also note that it may require # 1 more step in order to reach the sum. if (i % 2!=0): Sum -= n if (Sum % 2 != 0): ans.append(sign * i) Sum += i i += 1 ans[int(Sum / 2) - 1] *= -1 else: # If the current time instance is even # and sum is odd than it takes # 2 more steps and few # negations in previous elements # to reach there. Sum -= n if (Sum % 2 != 0): Sum -= 1 ans.append(sign * i) ans.append(sign * -1 * (i + 1)) ans[int((sum / 2)) - 1] *= -1 return ans # Driver coden = 20 if (n == 0): print("Minimum number of Steps: 0\nStep sequence:\n0")else: a = find(n) print("Minimum number of Steps:", len(a)) print("Step sequence:") print(*a, sep = " ") # This code is contributed by rag2127 // C# program to Find a// number in minimum stepsusing System;using System.Collections.Generic;public class GFG{ static List<int> find(int n) { // Steps sequence List<int> ans = new List<int>(); // Current sum int sum = 0; int i = 1; // Sign of the number int sign = (n >= 0 ? 1 : -1); n = Math.Abs(n); // Basic steps required to get // sum >= required value. for (; sum < n;) { ans.Add(sign * i); sum += i; i++; } // If we have reached ahead to destination. if (sum > sign * n) { /*If the last step was an odd number, then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum. */ if (i % 2 != 0) { sum -= n; if (sum % 2 != 0) { ans.Add(sign * i); sum += i; i++; } int a = ans[((sum / 2) - 1)]; ans.RemoveAt((sum / 2) - 1); ans.Insert(((sum / 2) - 1), a*(-1)); } else { /* If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there. */ sum -= n; if (sum % 2 != 0) { sum--; ans.Add(sign * i); ans.Add(sign * -1 * (i + 1)); } ans.Insert((sum / 2) - 1, ans[(sum / 2) - 1] * -1); } } return ans; } // Driver Program public static void Main(String[] args) { int n = 20; if (n == 0) Console.Write("Minimum number of Steps: 0\nStep sequence:\n0"); else { List<int> a = find(n); Console.Write("Minimum number of Steps: " + a.Count+ "\nStep sequence:\n"); foreach (int i in a) Console.Write(i + " "); } }} // This code is contributed by Rajput-Ji <script> // JavaScript program to Find a // number in minimum steps function find(n) { // Steps sequence let ans = []; // Current sum let sum = 0; let i = 1; // Sign of the number let sign = (n >= 0 ? 1 : -1); n = Math.abs(n); // Basic steps required to get // sum >= required value. for (; sum < n;) { ans.push(sign * i); sum += i; i++; } // If we have reached ahead to destination. if (sum > sign * n) { /*If the last step was an odd number, then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum. */ if (i % 2 != 0) { sum -= n; if (sum % 2 != 0) { ans.push(sign * i); sum += i; i++; } ans[parseInt(sum / 2, 10) - 1] = ans[parseInt(sum / 2, 10) - 1]*(-1); } else { /* If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there. */ sum -= n; if (sum % 2 != 0) { sum--; ans.push(sign * i); ans.push(sign * -1 * (i + 1)); } ans[parseInt(sum / 2, 10) - 1] = ans[parseInt(sum / 2, 10) - 1] * -1; } } return ans; } let n = 20; if (n == 0) document.write("Minimum number of Steps: 0" + "</br>" + "Step sequence:" + "</br>" + "0"); else { let a = find(n); document.write("Minimum number of Steps: " + a.length + "</br>" + "Step sequence:" + "</br>"); for (let i = 0; i < a.length; i++) document.write(a[i] + " "); } </script> Output : Minimum number of Steps: 7 Step sequence: 1 2 3 -4 5 6 7 If n is the sum that it is required and s is the minimum steps then: n = (s+1)*(s+2)/2 + 1 (or +2) Hence n = O(s*s)Therefore s = O(sqrt(n)) Space Complexity : O(sqrt(n)) Time complexity : O(sqrt(n)) https://youtu.be/GcrapHAFnLgPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Shreyans Vora mohit kumar 29 rag2127 aashish1995 Rajput-Ji GauravRajput1 rutvik_56 suresh07 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Binary Tree | Set 2 (Properties) Decision Tree Introduction to Tree Data Structure Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Construct Tree from given Inorder and Preorder traversals Expression Tree BFS vs DFS for Binary Tree Sorted Array to Balanced BST Binary Tree (Array implementation) Deletion in a Binary Tree
[ { "code": null, "e": 25308, "s": 25280, "text": "\n02 Jul, 2021" }, { "code": null, "e": 25438, "s": 25308, "text": "Given an infinite number line from -INFINITY to +INFINITY and we are on zero. We can move n steps either side at each n’th time. " }, { "code": null, "e": 25463, "s": 25438, "text": "Approach 1 : Using Tree " }, { "code": null, "e": 25830, "s": 25463, "text": "1st time; we can move only 1 step to both ways, means -1 1;\n\n2nd time we can move 2 steps from -1 and 1;\n-1 : -3 (-1-2) 1(-1+2)\n 1 : -1 ( 1-2) 3(1+2)\n\n3rd time we can move 3 steps either way from -3, 1, -1, 3 \n-3: -6(-3-3) 0(-3+3)\n1: -2(1-3) 4(1+3)\n-1: -4(-1-3) 2(-1+3)\n3: 0(0-3) 6(3+3) \n\nFind the minimum number of steps to reach a given number n." }, { "code": null, "e": 25841, "s": 25830, "text": "Examples: " }, { "code": null, "e": 25982, "s": 25841, "text": "Input : n = 10\nOutput : 4\nWe can reach 10 in 4 steps, 1, 3, 6, 10 \n\n\nInput : n = 13\nOutput : 5\nWe can reach 10 in 4 steps, -1, 2, 5, 9, 14" }, { "code": null, "e": 26135, "s": 25982, "text": "This problem can be modeled as tree. We put initial point 0 at root, 1 and -1 as children of root. Next level contains values at distance 2 and so on. " }, { "code": null, "e": 26261, "s": 26135, "text": " 0\n / \\\n -1 1 \n / \\ / \\\n 1 -3 -1 3\n / \\ / \\ / \\ / \\" }, { "code": null, "e": 26511, "s": 26261, "text": "The problem is now to find the closes node to root with value n. The idea is to do Level Order Traversal of tree to find the closest node. Note that using DFS for closest node is never a good idea (we may end up going down many unnecessary levels). " }, { "code": null, "e": 26562, "s": 26511, "text": "Below is C++, Python implementation of above idea." }, { "code": null, "e": 26566, "s": 26562, "text": "C++" }, { "code": null, "e": 26571, "s": 26566, "text": "Java" }, { "code": null, "e": 26579, "s": 26571, "text": "Python3" }, { "code": null, "e": 26582, "s": 26579, "text": "C#" }, { "code": null, "e": 26593, "s": 26582, "text": "Javascript" }, { "code": "// C++ program to find a number in minimum steps#include <bits/stdc++.h>using namespace std;#define InF 99999 // To represent data of a node in treestruct number { int no; int level; public: number() {} number(int n, int l) : no(n), level(l) { }}; // Prints level of node nvoid findnthnumber(int n){ // Create a queue and insert root queue<number> q; struct number r(0, 1); q.push(r); // Do level order traversal while (!q.empty()) { // Remove a node from queue struct number temp = q.front(); q.pop(); // To avoid infinite loop if (temp.no >= InF || temp.no <= -InF) break; // Check if dequeued number is same as n if (temp.no == n) { cout << \"Found number n at level \" << temp.level - 1; break; } // Insert children of dequeued node to queue q.push(number(temp.no + temp.level, temp.level + 1)); q.push(number(temp.no - temp.level, temp.level + 1)); }} // Driver codeint main(){ findnthnumber(13); return 0;}", "e": 27686, "s": 26593, "text": null }, { "code": "// Java program to find a number in minimum stepsimport java.util.*;class GFG{ static final int InF = 99999; // To represent data of a node in tree static class number { int no; int level; number() {} number(int n, int l) { this.no = n; this.level = l; } }; // Prints level of node n static void findnthnumber(int n) { // Create a queue and insert root Queue<number> q = new LinkedList<>(); number r = new number(0, 1); q.add(r); // Do level order traversal while (!q.isEmpty()) { // Remove a node from queue number temp = q.peek(); q.remove(); // To astatic void infinite loop if (temp.no >= InF || temp.no <= -InF) break; // Check if dequeued number is same as n if (temp.no == n) { System.out.print(\"Found number n at level \" + (temp.level - 1)); break; } // Insert children of dequeued node to queue q.add(new number(temp.no + temp.level, temp.level + 1)); q.add(new number(temp.no - temp.level, temp.level + 1)); } } // Driver code public static void main(String[] args) { findnthnumber(13); }} // This code is contributed by gauravrajput1", "e": 28913, "s": 27686, "text": null }, { "code": "from collections import deque # Python program to find a number in minimum stepsInF = 99999 # To represent data of a node in treeclass number: def __init__(self,n,l): self.no = n self.level = l # Prints level of node ndef findnthnumber(n): # Create a queue and insert root q = deque() r = number(0, 1) q.append(r) # Do level order traversal while (len(q) > 0): # Remove a node from queue temp = q.popleft() # q.pop() # To avoid infinite loop if (temp.no >= InF or temp.no <= -InF): break # Check if dequeued number is same as n if (temp.no == n): print(\"Found number n at level\", temp.level - 1) break # Insert children of dequeued node to queue q.append(number(temp.no + temp.level, temp.level + 1)) q.append(number(temp.no - temp.level, temp.level + 1)) # Driver codeif __name__ == '__main__': findnthnumber(13) # This code is contributed by mohit kumar 29", "e": 29917, "s": 28913, "text": null }, { "code": "// C# program to find a number in minimum stepsusing System;using System.Collections.Generic;publicclass GFG{ static readonly int InF = 99999; // To represent data of a node in tree public class number { public int no; public int level; public number() {} public number(int n, int l) { this.no = n; this.level = l; } }; // Prints level of node n static void findnthnumber(int n) { // Create a queue and insert root Queue<number> q = new Queue<number>(); number r = new number(0, 1); q.Enqueue(r); // Do level order traversal while (q.Count != 0) { // Remove a node from queue number temp = q.Peek(); q.Dequeue(); // To astatic void infinite loop if (temp.no >= InF || temp.no <= -InF) break; // Check if dequeued number is same as n if (temp.no == n) { Console.Write(\"Found number n at level \" + (temp.level - 1)); break; } // Insert children of dequeued node to queue q.Enqueue(new number(temp.no + temp.level, temp.level + 1)); q.Enqueue(new number(temp.no - temp.level, temp.level + 1)); } } // Driver code public static void Main(String[] args) { findnthnumber(13); }} // This code is contributed by gauravrajput1", "e": 31217, "s": 29917, "text": null }, { "code": "<script> // JavaScript program to find a number in minimum steps var InF = 99999; // To represent data of a node in tree class number { constructor(n, l) { this.no = n; this.level = l; } }; // Prints level of node n function findnthnumber(n) { // Create a queue and insert root var q = []; var r = new number(0, 1); q.push(r); // Do level order traversal while (q.length != 0) { // Remove a node from queue var temp = q[0]; q.shift(); // To astatic void infinite loop if (temp.no >= InF || temp.no <= -InF) break; // Check if dequeued number is same as n if (temp.no == n) { document.write(\"Found number n at level \" + (temp.level - 1)); break; } // Insert children of dequeued node to queue q.push(new number(temp.no + temp.level, temp.level + 1)); q.push(new number(temp.no - temp.level, temp.level + 1)); } } // Driver code findnthnumber(13); </script>", "e": 32237, "s": 31217, "text": null }, { "code": null, "e": 32246, "s": 32237, "text": "Output: " }, { "code": null, "e": 32272, "s": 32246, "text": "Found number n at level 5" }, { "code": null, "e": 32319, "s": 32272, "text": "The above solution is contributed by Mu Ven. " }, { "code": null, "e": 32345, "s": 32319, "text": "Approach 2 : Using Vector" }, { "code": null, "e": 32735, "s": 32345, "text": "The above solution uses binary tree for nth time instance i.e. -n and n. But as the level of tree increases this becomes inefficient. For values like abs(200) or more above program gives segmentation fault.Below solution does not make a tree and takes complexity equal to exact number of steps required. Also the steps required are printed in the array which equals the exact sum required." }, { "code": null, "e": 32748, "s": 32735, "text": "Main Idea: " }, { "code": null, "e": 32877, "s": 32748, "text": "Distance between +n and -n is 2*n. So if you negate a number from +ve to -ve it will create difference of 2*n from previous sum." }, { "code": null, "e": 33044, "s": 32877, "text": "If a number lies between n(n+1)/2 and (n+1)(n+2)/2 for any n then we go to step (n+1)(n+2)/2 and try to decrease the sum to the difference using idea discussed above." }, { "code": null, "e": 33295, "s": 33044, "text": "If we go to n(n+1)/2 and then try to increase than it will ultimately lead you to same number of steps. And since you cannot negate any number (as sum is already less than required sum) from n(n+1)/2 this proves that it takes minimum number of steps." }, { "code": null, "e": 33299, "s": 33295, "text": "C++" }, { "code": null, "e": 33304, "s": 33299, "text": "Java" }, { "code": null, "e": 33312, "s": 33304, "text": "Python3" }, { "code": null, "e": 33315, "s": 33312, "text": "C#" }, { "code": null, "e": 33326, "s": 33315, "text": "Javascript" }, { "code": "// C++ program to Find a// number in minimum steps#include <bits/stdc++.h>using namespace std; vector<int> find(int n){ // Steps sequence vector<int> ans; // Current sum int sum = 0; int i; // Sign of the number int sign = (n >= 0 ? 1 : -1); n = abs(n); // Basic steps required to get // sum >= required value. for (i = 1; sum < n; i++) { ans.push_back(sign * i); sum += i; } // If we have reached ahead to destination. if (sum > sign * n) { /*If the last step was an odd number, then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum. */ if (i % 2) { sum -= n; if (sum % 2) { ans.push_back(sign * i); sum += i++; } ans[(sum / 2) - 1] *= -1; } else { /* If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there. */ sum -= n; if (sum % 2) { sum--; ans.push_back(sign * i); ans.push_back(sign * -1 * (i + 1)); } ans[(sum / 2) - 1] *= -1; } } return ans;} // Driver Programint main(){ int n = 20; if (n == 0) cout << \"Minimum number of Steps: 0\\nStep sequence:\\n0\"; else { vector<int> a = find(n); cout << \"Minimum number of Steps: \" << a.size() << \"\\nStep sequence:\\n\"; for (int i : a) cout << i << \" \"; } return 0;}", "e": 35050, "s": 33326, "text": null }, { "code": "// Java program to Find a// number in minimum stepsimport java.util.*;class GFG{ static Vector<Integer> find(int n) { // Steps sequence Vector<Integer> ans = new Vector<>(); // Current sum int sum = 0; int i = 1; // Sign of the number int sign = (n >= 0 ? 1 : -1); n = Math.abs(n); // Basic steps required to get // sum >= required value. for (; sum < n;) { ans.add(sign * i); sum += i; i++; } // If we have reached ahead to destination. if (sum > sign * n) { /*If the last step was an odd number, then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum. */ if (i % 2 != 0) { sum -= n; if (sum % 2 != 0) { ans.add(sign * i); sum += i; i++; } int a = ans.get((sum / 2) - 1); ans.remove((sum / 2) - 1); ans.add(((sum / 2) - 1), a*(-1)); } else { /* If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there. */ sum -= n; if (sum % 2 != 0) { sum--; ans.add(sign * i); ans.add(sign * -1 * (i + 1)); } ans.add((sum / 2) - 1, ans.get((sum / 2) - 1) * -1); } } return ans; } // Driver Program public static void main(String[] args) { int n = 20; if (n == 0) System.out.print(\"Minimum number of Steps: 0\\nStep sequence:\\n0\"); else { Vector<Integer> a = find(n); System.out.print(\"Minimum number of Steps: \" + a.size()+ \"\\nStep sequence:\\n\"); for (int i : a) System.out.print(i + \" \"); } }} // This code is contributed by aashish1995", "e": 36982, "s": 35050, "text": null }, { "code": "# Python3 program to Find a# number in minimum stepsdef find(n): # Steps sequence ans = [] # Current sum Sum = 0 i = 0 # Sign of the number sign = 0 if (n >= 0): sign = 1 else: sign = -1 n = abs(n) i = 1 # Basic steps required to get # sum >= required value. while (Sum < n): ans.append(sign * i) Sum += i i += 1 # If we have reached ahead to destination. if (Sum > sign * n): # If the last step was an odd number, # then it has following mechanism for # negating a particular number and # decreasing the sum to required number # Also note that it may require # 1 more step in order to reach the sum. if (i % 2!=0): Sum -= n if (Sum % 2 != 0): ans.append(sign * i) Sum += i i += 1 ans[int(Sum / 2) - 1] *= -1 else: # If the current time instance is even # and sum is odd than it takes # 2 more steps and few # negations in previous elements # to reach there. Sum -= n if (Sum % 2 != 0): Sum -= 1 ans.append(sign * i) ans.append(sign * -1 * (i + 1)) ans[int((sum / 2)) - 1] *= -1 return ans # Driver coden = 20 if (n == 0): print(\"Minimum number of Steps: 0\\nStep sequence:\\n0\")else: a = find(n) print(\"Minimum number of Steps:\", len(a)) print(\"Step sequence:\") print(*a, sep = \" \") # This code is contributed by rag2127", "e": 38684, "s": 36982, "text": null }, { "code": "// C# program to Find a// number in minimum stepsusing System;using System.Collections.Generic;public class GFG{ static List<int> find(int n) { // Steps sequence List<int> ans = new List<int>(); // Current sum int sum = 0; int i = 1; // Sign of the number int sign = (n >= 0 ? 1 : -1); n = Math.Abs(n); // Basic steps required to get // sum >= required value. for (; sum < n;) { ans.Add(sign * i); sum += i; i++; } // If we have reached ahead to destination. if (sum > sign * n) { /*If the last step was an odd number, then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum. */ if (i % 2 != 0) { sum -= n; if (sum % 2 != 0) { ans.Add(sign * i); sum += i; i++; } int a = ans[((sum / 2) - 1)]; ans.RemoveAt((sum / 2) - 1); ans.Insert(((sum / 2) - 1), a*(-1)); } else { /* If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there. */ sum -= n; if (sum % 2 != 0) { sum--; ans.Add(sign * i); ans.Add(sign * -1 * (i + 1)); } ans.Insert((sum / 2) - 1, ans[(sum / 2) - 1] * -1); } } return ans; } // Driver Program public static void Main(String[] args) { int n = 20; if (n == 0) Console.Write(\"Minimum number of Steps: 0\\nStep sequence:\\n0\"); else { List<int> a = find(n); Console.Write(\"Minimum number of Steps: \" + a.Count+ \"\\nStep sequence:\\n\"); foreach (int i in a) Console.Write(i + \" \"); } }} // This code is contributed by Rajput-Ji", "e": 40623, "s": 38684, "text": null }, { "code": "<script> // JavaScript program to Find a // number in minimum steps function find(n) { // Steps sequence let ans = []; // Current sum let sum = 0; let i = 1; // Sign of the number let sign = (n >= 0 ? 1 : -1); n = Math.abs(n); // Basic steps required to get // sum >= required value. for (; sum < n;) { ans.push(sign * i); sum += i; i++; } // If we have reached ahead to destination. if (sum > sign * n) { /*If the last step was an odd number, then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum. */ if (i % 2 != 0) { sum -= n; if (sum % 2 != 0) { ans.push(sign * i); sum += i; i++; } ans[parseInt(sum / 2, 10) - 1] = ans[parseInt(sum / 2, 10) - 1]*(-1); } else { /* If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there. */ sum -= n; if (sum % 2 != 0) { sum--; ans.push(sign * i); ans.push(sign * -1 * (i + 1)); } ans[parseInt(sum / 2, 10) - 1] = ans[parseInt(sum / 2, 10) - 1] * -1; } } return ans; } let n = 20; if (n == 0) document.write(\"Minimum number of Steps: 0\" + \"</br>\" + \"Step sequence:\" + \"</br>\" + \"0\"); else { let a = find(n); document.write(\"Minimum number of Steps: \" + a.length + \"</br>\" + \"Step sequence:\" + \"</br>\"); for (let i = 0; i < a.length; i++) document.write(a[i] + \" \"); } </script>", "e": 42610, "s": 40623, "text": null }, { "code": null, "e": 42620, "s": 42610, "text": "Output : " }, { "code": null, "e": 42679, "s": 42620, "text": " \nMinimum number of Steps: 7\nStep sequence:\n1 2 3 -4 5 6 7" }, { "code": null, "e": 43032, "s": 42679, "text": "If n is the sum that it is required and s is the minimum steps then: n = (s+1)*(s+2)/2 + 1 (or +2) Hence n = O(s*s)Therefore s = O(sqrt(n)) Space Complexity : O(sqrt(n)) Time complexity : O(sqrt(n)) https://youtu.be/GcrapHAFnLgPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 43046, "s": 43032, "text": "Shreyans Vora" }, { "code": null, "e": 43061, "s": 43046, "text": "mohit kumar 29" }, { "code": null, "e": 43069, "s": 43061, "text": "rag2127" }, { "code": null, "e": 43081, "s": 43069, "text": "aashish1995" }, { "code": null, "e": 43091, "s": 43081, "text": "Rajput-Ji" }, { "code": null, "e": 43105, "s": 43091, "text": "GauravRajput1" }, { "code": null, "e": 43115, "s": 43105, "text": "rutvik_56" }, { "code": null, "e": 43124, "s": 43115, "text": "suresh07" }, { "code": null, "e": 43129, "s": 43124, "text": "Tree" }, { "code": null, "e": 43134, "s": 43129, "text": "Tree" }, { "code": null, "e": 43232, "s": 43134, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43241, "s": 43232, "text": "Comments" }, { "code": null, "e": 43254, "s": 43241, "text": "Old Comments" }, { "code": null, "e": 43287, "s": 43254, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 43301, "s": 43287, "text": "Decision Tree" }, { "code": null, "e": 43337, "s": 43301, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 43420, "s": 43337, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 43478, "s": 43420, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 43494, "s": 43478, "text": "Expression Tree" }, { "code": null, "e": 43521, "s": 43494, "text": "BFS vs DFS for Binary Tree" }, { "code": null, "e": 43550, "s": 43521, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 43585, "s": 43550, "text": "Binary Tree (Array implementation)" } ]
AngularJS | Modules - GeeksforGeeks
31 May, 2019 The AngularJS module defines the functionality of the application which is applied on the entire HTML page. It helps to link many components. So it is just a group of related components. It is a container which consists of different parts like controllers, services, directives. Note: This modules should be made in a normal HTML files like index.html and no need to create a new project in VisualStudio for this section. How to create a Module: var app = angular.module("Module-name", []); In this [] we can add a list of components needed but we are not including any components in this case. This created module is bound with any tag like div, body, etc by adding it to the list of modules. <div ng-app = "module-name"> The code in which the module is required.</div> Adding a Controller: app.controller("Controller-name", function($scope) { $scope.variable-name= ""; }); Here, we can add any number of variables in controller and use them in the html files, body of the tag in which the controller is added to that tag by writing: <body><div ng-app="Module-name"> <div ng-controller="Controller-name"> {{variable-name}} </div> <!-- This wont get printed since itsnot part of the div in which controller is included -->{{variable-name}} </div></body> Module and Controllers in Files: While we can make modules and controllers in the same file along with the HTML file which requiring it however we may want to use this module in some other file. Hence this will lead to redundancy so we will prefer to create Module, Controller and HTML file separately. The Module and Controller are to be stored by using .js files and in order to use them in the HHTML file we have to include them in this way: Example: DemoComponent.js// Here the Component name is DemoComponent// so saving the file as DemoComponent.js app.controller('DemoController', function($scope) { $scope.list = ['A', 'E', 'I', 'O', 'U']; $scope.choice = 'Your choice is: GeeksforGeeks'; $scope.ch = function(choice) { $scope.choice = "Your choice is: " + choice; }; $scope.c = function() { $scope.choice = "Your choice is: " + $scope.mychoice; };}); // Here the Component name is DemoComponent// so saving the file as DemoComponent.js app.controller('DemoController', function($scope) { $scope.list = ['A', 'E', 'I', 'O', 'U']; $scope.choice = 'Your choice is: GeeksforGeeks'; $scope.ch = function(choice) { $scope.choice = "Your choice is: " + choice; }; $scope.c = function() { $scope.choice = "Your choice is: " + $scope.mychoice; };}); Module-name: DemoApp.jsvar app = angular.module('DemoApp', []); var app = angular.module('DemoApp', []); index.html file<!DOCTYPE html><html> <head> <title> Modules and Controllers in Files </title> </head> <body ng-app="DemoApp"> <h1> Using controllers in Module </h1> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <script src="DemoApp.js"></script> <script src="DemoController"></script> <div ng-app="DemoApp" ng-controller="DemoController"> Vowels List : <button ng-click="ch('A')" >A</button> <button ng-click="ch('E')" >E</button> <button ng-click="ch('I')" >I</button> <button ng-click="ch('O')" >O</button> <button ng-click="ch('U')" >U</button> <p>{{ choice }}</p> Vowels List : <select ng-options="option for option in list" ng-model="mychoice" ng-change="c()"> </select> <p>{{ choice }}</p> </div></body> </html> <!DOCTYPE html><html> <head> <title> Modules and Controllers in Files </title> </head> <body ng-app="DemoApp"> <h1> Using controllers in Module </h1> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <script src="DemoApp.js"></script> <script src="DemoController"></script> <div ng-app="DemoApp" ng-controller="DemoController"> Vowels List : <button ng-click="ch('A')" >A</button> <button ng-click="ch('E')" >E</button> <button ng-click="ch('I')" >I</button> <button ng-click="ch('O')" >O</button> <button ng-click="ch('U')" >U</button> <p>{{ choice }}</p> Vowels List : <select ng-options="option for option in list" ng-model="mychoice" ng-change="c()"> </select> <p>{{ choice }}</p> </div></body> </html> Output: Note: It makes sure the module and component files are in the same folder otherwise provide the path in which they are saved and run. Directives in a Module: To add a directive in module follow the steps: Creating a module like we did earlier:var app = angular.module("DemoApp", []); var app = angular.module("DemoApp", []); Creating a directive:app.directive("Directive-name", function() { return { template : "string or some code which is to be executed" }; }); app.directive("Directive-name", function() { return { template : "string or some code which is to be executed" }; }); Example: <!DOCTYPE html><html> <head> <title> Modules and Controllers in Files </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <div ng-app="GFG" w3-test-directive></div> <script> var gfg_app = angular.module("GFG", []); gfg_app.directive("w3TestDirective", function() { return { template : "Welcome to GeeksforGeeks!" }; }); </script> </body></html> Output: Welcome to GeeksforGeeks! Note: Here anything to be printed should not be put in the div which is calling the directive since it gets overwritten by the code in the template. Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular File Upload Auth Guards in Angular 9/10/11 Angular | keyup event What is AOT and JIT Compiler in Angular ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28271, "s": 28243, "text": "\n31 May, 2019" }, { "code": null, "e": 28550, "s": 28271, "text": "The AngularJS module defines the functionality of the application which is applied on the entire HTML page. It helps to link many components. So it is just a group of related components. It is a container which consists of different parts like controllers, services, directives." }, { "code": null, "e": 28693, "s": 28550, "text": "Note: This modules should be made in a normal HTML files like index.html and no need to create a new project in VisualStudio for this section." }, { "code": null, "e": 28717, "s": 28693, "text": "How to create a Module:" }, { "code": null, "e": 28762, "s": 28717, "text": "var app = angular.module(\"Module-name\", []);" }, { "code": null, "e": 28965, "s": 28762, "text": "In this [] we can add a list of components needed but we are not including any components in this case. This created module is bound with any tag like div, body, etc by adding it to the list of modules." }, { "code": "<div ng-app = \"module-name\"> The code in which the module is required.</div>", "e": 29045, "s": 28965, "text": null }, { "code": null, "e": 29066, "s": 29045, "text": "Adding a Controller:" }, { "code": null, "e": 29153, "s": 29066, "text": "app.controller(\"Controller-name\", function($scope) {\n $scope.variable-name= \"\";\n});" }, { "code": null, "e": 29313, "s": 29153, "text": "Here, we can add any number of variables in controller and use them in the html files, body of the tag in which the controller is added to that tag by writing:" }, { "code": "<body><div ng-app=\"Module-name\"> <div ng-controller=\"Controller-name\"> {{variable-name}} </div> <!-- This wont get printed since itsnot part of the div in which controller is included -->{{variable-name}} </div></body>", "e": 29547, "s": 29313, "text": null }, { "code": null, "e": 29992, "s": 29547, "text": "Module and Controllers in Files: While we can make modules and controllers in the same file along with the HTML file which requiring it however we may want to use this module in some other file. Hence this will lead to redundancy so we will prefer to create Module, Controller and HTML file separately. The Module and Controller are to be stored by using .js files and in order to use them in the HHTML file we have to include them in this way:" }, { "code": null, "e": 30001, "s": 29992, "text": "Example:" }, { "code": null, "e": 30455, "s": 30001, "text": "DemoComponent.js// Here the Component name is DemoComponent// so saving the file as DemoComponent.js app.controller('DemoController', function($scope) { $scope.list = ['A', 'E', 'I', 'O', 'U']; $scope.choice = 'Your choice is: GeeksforGeeks'; $scope.ch = function(choice) { $scope.choice = \"Your choice is: \" + choice; }; $scope.c = function() { $scope.choice = \"Your choice is: \" + $scope.mychoice; };});" }, { "code": "// Here the Component name is DemoComponent// so saving the file as DemoComponent.js app.controller('DemoController', function($scope) { $scope.list = ['A', 'E', 'I', 'O', 'U']; $scope.choice = 'Your choice is: GeeksforGeeks'; $scope.ch = function(choice) { $scope.choice = \"Your choice is: \" + choice; }; $scope.c = function() { $scope.choice = \"Your choice is: \" + $scope.mychoice; };});", "e": 30893, "s": 30455, "text": null }, { "code": null, "e": 30957, "s": 30893, "text": "Module-name: DemoApp.jsvar app = angular.module('DemoApp', []);" }, { "code": "var app = angular.module('DemoApp', []);", "e": 30998, "s": 30957, "text": null }, { "code": null, "e": 31954, "s": 30998, "text": "index.html file<!DOCTYPE html><html> <head> <title> Modules and Controllers in Files </title> </head> <body ng-app=\"DemoApp\"> <h1> Using controllers in Module </h1> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <script src=\"DemoApp.js\"></script> <script src=\"DemoController\"></script> <div ng-app=\"DemoApp\" ng-controller=\"DemoController\"> Vowels List : <button ng-click=\"ch('A')\" >A</button> <button ng-click=\"ch('E')\" >E</button> <button ng-click=\"ch('I')\" >I</button> <button ng-click=\"ch('O')\" >O</button> <button ng-click=\"ch('U')\" >U</button> <p>{{ choice }}</p> Vowels List : <select ng-options=\"option for option in list\" ng-model=\"mychoice\" ng-change=\"c()\"> </select> <p>{{ choice }}</p> </div></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> Modules and Controllers in Files </title> </head> <body ng-app=\"DemoApp\"> <h1> Using controllers in Module </h1> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <script src=\"DemoApp.js\"></script> <script src=\"DemoController\"></script> <div ng-app=\"DemoApp\" ng-controller=\"DemoController\"> Vowels List : <button ng-click=\"ch('A')\" >A</button> <button ng-click=\"ch('E')\" >E</button> <button ng-click=\"ch('I')\" >I</button> <button ng-click=\"ch('O')\" >O</button> <button ng-click=\"ch('U')\" >U</button> <p>{{ choice }}</p> Vowels List : <select ng-options=\"option for option in list\" ng-model=\"mychoice\" ng-change=\"c()\"> </select> <p>{{ choice }}</p> </div></body> </html>", "e": 32895, "s": 31954, "text": null }, { "code": null, "e": 32903, "s": 32895, "text": "Output:" }, { "code": null, "e": 33037, "s": 32903, "text": "Note: It makes sure the module and component files are in the same folder otherwise provide the path in which they are saved and run." }, { "code": null, "e": 33108, "s": 33037, "text": "Directives in a Module: To add a directive in module follow the steps:" }, { "code": null, "e": 33187, "s": 33108, "text": "Creating a module like we did earlier:var app = angular.module(\"DemoApp\", []);" }, { "code": null, "e": 33228, "s": 33187, "text": "var app = angular.module(\"DemoApp\", []);" }, { "code": null, "e": 33384, "s": 33228, "text": "Creating a directive:app.directive(\"Directive-name\", function() {\n return {\n template : \"string or some code which is to be executed\"\n };\n});\n" }, { "code": null, "e": 33519, "s": 33384, "text": "app.directive(\"Directive-name\", function() {\n return {\n template : \"string or some code which is to be executed\"\n };\n});\n" }, { "code": null, "e": 33528, "s": 33519, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Modules and Controllers in Files </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body> <div ng-app=\"GFG\" w3-test-directive></div> <script> var gfg_app = angular.module(\"GFG\", []); gfg_app.directive(\"w3TestDirective\", function() { return { template : \"Welcome to GeeksforGeeks!\" }; }); </script> </body></html>", "e": 34001, "s": 33528, "text": null }, { "code": null, "e": 34009, "s": 34001, "text": "Output:" }, { "code": null, "e": 34035, "s": 34009, "text": "Welcome to GeeksforGeeks!" }, { "code": null, "e": 34184, "s": 34035, "text": "Note: Here anything to be printed should not be put in the div which is calling the directive since it gets overwritten by the code in the template." }, { "code": null, "e": 34191, "s": 34184, "text": "Picked" }, { "code": null, "e": 34201, "s": 34191, "text": "AngularJS" }, { "code": null, "e": 34218, "s": 34201, "text": "Web Technologies" }, { "code": null, "e": 34316, "s": 34218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34360, "s": 34316, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 34380, "s": 34360, "text": "Angular File Upload" }, { "code": null, "e": 34411, "s": 34380, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 34433, "s": 34411, "text": "Angular | keyup event" }, { "code": null, "e": 34475, "s": 34433, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 34517, "s": 34475, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 34550, "s": 34517, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34593, "s": 34550, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 34655, "s": 34593, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to Pretty-Print Pandas DataFrames and Series | Towards Data Science
When we have to work with large pandas DataFrames that may also have multiple columns and rows it’s important to be able to display the DataFrames in a readable format. This is probably useful when debugging your code, too. By default, only a subset of columns is displayed to the standard output when a DataFrame is printed out and has fairly large number of columns. The displayed columns may even be printed out in multiple lines. In today’s article we are going to explore how to configure the required pandas options that will allow us to “pretty-print” pandas DataFrames. Suppose we have the following DataFrame: Now if the number of columns exceeds the value of the display option display.max_rows then the output DataFrame may be incomplete like the one shown below. Only a subset of the columns is displayed (column4 and column5 are missing) while the remaining columns are printed in a multi-line fashion. While the output is still somewhat readable it’s definitely not ideal to have columns left out or printed in multiple lines. If your monitor is wide enough and is able to fit more columns you may probably have to tweak a few display options. The values I’ll use below may not work for your setup so make sure to adjust them accordingly. Personally, I use an ultra-wide monitor I am able to print out fairly high number of columns when necessary. Now in order to display all the columns (if your monitor can fit them) and in just one line all you have to do is set the display option expand_frame_repr to False: pd.set_option('expand_frame_repr', False) display.expand_frame_repr default: True Whether to print out the full DataFrame repr for wide DataFrames across multiple lines, max_columns is still respected, but the output will wrap-around across multiple “pages” if its width exceeds display.width Alternatively, instead of setting expand_frame_repr to False you can change the value of display.max_rows: pd.set_option(‘display.max_rows’, False) Note that if the columns are still printed in multiple pages, then you may have to adjust display.width as well. Now if your DataFrame contains more than a certain number of rows, only a few records (coming from the head and tail of your df) will be displayed: If you want to display a wider range (or even all) of rows you need to set display.max_rows to the number of rows you want to output. If you want to display all the rows set it to None: pd.set_option('display.max_rows', None) A better approach is to use option_context() which is a context manager that you can use to temporarily set specific options in the with statement context. The are more display options you can tweak and change the way pandas DataFrames are displayed. display.max_colwidth: This is the maximum number of characters are displayed for column names. If a certain column name overflows, a placeholder (...)will be added instead. pd.set_option('display.max_colwidth', None) display.precision: This is the precision that will be used for floating points. It specifies the number of places after the decimal. display.width: This is the overall number of characters of the display. If you want to display more columns you may some times have to also adjust the display.width as well. You can find the full list of display using describe_option(): pd.describe_option(‘display’) . If you are working with Jupyter Notebooks, instead of print(df) simply use display(df) and the width will be adjusted accordingly. In todays article we discussed a few display options for pandas let you pretty-print DataFrames according to what you want to display and probably to what monitor you use, too. Pandas comes with an options system that lets users adjust and customize the display functionality. We covered only a small subset of the available display options. Make sure to read the Options and Settings section of the official documentation.
[ { "code": null, "e": 396, "s": 172, "text": "When we have to work with large pandas DataFrames that may also have multiple columns and rows it’s important to be able to display the DataFrames in a readable format. This is probably useful when debugging your code, too." }, { "code": null, "e": 606, "s": 396, "text": "By default, only a subset of columns is displayed to the standard output when a DataFrame is printed out and has fairly large number of columns. The displayed columns may even be printed out in multiple lines." }, { "code": null, "e": 750, "s": 606, "text": "In today’s article we are going to explore how to configure the required pandas options that will allow us to “pretty-print” pandas DataFrames." }, { "code": null, "e": 791, "s": 750, "text": "Suppose we have the following DataFrame:" }, { "code": null, "e": 1088, "s": 791, "text": "Now if the number of columns exceeds the value of the display option display.max_rows then the output DataFrame may be incomplete like the one shown below. Only a subset of the columns is displayed (column4 and column5 are missing) while the remaining columns are printed in a multi-line fashion." }, { "code": null, "e": 1213, "s": 1088, "text": "While the output is still somewhat readable it’s definitely not ideal to have columns left out or printed in multiple lines." }, { "code": null, "e": 1534, "s": 1213, "text": "If your monitor is wide enough and is able to fit more columns you may probably have to tweak a few display options. The values I’ll use below may not work for your setup so make sure to adjust them accordingly. Personally, I use an ultra-wide monitor I am able to print out fairly high number of columns when necessary." }, { "code": null, "e": 1699, "s": 1534, "text": "Now in order to display all the columns (if your monitor can fit them) and in just one line all you have to do is set the display option expand_frame_repr to False:" }, { "code": null, "e": 1741, "s": 1699, "text": "pd.set_option('expand_frame_repr', False)" }, { "code": null, "e": 1767, "s": 1741, "text": "display.expand_frame_repr" }, { "code": null, "e": 1781, "s": 1767, "text": "default: True" }, { "code": null, "e": 1992, "s": 1781, "text": "Whether to print out the full DataFrame repr for wide DataFrames across multiple lines, max_columns is still respected, but the output will wrap-around across multiple “pages” if its width exceeds display.width" }, { "code": null, "e": 2099, "s": 1992, "text": "Alternatively, instead of setting expand_frame_repr to False you can change the value of display.max_rows:" }, { "code": null, "e": 2140, "s": 2099, "text": "pd.set_option(‘display.max_rows’, False)" }, { "code": null, "e": 2253, "s": 2140, "text": "Note that if the columns are still printed in multiple pages, then you may have to adjust display.width as well." }, { "code": null, "e": 2401, "s": 2253, "text": "Now if your DataFrame contains more than a certain number of rows, only a few records (coming from the head and tail of your df) will be displayed:" }, { "code": null, "e": 2587, "s": 2401, "text": "If you want to display a wider range (or even all) of rows you need to set display.max_rows to the number of rows you want to output. If you want to display all the rows set it to None:" }, { "code": null, "e": 2627, "s": 2587, "text": "pd.set_option('display.max_rows', None)" }, { "code": null, "e": 2783, "s": 2627, "text": "A better approach is to use option_context() which is a context manager that you can use to temporarily set specific options in the with statement context." }, { "code": null, "e": 2878, "s": 2783, "text": "The are more display options you can tweak and change the way pandas DataFrames are displayed." }, { "code": null, "e": 3051, "s": 2878, "text": "display.max_colwidth: This is the maximum number of characters are displayed for column names. If a certain column name overflows, a placeholder (...)will be added instead." }, { "code": null, "e": 3095, "s": 3051, "text": "pd.set_option('display.max_colwidth', None)" }, { "code": null, "e": 3228, "s": 3095, "text": "display.precision: This is the precision that will be used for floating points. It specifies the number of places after the decimal." }, { "code": null, "e": 3402, "s": 3228, "text": "display.width: This is the overall number of characters of the display. If you want to display more columns you may some times have to also adjust the display.width as well." }, { "code": null, "e": 3465, "s": 3402, "text": "You can find the full list of display using describe_option():" }, { "code": null, "e": 3498, "s": 3465, "text": "pd.describe_option(‘display’) . " }, { "code": null, "e": 3629, "s": 3498, "text": "If you are working with Jupyter Notebooks, instead of print(df) simply use display(df) and the width will be adjusted accordingly." }, { "code": null, "e": 3806, "s": 3629, "text": "In todays article we discussed a few display options for pandas let you pretty-print DataFrames according to what you want to display and probably to what monitor you use, too." } ]
How to manipulate Date in PowerShell?
To add/remove date from the date string you need to use AddDay() method. For example, We need to add 6 days to the current date. (Get-Date).AddDays(6) 25 March 2020 22:40:36 To go back to the specific number of days, the same AddDays() method will be used but the numbers are negative. For example, (Get-Date).AddDays(-6) 13 March 2020 22:45:34
[ { "code": null, "e": 1148, "s": 1062, "text": "To add/remove date from the date string you need to use AddDay() method. For example," }, { "code": null, "e": 1191, "s": 1148, "text": "We need to add 6 days to the current date." }, { "code": null, "e": 1236, "s": 1191, "text": "(Get-Date).AddDays(6)\n25 March 2020 22:40:36" }, { "code": null, "e": 1348, "s": 1236, "text": "To go back to the specific number of days, the same AddDays() method will be used but the numbers are negative." }, { "code": null, "e": 1362, "s": 1348, "text": " For example," }, { "code": null, "e": 1408, "s": 1362, "text": "(Get-Date).AddDays(-6)\n13 March 2020 22:45:34" } ]
Removing Duplicate or Similar Images in Python | by Angel Igareta | Towards Data Science
One of the most naive approaches to detecting duplicate images would be to compare pixel by pixel by checking that all values are the same. However, this becomes very inefficient when testing a large number of images. A second very common approach would be to extract the cryptographic hash of both images and compare if they are the same, using popular hash algorithms such as MD5 or SHA-1. Although this approach is much more efficient, it would only detect identical images. In case one of the pixels differs (due to a slight change in lighting, for example) the hashes would be completely different. The reason for this is that the data used by these cryptographic algorithms is based only on the pixels of the image and a random seed. The same data and the same seed will produce the same result, but different data will generate different results. For our use case, it would make more sense for similar images to have similar hashes, right? That is precisely the goal of image hashing algorithms. They focus on the structure of the image and its visual appearance to calculate the hash. Depending on your use case, some algorithms will be better than others. For instance, if you want images with the same shape but different colors to have the same hash, perceptual or difference hashing could be used. Keep in mind that there is always the possibility of using a larger image hash size and obtaining less similar images, which, depending on the use case, would have to be hyper-tuned. For use in Python, I recommend the ImageHash library, which supports multiple image hashing algorithms, such as average, perceptual, difference, wavelet, HSV-color, and crop-resistant. It can be easily installed with the following command: pip install imagehash As stated above, each algorithm can have its hash size adjusted, the higher this size is, the more sensitive to changes the hash is. Based on my experience, I recommend using the dhash algorithm with hash size 8 and the z-transformation available in the repository. Below you can see the code needed to load an image, transform it and calculate the d-hash, which is encapsulated in the dhash_z_transformed method. To apply it in a data pipeline, simply call the dhash_z_transformed method with the path of the image you want to hash. If the method produces the same hash for two images, it means that they are very similar. You can then choose to remove duplicates by keeping one copy or neither, depending on your use case. I encourage you to adjust the sensitivity threshold by changing the hash_size for finer results to your use case. In this short post, I have presented an important step to take into account when training machine learning models that receive images as input. Instead of showing how to detect only identical images, I introduce image hashing algorithms to identify also similar images (different size but same image, slight changes in brightness...). Finally, I provide examples of how to compute these image hashes in Python using an external library. If you want to discover more posts like this one, you can find me at:
[ { "code": null, "e": 390, "s": 172, "text": "One of the most naive approaches to detecting duplicate images would be to compare pixel by pixel by checking that all values are the same. However, this becomes very inefficient when testing a large number of images." }, { "code": null, "e": 776, "s": 390, "text": "A second very common approach would be to extract the cryptographic hash of both images and compare if they are the same, using popular hash algorithms such as MD5 or SHA-1. Although this approach is much more efficient, it would only detect identical images. In case one of the pixels differs (due to a slight change in lighting, for example) the hashes would be completely different." }, { "code": null, "e": 1026, "s": 776, "text": "The reason for this is that the data used by these cryptographic algorithms is based only on the pixels of the image and a random seed. The same data and the same seed will produce the same result, but different data will generate different results." }, { "code": null, "e": 1119, "s": 1026, "text": "For our use case, it would make more sense for similar images to have similar hashes, right?" }, { "code": null, "e": 1337, "s": 1119, "text": "That is precisely the goal of image hashing algorithms. They focus on the structure of the image and its visual appearance to calculate the hash. Depending on your use case, some algorithms will be better than others." }, { "code": null, "e": 1482, "s": 1337, "text": "For instance, if you want images with the same shape but different colors to have the same hash, perceptual or difference hashing could be used." }, { "code": null, "e": 1665, "s": 1482, "text": "Keep in mind that there is always the possibility of using a larger image hash size and obtaining less similar images, which, depending on the use case, would have to be hyper-tuned." }, { "code": null, "e": 1850, "s": 1665, "text": "For use in Python, I recommend the ImageHash library, which supports multiple image hashing algorithms, such as average, perceptual, difference, wavelet, HSV-color, and crop-resistant." }, { "code": null, "e": 1905, "s": 1850, "text": "It can be easily installed with the following command:" }, { "code": null, "e": 1927, "s": 1905, "text": "pip install imagehash" }, { "code": null, "e": 2193, "s": 1927, "text": "As stated above, each algorithm can have its hash size adjusted, the higher this size is, the more sensitive to changes the hash is. Based on my experience, I recommend using the dhash algorithm with hash size 8 and the z-transformation available in the repository." }, { "code": null, "e": 2341, "s": 2193, "text": "Below you can see the code needed to load an image, transform it and calculate the d-hash, which is encapsulated in the dhash_z_transformed method." }, { "code": null, "e": 2652, "s": 2341, "text": "To apply it in a data pipeline, simply call the dhash_z_transformed method with the path of the image you want to hash. If the method produces the same hash for two images, it means that they are very similar. You can then choose to remove duplicates by keeping one copy or neither, depending on your use case." }, { "code": null, "e": 2766, "s": 2652, "text": "I encourage you to adjust the sensitivity threshold by changing the hash_size for finer results to your use case." }, { "code": null, "e": 2910, "s": 2766, "text": "In this short post, I have presented an important step to take into account when training machine learning models that receive images as input." }, { "code": null, "e": 3203, "s": 2910, "text": "Instead of showing how to detect only identical images, I introduce image hashing algorithms to identify also similar images (different size but same image, slight changes in brightness...). Finally, I provide examples of how to compute these image hashes in Python using an external library." } ]
What are the rules for a local variable in lambda expression in Java?
A lambda expression can capture variables like local and anonymous classes. In other words, they have the same access to local variables of the enclosing scope. We need to follow some rules in case of local variables in lambda expressions. A lambda expression can't define any new scope as an anonymous inner class does, so we can't declare a local variable with the same which is already declared in the enclosing scope of a lambda expression. Inside lambda expression, we can't assign any value to some local variable declared outside the lambda expression. Because the local variables declared outside the lambda expression can be final or effectively final. The rule of final or effectively final is also applicable for method parameters and exception parameters. The this and super references inside a lambda expression body are the same as their enclosing scope. Because lambda expressions can't define any new scope. import java.util.function.Consumer; public class LambdaTest { public int x = 1; class FirstLevel { public int x = 2; void methodInFirstLevel(int x) { Consumer<Integer> myConsumer = (y) -> { // Lambda Expression System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("this.x = " + this.x); System.out.println("LambdaTest.this.x = " + LambdaTest.this.x); }; myConsumer.accept(x); } } public static void main(String args[]) { final LambdaTest outerClass = new LambdaTest(); final LambdaTest.FirstLevel firstLevelClass = outerClass.new FirstLevel(); firstLevelClass.methodInFirstLevel(10); } } x = 10 y = 10 this.x = 2 LambdaTest.this.x = 1
[ { "code": null, "e": 1302, "s": 1062, "text": "A lambda expression can capture variables like local and anonymous classes. In other words, they have the same access to local variables of the enclosing scope. We need to follow some rules in case of local variables in lambda expressions." }, { "code": null, "e": 1507, "s": 1302, "text": "A lambda expression can't define any new scope as an anonymous inner class does, so we can't declare a local variable with the same which is already declared in the enclosing scope of a lambda expression." }, { "code": null, "e": 1724, "s": 1507, "text": "Inside lambda expression, we can't assign any value to some local variable declared outside the lambda expression. Because the local variables declared outside the lambda expression can be final or effectively final." }, { "code": null, "e": 1830, "s": 1724, "text": "The rule of final or effectively final is also applicable for method parameters and exception parameters." }, { "code": null, "e": 1986, "s": 1830, "text": "The this and super references inside a lambda expression body are the same as their enclosing scope. Because lambda expressions can't define any new scope." }, { "code": null, "e": 2733, "s": 1986, "text": "import java.util.function.Consumer;\n\npublic class LambdaTest {\n public int x = 1;\n class FirstLevel {\n public int x = 2;\n void methodInFirstLevel(int x) {\n Consumer<Integer> myConsumer = (y) -> { // Lambda Expression\n System.out.println(\"x = \" + x);\n System.out.println(\"y = \" + y);\n System.out.println(\"this.x = \" + this.x);\n System.out.println(\"LambdaTest.this.x = \" + LambdaTest.this.x);\n };\n myConsumer.accept(x);\n }\n }\n public static void main(String args[]) {\n final LambdaTest outerClass = new LambdaTest();\n final LambdaTest.FirstLevel firstLevelClass = outerClass.new FirstLevel();\n firstLevelClass.methodInFirstLevel(10);\n }\n}" }, { "code": null, "e": 2780, "s": 2733, "text": "x = 10\ny = 10\nthis.x = 2\nLambdaTest.this.x = 1" } ]
Frequency of each character in String in Python
Text processing has emerged as an important field in machine learning and AI. Python supports this filed with many available tools and libraries. In this article we will see how we can find the number of occurrence of each letter of a given string. The Counter method counts the number of occurrences of an element in an iterable. So it is straight forward to use by passing the required string into it. Live Demo from collections import Counter # Given string strA = "timeofeffort" print("Given String: ",strA) # Using counter res = {} for keys in strA: res[keys] = res.get(keys, 0) + 1 # Result print("Frequency of each character :\n ",res) Running the above code gives us the following result − Given String: timeofeffort Frequency of each character : {'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1} We can treat the string as a dictionary and count the keys for each character using get() in a for loop. Live Demo # Given string strA = "timeofeffort" print("Given String: ",strA) # Using counter res = {} for keys in strA: res[keys] = res.get(keys, 0) + 1 # Result print("Frequency of each character :\n ",res) Running the above code gives us the following result − Given String: timeofeffort Frequency of each character : {'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1} A set in python stores unique elements. So we can use it wisely by counting the number of times the same character is encountered again and again when looping through the string as an iterable. Live Demo # Given string strA = "timeofeffort" print("Given String: ",strA) # Using counter res = {} res={n: strA.count(n) for n in set(strA)} # Result print("Frequency of each character :\n ",res) Running the above code gives us the following result − Given String: timeofeffort Frequency of each character : {'f': 3, 'r': 1, 'm': 1, 'o': 2, 'i': 1, 't': 2, 'e': 2}
[ { "code": null, "e": 1311, "s": 1062, "text": "Text processing has emerged as an important field in machine learning and AI. Python supports this filed with many available tools and libraries. In this article we will see how we can find the number of occurrence of each letter of a given string." }, { "code": null, "e": 1466, "s": 1311, "text": "The Counter method counts the number of occurrences of an element in an iterable. So it is straight forward to use by passing the required string into it." }, { "code": null, "e": 1477, "s": 1466, "text": " Live Demo" }, { "code": null, "e": 1709, "s": 1477, "text": "from collections import Counter\n\n# Given string\nstrA = \"timeofeffort\"\nprint(\"Given String: \",strA)\n# Using counter\nres = {}\n\nfor keys in strA:\nres[keys] = res.get(keys, 0) + 1\n\n# Result\nprint(\"Frequency of each character :\\n \",res)" }, { "code": null, "e": 1764, "s": 1709, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1878, "s": 1764, "text": "Given String: timeofeffort\nFrequency of each character :\n{'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1}" }, { "code": null, "e": 1983, "s": 1878, "text": "We can treat the string as a dictionary and count the keys for each character using get() in a for loop." }, { "code": null, "e": 1994, "s": 1983, "text": " Live Demo" }, { "code": null, "e": 2193, "s": 1994, "text": "# Given string\nstrA = \"timeofeffort\"\nprint(\"Given String: \",strA)\n# Using counter\nres = {}\n\nfor keys in strA:\nres[keys] = res.get(keys, 0) + 1\n\n# Result\nprint(\"Frequency of each character :\\n \",res)" }, { "code": null, "e": 2248, "s": 2193, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2362, "s": 2248, "text": "Given String: timeofeffort\nFrequency of each character :\n{'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1}" }, { "code": null, "e": 2556, "s": 2362, "text": "A set in python stores unique elements. So we can use it wisely by counting the number of times the same character is encountered again and again when looping through the string as an iterable." }, { "code": null, "e": 2567, "s": 2556, "text": " Live Demo" }, { "code": null, "e": 2757, "s": 2567, "text": "# Given string\nstrA = \"timeofeffort\"\nprint(\"Given String: \",strA)\n# Using counter\nres = {}\n\nres={n: strA.count(n) for n in set(strA)}\n\n# Result\nprint(\"Frequency of each character :\\n \",res)" }, { "code": null, "e": 2812, "s": 2757, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2926, "s": 2812, "text": "Given String: timeofeffort\nFrequency of each character :\n{'f': 3, 'r': 1, 'm': 1, 'o': 2, 'i': 1, 't': 2, 'e': 2}" } ]