Thresholding with OpenCV

Thresholding is a technique that converts a grayscale or color image into a binary image, where each pixel is either black or white. Thresholding can be useful for image segmentation, edge detection, and other applications. In this blog post, I will show you how to perform different types of thresholding with OpenCV, a popular library for computer vision in Python.

Simple Thresholding

Simple thresholding is the simplest way of thresholding, where we use a global value as a threshold. If the pixel value is below the threshold, it is set to black; otherwise, it is set to white. We can use the cv2.threshold function to apply simple thresholding. The function takes four arguments: the source image, the threshold value, the maximum value, and the thresholding type. The function returns two values: the threshold value used and the thresholded image.

Here is an example of simple thresholding with OpenCV:import cv2 import numpy as np from matplotlib import pyplot as plt # Read the image and convert it to grayscale img = cv2.imread('ex2.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply simple thresholding with a threshold value of 127 and a maximum value of 255 ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # Show the original and thresholded images plt.subplot(121), plt.imshow(img, cmap='gray') plt.title('Original Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(thresh, cmap='gray') plt.title('Thresholded Image'), plt.xticks([]), plt.yticks([]) plt.show()

The output of the code is:

Simple Thresholding

We can see that the thresholded image has only two colors: black and white. The pixels that are below 127 are set to black, and the pixels that are above 127 are set to white.

Adaptive Thresholding

Simple thresholding may not work well if the image has different lighting conditions in different regions. In that case, adaptive thresholding can help. Adaptive thresholding determines the threshold for each pixel based on a small region around it. This way, we can get different thresholds for different regions of the same image, which can improve the results for images with varying illumination.

To apply adaptive thresholding, we can use the cv2.adaptiveThreshold function. The function takes six arguments: the source image, the maximum value, the adaptive method, the thresholding type, the block size, and a constant value. The function returns the thresholded image.

The adaptive method can be one of the following:

  • cv2.ADAPTIVE_THRESH_MEAN_C: The threshold value is the mean of the neighborhood area minus the constant C.
  • cv2.ADAPTIVE_THRESH_GAUSSIAN_C: The threshold value is the weighted sum of the neighborhood area minus the constant C. The weights are a Gaussian window.

The block size determines the size of the neighborhood area. It must be an odd number.

Here is an example of adaptive thresholding with OpenCV:import cv2 import numpy as np from matplotlib import pyplot as plt # Read the image and convert it to grayscale img = cv2.imread('ex2.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply simple thresholding with a threshold value of 127 and a maximum value of 255 ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # Apply adaptive thresholding with a block size of 11 and a constant of 2 # Use the mean method and the binary thresholding type thresh2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2) # Apply adaptive thresholding with a block size of 11 and a constant of 2 # Use the Gaussian method and the binary thresholding type thresh3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) # Show the original and thresholded images titles = ['Original Image', 'Simple Thresholding', 'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding'] images = [img, thresh1, thresh2, thresh3] for i in range(4): plt.subplot(2, 2, i+1), plt.imshow(images[i], 'gray') plt.title(titles[i]), plt.xticks([]), plt.yticks([]) plt.show()

The output of the code is:

Adaptive Thresholding

We can see that the adaptive thresholding images are better than the simple thresholding image, especially for the regions that have different lighting conditions. The adaptive mean thresholding image has some noise, while the adaptive Gaussian thresholding image is smoother.

Otsu’s Thresholding

Otsu’s thresholding is another way of thresholding, where we do not need to specify the threshold value manually. Instead, the algorithm finds the optimal threshold value that minimizes the within-class variance of the pixel values. Otsu’s thresholding can be useful for images that have a bimodal histogram, where the pixel values are clustered into two distinct groups.

To apply Otsu’s thresholding, we can use the same cv2.threshold function as before, but with an extra flag: cv2.THRESH_OTSU. The function will then ignore the threshold value argument and use Otsu’s algorithm to find the optimal threshold. The function will return the optimal threshold value and the thresholded image.

Here is an example of Otsu’s thresholding with OpenCV:import cv2 import numpy as np from matplotlib import pyplot as plt # Read the image and convert it to grayscale img = cv2.imread('ex2.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply simple thresholding with a threshold value of 127 and a maximum value of 255 ret1, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # Apply Otsu's thresholding with a maximum value of 255 # The threshold value will be determined by the algorithm ret2, thresh2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Show the original and thresholded images titles = ['Original Image', 'Simple Thresholding', 'Otsu\'s Thresholding'] images = [img, thresh1, thresh2] for i in range(3): plt.subplot(1, 3, i+1), plt.imshow(images[i], 'gray') plt.title(titles[i]), plt.xticks([]), plt.yticks([]) plt.show() # Print the threshold values print('Simple Thresholding:', ret1) print('Otsu\'s Thresholding:', ret2)

