Saturday, May 11, 2013

Android programming - How to convert a date string to a date as milisecond value

Here is a function to convert a date string to a date as a millisecond value. The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.

public long longDate (String sdate){
  
  long longDate = System.currentTimeMillis(); //Initializes var with current time in case parsing fails
   
  SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy, HH:mm", Locale.US); //Describes date pattern
  format.setLenient(false); //enforces strict pattern matching  
    
  try {
   Date date = format.parse(sdate); //converts string to a date object
   longDate = date.getTime(); 
  } catch (ParseException e) {
  }
    
  return longDate;  
  }


So basically you would call the function like longDate (11/05/2013, 22:25).

Sunday, March 24, 2013

How to display code in blogger posts

In this post, I'm going to show step by step how to display code nicely in blogger posts using SyntaxHighlighter.

1) First, we need to add the html code below on the head section of our blogger template. To do this, inside blogger:
  • Select Template on the left hand side.
  • Click Edit HTML.
  • Then copy the code below just before the closing head tag (i.e </head>). You can easily find it by using the search box accessing to it with Control+F.

<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeEclipse.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
<script language='javascript' type='text/javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.all();
</script>

On line 4 and 5 (violet color), I'm loading the syntax template for Java code and XML code, but there are much more like PHP, Perl, SQL,... you can find the complete list here.


2) Now that the blogger template is ready, we need to prepare the code to ensure correct rendering. Basically, we need to HTML escape some characters like right angle brackets, e.g. all < must be replaced with &lt;. To do so, you can use one of the following online tools:

http://www.accessify.com/tools-and-wizards/developer-tools/quick-escape/default.php


3) Once you have the code with escaped characters, you can copy it on your blogger post inside <pre> tags. In the title you can choose a title for the code block and in the class you choose the code template to use.

<pre title="here goes a title" class="brush:xml;">
...
</pre>


4) And that's it, here is an example:
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeEclipse.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
<script language='javascript' type='text/javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
</script>

Saturday, March 23, 2013

Android programming - Call forwarding

In this post, I'm sharing with you the Android code to activate/deactivate call forwarding programatically.

The idea behing is to instruct the phone to send the MMI codes to tell the network operator to activate/deactivate the call forwaring. Please notice, that your operator must allow you to use this service otherwise it will not work.

In the exemple below, the call forwarding applies to all calls but you can use other options such as only when you are busy or you don't answer. You can find additional info here: http://en.wikipedia.org/wiki/Call_forwarding#Keypad_codes

package com.danielthat.callforwarding;

import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;

public class CallForwarding extends Activity 
{
 Button buttonCallForwardOn;
 Button buttonCallForwardOff;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.call_forwarding_layout);
  
  buttonCallForwardOn = (Button) findViewById(R.id.buttonCallForwardOn);
  buttonCallForwardOn.setOnClickListener(new View.OnClickListener()
  {
   public void onClick(View v)
   {
    callforward("*21*0123456789#"); // 0123456789 is the number you want to forward the calls.
   }
  });
  
  buttonCallForwardOff = (Button) findViewById(R.id.buttonCallForwardOff);
  buttonCallForwardOff.setOnClickListener(new View.OnClickListener()
  {
   public void onClick(View v)
   {
    callforward("#21#");
   }
  });
 }
 
 private void callforward(String callForwardString)
    {
        PhoneCallListener phoneListener = new PhoneCallListener();
        TelephonyManager telephonyManager = (TelephonyManager)
         this.getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
              
        Intent intentCallForward = new Intent(Intent.ACTION_CALL);
        Uri mmiCode = Uri.fromParts("tel", callForwardString, "#");
        intentCallForward.setData(mmiCode);
        startActivity(intentCallForward);
    }
 
 private class PhoneCallListener extends PhoneStateListener 
 {
        private boolean isPhoneCalling = false;        

        @Override
        public void onCallStateChanged(int state, String incomingNumber) 
        {
            if (TelephonyManager.CALL_STATE_RINGING == state)
            {
                // phone ringing
            }

            if (TelephonyManager.CALL_STATE_OFFHOOK == state) 
            {
                // active
                isPhoneCalling = true;
            }

            if (TelephonyManager.CALL_STATE_IDLE == state) 
            {
                // run when class initial and phone call ended, need detect flag
                // from CALL_STATE_OFFHOOK
                if (isPhoneCalling)
                {
                    // restart app
                    Intent i = getBaseContext().getPackageManager()
                            .getLaunchIntentForPackage(getBaseContext().getPackageName());
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                    isPhoneCalling = false;
                }
            }
        }
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.danielthat.callforwarding"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.danielthat.callforwarding.CallForwarding"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".CallForwarding" > 
    
    <Button
        android:id="@+id/buttonCallForwardOn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Activate Call forward" />

    <Button
        android:id="@+id/buttonCallForwardOff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/buttonCallForwardOn"
        android:layout_below="@+id/buttonCallForwardOn"
        android:text="Cancel Call forward" />

</RelativeLayout>

Monday, February 25, 2013

No ringback tone asterisk

no ringback tone asterisk








You have callers calling in to your Asterisk server using a SIP trunk and they don't hear ringback tone?

Here is what it worked for me.

In the sip.conf file, located in /etc/asterisk/sip.conf:

- In the [general] context check that the parameter prematuremedia=no is present.

- For the related peer (trunk) use the parameter progressinband=yes.

Saturday, December 15, 2012

How to send email from command line using Gmail (or any other provider)

If you want to send email from command line using a Gmail account (or any other provider), you can use SendEmail.

SendEmail is a lightweight, completely command line based, SMTP email agent. It was designed to be used in bash scripts, Perl programs, and web sites, but it is also quite useful in many other contexts. SendEmail is written in Perl.

1) Install SendEmail
 In debian 
#apt-get install libio-socket-ssl-perl libnet-ssleay-perl perl
#apt-get install sendemail

For other distributions:
Refer to the official site http://caspian.dotconf.net/menu/Software/SendEmail/


2) Run it
Here is an example:
sendEmail -f user@gmail.com -t myfriend@gmail.com \
-u "this is the test subject" -m "this is a test message" \
-s "smtp.gmail.com" \
-o tls=yes \
-xu user -xp password



3) Problems
If you get the following error:
"invalid SSL_version specified at /usr/share/perl5/IO/Socket/SSL.pm line 332"

It is a known bug: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=679911

A temporary workaround is to edit the file /usr/bin/sendemail on line 1907 by changing 'SSLv3 TLSv1'in  to 'SSLv3',


1903     ## Start TLS if possible
1904     if ($conf{'tls_server'} == 1 and $conf{'tls_client'} == 1 and $opt{'tls'} =~ /^(yes|auto)$/) {
1905         printmsg("DEBUG => Starting TLS", 2);
1906         if (SMTPchat('STARTTLS')) { quit($conf{'error'}, 1); }
1907         if (! IO::Socket::SSL->start_SSL($SERVER, SSL_version => 'SSLv3 TLSv1')) {
1908             quit("ERROR => TLS setup failed: " . IO::Socket::SSL::errstr(), 1);
1909         }
1910         printmsg("DEBUG => TLS: Using cipher: ". $SERVER->get_cipher(), 3);
1911         printmsg("DEBUG => TLS session initialized :)", 1);
1912 
1913         ## Restart our SMTP session
1914         if (SMTPchat('EHLO ' . $opt{'fqdn'})) { quit($conf{'error'}, 1); }
1915     }
1916     elsif ($opt{'tls'} eq 'yes' and $conf{'tls_server'} == 0) {
1917         quit("ERROR => TLS not possible! Remote SMTP server, $conf{'server'},  does not support it.", 1);
1918     }


Saturday, November 24, 2012

How to launch Raspberry Pi GUI from SSH connection

To launch Raspberry Pi GUI from a SSH connection on windows:

- First ensure you have an X server running in Windows. Me I'm using Xming.
- Then create a SSH connection with X forwarding. If you need help with this point, check this site.
- Once connected, launch the GUI with lxsession command.

Sunday, October 21, 2012

PuTTy Fatal Error - Network error: Software caused connection abort [SOLVED]

In order to prevent this error after some time of inactivity you can do the following:

PuTTy Fatal Error - Network error - Software caused connection abort



1- Open Putty and go to "Connection".




















2- Change the "Seconds between keepalives" to a number higher than zero. 120 should be good.




















3- Now go to Session and save as "Default Settings"





















4- Done! Now every time you launch a SSH session with Putty, these settings will be used.


Comments welcomed!