Thursday, May 14, 2015

Format mata uang (currency) dengan Javascript

Bagi yang tidak terlalu suka menggunakan javascript framework mem-format mata uang bisa dilakukan dengan cara sebagai berikut.


  1. /*
  2. decimal_sep: character used as deciaml separtor, it defaults to '.' when omitted
  3. thousands_sep: char used as thousands separator, it defaults to ',' when omitted
  4. */
  5. Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)
  6. {
  7. var n = this,
  8. c = isNaN(decimals) ? 2 : Math.abs(decimals), //if decimal is zero we must take it, it means user does not want to show any decimal
  9. d = decimal_sep || '.', //if no decimal separator is passed we use the dot as default decimal separator (we MUST use a decimal separator)
  10. /*
  11. according to [http://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]
  12. the fastest way to check for not defined parameter is to use typeof value === 'undefined'
  13. rather than doing value === undefined.
  14. */
  15. t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, //if you don't want to use a thousands separator you can pass empty string as thousands_sep value
  16. sign = (n < 0) ? '-' : '',
  17. //extracting the absolute value of the integer part of the number and converting to string
  18. i = parseInt(n = Math.abs(n).toFixed(c)) + '',
  19. j = ((j = i.length) > 3) ? j % 3 : 0;
  20. return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
  21. }


Untuk penyesuaian format bisa dilakukan sendiri ya :D.
Nah, jika ingin lebih praktis banyak juga library yang sudah dibuat para orang budiman yang berbaik hati mau berbagi. Salah satu contohnya adalah accounting.js.
Penggunaannya cukup mudah berikut beberapa contohnya.
// Standard usage and parameters (returns string):
accounting.formatMoney(number,[symbol = "$"],[precision = 2],[thousand = ","],[decimal = "."],[format = "%s%v"])

// Second parameter can be an object:
accounting.formatMoney(number, [options])

// Available fields in options object, matching `settings.currency`:
var options = {
 symbol : "$",
 decimal : ".",
 thousand: ",",
 precision : 2,
 format: "%s%v"
};

// Example usage:
accounting.formatMoney(12345678); // $12,345,678.00
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000

// Example usage with options object:
accounting.formatMoney(5318008, {
 symbol: "GBP",
 precision: 0,
 thousand: "·",
 format: {
  pos : "%s %v",
  neg : "%s (%v)",
  zero: "%s  --"
 }
});

// Will recursively format an array of values:
accounting.formatMoney([123, 456, [78, 9]], "$", 0); // ["$123", "$456", ["$78", "$9"]]
Gitu aja :D. Sampai jumpa di lain post. Thanks
Oh iya lupa kasi referensinya : http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript dan http://openexchangerates.github.io/accounting.js

Memperbaiki Sublime apostrophe key (tanda petik satu) tidak normal

Pernahkah kamu mengalami kejadian seperti judul diatas? Mungkin yang tidak suka mengotak-atik laptopnya kejadian seperti ini tidak akan mungkin dihadapi. Tapi saya pernah. :D

Ini berawal ketika saya mencoba layout Keyboard Dvorak. Jadi saya hapus layout keyboard aslinya (QWERTY) dan hanya ada layout keyboard Dvorak saat itu. Apa jadinya?

Saya stuck. Saat itu cukup banyak job yang harus dikerjakan. Bisa dibilang itu cukup frustating tapi yah mau bagaimana lagi. Eh lah ko curhat :v. Maaf.