The output of the code is:

Otsu's Thresholding

Simple Thresholding: 127.0
Otsu’s Thresholding: 121.0

We can see that the Otsu’s thresholding image is similar to the simple thresholding image, but with a slightly different threshold value. The Otsu’s algorithm found that 121 is the optimal threshold value for this image, which minimizes the within-class variance.

Conclusion

In this blog post, I have shown you how to perform different types of thresholding with OpenCV, such as simple thresholding, adaptive thresholding, and Otsu’s thresholding. Thresholding is a useful technique for image processing and computer vision, as it can help to segment, detect, and enhance images. I hope you have learned something new and useful from this post. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!

Source: Conversation with Bing, 2/16/2024
(1) OpenCV: Image Thresholding. https://docs.opencv.org/3.4/d7/d4d/tutorial_py_thresholding.html.
(2) Image Thresholding in Python OpenCV – GeeksforGeeks. https://www.geeksforgeeks.org/image-thresholding-in-python-opencv/.
(3) OpenCV cv2.threshold() Function – Scaler Topics. https://www.scaler.com/topics/cv2-threshold/.
(4) Simple Thresholding with OpenCV and Python – Jeremy Morgan. https://www.jeremymorgan.com/tutorials/opencv/simple-thresholding/.
(5) github.com. https://github.com/alex-ta/ImageProcessing/tree/dfeb8b4d80bfc1cfda8ea0d39a38d090f7410d3b/test%20-%20Kopie.py.
(6) github.com. https://github.com/zkzk5214/Py_road/tree/a67edc1604d468a37ab967d35ab1dc1f7a4f7742/openCV%2F15_Threshold%2F15_2.py.
(7) github.com. https://github.com/samuelxu999/Research/tree/187965ff3c86a02c7f5cc853d4cdb77ec805a786/OpenCV%2Fpy_dev%2Fsrc%2Ftest_demo%2FImageProcessing%2FImageThresholding.py.
(8) github.com. https://github.com/jgj03/opencv_library_basics/tree/b10f5871c1d4c5169385275abab59712b9bca364/001_opencv_basics.py.

What You Need to Know About Pet First Aid

If you have a pet, you know how much they mean to you. They are part of your family and you want to keep them safe and healthy. But what if your pet gets injured or sick? Do you know what to do in an emergency?

Pet first aid is the immediate care you provide to your pet when they are hurt or ill until you can get them to a veterinarian. It can make a difference between life and death, recovery and disability, or comfort and pain for your pet.

In this blog post, we will cover some basic tips and skills for pet first aid that every pet owner should know.

What should you have in your pet first aid kit?

It is a good idea to have a pet first aid kit at home and in your car, so you are prepared for any situation. You can buy a ready-made kit or make your own with some common items. Here are some things you should have in your pet first aid kitAd1:

  • Antiseptic spray or ointment
  • Hydrogen peroxide for cleaning wounds
  • Gauze, cotton balls, bandage material, adhesive tape
  • A pair of tweezers and a pair of scissors
  • A digital thermometer
  • A muzzle or a soft cloth to prevent biting
  • A leash or a carrier to restrain your pet
  • A blanket or a towel to keep your pet warm
  • Gloves to protect yourself from infection
  • Your veterinarian’s phone number and address
  • A copy of your pet’s medical records and medications

How do you perform CPR on your pet?

CPR stands for cardiopulmonary resuscitation. It is a lifesaving technique that can help restore breathing and blood circulation in your pet if they stop breathing or their heart stops beating. CPR should only be performed if your pet is unconscious and has no pulse2.

To perform CPR on your pet, follow these steps2:

  1. Check for breathing and pulse. You can use your hand to feel for the chest movement or the heartbeat on the left side of the chest. You can also use a stethoscope if you have one.
  2. If there is no breathing or pulse, place your pet on their right side on a flat surface. Make sure their neck is straight and their mouth is closed.
  3. For dogs, place one hand over the rib cage where the elbow touches the chest. For cats and small dogs, place one hand over the heart. Compress the chest about one-third to one-half of its width at a rate of 100 to 120 compressions per minute.
  4. After 30 compressions, give two rescue breaths by gently holding the mouth closed and blowing into the nose until you see the chest rise. Repeat the cycle of 30 compressions and two breaths until your pet starts breathing or has a pulse, or until you reach a veterinary clinic.
  5. If possible, have someone else call your veterinarian or drive you to the nearest emergency hospital while you perform CPR.

