Category Archives: Programming

Collection of articles about programming in various popular and unpopular languages ( C, Python, Java, JavaScript, Objective C, Lua)

How to run twisted script as daemon without twistd command

Warning:- this article assumes you are familiar with twisted
we have scenarios like run different services on different ports
to create multiservice architecture.
So, here we cannot run the services on from the command line
we have to run them as daemon service, like using cron jobs in linux.

– Create a simple twisted with protocol and factory and save to test.py or any name you like.

#!/usr/bin/env python2.7

from twisted.internet import protocol, reactor

class echo(protocol.Protocol):
        def dataReceived(self, data):
                self.transport.write(data.upper())

class echoFactory(protocol.Factory):
        def buildProtocol(sef,addr):
                print 'called'
                return echo()

reactor.listenTCP(8000,echoFactory())
reactor.run()

this is a normal echo server script which can run using

./test.py # assuming the script is saved in test.py

But our script cannot run this is as a daemon service
daemon service is some task runs in the background, and it logs to some specific location, not on stdout. When we run this script like specified above, it blocks the current terminal ( if you are running from a terminal ) which is not something daemon script do.
To make this script run as a daemon, we need to use twistd inside the script
means it’ll run and execute, create a process in the background.

from twisted.scripts import twistd
import sys
sys.argv.append('-y dummy')
sys.argv.append('--pidfile={0} --logfile=/dev/null'.format('/tmp/echo.pid'))

application = service.Application('echo_daemon')
tcp_service = internet.TCPServer(interface='127.0.0.1',port=8000, factory=factory)
tcp_service.setServiceParent(application)

class ApplicationRunner(twistd._SomeApplicationRunner):
    def createOrGetApplication(self):
        return application

    def run(self):
        self.preApplication()
        self.application = self.createOrGetApplication()
        self.postApplication()


twistd._SomeApplicationRunner = ApplicationRunner
twistd.run()

#~ python2.7 test.py

How should we cross-check if the service is running or not
Use the following command on Linux system (in shell/terminal for simple word).

netstat -ntulp

You get a list of all ports (UDP, TCP) open on the system.

How to edit file with sed

This tutorial is about how to replace the pattern with sed command in the same file you are reading from.

What is sed?
Sed stands for stream editor, as per the Linux man page.
But sed is more than it. We can write more powerful bash scripts with just a single line using sed. It can be used for fetching specific lines, a bunch of lines, replace the character with patterns and so much. Basically, just manipulate the stream of characters with whatever logic you projectile

Let’s get started,
We understand more with the task in hand. So, our task for this tutorial is to replace some characters with our characters.
Suppose we have a file like content below,

  304  PULSEaudio -k
  306  PULSEaudio --cleanup-shm 
  310  PULSEaudio --check 
  311  PULSEaudio --start 
  312  PULSEaudio --kill 
  322  PULSEaudio -k
  323  PULSEaudio --check 
  324  killall PULSEaudio
  325  PULSEaudio --check 
  331  ls * | grep -e PULSE
  332  cd PULSE/
  340  PULSEaudio -k
  344  PULSEaudio -D
  345  PULSEaudio -d
  346  service PULSEaudio status
  348  ps -eo "user args" | grep PULSE
  350  ps -eo "user args" | grep PULSE
  351  PULSEaudio -k
  352  killall PULSEaudio 

And we are supposed to replace the characters PULSE to pulse.
Either, we can open this file in VIM and type command like

 %s/PULSE/pulse/gc

If you are familiar with vim. You’ll know what I am talking about
But if you are using this output for some reason in your bash script, you need to do this with a single command.

Here comes our savior sed.

sed s/pattern/replace_char/ <file_name>

This command does our task, but the problem is it gives output on stdout.

Common error:- we generally try to redirect that output to the file we are editing
If we are editing the file named replace.txt then the command will be
sed s/PULSE/pulse/ replace.txt 2> replace.txt

But sed creates a problem here. It doesn’t work that way it’s not sed’s problem, Its problem with the order of file descriptors it set.

