Saturngod

What's on my mind

Number padding with decimal

You may see some personal fincial app , you need to put the number like calculator.

Example : First it show 0.00

You enter 1

it will be like 0.01. And then press 5 , it will be 0.15. And then press 3 , it will be 1.53 .

So, how to write this one ?

Normal thinking way it, you need to check

  1. Append the string at the end
  2. Check first number is zero or not.
  3. If zero , remove it.
  4. Move the decimal posiotion.

A bit complicate. Actually it’s not hard like that.

Very simple way is

  1. Append the string at the end.
  2. remove .
  3. dvided by 100

That all. Very simple step.

Example with objective-c , it will be like

NSString* str = [NSString stringWithFormat:@"%@%@", txtAmount.text,string];
str = [str stringByReplacingOccurrencesOfString:@"." withString:@""]; 
txtAmount.text = [@"" stringByAppendingFormat:@"%0.2f", [str doubleValue]/100.0];

Custom Wintersmith Helper

Today , I was trying to add twitter card in my blog. It have a problem for twitter card description. Wintersmith didn’t support plain text for blog post. Blog intro already using the HTML code. So, I need to remove.

So, I create the custom helper like following.

Create a wintersmith-custom-helper folder under node_modules

In the wintersmith-custom-helper , it have 2 file. index.js and package.json .

In the package.json

{
  "name": "wintersmith-customhelper",
  "version": "1.0.0",
  "description": "Custom Helper For My Blog",
  "author": "saturngod",
  "license": "MIT",
  "keywords": [
    "wintersmith",
    "wintersmith-custom-helper"
  ],
  "main": "index.js",
  "dependencies": {
  },
  "devDependencies": {
    "vows": "0.7.x",
    "wintersmith": "2.x"
  },
  "peerDependencies": {
    "wintersmith": "2.x"
  }
}

I gave the module name is wintersmith-customhelper.

In the index.html

module.exports = function(env, callback) {
  env.helpers.getDescription = function(htmlcode) {
    var code;
    code = htmlcode.replace(/(<([^>]+)>)/g, "");
    code = code.substring(0, 255);
    code = code.replace("\n", " ");
    code = code.replace("\"", "");
    return code = code + " ... ";
  };
  return callback();
};

I create the getDescription helper for description.

After finish that, need to update the config.json

In the config.json , we need to put the plugin. So, it will be like

"plugins": [
    "wintersmith-tag",
    "./node_modules/wintersmith-custom-helper"
  ],

Done. So, we can call env.helpers.getDescription in our template.

- var plain = env.helpers.getDescription(page.intro)
meta(name='twitter:description', content="#{plain}")

It easy to create helper and you can also use .coffce instead of .js file for plugin.

Decimal Format In Android

Yesterday , I found a bug in the app that I working on. If it’s a indonesia language in phone , my app can’t work properly. Because Android didn’t return the decimal if we are using indonesia language setting.

Example :

String amt = String.format("%.2f",20.05);
Log.i("test","Amount is " + amt); //if indo language , it will return 20,00 instead of 20.05

I tested with DecimalFormat but same result.

DecimalFormat f = new DecimalFormat("##.00");
String atm = f.format(d); 
Log.i("test","Amount is " + amt); //if indo language , it will return 20,00 instead of 20.05

So, I am using like following for now.

String amt = String.format("%.2f",20.05);

if(atm.indexOf(",") != -1)
{
    atm = atm.replace(",", ".");
}

Log.i("test","Amount is " + amt);

Redmi Note With adb in mac

  • Enable Developer Options.
  • Enable USB Debugging.

In terminal,

$ echo "0x2717" > ~/.android/adb_usb.ini
$ ./adb kill-server
$ ./adb devices

Unable To Downloaded Application with Testflight

Yesterday , I got a problem with Testflight. I gave them the app with testflight for testing. However, they can’t install and always got “Unable to Download Application”.

I found the article on testflight .

  • Device storage is full
  • The provisioning profile is a developer provisioning profile
  • The ad hoc distribution provisioning profile is corrupted and the device is having an issue with it (this can happen for multiple reasons. Including issues with 3rd party dev tools that could be causing a conflict).
  • The device was restored from a backup and is causing a conflict for over-the-air distribution
  • There was a network timeout
  • Architecture settings of the build and the device are incompatible ( can sometimes happen when “Build Active Architecture Only” is on when building).
  • The target minimum iOS version for the app is greater than the iOS version installed on the device.
  • Not Using Mobile Safari.

Everthing is correct. But I forget to check Architecture settings. I am using Build Active Architecture Only . So, it’s a problem. Ater I change to the Build Active Architecture Only to NO and it’s working fine.

Swift Is Fast Now

Today, I update the Xcode 6 Beta 3 and retest the bubble sort that I wrote yesterday. In Beta 3, bubble sort is done in 11 miliseconds in Debug Mode. Before it done in 14 miliseconds. After that I changed to the Release Mode and run it. It done in the 0.15 miliseconds. Yes, this time swift is faster than Objective-C now. In objective-C , it done in 0.28 miliseconds.

Swift Programming Language book has been updated and you need to update it.

