Saturday 30 November 2019

Python Function and String Method

Hi Guys!!

Today I am discuss Python Function and String inbuilt method.

Python’s functions are first-class objects. We can

  •      assign them to variables, 
  •      store them in data structures, 
  •      pass them as arguments to other functions, and 
  •      even return them as values from other functions.
# 1. Functions Are Objects. we can assign it to another variable, just like any other object(example strings, lists)
def welcomeMsg(name):
return 'Welcome {} !!'.format(name)
receive = welcomeMsg
# The above line does’t call the function. It takes the function object
reference and creates a second name,
# We can execute the method by calling receive:
print(receive("Saurabh"))
# Function objects and their names are two separate things. We can delete the functions’ original name  and still call the function, since another name still points to it.
del welcomeMsg
#print(welcomeMsg("Saurabh")) # O/P : NameError: "name 'greet' is not
defined"
print(receive("Saurabh")) # O/P :Welcome Saurabh !!
# 2. Functions Can Be Stored in Data Structures. we can add functions to a list:
funcs = [len, str.isdigit, str.upper]

for f in funcs:
print(f, f('Hello World!'))
Output :
<built-in function len> 12
<method 'isdigit' of 'str' objects> False
<method 'upper' of 'str' objects> HELLO WORLD!
# 3. Functions Can Be Passed to Other Functions
# 3. Functions Can Be Passed to Other Functions
def accept(func):
msg = func('Roark')
print(msg)
def welcomeMsg(name):
return 'Welcome {} !!'.format(name)
def leave(name):
return "Good Bye {}!".format(name)
accept(welcomeMsg)
accept(leave)
Output :
Welcome Roark !!
Good Bye Roark!

The ability to pass function objects as arguments to other functions is powerful.  It allows us to abstract away and pass around behaviours.  In above example, accept function stays the same but we can influence its output by passing in different behaviours.

# 4. Functions Can Be Nested. They are often called nested functions or inner functions.
def num1(x):
def num2(y):
return x * y
return num2
res = num1(10)
print(res(5)) # O/P :- 50

A string is a sequence of characters. The built-in string class in Python represents strings based upon the Unicode international character set. All the string methods always return new values and do not change or manipulate the original string.
Below are some famous method under String object in Python 
  1. center( ) : center aligns a string
  2. count( ) returns the count or the number of times a particular value appears in a string
  3. find() method returns the lowest index of a particular substring in a string
  4. swapcase() method returns a copy of the string with all its uppercase letters converted into lower case and vice versa
  5. The swapcase() method returns a copy of the string with all its uppercase letters 
  6. startswith( ) and endswith( ) method returns True/False for given string
  7. split( ) spilt the string as list with given delimiter bydefault is space is delimeter
  8. capitalize( ) method capitalizes only the first character of a string.
  9. upper( ) method capitalizes all the letters of the string.
  10. string.title( ) method capitalizes all the first letters of the given string.
  11. The zfill() method adds zeros(0) at the beginning of the string
  12. The strip() method returns a copy of the string with the leading and trailing characters removed.Default character to be removed is whitespace
All above method example you can find from my github page 
# 1. center( ) : center aligns a string
words = "Saurabh"
print(words.center(15, " "))
# 2. count( ) returns the count or the number of times a particular value appears in a string
str1 = "Kuamr Sharma Saurabh Kumar Sharma Saurabh kumar Saurabh Sharma"
print(str1.count('Saurabh'))
print(str1.count('Saurabh',9,36))
# 3. The find()method returns the lowest index of a particular substring in a string
print(str1.find('Saurabh'))
print(str1.rfind('Saurabh')) # rfind highest index
# 4. The swapcase() method returns a copy of the string with all its uppercase letters
# converted into lower case and vice versa
str2 = "Saurabh Kumar Sharma"
print(str2.swapcase())
# 5. startswith( ) and endswith( )
print(str2.startswith('Kumar'))
print(str2.endswith("Sharma"))
# 6. split( )
fruits = "Apple, Mango, Grapes, Banana"
print(fruits.split())
print(fruits.split(","))
print(fruits.split(",", maxsplit=2))
.......See my github page for more details. 
Thanks 
Happy Coding !!!!
Saurabh Sharma

Sunday 24 November 2019

AlarmManager Vs WorkManager Android Background task processing

 Hi Guys!!!

Today topic is " background processing in Android" . There is a lot of things added in Android from initial day to till now to perform background processing in android efficiently.

Today i am going to focus on Alarm Manager and Work Manager API in Android. You can find my example source code from my github page.

As we know every Android app has a main thread which is in charge of handling UI (including measuring and drawing views) , coordinating user interactions, and receiving lifecycle events.

If there is too much work happening on this thread, the app appears to hang or slow down, leading to an undesirable user experience. That's why we need to off load Main UI Thread and perform long operation in background.

When to use WorkManager
  • If the work dependent on system conditions
  • Your job to run only when the device meets certain conditions(such as being connected to power) 
WorkManager mWorkManager = WorkManager.getInstance(MainActivity.this);
PeriodicWorkRequest.Builder myWorkBuilder =
        new PeriodicWorkRequest.Builder(RebootWorker.class, 1, TimeUnit.MINUTES);
PeriodicWorkRequest workRequest = myWorkBuilder.build();
WorkManager mWorkManager.enqueue(workRequest);

When to use AlaramManager


  • Job need to run at a precise time
  • A calendar app might let a user set up a reminder for an event at a specific time

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, uniqueInt, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, pendingIntent);

Choosing the right background Processing for your work
There is lot more  long background task processing is avilable to perform your job as per your requirement. I named few below :-
  • WorkManager
  • Foreground services
  • AlarmManager
  • DownloadManager

Use below decision making daigram to choose right one

refe link:- https://developer.android.com/images/guide/background/bg-job-choose.svg

Thanks 

Happy Coding !!!!
Saurabh Sharma

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...