How do you treat common injuries and illnesses in your pet?

There are many situations where your pet may need first aid care. Some of them are:

How do you prevent accidents and emergencies with your pet?

The best way to keep your pet safe and healthy is to prevent accidents and emergencies from happening in the first place. Here are some tips to prevent common hazards for your pet4:

  • Keep your pet up to date on their vaccinations and parasite prevention.
  • Spay or neuter your pet to reduce the risk of reproductive diseases and unwanted pregnancies.
  • Microchip and tag your pet with your contact information in case they get lost or stolen.
  • Keep your pet on a leash or in a carrier when outside or in unfamiliar places.
  • Avoid feeding your pet human foods that can be toxic or harmful, such as chocolate, grapes, onions, garlic, xylitol, alcohol, etc.
  • Store medications, household cleaners, antifreeze, pesticides, and other chemicals out of reach of your pet.
  • Provide your pet with adequate water, food, shelter, exercise, and socialization.
  • Train your pet to obey basic commands and avoid aggressive or fearful behaviors.
  • Regularly check your pet for signs of illness or injury and visit your veterinarian for routine check-ups.

Conclusion

Pet first aid is an essential skill for every pet owner. It can help you save your pet’s life in an emergency or reduce their pain and suffering until you can get them to a veterinarian. By having a pet first aid kit, knowing how to perform CPR, treating common injuries and illnesses, and preventing accidents and emergencies, you can be prepared for any situation that may arise with your pet.

We hope this blog post has been helpful and informative for you. If you have any questions or comments, please feel free to leave them below. And remember, if your pet is in serious trouble, always call your veterinarian or an emergency clinic right away.

Thank you for reading and stay safe!

Creational Design Patterns in Kotlin Android

Creational design patterns are a set of solutions to common software development problems that deal with how objects are being created. Using such patterns will ensure that your code is flexible and reusable, and that you avoid hard-coded dependencies and tight coupling between classes.

In this blog post, I will show you some of the most important and widely used creational design patterns in Kotlin Android. You will learn how to apply these patterns to your projects and how they can help you write better and more maintainable code. I will cover four creational design patterns:

  • Factory and abstract factory (provider model) method
  • Singleton
  • Builder
  • Dependency injection

Factory and abstract factory (provider model) method

The factory method pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. The abstract factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

These patterns are useful when you want to decouple the creation of objects from their usage, or when you want to provide different implementations of the same interface depending on some conditions. For example, you can use these patterns to create different types of views or fragments based on the device configuration or user preferences.

In Kotlin, you can use the provider model to implement these patterns. The provider model is a way of creating objects using lambda expressions or function references that act as factories. For example, you can use a provider function to create different types of fragments based on a parameter:

// An interface for fragments that display some content interface ContentFragment { fun showContent(content: String) } // A concrete implementation of ContentFragment that shows content in a text view class TextFragment : Fragment(), ContentFragment { private lateinit var textView: TextView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.text_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) textView = view.findViewById(R.id.text_view) } override fun showContent(content: String) { textView.text = content } } // Another concrete implementation of ContentFragment that shows content in a web view class WebFragment : Fragment(), ContentFragment { private lateinit var webView: WebView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.web_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) webView = view.findViewById(R.id.web_view) } override fun showContent(content: String) { webView.loadUrl(content) } } // A provider function that returns a ContentFragment based on a parameter fun provideContentFragment(type: String): ContentFragment = when (type) { "text" -> TextFragment() "web" -> WebFragment() else -> throw IllegalArgumentException("Unknown type: $type") }

Singleton

The singleton pattern ensures that a class has only one instance and provides a global point of access to it. This pattern is useful when you want to have a single source of truth for some data or functionality in your app. For example, you can use this pattern to create a repository that handles data access from different sources.

In Kotlin, you can use the object declaration to create a singleton class. The object declaration combines a class declaration and a single instance of that class into one expression. For example, you can use an object declaration to create a news repository that fetches data from a remote data source:

// A singleton class that acts as a repository for news data object NewsRepository { // A reference to the remote data source private val newsRemoteDataSource = // getDataSource() // A flow that emits the latest news from the remote data source val latestNews: Flow<List<ArticleHeadline>> = newsRemoteDataSource.latestNews // A function that returns the details of an article by its id suspend fun getArticleDetails(id: String): ArticleDetails { return newsRemoteDataSource.getArticleDetails(id) } }

Builder

The builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. This pattern is useful when you want to create objects with many optional parameters or when you want to have more control over how the object is constructed. For example, you can use this pattern to create an alert dialog with various options.

In Kotlin, you can use named arguments and default values to implement this pattern. Named arguments allow you to specify the name of a parameter when calling a function, which makes the code more readable and avoids errors when there are many parameters. Default values allow you to omit some parameters when calling a function if they have a predefined value. For example, you can use named arguments and default values to create an alert dialog builder class:

// A class that represents an alert dialog with various options class AlertDialog( val title: String, val message: String, val positiveButton: String = "OK", val negativeButton: String? = null, val icon: Int? = null, val onPositiveClick: () -> Unit = {}, val onNegativeClick: () -> Unit = {} ) { // A function that shows the alert dialog on the screen fun show() { // Create and display an alert dialog using the Android SDK ... } } // A builder class that creates an AlertDialog instance using named arguments and default values class AlertDialogBuilder { // A function that returns an AlertDialog instance with the given parameters fun build( title: String, message: String, positiveButton: String = "OK", negativeButton: String? = null, icon: Int? = null, onPositiveClick: () -> Unit = {}, onNegativeClick: () -> Unit = {} ): AlertDialog { return AlertDialog( title = title, message = message, positiveButton = positiveButton, negativeButton = negativeButton, icon = icon, onPositiveClick = onPositiveClick, onNegativeClick = onNegativeClick ) } }

Dependency injection

The dependency injection pattern is a technique whereby one object supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.

This pattern is useful when you want to reduce coupling and increase testability between classes by delegating the responsibility of creating and providing dependencies to another object or framework. For example, you can use this pattern to inject dependencies into your activities or view models.

In Kotlin Android, you can use frameworks like Dagger or Koin to implement this pattern. These frameworks provide annotations or DSLs to define dependencies and inject them into your classes. For example, you can use Koin to inject dependencies into your view model:

// A class that represents a user profile view model with some dependencies class UserProfileViewModel( private val userRepository: UserRepository, private val analyticsService: AnalyticsService ) : ViewModel() { // Some view model logic using userRepository and analyticsService ... } // A module that defines dependencies using Koin DSL val appModule = module { // Define UserRepository as a singleton using factory function single<UserRepository> { UserRepositoryImpl(get()) } // Define AnalyticsService as a singleton using constructor injection single<AnalyticsService> { AnalyticsServiceImpl() } // Define UserProfileViewModel using constructor injection viewModel { UserProfileViewModel(get(), get()) } } // Start Koin with appModule in Application class class MyApp : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@MyApp) modules(appModule) } } } // Get UserProfileViewModel instance using Koin extension function in Activity class class UserProfileActivity : AppCompatActivity() { // Inject UserProfileViewModel private val viewModel by viewModel<UserProfileViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user_profile) // Use viewModel ... } }

Conclusion

In this blog post, you learned how to use creational design patterns in Kotlin Android. You learned how to apply these patterns to your projects and how they can help you write better and more maintainable code. You learned how to use factory and abstract factory (provider model) method, singleton, builder, and dependency injection patterns.

If you want to learn more about design patterns and other Kotlin features for Android development, check out these resources:

I hope you enjoyed this blog post and found it useful. Happy coding! 😊

How to use Flow in Android Programming

Flow is a stream processing API in Kotlin developed by JetBrains1It’s an implementation of the Reactive Stream specification, an initiative whose goal is to provide a standard for asynchronous stream processing1Jetbrains built Kotlin Flow on top of Kotlin Coroutines, which means that you can use suspend functions to produce and consume values asynchronously2.

In this blog post, I will show you how to use Flow in your Android project to handle live data updates and endless streams of data. You will learn how to create flows, modify them, collect them, and use StateFlow and SharedFlow to share state and events across your app.

Creating a flow

To create flows, use the flow builder APIs. The flow builder function creates a new flow where you can manually emit new values into the stream of data using the emit function2. For example, you can use a flow to receive live updates from a network API:

class NewsRemoteDataSource( private val newsApi: NewsApi, private val refreshIntervalMs: Long = 5000 ) { val latestNews: Flow<List<ArticleHeadline>> = flow { while(true) { val latestNews = newsApi.fetchLatestNews() emit(latestNews) // Emits the result of the request to the flow delay(refreshIntervalMs) // Suspends the coroutine for some time } } } // Interface that provides a way to make network requests with suspend functions interface NewsApi { suspend fun fetchLatestNews(): List<ArticleHeadline> }

The flow builder is executed within a coroutine. Thus, it benefits from the same asynchronous APIs, but some restrictions apply:

Modifying the stream

You can use various operators to transform or filter the values emitted by a flow. For example, you can use map to apply a function to each value, filter to remove unwanted values, or combine to merge two flows into one2. For example, you can use map to convert the list of article headlines into a list of article titles:

val latestNewsTitles: Flow<List<String>> = latestNews.map { headlines -> headlines.map { headline -> headline.title } }

You can also use operators that are specific to flows, such as debounce or distinctUntilChanged. These operators help you deal with flows that emit values too frequently or unnecessarily2. For example, you can use debounce to ignore values that are emitted in quick succession:

val debouncedNewsTitles: Flow<List<String>> = latestNewsTitles.debounce(1000) // Ignores values that are emitted less than 1000 ms apart

Collecting from a flow

To start receiving values from a flow, you need to collect it. Collecting is a terminal operation that triggers the execution of the flow and invokes a given action for every value emitted by the flow2. You need to collect flows from a coroutine or a suspend function. For example, you can collect the debounced news titles from an activity:

class LatestNewsActivity : AppCompatActivity() { private val newsRemoteDataSource = // getDataSource() override fun onCreate(savedInstanceState: Bundle?) { ... // Start a coroutine in the lifecycle scope lifecycleScope.launch { // repeatOnLifecycle launches the block in a new coroutine every time the // lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED. repeatOnLifecycle(Lifecycle.State.STARTED) { // Trigger the flow and start listening for values. newsRemoteDataSource.debouncedNewsTitles.collect { titles -> // Update UI with new titles } } } } }

Note that collecting from a flow can be a suspending operation if the flow is infinite or slow. This means that you should not collect from multiple flows sequentially in the same coroutine, as this will block the execution of the next collect until the previous one finishes. Instead, you should launch multiple coroutines or use other operators like zip or flatMapMerge to collect from multiple flows concurrently2.

StateFlow and SharedFlow

StateFlow and SharedFlow are Flow APIs that enable flows to optimally emit state updates and emit values to multiple consumers3.

StateFlow is a state-holder observable flow that emits the current and new state updates to its collectors. The current state value can also be read through its value property. To update state and send it to the flow, assign a new value to the value property of the MutableStateFlow class3.

In Android, StateFlow is a great fit for classes that need to maintain an observable mutable state. For example, you can use StateFlow to expose UI state from a ViewModel:

class LatestNewsViewModel( private val newsRepository: NewsRepository ) : ViewModel() { // Backing property to avoid state updates from other classes private val _uiState = MutableStateFlow(LatestNewsUiState.Success(emptyList())) // The UI collects from this StateFlow to get its state updates val uiState: StateFlow<LatestNewsUiState> = _uiState init { viewModelScope.launch { newsRepository.favoriteLatestNews // Update View with the latest favorite news // Writes to the value property of MutableStateFlow, // adding a new element to the flow and updating all // of its collectors .collect { favoriteNews -> _uiState.value = LatestNewsUiState.Success(favoriteNews) } } } } // Represents different states for the LatestNews screen sealed class LatestNewsUiState { data class Success(val news: List<ArticleHeadline>): LatestNewsUiState() data class Error(val exception: Throwable): LatestNewsUiState() }

Unlike a cold flow built using the flow builder, a StateFlow is hot: collecting from the flow doesn’t trigger any producer code. A StateFlow is always active and in memory, and it becomes eligible for garbage collection only when there are no other references to it from a garbage collection root. When a new consumer starts collecting from the flow, it receives the last state in the stream and any subsequent states. You can find this behavior in other observable classes like LiveData3.

SharedFlow is an observable hot flow that emits values only when active collectors are present. Unlike StateFlow, SharedFlow does not have any initial value nor does it store any value at all. To emit values into SharedFlow use its emit function3.

In Android, SharedFlow is useful for sharing events among multiple consumers without having any initial value or state associated with them. For example, you can use SharedFlow to broadcast user input events across your app:

class UserInputManager { // Creates an instance of MutableSharedFlow with zero replay buffer size, // meaning that only new events will be emitted by this SharedFlow. private val _userInputEvents = MutableSharedFlow<UserInputEvent>() // Exposes only SharedFlow interface so other classes cannot modify it. val userInputEvents: SharedFlow<UserInputEvent> = _userInputEvents fun onUserInput(event: UserInputEvent) { viewModelScope.launch { _userInputEvents.emit(event) // Emits event into SharedFlow } } } // Represents different types of user input events sealed class UserInputEvent { data class Tap(val x: Float, val y: Float): UserInputEvent() data class Swipe(val direction: Direction): UserInputEvent() }

To collect from StateFlow or SharedFlow, you can use any terminal operator like collect or first as with any other flow.

Conclusion

In this blog post, you learned how to use Flow in your Android project to handle live data updates and endless streams of data. You learned how to create flows, modify them, collect them, and use StateFlow and SharedFlow to share state and events across your app.

If you want to learn more about Flow and other Kotlin features for Android development, check out these resources:

I hope you enjoyed this blog post and found it useful. Happy coding! 😊

Kotlin Nullability with extension functions and examples

Nullability and Common Extension Functions in Kotlin Explained with Code Examples

Kotlin is a statically typed programming language that was designed to be a safer alternative to Java. One of the ways it achieves this safety is through nullability, which allows developers to prevent null pointer exceptions at runtime by making them compile-time errors. In this blog post, we will explore nullability in Kotlin and common extension functions that can help you work with null values more efficiently.

Nullability in Kotlin

Nullability is a concept in programming that refers to the ability of a variable or object to hold a null value. In Kotlin, nullability is controlled with two types: nullable and non-nullable. A nullable type can hold a null value, while a non-nullable type cannot.

To make a variable or object nullable in Kotlin, you simply add a question mark after its type. For example, the following code creates a nullable String:


var nullableString: String? = null


To make a variable or object non-nullable in Kotlin, you do not add a question mark after its type. For example, the following code creates a non-nullable String:


val nonNullableString: String = “Hello, World!”


If you try to assign a null value to a non-nullable type, the compiler will give you an error:


val nonNullableString: String = null // Error: Null can not be value of a non-null type String


Common Extension Functions for Nullability

There are several extension functions in Kotlin that can help you work with null values more efficiently. Let’s look at some of the most common ones:

1. safeCall

The safeCall function allows you to execute a method or property on a nullable object without the risk of a null pointer exception. If the object is null, the function returns null.

For example, the following code uses the safeCall function to print the length of a nullable String:


val nullableString: String? = null
println(nullableString?.length) // Prints null


2. Elvis Operator

The Elvis operator allows you to assign a default value to a nullable variable or object. If the value is null, the operator returns the default value instead.

For example, the following code uses the Elvis operator to assign a default value to a nullable String:


val nullableString: String? = null
val length = nullableString?.length ?: -1
println(length) // Prints -1


3. Let Function

The let function allows you to execute a block of code if a nullable variable or object is not null. Inside the block, the variable or object is called with the it keyword.

For example, the following code uses the let function to print the length of a nullable String if it is not null:


val nullableString: String? = “Hello, World!”
nullableString?.let { println(it.length) } // Prints 13


4. Nullable Type Conversion

The toIntOrNull and toDoubleOrNull functions allow you to convert a nullable String to an Int or Double, respectively. If the String is null or cannot be parsed, the functions return null.

For example, the following code converts a nullable String to an Int using the toIntOrNull function:


val nullableString: String? = “123”
val nullableInt: Int? = nullableString?.toIntOrNull()
println(nullableInt) // Prints 123


In conclusion, nullability is an essential concept in Kotlin that helps prevent null pointer exceptions. By using common extension functions like safeCall, Elvis operator, Let function, and nullable type conversion, you can work with null values more efficiently and safely. We hope this blog post has been helpful in understanding nullability in Kotlin and its common extension functions.

Test Driven Development for Existing Codebases

Test Driven Development or TDD can be a useful deterrent for bugs in huge codebases. Writing tests can get complex when trying to introduce them into an existing codebase, especially if there is tightly coupled classes. One way to start doing TDD in an existing codebase is to start introducing unit tests for each bug that the engineer is working on. Ideally every time an engineer is fixing a bug, they would make the unit test that would verify the expected behavior, then once they have the unit test failing, they would actually fix the bug. If engineers took this approach to start doing TDD in an existing codebase, eventually code coverage will grow as the bugs are resolved one by one.

One problem with introducing TDD into an existing project is the testability of the code. Depending on the quality of the architecture and design patterns used in the codebase and amount of coupling, the engineer might have to do substantial refactoring to make the code testable. Either way refactoring code to be testable is actually a major improvement which will facilitate more ease of development. Other engineers will be more confident that they will not break other parts of code once tests are introduced from other TDD tasks and code coverage climbs.

TDD can be a very powerful way to ensure quality of production code and engineers will have to deal with a great deal less of bugs in the long run. At first doing TDD in an existing codebase will take longer than if it was done since the beginning of writing the application. Once the coverage gets to a certain point in an application, the code should be refactored to be testable enough that engineers will take less time to introduce new tests and code.

×
Your Donation

privacy policy for genie lamp free

Privacy Policy

built the Genie Lamp Free app as an Ad Supported app. This SERVICE is provided by at no cost and is intended for use as is.

This page is used to inform visitors regarding my policies with the collection, use, and disclosure of Personal Information if anyone decided to use my Service.

If you choose to use my Service, then you agree to the collection and use of information in relation to this policy. The Personal Information that I collect is used for providing and improving the Service. I will not use or share your information with anyone except as described in this Privacy Policy.

The terms used in this Privacy Policy have the same meanings as in our Terms and Conditions, which is accessible at Genie Lamp Free unless otherwise defined in this Privacy Policy.

Information Collection and Use

For a better experience, while using our Service, I may require you to provide us with certain personally identifiable information. The information that I request will be retained on your device and is not collected by me in any way.

The app does use third party services that may collect information used to identify you.

Link to privacy policy of third party service providers used by the app

Log Data

I want to inform you that whenever you use my Service, in a case of an error in the app I collect data and information (through third party products) on your phone called Log Data. This Log Data may include information such as your device Internet Protocol (“IP”) address, device name, operating system version, the configuration of the app when utilizing my Service, the time and date of your use of the Service, and other statistics.

Cookies

Cookies are files with a small amount of data that are commonly used as anonymous unique identifiers. These are sent to your browser from the websites that you visit and are stored on your device’s internal memory.

This Service does not use these “cookies” explicitly. However, the app may use third party code and libraries that use “cookies” to collect information and improve their services. You have the option to either accept or refuse these cookies and know when a cookie is being sent to your device. If you choose to refuse our cookies, you may not be able to use some portions of this Service.

Service Providers

I may employ third-party companies and individuals due to the following reasons:

  • To facilitate our Service;
  • To provide the Service on our behalf;
  • To perform Service-related services; or
  • To assist us in analyzing how our Service is used.

I want to inform users of this Service that these third parties have access to your Personal Information. The reason is to perform the tasks assigned to them on our behalf. However, they are obligated not to disclose or use the information for any other purpose.

Security

I value your trust in providing us your Personal Information, thus we are striving to use commercially acceptable means of protecting it. But remember that no method of transmission over the internet, or method of electronic storage is 100% secure and reliable, and I cannot guarantee its absolute security.

Links to Other Sites

This Service may contain links to other sites. If you click on a third-party link, you will be directed to that site. Note that these external sites are not operated by me. Therefore, I strongly advise you to review the Privacy Policy of these websites. I have no control over and assume no responsibility for the content, privacy policies, or practices of any third-party sites or services.

Children’s Privacy

These Services do not address anyone under the age of 13. I do not knowingly collect personally identifiable information from children under 13. In the case I discover that a child under 13 has provided me with personal information, I immediately delete this from our servers. If you are a parent or guardian and you are aware that your child has provided us with personal information, please contact me so that I will be able to do necessary actions.

Changes to This Privacy Policy

I may update our Privacy Policy from time to time. Thus, you are advised to review this page periodically for any changes. I will notify you of any changes by posting the new Privacy Policy on this page. These changes are effective immediately after they are posted on this page.

Contact Us

If you have any questions or suggestions about my Privacy Policy, do not hesitate to contact me at copypasteearth@gmail.com.

This privacy policy page was created at privacypolicytemplate.net and modified/generated by App Privacy Policy Generator

Smart Refrigerator Security Vulnerability

These days we are in the IOT revolution.  Everyone is flocking to the electronic stores to purchase smart appliances, so they have more convenience in their everyday lives.  Security vulnerabilities are being found by security researchers constantly as these new smart devices find their way to the stores.  It seems that for every IOT device that is released there is a corresponding security threat that seems to be discovered.  It turns out that even a smart refrigerator could be vulnerable to malicious people trying to obtain a user’s personal information.  While researching smart refrigerator vulnerabilities I came across a hack that lets malicious users obtain a user’s Google login credentials and I thought that this hack is definitely noteworthy.  In this document I will go over who discovered this smart refrigerator vulnerability, details on how this vulnerability is utilized, and what a user can do to prevent being a victim of this security vulnerability.

