Sunday 25 December 2016

Combine multiple PDF files into one in your Mac OS

Background

Couple of days back I had to upload a signed copy of an online document So I took it's printout and then scanned each page as a PDF. TO re upload I had to make it back into a single pdf file. Well of its a generic document you can use online pdf tools. But in my case the document was somewhat private and well it had my sign. So I could not do it online. In mac you can do it offline with in in built application called preview. Let us see how we can do it.


Combine multiple PDF files into one in your Mac OS

  • First open your PDF file with preview application. To do so you can right click and select over with preview.

  • Next go to View and Enable Thumbnails. You should see your current pfd in thumbnail panel on the left.

  • Now go to edit and select edit -> Page from file and then select other pdf file you need to combine. Do this for as many pdf files as you need to combine.

  • You can also drag and reorder pdf files in the thumbnail panel. You can also select pdf in this panel and click delete to delete the page.

  • Finally click on File -> Save to save the combined PDF.

Sunday 18 December 2016

Greasemonkey script to dim white background webpages in Firefox

Background

In some of the previous posts we saw some greasemomkey scripts -
 This is a similar script.

Bright white pages strain your eyes. I love dark black/grey themes and they dont strain your eyes as well. So was looking out for an addon to do this.
Chrome has a beautiful addon called -
Unfortunately there is no such good plugin available on Firefox. Hence this script. You can configure RGB to the background color you wish to have. The script will be executed when your DOM(Document object model) is loaded.

Greasemonkey script to dim white background webpages in Firefox

I am not going to paste the code here. It is available on my Github gists page -
Feel free to fork it and change it as per you need. Google homepage looks like below post this change -


It has sort of greyish background.


NOTE : This is not a script originally written by me. I have just modified it to suit my needs. Feel free to edit it and use as per your requirements.

Related Links

Saturday 17 December 2016

Introduction to crontab - scheduling tasks in Linux

Background

Cron is a daemon that runs in background and helps executing commands or set of commands at a predefined time. You can use to to schedule your commands at regular intervals. For example a batch job to pull all your unread mails.

Crontab


This will be per user. So each user can have their cron jobs and are stored in separate files called crontab files. To handle these the command used is crontab. The crontab file is often stored in

  • /var/spool/cron/crontabs/<user> (Unix/Slackware/*BSD),
  • /var/spool/cron/<user> (RedHat) or 
  • /var/cron/tabs/<user> (SuSE),
but might be kept elsewhere depending on what Un*x flavor you're running. Though these files are in var they are not supposed to be edited directly. As mentioned earlier you should use crontab commands.
  • crontab [ -u user ] file
  • crontab [ -u user ] { -l | -r | -e }
Options are as follows -
  • The -l option causes the current crontab to be displayed  on  standard output. 
  • The -r option causes the current crontab to be removed.
  • The  -e option is used to edit the current crontab using the editor specified by the VISUAL or EDITOR environment variables.  After you exit  from the editor, the modified crontab will be installed auto‐matically. If neither of the environment variables is defined, then the default editor /usr/bin/editor is used.
For more details see
  • man crontab 


 As mentioned in the usage of edit crontab option you need to first set your editor -
  • aniket@aniket-Compaq-610:~$ export EDITOR=vi

 Creating a new cron job

Edit your crontab file with command -
  •  aniket@aniket-Compaq-610:~$ crontab -e
Now your crontab file should be opened in vi. Enter following command, press enter and save your file.

  • */1 * * * * date >> /tmp/log.txt 2>&1
This essentially puts current date every 2 mins in /tmp/log.txt file (combines standard output and error streams to stdout)

You should see following output -
crontab: installing new crontab

Post saving you can check the contents of your crontab file with command -
  • crontab -l



You can now check /tmp/log.txt file for output -



 
Finally you can delete your crontab file using command -
  • crontab -r


Format of crontab file command line

Syntax is as follows -
  • minute hour day-of-month month day-of-week command 
Possible values -
  • The asterisk (*) operator specifies all possible values for a field. e.g. every hour.
  • The comma (,) operator specifies a list of values. For eg every 2nd and 10th hour of the day.
  • The dash (-) operator specifies a range of values, Eg: "1-4", which is equivalent to "1,2,3,4".
  • The slash (/) operator, can be used to skip a given number of values. Eg "*/4" in the hour part of syntax would be equivalent to "0,4,8,12,16,20". "*" specifies 'every hour' but the "/4" means that skip 4 and try.
 Now lets revisit the command we used -
  • */1 * * * * date >> /tmp/log.txt 2>&1 
It means execute command every minute, every hour, every day of month, every year, each day of a week.

There are also special string that you can use instead of above syntax -

 

NOTES

  • As mentioned earlier each user has his/her crontab file. If you want to do operations that require root permissions you need to use root crontab file. To use that you can execute 
    • sudo crontab -e
  • In the /etc directory you will probably find some sub directories called  
    • 'cron.hourly', 
    • 'cron.daily', '
    • cron.weekly' and 
    • 'cron.monthly'.
      If you place a script into one of those directories it will be run either hourly, daily, weekly or monthly, depending on the name of the directory. 
  • Cron will email to the user all output of the commands it runs, to silence this, redirect the output to a log file or to /dev/null.
    • Eg. */1 * * * * date >> /dev/null 2>&1
  • For Cron permissions these two files play an important role:
    • /etc/cron.allow - If this file exists, it must contain your username for you to use cron jobs.
    • /etc/cron.deny - If the cron.allow file does not exist but the /etc/cron.deny file does exist then, to use cron jobs, you must not be listed in the /etc/cron.deny file.

Related Links

Tuesday 13 December 2016

Reset raspberry Pi forgotten password

Background

Well the background is bit embarrassing really :) To secure my raspberry Pi I set a very strong password and guess who forgot after a while :). Well I made my way back into the Pi but it was interesting. So will share this with you as well. Another constraint that I had is that I did not have my external keyboard with me so had to hack my way in. Will should you the same. However I will also list down a neater way in case you do have a keyboard.