Changes in Xcode 6 beta 3 for Swift are

  • Array in Swift has been completely redesigned to have full value semantics like Dictionary and String have always had in Swift. This resolves various mutability problems – now a ‘let’ array is completely immutable, and a ‘var’ array is completely mutable – composes properly with Dictionary and String, and solves other deeper problems. Value semantics may be surprising if you are used to NSArray or C arrays: a copy of the array now produces a full and independent copy of all of the elements using an efficient lazy copy implementation. This is a major change for Array, and there are still some performance issues to be addressed. Please see the Swift Programming Language for more information. (17192555)!
  • The Array and Dictionary “sugar” syntax has been redesigned: You now declare arrays as [Int] instead of as Int[], as shorthand for Array. The old syntax made sense when arrays had semantics closer to C arrays, but would be misleading with the new value semantics approach. Along with this, Dictionary syntax has improved so that [Key:Value] is treated as sugar for Dictionary. Both of these are now consistent with each other and with the literal syntax used to build an array or dictionary. Please see the Swift Programming Language for more information.!
  • NSDictionary* is now imported from Objective-C APIs as [NSObject : AnyObject]. (16870626)!
  • The half-closed range operator has been changed from .. to ..< to reduce confusion and ambiguity. Now the two range operators are ..< and … for half-closed and closed ranges, respectively (17203527).!
  • nil is now a literal in the language, not a global constant of _Nil type. This change resolved a number of problems with nil; e.g. nil in a collection, nil converting to Any, etc. Types can now indicate that they are nil compatible by conforming to the NilLiteralConvertible protocol. (16951729)!
  • APIs imported from C no longer use type aliases like CInt or CFloat, which obfuscated the underlying type. They are now imported as Int32 and Float, etc.!
  • APIs imported from C that use C pointers are now imported with a much simpler API type structure which is more predictable, preserves const mutability in more cases, and preserves __autoreleased pointer information. Now you will see UnsafePointer, ConstUnsafePointer, AutoreleasingUnsafePointer, etc. Function pointers are also imported now, and can be referenced and passed around. However, you cannot call a C function pointer or convert a closure to C function pointer type.!

You can read more at here

Is Swift Really Fast ?

Apple claimed that swift is faster than the Objective-C. However, I feel is slower than Objective-C. When I writing the custom keyboard with Swift , IDE response too slow and Sourcekitservice use over 100% CPU usages. It may be the IDE bug and X-Code 6 still beta 2.

So, I tried to sort the array with bubblesort with Objective-C and Swift like following.

As the result , Objective-C done is 0.297070 miliseconds and Swift Done in 14 miliseconds. It’s so much different. So, I change the swift compiler method to Fastest and It done ine 0.5 miliseconds. Not so much different with Objective-C but still slow.

I hope, it’s a bug and apple will fix in next version of xcode 6 release. I love the Swift because it’s safer and easier than Objective-C. However, I don’t want to use if it’s slower than Obective-C at run time.

Group By Date in mongodb

I am using mongodb for tracking my website. I am saving date and time with ISODate , "time" : ISODate("2014-05-18T13:23:04.227Z") .

So, I wrote like that.

db.analystic.aggregate(
{
    "$project": {
        "y": {
            "$year": "$time"
        },
        "m": {
            "$month": "$time"
        },
        "d": {
            "$dayOfMonth": "$time"
        }
    }
},
{
    "$group": {
        "_id": {
            "year": "$y",
            "month": "$m",
            "day": "$d"
        },
        count: {
            "$sum": 1
        }
    }
},
{
    $sort: {
        "_id.year": 1,
        "_id.month": 1,
        "_id.day": 1
    }
})

First , need to separate the year , month and date. After that , make a group and then sort it.

EMV TLV Decoder For Objective-c

I couldn’t find the EMV TLV decoder for iOS. However, I found a PHP code on github. So, I port to iOS version. However, I only need decoder. So, ios code include only decoder.

#import "SGTLVDecode.h"

//some of your code
//usage it

NSDictionary *value = [SGTLVDecode decodeWithString:@"Your TLV String"];

NSLog(@"TLV %@",value);

Fixed Disqus For WinterSmit

I am using disqus for my blog. However, it has a problem. If the URL is include query string , comments can’t show and it’s showing new one. I found a solution JavaScript configuration variables of disqus.

We need to put correct URL at disqus_url variable. So, I put

var disqus_url = document.location.origin + document.location.pathname;

For jade template , it will look like

#disqus_thread
  script(type='text/javascript')
      |/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
      |var disqus_shortname = 'myblogname'; // required: replace example with your forum shortname
      |var disqus_url = document.location.origin + document.location.pathname;
      |/* * * DON'T EDIT BELOW THIS LINE * * */
      |(function() {
      |var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
      |dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
      |(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      |})();
    noscript
      | Please enable JavaScript to view the
      a(href='http://disqus.com/?ref_noscript') comments powered by Disqus.
    a.dsq-brlink(href='http://disqus.com')
      | comments powered by
      span.logo-disqus Disqus

After that , there is no more problem about query string URL problem.