         This hack to find out a user’s Google login credentials through the Samsung smart refrigerator was discovered by security researchers at a security company named Pen Test Partners.  These security researchers discovered this hack at an IOT hacking challenge called the Def Con Security Conference (Neagle, 2015).  Security researchers at Pen Test Partners went through a bunch of different routes to find vulnerabilities in the Samsung smart refrigerator like firmware attacks, tearing down the mobile app, and TCP services (Venda, 2015).  Where the security researchers found the vulnerability was in the smart refrigerators implementation of SSL because it failed to validate the SSL certificates.  Since the refrigerator failed to validate the SSL certificates, that led to the ability of performing a man in the middle attack allowing a malicious user to obtain Google login credentials because the refrigerator has a Google calendar application on it letting a user post calendar events and notes on the door of the refrigerator.  Having a Google calendar on the door of your refrigerator sounds like a great idea and could be very convenient in organization of tasks and meetings for a user’s family.  Unfortunately, the hack discovered by Pen Test Partners makes the Google Calendar a prime target for the user’s personal information.

         This smart refrigerator hack is basically a man in the middle attack.  A man in the middle attack is when a malicious user is listening for packets between a device and servers communications.  Since the SSL implementation in the Samsung smart refrigerator does not validate the SSL certificates, that means that anyone can intercept the information being exchanged by the refrigerator and the server with a packet sniffer like Wireshark.  Packet sniffers like Wireshark can intercept information being transmitted over a network, specifically unencrypted information (Nohe, 2018).  This hack could be the result of the lack of security testing on the Samsung smart refrigerator where the developers of the refrigerators smart abilities just did not know how to implement SSL correctly.  It seems that this hack could be easily fixed with a software update and Samsung has reported that they are looking into the vulnerability (Neagle, 2015).  Although having your Google credentials exposed to a malicious user could be a very terrible thing, the malicious user would have to be able to have access to the same network that the smart refrigerator is a part of to be able to execute this attack.