This is a common error, we want to modify a file using something that reads from a file and writes the result to stdout. To do this, we redirect stdout to the file we want to modify. The problem here is that, as we have seen, the redirections are setup before the command is actually executed.
So BEFORE sed starts, standard output has already been redirected, with the additional side effect that, because we used >, “file” gets truncated. When sed starts to read the file, it contains nothing
( if you don’t know what it is read this link https://wiki.bash-hackers.org/howto/redirection_tutorial ).

Sed added one feature which internally sets this redirection of a file descriptor for us. Use -i option to overcome this problem.

The final command will be

sed s/PULSE/pulse/ replace.txt -i

How to make hello world program in wxPython

In this article we will look at creating a simple hello world program using wxPython. This program will create and display simple window with a big button on it. Up on clicking the button program will exit. Use the following code to create hello world program. You must already have wxPython library installed

Hello world program

import wx

class MainWindow(wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__(self,parent,title="Hello World")
        self.killButton = wx.Button(self,label="Kill Me")
        self.killButton.Bind(wx.EVT_BUTTON,self.kill)
        self.Show()

    def kill(self,event):
        self.Close()
        print("Bye Bye cruel world")
        
app = wx.App(False)
frame = MainWindow(None)
app.MainLoop()

Explanation

We will go line by line here and try to explain what’s going on in this program. Most of the lines of self explanatory. If you are just getting started in programming the following explanation will be helpful.

  1. Import wxpython library
  2. Inherit from wx.Frame class. This is useful style for most of the programs that you will build. You can create one base frame or window and put rest of GUI widgets on top of it like Text controls, buttons,images, tables etc.
  3. Instantiate the inherited frame the desired title. parent argument is usually None for main windows.
  4. Create a button with label “Kill Me”. The first argument is parent. In this case we use “self” which is the main window we have just created.
  5. Bind the button click event (EVT_BUTTON) of the killButton to kill method. Whenever, EVT_BUTTON event is fired aka the killButton is clicked, kill method will be called.
  6. This line will cause the window to get displayed on screen. It’s customary to call this method after being done with construction of GUI i.e. create main window, place widgets, bind event like we did here.
  7. Create wxPython application by call wx.App. Every wxPython program must have this application.
  8. Start the main loop. Which will hand over control to wxPython library. This post explains why main loop has to be called.

Output

This program will launch the following window. The button takes all the available space on the window since there are no other widgets. You need a few more lines of code to make the button look like what users are used to – small and horizontal. You can exit the program by clicking the button.

Manhole service in Twisted Application.

What is Manhole?

Manhole is an in-process service, that will accept UNIX domain socket connections and present the stack traces for all threads and an interactive prompt.

Using it we can access and modify objects or definition in the running application, like change or add the method in any class, change the definition of any method of class or module.

This allows us to make modifications in running an application without restarting the application, it makes work easy like debugging the application, you are able to check the values of the object while the program is running.

How to configure it?

from twisted.internet import reactor
from twisted.conch import manhole, manhole_ssh
from twisted.conch.ssh.keys import Key
from twisted.cred import portal, checkers

DATA = {"Service": "Manhole"}


def get_manhole_factory(namespace, **passwords):

    def get_manhole(arg):
        return manhole.ColoredManhole(namespace)
            
    realm = manhole_ssh.TerminalRealm()
    realm.chainedProtocolFactory.protocolFactory = get_manhole
    p = portal.Portal(realm)
    p.registerChecker(checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords))
    f = manhole_ssh.ConchFactory(p)
    f.publicKeys = {"ssh-rsa": Key.fromFile("keys/manhole.pub")}
    f.privateKeys = {"ssh-rsa": Key.fromFile("keys/manhole")}
    return f


reactor.listenTCP(2222, get_manhole_factory(globals(), admin='admin'))
reactor.run()

Once you run above snippet, the service will start on TCP port 2222.

You need to use SSH command to get login into the service.

See below how it looks like.

[lalit : ~]₹ ssh admin@localhost -p 2222
admin@localhost's password:
>>> dir() 
['DATA', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'checkers', 'get_manhole_factory', 'manhole', 'manhole_ssh', 'portal', 'reactor'] 
>>> DATA 
{'Service': 'Manhole'}
>>> DATA['Service'] = "Edited" 
>>> DATA 
{'Service': 'Edited'}
[lalit : ~]₹ ssh admin@localhost -p 2222
admin@localhost's password: 
>>> dir() 
['DATA', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'checkers', 'get_manhole_factory', 'manhole', 'manhole_ssh', 'portal', 'reactor'] 
>>> DATA 
{'Service': 'Edited'} 

Here In the first login, we change the value in DATA dictionary in running application, as we can see we get the new value in the second login.

Working with Spinner in Android (Single Selector)

Spinner

Spinners provide a quick way to select one value from a set then we called it a single selector. A spinner shows its currently selected value from set. In the default state, it shows 0 index value from a set. Touching the spinner displays a dropdown menu or dialog with all other available values in the set, So we can be called it a dropdown.

Dropdown

 

 

 

 

 

 

Let’s check, how we can use it in an application.

Spinner integration has 3 key classes:-

1.  Spinner

2. Spinner Adapter

3. Spinner OnItemSelectedListener

So we will discuss above these classes also, with integration. You can add a spinner to your layout XML file. You can use the below sample code –

<Spinner
    android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

Spinner Adapter uses for bind between data set and spinner widget and it manages view for the spinner row item. We can use data as an array of string. See sample code –

String[] items = { "Home", "Work", "Other" "Custom"};

Above string array, we will use for the display. So now we need to get reference Spinner which we defined in the XML file. We can use the below sample code –

// reading spinner reference
Spinner spinner = (Spinner) findViewById(R.id.spinner);

So now we need to set values in ArrayAdapter. and We set this ArrayAdapter in Spinner. Use below code –

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
// set Adapter
spinner.setAdapter(adapter);

When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event. for manage event, we can use OnItemSelectedListener in the Spinner. Sample code –

//Register a callback to be invoked when an item in this AdapterView has been selected
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

      @Override
      public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int position, long id) { 
        // TODO Auto-generated method stub
               
      }

      @Override
      public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

      }

});

onItemSelected gives us a selected position of the spinner.

That’s it. Happy Coding 🙂

Reference:-

https://developer.android.com/guide/topics/ui/controls/spinner#java

Migrate an Existing Project to AndroidX

AndroidX is an open-source project by Google that provides a major improvement to the original Android Support Library. AndroidX is replaced the Support Library. Like support library, Google keeps AndroidX is independently from the Android OS and provides backward-compatibility across Android releases. AndroidX package structure is to encourage smaller and more focused libraries.

AndroidX replaces the original support library APIs with packages in the androidx namespace. Only the package and import names changed. Class, method, and field names did not change in migration.

Example:-

android.support.v7.widget.RecyclerView is changed to androidx.recyclerview.widget.RecyclerView

android.support.v7 is replced by androidx.

Migrating existing project:-

Before start migration, we need to make sure to follow the below things:-

1.  Android studio version should be higher than 3.2, You can check your android studio version from About Android Studio section. also use the latest Gradle version. Check project level Build.Gradle file to change the version.

2. Target SDK version and Compile SDK version should be 28 or greater. Check your app level Build.Gradle file to change target and compile SDK version.

3. Take a backup of your project. 

4. Add below properties to gradle.properties file. You can find this file on Project Level.

android.useAndroidX=true
android.enableJetifier=true

A.) android.useAndroidX: set to true, the Android plugin uses the AndroidX library instead of a Support Library. The value is false by default.

B.) android.enableJetifier: set to true, the Android plugin automatically migrates existing third-party libraries to use AndroidX. The value is false by default.

Let’s start migration:-

1.  Click Refactor from the menu in Android studio.

2. Then Click on Migrate to AndroidX from Refactor dropdown.

3. After that, It will ask you to take a backup of the whole project. If you have already taken the backup then ignore this step.

4. After the backup process clicks on Migrate, It will show list all support library where we are using in this project. Just click on Do Refactor and wait for some time.

5. After some time, you can see the project all support library replaced by the AndroidX library. Most of the support library will merge automatically and few we need to replaced manually. If you found any error,  Fix it manually. and test your app carefully. The application could crash due to incorrect auto-correction during migration.

That’s it. Enjoy Coding using AndroidX. 🙂

Reference:-

https://developer.android.com/jetpack/androidx/migrate

TabLayout Example using ViewPager and Fragments in Android

If you are using the latest android application then you have noticed that now days android is following a design pattern. This is material design and it came with Android Lollipop (5.0). Though we can still use this design pattern for the older versions (>4.0) by using the support libraries. One of the component of material design is TabLayout. So in this TablLayout Example we will see how we can implement it in our android application.

What is TabLayout ?

Android TabLayout provides horizontal layout to display tabs. We can display more screens in a single screen using tabs. User can swipe the tabs quickly as you can see in the image below.

Creating a new project and add necessary libraries

Open Android Studio and create a new project. I have created DemoTabLayout.

After create a new project, First of all we have to need include design libraries in the dependencies section of our build.gradle file so include this libraries in your build.gradle file by below line.

implementation 'com.android.support:design:28.0.0'

Remove action bar from style

Now since we will be using Android Toolbar and TabLayout classes to show tabs, lets remove the action bar from layout by using styles,

Go to style.xml file and change the parent of theme which you are using in your app.Change parent with “Theme.AppCompat.Light.NoActionBar”. So now your style file will look like below code

<resources>
  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
     <item name="colorPrimary">#3F51B5</item>
     <item name="colorPrimaryDark">#303F9F</item>
     <item name="colorAccent">#FF4081</item>
  </style>

</resources>

Creating fragments

We are creating an application which will have three tabs, So let’s define three fragment and their layouts.

First Fragment

package com.vikas.demotablayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
class tab1 extends Fragment {
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
               Bundle savedInstanceState) {
           return inflater.inflate(R.layout.fragment_tab1, container, false);
         }
   }

It’s layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
     
    <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Tab 1"
      android:textAppearance="?android:attr/textAppearanceLarge"/>

 </RelativeLayout>

 

Second Fragment

package com.vikas.demotablayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class Tab2 extends Fragment {
   
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
               Bundle savedInstanceState) {
          return inflater.inflate(R.layout.fragment_tab2, container, false);
	}
   }

it’s layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
	<TextView
          android:id="@+id/textView"
	  android:layout_width="wrap_content"
 	  android:layout_height="wrap_content"
          android:layout_centerInParent="true"
	  android:text="Tab 2"
          android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>

Third Fragment

package com.vikas.demotablayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Tab2 extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

	 return inflater.inflate(R.layout.fragment_tab3, container, false);
      }

}

its layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical">
     <TextView
        android:id="@+id/textView"
	android:layout_width="wrap_content"
        android:layout_height="wrap_content"
	android:layout_centerInParent="true"
        android:text="Tab 2"
	android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>

Now we will define a view pager adapter to create tab swipe functionality.

package com.vikas.demotablayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class PagerAdapter extends FragmentStatePagerAdapter {

    int mNumOfTabs;
    public PagerAdapter(FragmentManager fm, int NumOfTabs) {
     	super(fm);
	this.mNumOfTabs = NumOfTabs;
    }
    @Override
    public Fragment getItem(int position) {
       switch (position) {
	  case 0:
            tab1 tab1 = new tab1();
            return tab1;
          case 1:
            Tab2 tab2 = new Tab2();
            return tab2;
          case 2:
            Tab3 tab3 = new Tab3();
            return tab3;
          default:
            return null;
        }
    }
    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

Now we will create an Activity named MainActivity which will hold the tabs . This Activity will have two part first is code file and second is layout file. layout file code given below

<RelativeLayout
        android:id="@+id/main_layout"
        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">
	<android.support.v7.widget.Toolbar
	    android:id="@+id/toolbar"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:layout_alignParentTop="true"
	    android:background="?attr/colorPrimary"
	    android:elevation="6dp"
	    android:minHeight="?attr/actionBarSize"
	    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
	    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
	<android.support.design.widget.TabLayout
	    android:id="@+id/tab_layout"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:layout_below="@+id/toolbar"
	    android:background="?attr/colorPrimary"
	    android:elevation="6dp"
	    android:minHeight="?attr/actionBarSize"
	    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
	<android.support.v4.view.ViewPager
	    android:id="@+id/pager"
	    android:layout_width="match_parent"
	    android:layout_height="fill_parent"
	    android:layout_below="@id/tab_layout"/>
</RelativeLayout>

We can see above that here we add a Toolbar, second is Tablayout and third thing is Viewpager. Toolbar is for showing application name and menu icon. TabLayout is for showing Tabs and viewpager is for holding fragments. Now we write code for attach this layout with fragments in MainActivity code file. Code is given below:

package com.vikas.demotablayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
	TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
	tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
          @Override
          public void onTabSelected(TabLayout.Tab tab) {
	          viewPager.setCurrentItem(tab.getPosition());
	  }
          @Override
          public void onTabUnselected(TabLayout.Tab tab) {
	  }
          @Override
          public void onTabReselected(TabLayout.Tab tab) {
          }
        });
     }

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
	    getMenuInflater().inflate(R.menu.menu_main, menu);
	    return true;
     }

}

That’s all, Now you can run your project.

Happy coding…

DatePicker Example in Android

In android, DatePicker is a control which will allow users to select the date by day, month and year in our application user interface.

The images of datePicker are given blow

Create DatePicker with xml

We can create DatePicker using <Datepicker> element in xml file, which is given below

<DatePicker android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

There are two types of view of DatePicker

1. Complete Calendar view

2. Spinner View

Complete Calendar view :- We can create complete calendar view with below code

<DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:datePickerMode="calendar"/>

This is output

Spinner view :- We can create complete calendar view with below code

 <DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:datePickerMode="spinner"
    android:calendarViewShown="false"
/>

This is output

Now we will create an example of datePicker in which we will set date picker on edit text and we will create date picker using java code also. In this example we will create a Textview and a button also. On button click we will show date in TextView.

Create a new android application using android studio and give name DatePickerDemo.

Now Open activity_main.xml file from \res\layout path and write code which is given below

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" android:gravity="center">
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:ems="10"
        android:hint="Enter Date" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="Get Date" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:textStyle="bold"
        android:textSize="18dp"/>
</LinearLayout>

Now open MainActivity.java file and write code which is given below

MainActivity.java

package com.vikas.datepickerdemo;

import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    DatePickerDialog datepicker;
    EditText eText;
    Button btn;
    TextView tvw;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvw=(TextView)findViewById(R.id.textView1);
        eText=(EditText) findViewById(R.id.editText1);
        eText.setInputType(InputType.TYPE_NULL);
        eText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar cldr = Calendar.getInstance();
                int day = cldr.get(Calendar.DAY_OF_MONTH);
                int month = cldr.get(Calendar.MONTH);
                int year = cldr.get(Calendar.YEAR);
                // date picker dialog
                datepicker = new DatePickerDialog(MainActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
                            }
                        }, year, month, day);
                datepicker.show();
            }
        });
        btn=(Button)findViewById(R.id.button1);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvw.setText("Selected Date: "+ eText.getText());
            }
        });


    }
}

In java code you can see that we set an Onclicklistener on EditText, when we click on EditText then will see calendar dialog, From which we can select date.

Output of example

That’s all . This is the final output of example.

Happy Coding…

importContactss

Fetch Contacts From Native Phonebook

Import Contacts In iOS

Contacts are We are going to use built in Contacts.framework to import all contacts in our app. To display a list of contacts, you must have access to the user’s address book. Apple does a great job of protecting the user’s privacy, so you can’t read any of their contacts’ data without asking the user for permission. Similar restrictions apply to access the user’s camera, location, photos, and more.

Whenever we need access to privacy-sensitive information, you are required to specify this in your app’s Info.plist file. This file keeps track of many of your app’s properties, such as its display name, supported interface orientations, and, in the case of accessing a user’s contacts, Info.plist also contains information about why you need access to the user’s contacts.

Let’s go step by step:-

  • Add usage description in Info.plist file for contacts.

Open Plist file and click on plus button to add new row for contact usage description.

Add Privacy – Contacts Usage Description in key

Select Type as String

Write the usage purpose of contacts in your app.

  • Import Contacts Framework in your class.

import Contacts

 

  •  Request for Contact permission

func getAuthStatus() -> CNAuthorizationStatus{

        

        return CNContactStore.authorizationStatus(for: .contacts)

    }

    

    func requestForAccess(_ completionHandler: @escaping (_ accessGrandted: Bool, _ authStatus: CNAuthorizationStatus) -> Void)  {

        

        let authorizationStatus = getAuthStatus()

        

        switch authorizationStatus {

        case .authorized:

            

            completionHandler(true, CNAuthorizationStatus.authorized)

            break

            

        case .notDetermined:

            let store = CNContactStore()

            store.requestAccess(for: .contacts, completionHandler: { (authorized: Bool, error: Error?) in

                

                if authorized {

                    completionHandler(true, CNAuthorizationStatus.authorized)

                }

                else {

                    

                    if self.getAuthStatus() == CNAuthorizationStatus.denied {

                        completionHandler(false, CNAuthorizationStatus.denied)

                    }

                }

            } )

            

            break

            

        case .denied :

            

            completionHandler(false, CNAuthorizationStatus.denied)

            

            break

            

        default:

            completionHandler(false, CNAuthorizationStatus.notDetermined)

            break

        }

    }

 

Above two function will check Contact authorisation status. If not determined it will show alert for contact permission. Keep in mind you can ask Contact permission only once. Once user denied you can just open Setting screen for enable Contact permission.

  • Fetch Contact Using CNContactStore:-

do {

            let store = CNContactStore()

            var results = [CNContact]()

            let containers = try store.containers(matching: nil)

            for container in containers {

                let predicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)

      

                

                let keyToFetch = [CNContactIdentifierKey,

                                  CNContactFormatter.descriptorForRequiredKeys(for: .fullName),

                                  CNContactEmailAddressesKey,

                                  CNContactPhoneNumbersKey,

                                  

                                  CNContactPostalAddressesKey,

                                  CNContactNoteKey,

                                  CNContactOrganizationNameKey] as [Any]

                let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keyToFetch as! [CNKeyDescriptor])

                results.append(contentsOf: contacts)

            }

return results

            

        }

        catch

        {

            // print("Error1 is \(error)")

            

        }

 

We create a CNContactStore instance and this object is used to communicate directly with the Contacts system on iOS. In this method, we wrap our code in a do-catch statement because two of the methods we use are throwing methods.We can retrieve different values using different Keys like first name, last name, contact image, mobile number, address, emails etc. We then create an array that contains a number of constant keys. These keys directly relate to the information your app has access too.

There is different container Group in Native phonebook. We can retrieve Contacts from different Container according our need. Here we are retrieving contacts of all Groups using store.containers(matching: nil) and iterate it one by one to fetch contacts.

store.unifiedContacts will return array of CNContact which you can store in Your app data or in your app’s database and display contacts In your own tableview Format.

Important:-

In iOS 13, apple have added a new entitlement that is needed if you wish to access the notes for contacts. The entitlement is com.apple.developer.contacts.notes. You can request permission to use this entitlement for an app being put in the App Store.

The reason it was added is primarily for privacy reasons — the notes field can contain any information you might have on the contact; and a lot of times this information is significantly more sensitive than just the contact information.

 

Happy Coding.

mutex lock

Locking your bash script against parallel execution

Sometimes there’s a need to ensure only one copy of a script runs, i.e prevent two or more copies running simultaneously. Imagine an important cronjob doing something very important, which will fail or corrupt data if two copies of the called program were to run at the same time. To prevent this, a form of MUTEX (mutual exclusion) lock is needed.

The basic procedure is simple: The script checks if a specific condition (locking) is present at startup, if yes, it’s locked – the script doesn’t start.

This article describes locking with common UNIX® tools.

Method 1

setting the noclobber shell option (set -C). This will cause redirection to fail, if the file the redirection points to already exists (using diverse open() methods). Need to write a code example here.

if ( set -o noclobber; echo "locked" > "$lockfile") 2> /dev/null; then
  trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
  echo "Locking succeeded" >&2
  rm -f "$lockfile"
else
  echo "Lock failed - exit" >&2
  exit 1
fi

 

Method 2

A simple way to get that is to create a lock directory – with the mkdir command. It will:

create a given directory only if it does not exist, and set a successful exit code
it will set an unsuccessful exit code if an error occurs – for example, if the directory specified already exists
With mkdir it seems, we have our two steps in one simple operation. A (very!) simple locking code might look like this:

if mkdir /var/lock/mylock; then
  echo "Locking succeeded" >&2
else
  echo "Lock failed - exit" >&2
  exit 1
fi

In case mkdir reports an error, the script will exit at this point – the MUTEX did its job!