Oke to the point. Bagi kamu yang pakai Editor Sublime tentu familiar dengan fitur auto close apostrophe-nya. Jadi kalau kita tekan tombol apostrophe/single qoute (tanda petik satu ') cursor akan berada ditengah antara quote pembuka dan penutup. Ini cukup amazing. Apalagi bagi yang suka ngetik dengan kecepatan maksimum kayak saya :v.

Jika fitur ini tidak sesuai harapan atau tidak ada pada sublime kamu. Masalah yang mungkin menyebabkan adalah tipe layout keyboardnya. Untuk sublime tipe layout yang didukung adalah US English tanpa ada embel-embel internasionalnya.

Untuk pindah layout keyboard pada Windows 7 cukup mudah, ikuti langkah-langkah berikut.

  1. Tekan tombol Windows (yang sebelah tombol alt itu)
  2. Ketik 'Region and Language' kemudian Enter
  3. Pindah ke tab 'Keyboard and Language'
  4. Change Keyboard
  5. Kemudian Add layout Keyboard US dan jadikan default
  6. Selesai
Itu saja post kali ini. Semoga bermanfaat. :D
Jika ingin lebih jelas silahkan kunjungi referensi nya :v ( http://superuser.com/questions/346142/my-windows-keyboard-is-being-clever-with-the-quote-keys-how-can-i-stop-it )
Linknya panjang kan ? Itu karena doi bingung mau gimana nanyanya, untung yang jawab pada paham masalahnya. :D Semangat vrooh :v

Memicu Even dengan JQuery Trigger

Terkadang kita ingin memicu sebuah even pada halaman website. Hal ini bisa kita lakukan dengan mudah menggunakan fungsi "trigger" pada JQuery.

.trigger()

Pada situs resminya deskripsi fungsi ini sebagai berikut.
Execute all handlers and behaviors attached to the matched elements for the given event type.

Penggunaan :
.trigger( eventType [, extraParameters ] )
// eventType (string): event yang ingin dipicu, misalnya event "click", "submit" dsb
// extraParameters (array atau object json): parameter tambahan yang ingin dilewatkan saat eksekusi fungsi ini
atau
.trigger( event [, extraParameters ] )
// event : jquery event object 
// extraParameters (array atau object json): parameter tambahan yang ingin dilewatkan saat eksekusi fungsi ini

Sekian post kali ini, terima kasih sudah membaca :D.
Jangan lupa berkomentar :v

Referensi: http://api.jquery.com/trigger/

Wednesday, May 13, 2015

Analisis ketika Gagal Membuat Tabel InnoDB pada MySQL (InnoDB Troubleshooting - MySQL)

Kegagalan saat membuat tabel InnoDB seringkali disebabkan oleh masalah sepele diantaranya perbedaan definisi kolom.

MySQL memiliki fasilitas untuk troubleshooting untuk masalah tersebut. Gunakan perintah berikut:


SHOW ENGINE INNODB STATUS

Mysql akan memberikan informasi error kira-kira seperti berikut:

TypeNameStatus
InnoDB===================================== 150513 9:29:01 INNODB MONITOR OUTPUT ===================================== Per second averages calculated from the last 5 seconds ----------------- BACKGROUND THREAD ----------------- srv_master_thread loops: 51 1_second, 51 sleeps, 4 10_second, 12 background, 12 flush srv_master_thread log flush and writes: 57 ---------- SEMAPHORES ---------- OS WAIT ARRAY INFO: reservation count 5, signal count 5 Mutex spin waits 1, rounds 30, OS waits 0 RW-shared spins 5, rounds 150, OS waits 5 RW-excl spins 0, rounds 0, OS waits 0 Spin rounds per wait: 30.00 mutex, 30.00 RW-shared, 0.00 RW-excl ------------------------ LATEST FOREIGN KEY ERROR ------------------------ 150513 9:22:01 Error in foreign key constraint of table inventori/pengadaan: FOREIGN KEY (`approval_id`) REFERENCES `inventori`.`user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB: Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. Note that the internal storage type of ENUM and SET changed in tables created with >= InnoDB-4.1.12, and such columns in old tables cannot be referenced by such columns in new tables. See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html for correct foreign key definition. ------------ TRANSACTIONS ------------ Trx id counter D7B48 Purge done for trx's n:o < D7B47 undo n:o < 0 History list length 1551 LIST OF TRANSACTIONS FOR EACH SESSION: ---TRANSACTION 0, not started MySQL thread id 34, OS thread handle 0x19e0, query id 709 localhost 127.0.0.1 root show engine innodb status ---TRANSACTION D7B05, not started MySQL thread id 8, OS thread handle 0x1b4c, query id 676 localhost 127.0.0.1 root ---TRANSACTION 0, not started MySQL thread id 7, OS thread handle 0x18d4, query id 677 localhost 127.0.0.1 root -------- FILE I/O -------- I/O thread 0 state: wait Windows aio (insert buffer thread) I/O thread 1 state: wait Windows aio (log thread) I/O thread 2 state: wait Windows aio (read thread) I/O thread 3 state: wait Windows aio (read thread) I/O thread 4 state: wait Windows aio (read thread) I/O thread 5 state: wait Windows aio (read thread) I/O thread 6 state: wait Windows aio (write thread) I/O thread 7 state: wait Windows aio (write thread) I/O thread 8 state: wait Windows aio (write thread) I/O thread 9 state: wait Windows aio (write thread) Pending normal aio reads: 0 [0, 0, 0, 0] , aio writes: 0 [0, 0, 0, 0] , ibuf aio reads: 0, log i/o's: 0, sync i/o's: 0 Pending flushes (fsync) log: 0; buffer pool: 0 693 OS file reads, 219 OS file writes, 46 OS fsyncs 0.00 reads/s, 0 avg bytes/read, 0.00 writes/s, 0.00 fsyncs/s ------------------------------------- INSERT BUFFER AND ADAPTIVE HASH INDEX ------------------------------------- Ibuf: size 1, free list len 0, seg size 2, 0 merges merged operations: insert 0, delete mark 0, delete 0 discarded operations: insert 0, delete mark 0, delete 0 Hash table size 69257, node heap has 2 buffer(s) 0.00 hash searches/s, 0.00 non-hash searches/s --- LOG --- Log sequence number 672691005 Log flushed up to 672691005 Last checkpoint at 672691005 0 pending log writes, 0 pending chkp writes 41 log i/o's done, 0.00 log i/o's/second ---------------------- BUFFER POOL AND MEMORY ---------------------- Total memory allocated 17006592; in additional pool allocated 0 Dictionary memory allocated 402804 Buffer pool size 1024 Free buffers 327 Database pages 695 Old database pages 273 Modified db pages 0 Pending reads 0 Pending writes: LRU 0, flush list 0, single page 0 Pages made young 0, not young 0 0.00 youngs/s, 0.00 non-youngs/s Pages read 682, created 13, written 177 0.00 reads/s, 0.00 creates/s, 0.00 writes/s No buffer pool page gets since the last printout Pages read ahead 0.00/s, evicted without access 0.00/s, Random read ahead 0.00/s LRU len: 695, unzip_LRU len: 0 I/O sum[0]:cur[0], unzip sum[0]:cur[0] -------------- ROW OPERATIONS -------------- 0 queries inside InnoDB, 0 queries in queue 1 read views open inside InnoDB Main thread id 3340, state: waiting for server activity Number of rows inserted 2, updated 0, deleted 0, read 21 0.00 inserts/s, 0.00 updates/s, 0.00 deletes/s, 0.00 reads/s ---------------------------- END OF INNODB MONITOR OUTPUT ============================

Sekian post kali ini... Kritik saran silahkan berkomentar :D