NOTE : If you have not changed the password then it might still be raspberry. Try it. 



Without the keybaord

First and foremost you must know where passwords are stored. For Linux OS it is stored in /etc/shadow file. Ofcourse it's a one way hash and there is no way to reverse engineer it. But the file and its contents are important to us.

  • You should have another Linux distro with you. In this create a new user using command
    • useradd testuser
  • Now go to /etc/shadow file and you should see an entry corresponding to testuser. Something like -
    • testuser:!:16406:0:99999:7:::
  • Now remove the ! (or two) from between the first two colons, so it is testuser::16406.... This makes this a passwordless account.
  • Now change the current user to testuser using su command and change the password using passwd command -
    • su testuser
    • passwd
  • One you set the password you can go back to the /etc/shadow file and the line corresponding to testuser should now have a has password hash - something that most probably begins with $6
  • Copy this string and note it down.
  • Now take out your SD card from your Pi. Plug it into another Linux distro. Now on this open up the /etc/shadow file of pi and replace the hash that you might be having with the one you just noted above (You can do this for pi user).
  • And thats it you can use the same password you have for testuser to log into pi now. Try an ssh. You should be good.





Alternate route - the one with USB keyboard 

This is kind of non hacky route assuming you have a USB keyboard.
  • Remove SD card from your Pi. Plug it into some other Linux distro. 
  • In the boot partition you should find a file named cmdline.txt. 



  • Edit it to append 'init=/bin/sh' at the end. Before and after screenshots below -



  •  Save the file. Put the SD card back in Pi and boot up. Now Pi will boot up in single user mode.
  • When you get a cursor type in
    • passwd pi
  • and change the password of user pi. You can then do a normal startup using command -
    •  sync exec /sbin/init 
  • And that's it. Do not forget to remove the appended text that we put in cmdline.txt file. Remove it once you have successfully changed the password and your subsequent boots should be normal again.


Related Links

Sunday 11 December 2016

Debug Android Apps on chromebook using ADB

Background

Chromebook now supports Android Apps to be run. At Google I/O 2016, it was announced that Android apps would be available to run on supported Chromebooks via the Google Play Store, which will result in having two app stores in Chrome OS. ARC's native code approach was abandoned, instead using unmodified copy of Android's framework running in a container. Android apps run in floating windows now. You can also see google playstore in your chrome once you enable it in settings -



In this post we will see how we can run ADB and side load android apps.

 Debug Android Apps on chromebook using ADB

First make sure you your chromebook is in developer mode and and you have also enabled developer options in android settings. All of this was already shown in my last post -
Now from developer options turn on ADB debugging.



Now go to your shell again and execute following commands -

  • sudo crossystem dev_boot_signed_only=0
  • sudo /usr/libexec/debugd/helpers/dev_features_rootfs_verification
  • sudo reboot
This should reboot your chromebook . This will setup set up developer features and enable disk-write access for the firewall settings changes.



 On reboot execute following command in shell -
  • sudo /usr/libexec/debugd/helpers/dev_features_ssh
This will configure secure shell for you.





 And you are done. Now just note down the ip of your chromebook (you can execute ifconfig in shell to know)



and from your development machine type connect adb. Eg if your chromebook ip is 192.168.1.6 you will type -
  • adb connect 192.168.1.2:22
You can type following command to verify it is connected -
  • adb devices


 Now you can execute all adb commands including install to install your dev apk builds.




And you should see it get installed on your chromebook -


Related Links

Saturday 10 December 2016

How to enable developer mode on a Chromebook

Before you Start

Caution: Modifications you make to the system are not supported by Google, may cause hardware, software or security issues and may void warranty.

Couple of things to note -
  1. You will have to turn of verified boot which mean you or anyone can install a custom (non google verified) image.
  2. This will give you access to root console/shell.
  3. All your local data will be erased. Your device will be essentially reset. All your cloud data will still be present.
So to sum up your device will be less secure. Do this on your own risk.

NOTE : This article in intended only for developers and advanced users.

If you are concerned about anything mentioned above this would be a good point to turn back.

How to enable developer mode on a Chromebook

  1. Press and hold 'Esc' and refresh key (the button with a circular arrow - which is in place of your F3). Holding these buttons press your power key.

  2. You should now see a recovery mode screen with an exclamation icon. Press 'Ctrl' + 'D'. You will see screen displaying press Enter to turn of OS verification.



  3. Press Enter. You will see a transition screen displaying message of transition to developer mode.

  4. After some time your device should reboot and start in developer mode. At the end you should see your normal setup screen with language, keyboard layout etc.


How would you test that you are in developer mode?

  • First of all you should be able to access shell (console). Press Ctrl + Alt + T. Then in opened console type shell. You should be getting access to your normal linux command line.

  •  You can also check your chrome setting. You should be able to see all new advanced setting available. You can also see Android internal setting here. You can very well go ahead tab on Build number in About devices and turn on Android developer mode to access developer options. You can use this to turn on USB debugging and adb.





That's it you are now in developer mode. You have root access and can do more cool stuff. But remember  - With great power comes great responsibility :)

NOTE :  If Ctrl + D is not working you  can press Refresh+Power to boot in developer mode with ctrl+D or hit space and wipe clean.

Related Links


How to take a screenshot on your Chromebook

Background

A Chromebook is a laptop running the Linux-based Chrome OS as its operating system. Yup you read it right it is Linux based. It used Linux kernel underneath. The devices are designed to be used primarily while connected to the Internet, with most applications and data residing in "the cloud".

Chromebooks ship with Google Chrome OS, an operating system that uses the Linux kernel and the Google Chrome web-browser with an integrated media-player.

Your Chromebook is different from your personal laptops and Desktops. There are two essential things to consider before you go for a chromebook
  1. Chrome OS : This is the OS that runs on your chromebook. You need to get familiar with it. Chrome OS is an operating system designed by Google and based upon the Linux kernel. Google announced the project in July 2009, conceiving it as an operating system in which both applications and user data reside in the cloud: hence Chrome OS primarily runs web applications. (Wiki)
  2. Cloud computing : This is a major deal breaker here. Chromebook essentially is a cloud computing device. You access your data stored in cloud and signout when done. Most if your data is in cloud. So even if you lose your chromebook your data is safe.
Without these two your chromebook is essentially a browser!

Following video posted by google which sums up what chromebook really is.




There are tons of different things associated with chromebook from it's keyboard layout, its file directories all the way to the apps you run on it. Will get into those details in perhaps upcoming posts but in this post we will see how to take a screenshot on your chromebook.

How to take a screenshot on your Chromebook


  • To take screenshot of entire screen you need to press ‘Ctrl’ and ‘Window Switcher’ keys together.

  • To get a part of the screen you need to press ‘Ctrl’ , ‘Shift’  and ‘Window Switcher’ keys together.



Once you do that you should see a notification saying "Screenshot taken".



Screenshots will be available under Downloads directory of your chromebook.


 As I mentioned earlier keyboard layout of your chromebook is different than your traditional laptop. For eg. you don't have a capslock or a delete button. Instead if capslock you would see a search button. Anyway to understand keyboard shortcuts you can press
  • Ctrl + Alt + ?
And you should see a keyboard layout. When you press on
  • Ctrl or
  • Search or
  • alt or
  • their combinations
you should see their corresponding key shortcuts. For rg when you press Ctrl while on that layout you can see all shortcuts starting with Ctrl. Notice the screenshot shortcut we saw above -





Related Links


Sunday 27 November 2016

How to Uninstall Apps from Android Wear

Background

In last post we had some discussion on how to add a wearable module to your existing android app. In this post we will see how to uninstall app from your your android wear. For this you need to have Android wear app installed on your phone -
 Lets see now how we can remove the app.


How to Uninstall Apps from Android Wear

  • Make sure you are connected to your wearable device from your wearable app installed on your phone




  • Next click on settings icon.


  • Under Device Setting click on your device connected



  • Next click on watch storage and you should see your app listed there.


  • You cannot directly uninstall app from here. Rather you cannot uninstall app from wear device and still keep it on your mobile (Unless you use adb command to remove it :)). Anyway uninstall the app from your device. Go to your connected app and click on Resync apps. Your app on wearable device should automatically get removed.

Related Links











Adding and packaging wear module to your existing Android application

Background

Smart watches are slowing making their way into the market. They are quite expensive today but hoping prices will slash down with increase of technology. Anyway this post is aimed to add a wearable module to your existing Android app. This post expects you
  1. Have an existing Android application code
  2. Have it setup in latest Android Studio
So now that we have our prerequisites in place lets see how we can do this.

Step 1 : Adding a wearable  module to your Android application

If you have have your android application code opened in studio you simply need to 
  1. Open module settings
  2. Create on + (plus) button and select "Android Wear Module" .
  3. Next give your module name (NOTE : Make sure your wear module bundle id is same as your main android app bundle id)
  4. Next select activity
  5. Give your activity/layout name
  6. Click Finish


 Once you do this you should see a new module in your project with the name you provided during configuration. It will have its own set of java files, resource files, icons, manifest, build.gradle file etc.

You can go ahead and code your logic into this. This will run on your wearable device.


Step 2 : Packaging Wearable Apps

The way wearable app is distributed is by packaging it inside your handheld application (apk gets bundled inside) and when this app is installed on your phone/handheld device the wearable apk will get pushed to your wearable device.

To properly package a wearable module -
  1. Include all the permissions declared in the manifest file of the wearable app module in the manifest file of the handheld app module. For example, if you specify the VIBRATE permission for the wearable app, you must also add that permission to the handheld app.
  2. Ensure that both the wearable and handheld app modules have the same package name and version number.
  3. Declare a Gradle dependency in the handheld app's build.gradle file that points to the wearable app module: 

    Eg.

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.4.0'
        compile 'com.android.support:support-v4:23.4.0'
        compile 'com.google.android.gms:play-services:9.0.0'
        wearApp project(':flashlightwear')
    }
    

  4. Click Build > Generate Signed APK.


How it works

  • Your android mobile/handheld application and your wearable application (apk) should be signed using same certificate (key). 
  • They must also have same package name and version number.
  • When you generate a release build if your handheld application your wearable apk will get bundled in your handheld apk.
  • When you install your handheld app on your mobile which is paired to your wearable device (eg smart watch) then wearable apk bundled within will be automatically pushed and installed on the wearable device.
  • You cannot take a call on which ones to keep or not keep. If you have an app installed on your mobile device and it has a wear module it will be installed on your wearable device. You cannot uninstall it unless you remove the app from your phone.

You should see a notification on your wear device that app is installed.


I have added wear module to a flashlight app that I had developer sometime back just to learn this stuff. You can check it out. Its available on playstore -


NOTES:
  1. Ensure that both the wearable and handheld app modules have the same package name and version number.
  2. Include all the permissions declared in the manifest file of the wearable app module in the manifest file of the handheld app module. 
  3.  Your android mobile/handheld application and your wearable application (apk) should be signed using same certificate (key).
  4. wearable apk gets automatically bundled with your handheld module and gets pushed to your wearable device once installed on handled device.



Related Links





Saturday 26 November 2016

Setting up Firebase Cloud Messaging (FCM) in Android application

Background

In last post we say what FCM was and how is it better then the old GCM notifications. 
 Last post was mainly about your server configuration to send FCM notification to a single device. But that assumed that your device is already registered to FCM server and your server has that ID. In this post we will see how to create, register and setup FCM on your Android device. This can be your smart phone or your smart watch app.


Getting started with Firebase Cloud Messaging (FCM)

First of all you need to log into Firebase console -
Log in. Signup if you already don't own a account. Once done you will need to create a new project.





 Once you do that you should see following page.


 As mentioned in previous post as FCM is cross platform you can see Android/iOS/Web. We will concentrate on Android for now. So go ahead and select it. Post clicking it you have 3 steps to perform

  1. provide your android bundle iD
  2. Download google-service.json file and put it under your app folder of Android project
  3. Add dependency to classpath







In app level build.gradle add the firebase dependency you need. For eg in this case we need cloud messaging for FCM. So you can add

compile 'com.google.firebase:firebase-messaging:10.0.0'


You can see all available dependencies here -

under Available libraries section. It looks like below -




Once that is setup your configuration is more or less done. You now also see the server API id we used in previous post from  this project that you have just created. Anyway lets move on the code changes we need.

Code changes needed

Add following services in your manifest file of android module -
        <service android:name="com.osfg.android.watch.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name="com.osfg.android.watch.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

These services are basically the ones which generate token (registration id we need while sending FCM from server) and receiving message from server. Code for them goes as follows -



package com.osfg.android.watch;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
/**
 * Created by athakur on 11/25/16.
 */
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String loggerName = MyFirebaseMessagingService.class.getSimpleName();

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d(loggerName,"From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData() != null) {
            Log.d(loggerName, "Message data payload: " + remoteMessage.getData());

            String title = remoteMessage.getData().get("messageTitle");
            String body = remoteMessage.getData().get("messageBody");

            if(StringUtils.hasText(title) && StringUtils.hasText(body))
            {
                Log.d(loggerName, "Showing notification for message");
                showNotification(title, body,this);
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(loggerName, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            showNotification(remoteMessage.getNotification().getBody(),this);
        }
    }
}




MyFirebaseMessagingService class will get the  payload send by server during FCM notification. Your payload can have data or notification payload. Notification payload is directly shown as notification on android device where as data payload needs to be handle by your client application


package com.osfg.android.watch;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
/**
 * Created by athakur on 11/25/16.
 */
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String loggerName = MyFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(loggerName, "FCM token refreshed: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        sendFcmTokenToServer(refreshedToken);
    }

    private void sendFcmTokenToServer(String token) {
        Log.d(loggerName, "Sending FCM refresh token to server");
    }
}



And you should be done.  MyFirebaseInstanceIDService class will give you a callback when token is refreshed , you need to update it on your server. Once that is done your server will be able to send FCM notifications to you (exactly what we saw in last post).


Once you do this on your app start these service should automatically start. You will get token in callback and message in other callback of respective services that we have implemented. You can take actions appropriately. Sync data or show notification etc.


NOTE

I have already implemented this in a demo android app that you can refer to. Link to github project -

Related Links

t> UA-39527780-1 back to top