         Personally, I would love to have a refrigerator with the kind of functionality that this Samsung smart refrigerator has.  The convenience of having my Google calendar presented on the door of the refrigerator with all of my notes and to-do lists could be very beneficial.  The first thing you would have to do to prevent this kind of hack from victimizing you is that you have to be very aware of who has access to the network that your refrigerator is running on.  I am sure that once Samsung was notified about this vulnerability that they made some updates to the refrigerators system software.  Always keep your IOT devices software up to date with the latest software because that is how many security vulnerabilities are combatted.  It is a shame that this kind of vulnerability was present in this smart refrigerator because a user’s Google credentials should always be kept confidential and the ability to do a man in the middle attack on a smart refrigerator should be addressed immediately.

         Although the man in the middle attack on this smart refrigerator doesn’t seem like a very severe security threat, it is still nonetheless a pretty substantial vulnerability. No one wants their personal information exposed to any malicious users in the technological world and this hack gave malicious users yet another way to deceive the regular users of IOT devices.  As I do more and more research on IOT devices and their vulnerabilities, it seems that company’s software engineering practices need to implement more security testing.  Samsung is a very big corporation with many customers, and I am sure that they already do plenty of security testing, but this is evidence that even the larger companies need to ramp up their security practices.

Works Cited

Neagle, C. (2015, August 26). Smart refrigerator hack exposes Gmail login credentials. Retrieved from networkworld.com: https://www.networkworld.com/article/2976270/smart-refrigerator-hack-exposes-gmail-login-credentials.html

Nohe, P. (2018, November 29). Executing a Man-in-the-Middle Attack in just 15 Minutes. Retrieved from thessistore.com: https://www.thesslstore.com/blog/man-in-the-middle-attack-2/

Venda, P. (2015, August 18). Hacking DefCon 23’s IoT Village Samsung fridge. Retrieved from pentestpartners.com: https://www.pentestpartners.com/security-blog/hacking-defcon-23s-iot-village-samsung-fridge/

×
Your Donation
%d bloggers like this: