Thursday, February 1, 2024

Some thoughts on 'population control'

 

Some thoughts on handling the so called population problem...

1. Govt to issue two credit vouchers to every person upon reaching legal marriage age. Tied to their adhar number.

2. The value of each voucher is equal to half of median (not average) cost of raising a child up to 18 years of age. It gets adjusted every year.

3. Every year up to 10% of the credit can be converted to cash depending upon the value of the voucher at that time. When the child turns 18 all of remaining value gets cashed and deposited in his account.

4. Govt schools/hospitals etc. will have no free facility. These credits will be used for payment at these facilities. 

5. Released credits amount get attached to child's adhar and can be used as payment card for child's expenses.

5. It must be legal for people to sell these vouchers to others. This will reward people to have less children (since they can sell the unused credit and make money) at the same time people who can afford to have more children, they can have if they want. These voucher will sell in market for a reduced value and will be bought by people who have decided to have more children.

6. 5% of the taxes paid by a household must go to surviving parents. This will encourage parents to raise their children to become productive citizens as a guaranteed income source.

7. If a parent does not educate his/her children severe punishment including auction off their property educate the children. Govt enables the parent for child RTE by giving the credit voucher, now its the parent's responsibility to ensure child's RTE.

Some benefits:

  • Illegal aliens won't able to leech tax payers money.
  • Poor people or childless couples can sell the voucher and make money to support their family.
  • Government will need not fund inefficient schools/hospitals since people will go where the service is good.


Friday, June 3, 2022

Using extended disk in a virtual machine

   

These are the steps to use the extended SCSI disk in a VM. The disk shows up in VM as device /dev/sdb mounted as /opt/app. It was extended from 1 TB to 2 TB.

 # Unmount the logical volume

  umount /opt/app

  # Create a new additional partition and change the system id to 8e. Use fdisk as shown below and chose to create a new primary partition. There is only one partition /dev/sdb1 to start with. New partition will be /dev/sdb2.

  fdisk /dev/sdb

  # Partprobe to reaload the prtition table into kernel

  partprobe

  # Create physical volume

  pvcreate /dev/sdb2

  # Find name of volume group to extend. In our case the name is localvg

  vgdisplay

  # Extend the volume group

  vgextend localvg /dev/sdb2

  # Find name of logical volume

  lvdisplay

  # Extend and resize the logical volume

  lvextend -r -l +100%FREE /dev/localvg/bbed92058c4903275172716dd4a26a15

  # Mount the logical volume

  mount /dev/localvg/bbed92058c4903275172716dd4a26a15 /opt/app

Thursday, May 9, 2019

How to install pip when you are behind corporate MITM proxy?

How to install pip when you are behind corporate MITM proxy?

1) Execute this to download get-pip.py
curl -k https://bootstrap.pypa.io/get-pip.py -o get-pip.py

2) Open the get-pip.py file and change this line.
shutil.rmtree(tmpdir, ignore_errors=True)
to this line:
print ("Pip extracted to " + tmpdir)#shutil.rmtree(tmpdir, ignore_errors=True)

3) Execute this:
python get-pip.py
 It will error out but print name of the host it is trying to contact and also create a tmp folder and extract pip into that folder. Look at the output and notice last line:
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Collecting pip
  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /simple/pip/
  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /simple/pip/
  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /simple/pip/
  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /simple/pip/
  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /simple/pip/
  Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)) - skipping
  ERROR: Could not find a version that satisfies the requirement pip (from versions: none)
ERROR: No matching distribution found for pip
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)) - skipping
Pip extracted to /tmp/tmpKGoLfQ

 4) Now go to the tmp folder (something like tmpKGoLfQ) and add it to the path.
cd /tmp/tmpKGoLfQ
export PATH=$PATH:`pwd`

5) Execute this from tmp folder (/tmp/tmpKGoLfQ):

sudo python -m pip install pip --trusted-host pypi.org --trusted-host files.pythonhosted.org
 if you find another mirror is being used then add that as another trusted host.
 It will install pip and now you can use it normally. If you need to install another package you can add --trusted-host option as shown above or the better choice, install your corporation's root CA cert in python's cert store as displayed by:
python -c "import ssl; print(ssl.get_default_verify_paths())"


Thursday, May 2, 2019

What is Intelligence?

Intelligence is ability to create cognitive models of observed reality. It is inversely proportional to the time taken to create the model, number of iterations needed to create the model and number of input required in each set of observation. It is directly proportional to the accuracy, precision and agility of the created model.

We deal with everything and everyone by running a simulation through these models. The difference between a normal person and 'madman' is that madman does not run most of his random thoughts through these models.

Culture is essentially "a package of cognitive models" that has helped that specific group survive.
Once a model is formed its more resource intensive to increase accuracy and precision.
Ever wonder why otherwise intelligent people have absolute wrong opinion about certain topics? Because they have created wrong cognitive model of those topics.

Monday, February 4, 2019

Security through obscurity is no security

So we have ssh client and some of our team member end of storing their passwords in the in the ssh client. Yes I know that its bad practice, but that's a separate discussion.
The interesting part is that the ssh client does not let you see the password once you have entered them. Of source its for "for security" reasons.

Few years after having entered these passwords, people leave, move to different projects and one is stuck with a ssh session that can be used for establishing the connection but can't change the password (since root ssh is not allowed and you can't do sudo because you don't have the password).

What the solution?
A ssh honeypot server.  http://3.91.206.83/
Change the IP of the session to this server and it will print the password back. If you can change the IP, redefine the host name in your local  hosts file to point to this IP.
Be aware that one your have retrieved your password through this, assume that it has been released to public. Change your password immediately.

The ssh client is trying to make the password secure by making it obscure. Newsflash! Its not secure. Its just making user's life difficult without adding any security.



Tuesday, October 16, 2018

Installing letscrypt certificate in grails

   Installing letsrcrypt certificate in grails.
   assumptions:
    domain name: app.example.com
    password   : supersecret
    linux app user account : appuser
 Use this URL to generate command for your site:

   As root:

   =============================================
   Step 1.
   Renew certificate using this command.
#certbot certonly
   (choose to renew option 1)
   It will create two file:
   /etc/letsencrypt/live/app.example.com/fullchain.pem
   and
   /etc/letsencrypt/live/app.example.com/privkey.pem
  
   Step 2.
   Combine cert and private key using this command.
#mkdir -p /home/appuser/etc/app.example.com
#openssl pkcs12 -export -in /etc/letsencrypt/live/app.example.com/fullchain.pem -inkey /etc/letsencrypt/live/app.example.com/privkey.pem -out /home/appuser/etc/app.example.com/app.example.com.cert.p12 -name app.example.com
<secret
as password>>
#chown -R appuser.appuser /home/appuser/etc/app.example.com

   As app user:

   =============================================
   Step 3.
   Convert p12 file into jks file using this command. Change supersecret to something that is really kept super secret.
$keytool -importkeystore -deststorepass supersecret -destkeypass supersecret -destkeystore /home/appuser/etc/app.example.com/app.example.com.cert.jks -srckeystore /home/appuser/etc/app.example.com/app.example.com.cert.p12 -srcstorepass secret  -srcstoretype PKCS12  -alias app.example.com
$rm /home/appuser/etc/app.example.com/app.example.com.cert.p12

   Step 4.
   Now pass these arguments to grails .
  
$./grailsw \
        -Dserver.address=0.0.0.0 \
        -Dserver.port=8443 \
        -Dserver.ssl.enabled=true \
        -Dserver.ssl.key-store-password=supersecret \
        -Dserver.ssl.key-store=/home/appuser/etc/app.example.com/app.example.com.cert.jks \
        -Dserver.ssl.key-alias=app.example.com \
        prod run-app



The form below hosted at https://jsfiddle.net/a2bfxdeq/2 generates command for you.


Sunday, March 18, 2018

Fixing grub2 on windows 10

Problem: Installed Linux on a external HDD connected to windows 10 using live CD and Grub got installed on internal HDD pointing to grub.cfg on external HDD. So if I remove the external HDD, grub.cfg is not found and can't boot windows.

Resolution:
1. Boot Linux by connecting the external HDD.
2. Mount the efi partition (Lets say its /dev/sda1. In my case it was first partition on internal HDD, about 256M in size)
  #mkdir /tmp/efi
  #mount /dev/sda1 /tmp/efi
3. Install grub.
  #grub-install --boot-directory /tmp/efi/grub --efi-directory /tmp/efi --uefi-secure-boot

4. Create the cfg file
  #grub-mkconfig > /tmp/efi/grub/grub/grub.cfg
 
 
Not tried but may be useful:
when you have grub prompt, try this:
echo $prefix

By default grub will look for $prefix/grub.cfg. If you can copy your grub.cfg from external HDD to the default location, that may work.

Monday, May 22, 2017

The Honeybees.




As per an article from Visual Capitalists (http://www.visualcapitalist.com/what-happens-internet-minute-2016/) there 20.8 million messages are handled by Whatspp, 2.4 million searches by Google and 70000 hours of video served by Netflix, every minute.
If one looks at last decade, Social Media and Smartphones has been the ‘the’ phenomenon of last decade. Most of the growth of S&P 500 since last crash has been from this revolution. Except for few companies like Apple, which is really Prada of smartphones, most of other players in these industries have a simple underlying business model: Monetize their user’s interaction with them while offering a ‘free’ service.
Very few their users realize that the companies own right to sell any content produced by them. Social media users search all over the internet archives, old albums, parks, beaches, oceans, mountains, back yard, front yard and gather pictures, quotes, analysis, comment and then happily handover to one of the social media giant for free. Then their friends review it (for free) and mark as interesting and uninteresting. The social media giants makes sweet profit while the users end up with lost privacy and ruined relationships.
Sometimes certain ‘data leaks’ and ‘hacks’ happen where the users also end up losing information that they hate to go public.
Enjoy being honeybee.

Sunday, July 12, 2015

Transfering file to remote machine using tcpdump and dd

Sometimes you need to transfer a file to a remote machine and do not have a file transfer tool available at the remote machine or may be restricted due to firewall rules.
If the remote machine has tcpdump and dd available then you can transfer the file following the process described below.

What do you need  on sender machine?
split and netcat

What do you need on receiver machine?
tcpdump , dd and one reachable port. Most like the dhcp port (67) is going to be open since there has to be a way for the remote to get IP :)

Steps:
On remote machine
1.a:
Create a shell script file like this:
cat > extract.sh <<EOF
# On the receving machine capture tcpdump file using
# tcpdump -i doc0 -w tcpdump.bin port 67

FILE_SIZE=$1
START=82
PACKET_SIZE=1000
FRAME_HEADER=58
BYTES_EXTRACTED=0
while [ $BYTES_EXTRACTED -lt $FILE_SIZE ]
do
        let partName=10000000+$START
        dd if=tcpdump.bin of=$partName.part bs=1 count=1000 skip=$START
        let START=$START+$PACKET_SIZE+$FRAME_HEADER
        let BYTES_EXTRACTED=$BYTES_EXTRACTED+$PACKET_SIZE
done

rm outfile.bin
for name in `ls -1 *.part`
do
        cat $name >> $2
done

EOF


1.b :
Launch tcpdump in a folder where you have write access (typically /dev/ is writable so you can create a folder called /dev/worktmp and launch tcpdump from there).
#mkdir /dev/worktmp
#cd  /dev/worktmp
tcpdump -i doc0 -w tcpdump.bin port 67

Steps on sender machine:
2.a:
Create a file like this:
cat  > sendAFile.sh <<EOF
#On the sending machine
#send the file using this
INFILE=$1
DEST=$2
rm x*
split -b 1000 $INFILE
for name in `ls x*`
do
        cat $name |  nc -w 1 -u $DEST  67 &
        sleep 1 ;
        pkill nc;
        sleep 1;
done
md5sum $INFILE
ls -l $INFILE

EOF

2.b :
Send the file (say the file name is strace) to the remote machine (10.2.2.3) using the script create above:
#bash sendAFile.sh strace 10.2.2.3

Steps on remote machine:
1.c:
Create the final file. The first argument is the file size and second argument is name of the file:
sh extract.sh 45654 strace

Wednesday, April 15, 2015

Transfer a file to a remote machine using console access

How to transfer a file to a remote machine using console access (telnet etc) when you have no file transfer tools?

Sometimes you are stuck on machine that is badly locked due to "security" reasons and does not contain any tools like wget, ftp, tftp. But you want to transfer a file on that machine. What to do now?
Assuming that the remote machine lets you some kind of console access via a tools that lets you copy paste (like putty) and also has these 3 tools:
  1. dd
  2. awk
  3. sh/bash/ash etc.

We are assuming you intend to transfer netcat.bin to remote machine.

Step 1) On remote machine, create a working folder at some volume that is writable. Even if everything else is write protected /tmp and /dev are generally writable.

Step 2) Change the working folder to the newly created folder.

Step 3) Create a file called hex2bin.dat (Yes, I am not naming it a .sh file you can name it if you want) on the remote machine. Contents of the file are as shown below.
#usage:
# cat data.txt | sh hex2bin.txt
#where data.txt is like this without # signs:
#cat data.txt
#0x64
#0x0a
#0x65
#0x0d
#0x66
#EEEE
#
# You also nee a file called zero.file which can be created like this:
# dd if=/dev/zero bs=1 count=1 of=zero.file

OFILE=$1
rm $OFILE
while [ 1 -eq 1 ]
do
        read aLine
        if [ x$aLine = "xEEEE" ]
        then
                exit
        else
                if [ x$aLine = x0x00 ]
                then
                        cat zero.file>>$OFILE
                else
                        echo $aLine| awk '{printf "%c", $1;}'>>$OFILE
                fi
        fi
done

Step 4) Create a file named zero.file by using the command shown below:
dd if=/dev/zero bs=1 count=1 of=zero.file

Step 5) Now on you local machine create a file named data.txt as shown below:
xxd -c 1 netcat.bin | awk '{print "0x" $2;}' > data.txt

Step 6) Now cat data.txt and take all the contents on clipboard.

Step 7) On remote machine create the same data.txt as shown below:
cat > data.txt << EOL
<<<< Paste the clipboard contents here      >>>>
<<<< Now type "EEEE" here, without quotes   >>>>
<<<< Now type "EOL"  here, without quotes   >>>>


Step 8) Now you should have a file named data.txt on remote machine. Do grep -vn "0x" data.txt and you should not see any empty lines. If you see any empty lines then you need to correct the empty lines using a text editor on remote machine by comparing contents of your local data.txt.

Step 9) Now just use following:
cat data.txt | sh hex2bin.txt netcat.bin


If you have a checksum tools on the remote machine (like md5sum or cksum) then you may want to do checksum comparison to make sure that file is good.

Sunday, September 14, 2014

Command line java/c/c++ code formatting

One can use eclipse to format java code on command line. Following is the syntax:
eclipse.exe -application org.eclipse.jdt.core.JavaCodeFormatter -verbose  -config

All the files in all subfolders below specified source folder will be formatted.

for example:
eclipse.exe -application org.eclipse.jdt.core.JavaCodeFormatter -verbose  -config .settings/org.eclipse.jdt.core.prefs .\src

I don't remember where I picked it from but I guess it was from
http://blogs.operationaldynamics.com/andrew/software/java-gnome/eclipse-code-format-from-command-line

Also apparently there is a way to format C/C++ code also using eclipse, although I have not tried it.
https://github.com/x8o1Y/EclipseCCodeFormatter

Wednesday, August 13, 2014

How to add ssl certificate from StartCom in Grails

StartCom provide free SSL/TLS certificate for you website that is valid for a year. This certificate is good enough to get going with SSL without warning etc.

Part1) get the certificate from StartCom
How to get a free certificate from StartCom?
1) visit https://www.startssl.com/?app=12
2) Click on express lane.
3) Supply the info to get your email address verified
4) Verify the email address, it will install a certificate in your browser.
5) Now visit https://www.startssl.com/?app=12 again and go to authneticate
6) Now go to Certificate Wizard and follow the instructions for getting Web Server SSL/TLS Certificate.
7) I opted for generating the the private key file from StartCom to make my life easier. It created a private key text that I saved as file mydomain.key and then they generated certificate for my domain  that I saved as mydomain.crt. Be careful about saving the private key text since I don't think you can retrieve that later. The certificate you can retrieve later also.

Part2) Create java key store file
1) create a pkcs12 file: You need to create a pkcs12 file using the private key and certificate. You can use the following command:
 openssl pkcs12 -export -inkey mydomain.key -in mydomain.crt -name mydomain_name -out mydomain.p12
It will ask for password, supply your favorite password. For simplicity I used the same password everywhere. StartCom also provides a tool to create this pkcs12 file under tools sections.

 2) Create a java keystore file: You can use keytool or you cal use kse (http://keystore-explorer.sourceforge.net/) GUI. Open the pk12 file in kse and change the type (Tools/Change Type/JKS). Then right click on the only entery you have and set password to your favorite password as above. The save this file as one with jks extension.

Part 3) To install this file in grails, 
add these two entries in conf/BuildConfig.groovy
grails.tomcat.keystorePath = "full file path of .jks file"
grails.tomcat.keystorePassword = "your password"

Saturday, June 28, 2014

Grails: How to provide tcp connection from outside to an embedded H2 database?

Step 1) Create web.xml configuration by executing:
grails create-web-xml-config
Step 2) Make this change in WebXmlConfig.groovy
listener.add = true
Step 3) Add a listener in WebXmlConfig.groovy:
listener.classNames = ["org.h2.server.web.DbStarter"]
Step 4) Add following line in WebXmlConfig.groovy:
contextparams = ["db.tcpServer": '-tcpAllowOthers']

Restart grails app now. H2 db should be accessible at port 9092.

Wednesday, April 9, 2014

How to use IR remote control with Camera

If your camera has IR remote control reception feature built in then you can use an IR remote control to take pictures. The advantage is that you won't touch the camera and it won't vibrate. Thus it might give better oicture
First it to find out how to activate IR remote control in the camera. Typically there is a setting along with timer. In my Nikon D5300, there is a button on left hand side just below the lens release button. Pressing it few times activates remote control feature.There are two setting for remote control, one enables instant shot and other enables shoot with 2 sec delay.

Also the remote is most likely to work from in front of the camera. After activating the remote control just go in front of the camera and press the key on your remote control. That's it.

Don't forget to say cheese.

Monday, February 24, 2014

How to get media files from whatsapp?

Recently a friend send a video recording to me through whatsapp on IPhone 5s. I wanted to take that file out and put on my dlna server but could not find an easy way to get these files out of whatsapp without paying for some app.

After doing some research I decided to jailbreak the phone and install ssh server on the phone. I found that the its fairly easy to get the files once I have shell access :)

Steps:
Go into this folder:
/private/var/mobile/Applications/

Execute the following command:
find . -name ChatStorage.sqlite

This will give the location of ChatStorage.sqlite . In my case it is at :
/private/var/mobile/Applications/78493F8B-6A56-4CBD-9B03-7855B216A33B/Documents/
Whatsapp media files are stored under Library folder in application's folder identified by a large GUID sepcific to each application. Each peer's media files are in a separate folder (identified by his account id for whatsapp) as shown below:
/private/var/mobile/Applications/78493F8B-6A56-4CBD-9B03-7855B216A33B/Library/Media/14045551234@s.whatsapp.net
You there are many folder under this folder. You can list them using:
find   .            #the dot is important
One you know where the file is you can scp it. You can even scp the whole library on your PC and then figure out which is which.

Thursday, July 25, 2013

Python Simple HTTP Server with SVG image type

Although you can run Python Simple HTTP Server by just typing:

python -m SimpleHTTPServer 8000


It does not serve svg images with correct mime type. To add your own mime type for svg files, run it like this:

#!/usr/bin/python
import SimpleHTTPServer
import SocketServer
import mimetypes

PORT = 8000

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

Handler.extensions_map['.svg']='image/svg+xml'

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()



Make sure to use correct the location of python (#!/usr/bin/python).

Tuesday, September 25, 2012

Transcoding to play for DLNA capable TV

I have a Canon camera (Power Shot ELPH 310 HS). It produces good enough HD videos. I also have a DLNA server built using Open WRT+minidlna.
minidlna does not do transcoding. And somehow the MOV files produced by the Canon camera can not be played by any of the DLNA players that I have. I know you would say I deserve it, since DLNA is a deliberately crippled spec, but right now I want to play my home videos.

Finally I found a solution using Arista Transcoder (http://www.transcoder.org/).
I created this profile called "SamsungTV" on a device named dlna. You can download it here and install in Arista. Then use the UI or command line to do the format conversion.

$arista-transcode -v -p SamsungTV  -d dlna  -o tmp.MP4  ../../inbox/MVI_0648.MOV

The resulting MP4 can be played in following DLNA players.
Samsung 3D TV , Sony BlueRay player BDP  500 and Samsung BlueRay player.

Note: I had to restart and rebuild  the database for my dlna server for some reason after I added a bunch of files.

#/etc/init.d/minidlna stop; /usr/bin/minidlna -R -f /tmp/minidlna.conf

Thursday, September 20, 2012

Bluetooth mouse too fast

I recently got a Bluetooth key and mouse pair to clean up my desk. The mouse, I found was way too fast compared to the wired one. After some  research I found this program (xinput) to be useful in this case.

My input devices:

-->
First I listed my input devices:
user@box:$ xinput --list --short
Virtual core pointer id=2 [master pointer (3)]
⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)]
⎜ ↳ Wacom ISDv4 E2 Finger touch id=10 [slave pointer (2)]
⎜ ↳ SynPS/2 Synaptics TouchPad id=12 [slave pointer (2)]
⎜ ↳ TPPS/2 IBM TrackPoint id=13 [slave pointer (2)]
⎜ ↳ Logitech Logitech USB Optical Mouse id=15 [slave pointer (2)]
⎜ ↳ Dell BT Mouse id=18 [slave pointer (2)]
⎜ ↳ Dell BT Keyboard id=19 [slave pointer (2)]
Virtual core keyboard id=3 [master keyboard (2)]
Virtual core XTEST keyboard id=5 [slave keyboard (3)]
Power Button id=6 [slave keyboard (3)]
Video Bus id=7 [slave keyboard (3)]
Sleep Button id=8 [slave keyboard (3)]
Integrated Camera id=9 [slave keyboard (3)]
AT Translated Set 2 keyboard id=11 [slave keyboard (3)]
ThinkPad Extra Buttons id=14 [slave keyboard (3)]
BTC USB Multimedia Keyboard id=16 [slave keyboard (3)]
BTC USB Multimedia Keyboard id=17 [slave keyboard (3)]

Then I checked the properties for my mouse:
user@box:$ xinput --list-props "Dell BT Mouse"
Device 'Dell BT Mouse':
Device Enabled (131): 1
Coordinate Transformation Matrix (133): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
Device Accel Profile (249): 0
Device Accel Constant Deceleration (250): 1.000000
Device Accel Adaptive Deceleration (251): 1.000000
Device Accel Velocity Scaling (252): 10.000000
Evdev Axis Inversion (311): 0, 0
Evdev Axes Swap (313): 0
Axis Labels (314): "Rel X" (141), "Rel Y" (142)
Button Labels (315): "Button Left" (134), "Button Middle" (135), "Button Right" (136), "Button Wheel Up" (137), "Button Wheel Down" (138), "Button Horiz Wheel Left" (139), "Button Horiz Wheel Right" (140), "Button Side" (546), "Button Extra" (547), "Button Forward" (548), "Button Back" (549), "Button Task" (550), "Button Unknown" (310), "Button Unknown" (310), "Button Unknown" (310), "Button Unknown" (310)
Evdev Middle Button Emulation (316): 0
Evdev Middle Button Timeout (317): 50
Evdev Wheel Emulation (318): 0
Evdev Wheel Emulation Axes (319): 0, 0, 4, 5
Evdev Wheel Emulation Inertia (320): 10
Evdev Wheel Emulation Timeout (321): 200
Evdev Wheel Emulation Button (322): 4
Evdev Drag Lock Buttons (323): 0


And then I adjusted the velocity scaling:
user@box:$xinput --set-float-prop "Dell BT Mouse" 252 1.0



Tuesday, September 11, 2012

Creating a repository of Photos

Over the years I have been taking digital photographs and now have many Gigs worth (?) of them.

A few problem that I typically face,
1) Finding duplicates. I mean multiple copies of the same picture scattered all over.
2) Finding one from a particular time, like Feb 08
3) Preventing overwrites. Some how all the camera's like to have common prefixes for naming pictures. And some are even worse, every time you change the memory card, they reset the sequence. So I end up seven of them having DSC0001.JPG and each one is a different picture.


To get handle on the situation I wrote a script that looks at the picture, finds date and time and md5 hash. Then organizes them in separate folder names by year and month and names each picture by the time it was taken. If it finds a new pictures with same date time then it names later one also using the md5 hash.
Here is the script.


user@yux:/tmp$ cat ~/bin/photoRepository.sh
#!/bin/bash

if [ $# -eq 0 ];then
usage
echo "find /pictures -iname *.jpg -type f -exec $0 {} \\;"
exit
fi

findCameraModel(){
echo `exifprobe -L $1| grep -w "JPEG.APP1.Ifd0.Model" | sed "s/'//g"| awk '{print $3 "_" $4 "_" $5}'`
}

TEST=echo
FILE_NAME=$1
EXT=`echo ${FILE_NAME/*./}`
BASE_NAME=`basename $FILE_NAME .$EXT`
#echo $BASE_NAME $EXT

# see if we have already processed this file
if [ ! x$RESUME_RUN == x ]; then
grep "$FILE_NAME" cumulative_log.txt
if [ $? -eq 0 ]; then
echo $FILE_NAME has already been processed.
exit
fi
fi

# Now find the date
DATE_TIME=`exifprobe -L $FILE_NAME| grep -w DateTime | sed "s/'//g"`
DATE=`echo $DATE_TIME | awk '{print $3;}'`
TIME=`echo $DATE_TIME | awk '{print $4;}'`

FOLDER=`echo $DATE | awk 'BEGIN { FS = ":" } ; { print $1 "_" $2 }'`

if [ "x$FOLDER" == "x_" ];then
echo No DATE info in $FILE_NAME, using UNKNOWN as folder
MD5=`md5sum $FILE_NAME | awk '{print $1}'`
CAMERA=`findCameraModel $FILE_NAME`
if [ "x$CAMERA" == "x" ];then
CAMERA=UNKNOWN_CAMERA
fi
FOLDER=$CAMERA/UNKNOWN/`echo $MD5 | cut -c 1 `
NEW_NAME=${CAMERA}_$MD5
else
NEW_NAME=`echo ${DATE}_${TIME} | sed "s/:/_/g"`
fi

if [ ! -d $FOLDER ]; then
echo folder $FOLDER will be created
mkdir -p $FOLDER
fi


FULLPATH=$FOLDER/$NEW_NAME.$EXT

if [ -f $FULLPATH ]; then
echo -n file $FULLPATH already exists

MD5SUM1=`md5sum $FILE_NAME | awk '{print $1}'`
MD5SUM2=`md5sum $FULLPATH | awk '{print $1}'`
if [ $MD5SUM1 == $MD5SUM2 ]; then
echo , and they have same checksum $MD5SUM1 so you need to delete $FILE_NAME
echo rm $FILE_NAME \# $MD5SUM2 $FULLPATH >> cumulative_log.txt
exit
else
FULLPATH=$FOLDER/${NEW_NAME}_${MD5SUM1}.$EXT
echo , This file will be copied as $FULLPATH
sleep 2
fi
fi

touch $FULLPATH
if [ $? -eq 0 ]; then
if [ ! -s $FULLPATH ]; then
rm $FULLPATH
fi
#$TEST mv $FILE_NAME $FOLDER/$NEW_NAME.$EXT
echo cp -v $FILE_NAME $FULLPATH \# $MD5SUM2 >> cumulative_log.txt
cp -v $FILE_NAME $FULLPATH
fi

Mounting SD card from Epson printer on a Linux machine.

Mounting SD card from Epson printer on a Linux machine.

I have my workstation that I need to copy pictures on, from my Camera. Hooking the SD card using a SD card adapter is a choice, but I am too lazy to do it. I also have a EPSON Workforce 545 which has SD card slot and wifi. I use it a scanner as well. When working as scanner it creates images on the SD card.

I am not sure if there are drivers for Linux or not, but who cares? I just pop in the SD card in the printer and turn it on. Then use this script to mount the SD card on my Linux workstation.
The method should work on any printer that exposes the SD card over network as SMB share.

Linux version:

user@yux:~/tmp$ uname -a
Linux yux 3.0.0-12-generic #20-Ubuntu SMP Fri Oct 7 14:56:25 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux

The script to do mounting:

user@yux:/tmp$ cat ~/bin/mountEpson.sh
#!/bin/bash
REPOSITORY=/home/krishna/Documents/epson
EPSON_MOUNT=/tmp/epson/
PRINTER_MAC=0026AB5FCDF9
SUBNET=192.168.11.0/24

mountEpson()
{
echo Discovering Epson printer, it may take a while.
#nmap -oG /tmp/nmap.txt -p 80,9100,631,445 192.168.11.0/24 > /tmp/nmap.verbose.txt
nmap -oG /tmp/nmap.txt -p 631 $SUBNET > /tmp/nmap.verbose.txt
PRINTER_IPS=`grep open /tmp/nmap.txt | grep -v closed | awk '{print $2 ;}'`
if [ "x$PRINTER_MAC" == "x" ]; then
echo Printer MAC Adress not defined, first found printer will be used.
PRINTER_IP=`echo $PRINTER_IPS | tr [:blank:] "\n" | head -1`
echo Using printer with IP $PRINTER_IP , Name `findPrinterModel $PRINTER_IP` and MAC `findMacAddress $PRINTER_IP`
else
for ONE_IP in `echo $PRINTER_IPS`
do
mac=`findMacAddress $ONE_IP`
if [ "x$mac" == "x$PRINTER_MAC" ]; then
echo Printer with IP $ONE_IP \($mac\), `findPrinterModel $ONE_IP` is our printer.
PRINTER_IP=$ONE_IP
else
echo Printer with IP $ONE_IP \($mac\), `findPrinterModel $ONE_IP` is not our printer.
fi
done
if [ "x$PRINTER_IP" == "x" ]; then
echo Could not find our printer with MAC Address of $PRINTER_MAC
fi
fi
echo Trying to unmount existing mount
umount $EPSON_MOUNT

echo " "

if [ ! -d $EPSON_MOUNT ]; then
mkdir -p $EPSON_MOUNT
fi

echo Now trying to mount the SD Card
mount -t smbfs //$PRINTER_IP/MEMORYCARD $EPSON_MOUNT -o username=defaults,password=defaults
if [ $? -eq 0 ]; then
echo mounted epson sd card at $EPSON_MOUNT
if [ ! -d $EPSON_MOUNT ]; then
mkdir $REPOSITORY
fi
else
echo Failed to mount SD card.
fi

}

findMacAddress()
{
snmpget -v1 -c public $1 iso.3.6.1.2.1.2.2.1.6.1 2> /dev/null | cut -f 2 --delimiter=':' | sed 's/ //g'
}
findPrinterModel()
{
snmpget -v1 -c public $1 iso.3.6.1.2.1.25.3.2.1.3.1 2> /dev/null | cut -f 2 --delimiter=':'
}

mountEpson