I have a code not very professional but it does what i want :). The code is basically doing if shop open count for how long if closed count how long left form opening. Now i wanted to style it with jQuery Countdown but i cant find any to just count hours,minutes, maybe seconds. I was trying UNIX countdowns but dunno what i`m doing wrong. I would like to ask you fellow citizens of Stackoverflow to help me out with this.
This is my code ( Just don`t be haters :) )
date_default_timezone_set('Greenwich'); //Fixes my server location
$openingtime = strtotime('06:00'); //Opening time
$closingtime = strtotime('23:10'); //Closing time
$timenow = strtotime('now'); //Current Server Time
$twentyfourhours = "24:00"; //Hours in a day
//echo date('G:i', $openingtime); //Just texting
//echo date('G:i', $closingtime);
//echo date('H:i', $timenow);
//echo $twentyfourhours;// Testing ends here
$openingin = $twentyfourhours - $timenow + $openingtime; //24:00 - 23:20 + 6:00 = How long left for opening
$closingdown = $closingtime - $timenow; //23:10 - 23:20 How long left to close
//If current time value is bigger then closing time then display when the shop will re-open again
if (date('H:i', $timenow) > date('H:i', $closingtime))
{
echo "The shop will be open in ".date('H:i', $openingin)." hours";
}
//If current time value is lower then closing time then display how long the shop will stay open
elseif (date('H:i', $timenow) < date('H:i', $closingtime))
{
echo "The shop will be open for ".date('H:i', $closingdown)." hours";
}
Ok i have managed to found one but now if you will go to My Testing Ground You will notice that the seconds instead of starting countdown from 60 they start from 00,99,98,97,97 and all the way down :( dunno why its happening im attaching JS code
var flipCounter = function(d, options){
// Default values
var defaults = {
value: 0,
inc: 1,
pace: 1000,
auto: true,
tFH: 39,
bFH: 64,
fW: 53,
bOffset: 390
};
var o = options || {},
doc = window.document,
divId = typeof d !== 'undefined' && d !== '' ? d : 'flip-counter',
div = doc.getElementById(divId);
for (var opt in defaults) o[opt] = (opt in o) ? o[opt] : defaults[opt];
var digitsOld = [], digitsNew = [], subStart, subEnd, x, y, nextCount = null, newDigit, newComma,
best = {
q: null,
pace: 0,
inc: 0
};
/**
* Sets the value of the counter and animates the digits to new value.
*
* Example: myCounter.setValue(500); would set the value of the counter to 500,
* no matter what value it was previously.
*
* #param {int} n
* New counter value
*/
this.setValue = function(n){
if (isNumber(n)){
x = o.value;
y = n;
o.value = n;
digitCheck(x,y);
}
return this;
};
/**
* Sets the increment for the counter. Does NOT animate digits.
*/
this.setIncrement = function(n){
o.inc = isNumber(n) ? n : defaults.inc;
return this;
};
/**
* Sets the pace of the counter. Only affects counter when auto == true.
*
* #param {int} n
* New pace for counter in milliseconds
*/
this.setPace = function(n){
o.pace = isNumber(n) ? n : defaults.pace;
return this;
};
/**
* Sets counter to auto-incrememnt (true) or not (false).
*
* #param {bool} a
* Should counter auto-increment, true or false
*/
this.setAuto = function(a){
if (a && ! o.atuo){
o.auto = true;
doCount();
}
if (! a && o.auto){
if (nextCount) clearNext();
o.auto = false;
}
return this;
};
/**
* Increments counter by one animation based on set 'inc' value.
*/
this.step = function(){
if (! o.auto) doCount();
return this;
};
/**
* Adds a number to the counter value, not affecting the 'inc' or 'pace' of the counter.
*
* #param {int} n
* Number to add to counter value
*/
this.add = function(n){
if (isNumber(n)){
x = o.value;
o.value += n;
y = o.value;
digitCheck(x,y);
}
return this;
};
/**
* Subtracts a number from the counter value, not affecting the 'inc' or 'pace' of the counter.
*
* #param {int} n
* Number to subtract from counter value
*/
this.subtract = function(n){
if (isNumber(n)){
x = o.value;
o.value -= n;
if (o.value >= 0){
y = o.value;
}
else{
y = "0";
o.value = 0;
}
digitCheck(x,y);
}
return this;
};
/**
* Increments counter to given value, animating by current pace and increment.
*
* #param {int} n
* Number to increment to
* #param {int} t (optional)
* Time duration in seconds - makes increment a 'smart' increment
* #param {int} p (optional)
* Desired pace for counter if 'smart' increment
*/
this.incrementTo = function(n, t, p){
if (nextCount) clearNext();
// Smart increment
if (typeof t != 'undefined'){
var time = isNumber(t) ? t * 1000 : 10000,
pace = typeof p != 'undefined' && isNumber(p) ? p : o.pace,
diff = typeof n != 'undefined' && isNumber(n) ? n - o.value : 0,
cycles, inc, check, i = 0;
best.q = null;
// Initial best guess
pace = (time / diff > pace) ? Math.round((time / diff) / 10) * 10 : pace;
cycles = Math.floor(time / pace);
inc = Math.floor(diff / cycles);
check = checkSmartValues(diff, cycles, inc, pace, time);
if (diff > 0){
while (check.result === false && i < 100){
pace += 10;
cycles = Math.floor(time / pace);
inc = Math.floor(diff / cycles);
check = checkSmartValues(diff, cycles, inc, pace, time);
i++;
}
if (i == 100){
// Could not find optimal settings, use best found so far
o.inc = best.inc;
o.pace = best.pace;
}
else{
// Optimal settings found, use those
o.inc = inc;
o.pace = pace;
}
doIncrement(n, true, cycles);
}
}
// Regular increment
else{
doIncrement(n);
}
}
/**
* Gets current value of counter.
*/
this.getValue = function(){
return o.value;
}
/**
* Stops all running increments.
*/
this.stop = function(){
if (nextCount) clearNext();
return this;
}
//---------------------------------------------------------------------------//
function doCount(){
x = o.value;
o.value += o.inc;
y = o.value;
digitCheck(x,y);
if (o.auto === true) nextCount = setTimeout(doCount, o.pace);
}
function doIncrement(n, s, c){
var val = o.value,
smart = (typeof s == 'undefined') ? false : s,
cycles = (typeof c == 'undefined') ? 1 : c;
if (smart === true) cycles--;
if (val != n){
x = o.value,
o.auto = true;
if (val + o.inc <= n && cycles != 0) val += o.inc
else val = n;
o.value = val;
y = o.value;
digitCheck(x,y);
nextCount = setTimeout(function(){doIncrement(n, smart, cycles)}, o.pace);
}
else o.auto = false;
}
function digitCheck(x,y){
digitsOld = splitToArray(x);
digitsNew = splitToArray(y);
var diff,
xlen = digitsOld.length,
ylen = digitsNew.length;
if (ylen > xlen){
diff = ylen - xlen;
while (diff > 0){
addDigit(ylen - diff + 1, digitsNew[ylen - diff]);
diff--;
}
}
if (ylen < xlen){
diff = xlen - ylen;
while (diff > 0){
removeDigit(xlen - diff);
diff--;
}
}
for (var i = 0; i < xlen; i++){
if (digitsNew[i] != digitsOld[i]){
animateDigit(i, digitsOld[i], digitsNew[i]);
}
}
}
function animateDigit(n, oldDigit, newDigit){
var speed, step = 0, w, a,
bp = [
'-' + o.fW + 'px -' + (oldDigit * o.tFH) + 'px',
(o.fW * -2) + 'px -' + (oldDigit * o.tFH) + 'px',
'0 -' + (newDigit * o.tFH) + 'px',
'-' + o.fW + 'px -' + (oldDigit * o.bFH + o.bOffset) + 'px',
(o.fW * -2) + 'px -' + (newDigit * o.bFH + o.bOffset) + 'px',
(o.fW * -3) + 'px -' + (newDigit * o.bFH + o.bOffset) + 'px',
'0 -' + (newDigit * o.bFH + o.bOffset) + 'px'
];
if (o.auto === true && o.pace <= 300){
switch (n){
case 0:
speed = o.pace/6;
break;
case 1:
speed = o.pace/5;
break;
case 2:
speed = o.pace/4;
break;
case 3:
speed = o.pace/3;
break;
default:
speed = o.pace/1.5;
break;
}
}
else{
speed = 80;
}
// Cap on slowest animation can go
speed = (speed > 80) ? 80 : speed;
function animate(){
if (step < 7){
w = step < 3 ? 't' : 'b';
a = doc.getElementById(divId + "_" + w + "_d" + n);
if (a) a.style.backgroundPosition = bp[step];
step++;
if (step != 3) setTimeout(animate, speed);
else animate();
}
}
animate();
}
// Creates array of digits for easier manipulation
function splitToArray(input){
return input.toString().split("").reverse();
}
// Adds new digit
function addDigit(len, digit){
var li = Number(len) - 1;
newDigit = doc.createElement("ul");
newDigit.className = 'cd';
newDigit.id = divId + '_d' + li;
newDigit.innerHTML = '<li class="t" id="' + divId + '_t_d' + li + '"></li><li class="b" id="' + divId + '_b_d' + li + '"></li>';
if (li % 2 == 0){
newComma = doc.createElement("ul");
newComma.className = 'cd';
newComma.innerHTML = '<li class="s"></li>';
div.insertBefore(newComma, div.firstChild);
}
div.insertBefore(newDigit, div.firstChild);
doc.getElementById(divId + "_t_d" + li).style.backgroundPosition = '0 -' + (digit * o.tFH) + 'px';
doc.getElementById(divId + "_b_d" + li).style.backgroundPosition = '0 -' + (digit * o.bFH + o.bOffset) + 'px';
}
// Removes digit
function removeDigit(id){
var remove = doc.getElementById(divId + "_d" + id);
div.removeChild(remove);
// Check for leading comma
var first = div.firstChild.firstChild;
if ((" " + first.className + " ").indexOf(" s ") > -1 ){
remove = first.parentNode;
div.removeChild(remove);
}
}
// Sets the correct digits on load
function initialDigitCheck(init){
// Creates the right number of digits
var initial = init.toString(),
count = initial.length,
bit = 1, i;
for (i = 0; i < count; i++){
newDigit = doc.createElement("ul");
newDigit.className = 'cd';
newDigit.id = divId + '_d' + i;
newDigit.innerHTML = newDigit.innerHTML = '<li class="t" id="' + divId + '_t_d' + i + '"></li><li class="b" id="' + divId + '_b_d' + i + '"></li>';
div.insertBefore(newDigit, div.firstChild);
if (bit != (count) && bit % 2 == 0){
newComma = doc.createElement("ul");
newComma.className = 'cd';
newComma.innerHTML = '<li class="s"></li>';
div.insertBefore(newComma, div.firstChild);
}
bit++;
}
// Sets them to the right number
var digits = splitToArray(initial);
for (i = 0; i < count; i++){
doc.getElementById(divId + "_t_d" + i).style.backgroundPosition = '0 -' + (digits[i] * o.tFH) + 'px';
doc.getElementById(divId + "_b_d" + i).style.backgroundPosition = '0 -' + (digits[i] * o.bFH + o.bOffset) + 'px';
}
// Do first animation
if (o.auto === true) nextCount = setTimeout(doCount, o.pace);
}
// Checks values for smart increment and creates debug text
function checkSmartValues(diff, cycles, inc, pace, time){
var r = {result: true}, q;
// Test conditions, all must pass to continue:
// 1: Unrounded inc value needs to be at least 1
r.cond1 = (diff / cycles >= 1) ? true : false;
// 2: Don't want to overshoot the target number
r.cond2 = (cycles * inc <= diff) ? true : false;
// 3: Want to be within 10 of the target number
r.cond3 = (Math.abs(cycles * inc - diff) <= 10) ? true : false;
// 4: Total time should be within 100ms of target time.
r.cond4 = (Math.abs(cycles * pace - time) <= 100) ? true : false;
// 5: Calculated time should not be over target time
r.cond5 = (cycles * pace <= time) ? true : false;
// Keep track of 'good enough' values in case can't find best one within 100 loops
if (r.cond1 && r.cond2 && r.cond4 && r.cond5){
q = Math.abs(diff - (cycles * inc)) + Math.abs(cycles * pace - time);
if (best.q === null) best.q = q;
if (q <= best.q){
best.pace = pace;
best.inc = inc;
}
}
for (var i = 1; i <= 5; i++){
if (r['cond' + i] === false){
r.result = false;
}
}
return r;
}
// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/1830844
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function clearNext(){
clearTimeout(nextCount);
nextCount = null;
}
// Start it up
initialDigitCheck(o.value);
};`
Related
I would like to compare to set of text and get how similar/relevant they are to each other, I use similar_text(), but i found out its not as accurate. Thank you.
For example the following text gives me 66%
Text1: Innovation game, eat, sleep, breathe innovation. It love creativity & passion power Internet drives . We understand time greatest asset, challege meet deadline.
Text2: Soviet union communist policy; Germany league organization disguise enermies beaten wanted.
My code is as below:
echo $student_answer = removeCommonWords($answer)."<br><br>";
$student_answer = strip_tags($student_answer);
echo $memo = removeCommonWords2($memo)."<br><br>";
echo similar_text($memo, $student_answer);
You can use the JS version:
http://phpjs.org/functions/similar_text/
The JS code shows you the precent code (you can modify the code):
return (sum * 200) / (firstLength + secondLength);
I hope this will help you!
EDIT:
How to use similar_text in JS?
Create a file named similar_text.js and copy&paste this code in it:
function similar_text (first, second, percent) {
// http://kevin.vanzonneveld.net
// + original by: RafaĆ Kukawski (http://blog.kukawski.pl)
// + bugfixed by: Chris McMacken
// + added percent parameter by: Markus Padourek (taken from http://www.kevinhq.com/2012/06/php-similartext-function-in-javascript_16.html)
// * example 1: similar_text('Hello World!', 'Hello phpjs!');
// * returns 1: 7
// * example 2: similar_text('Hello World!', null);
// * returns 2: 0
// * example 3: similar_text('Hello World!', null, 1);
// * returns 3: 58.33
if (first === null || second === null || typeof first === 'undefined' || typeof second === 'undefined') {
return 0;
}
first += '';
second += '';
var pos1 = 0,
pos2 = 0,
max = 0,
firstLength = first.length,
secondLength = second.length,
p, q, l, sum;
max = 0;
for (p = 0; p < firstLength; p++) {
for (q = 0; q < secondLength; q++) {
for (l = 0;
(p + l < firstLength) && (q + l < secondLength) && (first.charAt(p + l) === second.charAt(q + l)); l++);
if (l > max) {
max = l;
pos1 = p;
pos2 = q;
}
}
}
sum = max;
if (sum) {
if (pos1 && pos2) {
sum += this.similar_text(first.substr(0, pos2), second.substr(0, pos2));
}
if ((pos1 + max < firstLength) && (pos2 + max < secondLength)) {
sum += this.similar_text(first.substr(pos1 + max, firstLength - pos1 - max), second.substr(pos2 + max, secondLength - pos2 - max));
}
}
if (!percent) {
return sum;
} else {
return (sum * 200) / (firstLength + secondLength);
}
}
In your put the following line:
<script type="text/JavaScript" src="YOUR_PATH/similar_text.js"></script>
Now you can use it in your body:
<script>
similar_text('Hello World!', 'Hello phpjs!');
</script>
It will output 7.
Hope this wil help you!
i have here a sample computation, what i want to know is how can it be a money format output.
for example 1000+ 1000 =2000
i want to output it as 2,000.
also , when typing the value , i want it automatically look a money format.
<html>
<head>
</head>
<body>
<form name="haha" method="post" >
1:<input type="text" name="num1">
2:<input type="text" name="num2">
Total:<input type="label" name="total">
<input type="submit" value="add" name="submit">
</html>
</form>
<?
if (isset($_POST['submit']))
{
$num1=$_POST['num1'];
$num2=$_POST['num2'];
$total=$_POST['total'];
$total= $num1 + $num2;
echo $total;
}
?>
Try number_format
$english_format_number = number_format(floatval($total));
echo $english_format_number;
I'm assuming you're looking for number_format or its more advanced brother money_format. This will take care of the server-side for you.
As for the client-side, I would advise against making things change while the user's typing. Just let them type in the number how they want. Bonus points if you allow them to type in thousand separators (since you can just strip them out easily in PHP to get the number itself).
You need to use javascript for that, when user change the input value you need to call the function to format the value.
You have to something like this:
$("[name^='num']").change(function(){
var value = $(this).val();
$(this).val(money_format(format, value));
});
Here is the function for monet format :
Ref: https://github.com/kvz/phpjs/blob/master/functions/strings/money_format.js
function money_format (format, number) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brett-zamir.me)
// + input by: daniel airton wermann (http://wermann.com.br)
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// - depends on: setlocale
// % note 1: This depends on setlocale having the appropriate locale (these examples use 'en_US')
// * example 1: money_format('%i', 1234.56);
// * returns 1: 'USD 1,234.56'
// * example 2: money_format('%14#8.2n', 1234.5678);
// * returns 2: ' $ 1,234.57'
// * example 3: money_format('%14#8.2n', -1234.5678);
// * returns 3: '-$ 1,234.57'
// * example 4: money_format('%(14#8.2n', 1234.5678);
// * returns 4: ' $ 1,234.57 '
// * example 5: money_format('%(14#8.2n', -1234.5678);
// * returns 5: '($ 1,234.57)'
// * example 6: money_format('%=014#8.2n', 1234.5678);
// * returns 6: ' $000001,234.57'
// * example 7: money_format('%=014#8.2n', -1234.5678);
// * returns 7: '-$000001,234.57'
// * example 8: money_format('%=*14#8.2n', 1234.5678);
// * returns 8: ' $*****1,234.57'
// * example 9: money_format('%=*14#8.2n', -1234.5678);
// * returns 9: '-$*****1,234.57'
// * example 10: money_format('%=*^14#8.2n', 1234.5678);
// * returns 10: ' $****1234.57'
// * example 11: money_format('%=*^14#8.2n', -1234.5678);
// * returns 11: ' -$****1234.57'
// * example 12: money_format('%=*!14#8.2n', 1234.5678);
// * returns 12: ' *****1,234.57'
// * example 13: money_format('%=*!14#8.2n', -1234.5678);
// * returns 13: '-*****1,234.57'
// * example 14: money_format('%i', 3590);
// * returns 14: ' USD 3,590.00'
// Per PHP behavior, there seems to be no extra padding for sign when there is a positive number, though my
// understanding of the description is that there should be padding; need to revisit examples
// Helpful info at http://ftp.gnu.org/pub/pub/old-gnu/Manuals/glibc-2.2.3/html_chapter/libc_7.html and http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.bpxbd00/strfmp.htm
if (typeof number !== 'number') {
return null;
}
var regex = /%((=.|[+^(!-])*?)(\d*?)(#(\d+))?(\.(\d+))?([in%])/g; // 1: flags, 3: width, 5: left, 7: right, 8: conversion
this.setlocale('LC_ALL', 0); // Ensure the locale data we need is set up
var monetary = this.php_js.locales[this.php_js.localeCategories['LC_MONETARY']]['LC_MONETARY'];
var doReplace = function (n0, flags, n2, width, n4, left, n6, right, conversion) {
var value = '',
repl = '';
if (conversion === '%') { // Percent does not seem to be allowed with intervening content
return '%';
}
var fill = flags && (/=./).test(flags) ? flags.match(/=(.)/)[1] : ' '; // flag: =f (numeric fill)
var showCurrSymbol = !flags || flags.indexOf('!') === -1; // flag: ! (suppress currency symbol)
width = parseInt(width, 10) || 0; // field width: w (minimum field width)
var neg = number < 0;
number = number + ''; // Convert to string
number = neg ? number.slice(1) : number; // We don't want negative symbol represented here yet
var decpos = number.indexOf('.');
var integer = decpos !== -1 ? number.slice(0, decpos) : number; // Get integer portion
var fraction = decpos !== -1 ? number.slice(decpos + 1) : ''; // Get decimal portion
var _str_splice = function (integerStr, idx, thous_sep) {
var integerArr = integerStr.split('');
integerArr.splice(idx, 0, thous_sep);
return integerArr.join('');
};
var init_lgth = integer.length;
left = parseInt(left, 10);
var filler = init_lgth < left;
if (filler) {
var fillnum = left - init_lgth;
integer = new Array(fillnum + 1).join(fill) + integer;
}
if (flags.indexOf('^') === -1) { // flag: ^ (disable grouping characters (of locale))
// use grouping characters
var thous_sep = monetary.mon_thousands_sep; // ','
var mon_grouping = monetary.mon_grouping; // [3] (every 3 digits in U.S.A. locale)
if (mon_grouping[0] < integer.length) {
for (var i = 0, idx = integer.length; i < mon_grouping.length; i++) {
idx -= mon_grouping[i]; // e.g., 3
if (idx <= 0) {
break;
}
if (filler && idx < fillnum) {
thous_sep = fill;
}
integer = _str_splice(integer, idx, thous_sep);
}
}
if (mon_grouping[i - 1] > 0) { // Repeating last grouping (may only be one) until highest portion of integer reached
while (idx > mon_grouping[i - 1]) {
idx -= mon_grouping[i - 1];
if (filler && idx < fillnum) {
thous_sep = fill;
}
integer = _str_splice(integer, idx, thous_sep);
}
}
}
// left, right
if (right === '0') { // No decimal or fractional digits
value = integer;
} else {
var dec_pt = monetary.mon_decimal_point; // '.'
if (right === '' || right === undefined) {
right = conversion === 'i' ? monetary.int_frac_digits : monetary.frac_digits;
}
right = parseInt(right, 10);
if (right === 0) { // Only remove fractional portion if explicitly set to zero digits
fraction = '';
dec_pt = '';
} else if (right < fraction.length) {
fraction = Math.round(parseFloat(fraction.slice(0, right) + '.' + fraction.substr(right, 1))) + '';
if (right > fraction.length) {
fraction = new Array(right - fraction.length + 1).join('0') + fraction; // prepend with 0's
}
} else if (right > fraction.length) {
fraction += new Array(right - fraction.length + 1).join('0'); // pad with 0's
}
value = integer + dec_pt + fraction;
}
var symbol = '';
if (showCurrSymbol) {
symbol = conversion === 'i' ? monetary.int_curr_symbol : monetary.currency_symbol; // 'i' vs. 'n' ('USD' vs. '$')
}
var sign_posn = neg ? monetary.n_sign_posn : monetary.p_sign_posn;
// 0: no space between curr. symbol and value
// 1: space sep. them unless symb. and sign are adjacent then space sep. them from value
// 2: space sep. sign and value unless symb. and sign are adjacent then space separates
var sep_by_space = neg ? monetary.n_sep_by_space : monetary.p_sep_by_space;
// p_cs_precedes, n_cs_precedes // positive currency symbol follows value = 0; precedes value = 1
var cs_precedes = neg ? monetary.n_cs_precedes : monetary.p_cs_precedes;
// Assemble symbol/value/sign and possible space as appropriate
if (flags.indexOf('(') !== -1) { // flag: parenth. for negative
// Fix: unclear on whether and how sep_by_space, sign_posn, or cs_precedes have
// an impact here (as they do below), but assuming for now behaves as sign_posn 0 as
// far as localized sep_by_space and sign_posn behavior
repl = (cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') : '') + value + (!cs_precedes ? (sep_by_space === 1 ? ' ' : '') + symbol : '');
if (neg) {
repl = '(' + repl + ')';
} else {
repl = ' ' + repl + ' ';
}
} else { // '+' is default
var pos_sign = monetary.positive_sign; // ''
var neg_sign = monetary.negative_sign; // '-'
var sign = neg ? (neg_sign) : (pos_sign);
var otherSign = neg ? (pos_sign) : (neg_sign);
var signPadding = '';
if (sign_posn) { // has a sign
signPadding = new Array(otherSign.length - sign.length + 1).join(' ');
}
var valueAndCS = '';
switch (sign_posn) {
// 0: parentheses surround value and curr. symbol;
// 1: sign precedes them;
// 2: sign follows them;
// 3: sign immed. precedes curr. symbol; (but may be space between)
// 4: sign immed. succeeds curr. symbol; (but may be space between)
case 0:
valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol;
repl = '(' + valueAndCS + ')';
break;
case 1:
valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol;
repl = signPadding + sign + (sep_by_space === 2 ? ' ' : '') + valueAndCS;
break;
case 2:
valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol;
repl = valueAndCS + (sep_by_space === 2 ? ' ' : '') + sign + signPadding;
break;
case 3:
repl = cs_precedes ? signPadding + sign + (sep_by_space === 2 ? ' ' : '') + symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + sign + signPadding + (sep_by_space === 2 ? ' ' : '') + symbol;
break;
case 4:
repl = cs_precedes ? symbol + (sep_by_space === 2 ? ' ' : '') + signPadding + sign + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol + (sep_by_space === 2 ? ' ' : '') + sign + signPadding;
break;
}
}
var padding = width - repl.length;
if (padding > 0) {
padding = new Array(padding + 1).join(' ');
// Fix: How does p_sep_by_space affect the count if there is a space? Included in count presumably?
if (flags.indexOf('-') !== -1) { // left-justified (pad to right)
repl += padding;
} else { // right-justified (pad to left)
repl = padding + repl;
}
}
return repl;
};
return format.replace(regex, doReplace);
}
I'm new to Javascript, I got this Javascript timer from the net. I'm trying to stop the timer and insert the stopped time into the database if a certain PHP variable is set, but I'm not sure how to stop the timer. Here's the code. I saw this post and sadly, I still can't get it to work. How to stop a timer function from running?
Thanks!
<script type="text/javascript">
/**********************************************************************************************
* CountUp script by Praveen Lobo (http://PraveenLobo.com/techblog/javascript-countup-timer/)
* This notice MUST stay intact(in both JS file and SCRIPT tag) for legal use.
* http://praveenlobo.com/blog/disclaimer/
**********************************************************************************************/
function CountUp(initDate, id){
this.beginDate = new Date(initDate);
this.countainer = document.getElementById(id);
this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
this.hours = 0, this.minutes = 0, this.seconds = 0;
this.updateNumOfDays();
this.updateCounter();
}
CountUp.prototype.updateNumOfDays=function(){
var dateNow = new Date();
var currYear = dateNow.getFullYear();
if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
this.numOfDays[1] = 29;
}
var self = this;
setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
}
CountUp.prototype.datePartDiff=function(then, now, MAX){
var diff = now - then - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
CountUp.prototype.calculate=function(){
var currDate = new Date();
var prevDate = this.beginDate;
this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
CountUp.prototype.addLeadingZero=function(value){
return value < 10 ? ("0" + value) : value;
}
CountUp.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
CountUp.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML =
" <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? ":" : ":") + "</small>" +
" <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? ":" : ":") + "</small>" +
" <strong>" + this.seconds + "</strong> <small>" + "</small>";
var self = this;
setTimeout(function(){self.updateCounter();}, 1000);
}
<?php if(isset($results['calltime'])) {$timevar= date("M d, Y H:i:s",strtotime($results['calltime']));}?>
window.onload=function(){ new CountUp('<?php echo $timevar; ?>', 'counter'); }
//I need a function to stop timer if (isset($results['firstcall_time']))
</script>
In your method updateCounter() You have following statement
setTimeout(function(){self.updateCounter();}, 1000);
make it like following first.
myTimer = setTimeout(function(){self.updateCounter();}, 1000);
and then whenever you want to stop the timer call this method.
clearTimeout(myTimer);
and then record the time.
It uses setTimeout for counting so you have to use clearTimeout for stopping the contdown.
reffer Clear Timeout
Cheers
In the lines:
setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
And
setTimeout(function(){self.updateCounter();}, 1000);
You can see the recursion is being used, thus the timer keeps running.
So when you want to stop the timer do SOMETHING like this:
var flag = true;
<?php if (isset($results['firstcall_time'])){ ?>
flag = false;
<?php } ?>
And modify your script a little bit as:
setTimeout(function(){if(flag){self.updateNumOfDays();}else{//write code to cleartimeout}}, (new Date((currYear+1), 1, 2) - dateNow));//check for the flag before recursion
And
setTimeout(function(){if(flag){self.updateCounter();}}else{//write code to cleartimeout}, 1000);
He isn't using a timer. He is using setTimeout, but the executing function, is the same method, sort-of like recursion (but strictly speaking, it isn't). So, it's on going. Hope this makes sense.
A timer is implemented like:
// Start
var timerId = setInterval(func() {
// your code to execute
}, 5000);
// Stop
clearInterval(timerId);
I've added a stop method to CountUp. So you should now be able to do this:
// Start
var counter = new CountUp(new Date(), 'div');
// Stop
counter.stop();
Here's the code. I've just hand coded in here, so if there are any typos or something doesn't work then post a comment.
function CountUp(initDate, id){
this.beginDate = new Date(initDate);
this.countainer = document.getElementById(id);
this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
this.hours = 0, this.minutes = 0, this.seconds = 0;
this.daysTimerId = setInterval(this.updateNumOfDays(), this.getDaysTimerInterval());
this.updateTimerId = setInterval(this.updateCounter(), 1000);
}
CountUp.prototype.stop=function(){
clearInterval(this.daysTimerId);
clearInterval(this.updateTimerId);
}
CountUp.prototype.getDaysTimerInterval=function(dt){
var dateNow = dt || new Date();
return (new Date((dateNow.getFullYear()+1), 1, 2) - dateNow));
}
CountUp.prototype.updateNumOfDays=function(){
var dateNow = new Date();
var currYear = dateNow.getFullYear();
if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
this.numOfDays[1] = 29;
}
// var self = this;
// setTimeout(function(){self.updateNumOfDays();}, self.getDaysTimerInterval(dateNow));
}
CountUp.prototype.datePartDiff=function(then, now, MAX){
var diff = now - then - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
CountUp.prototype.calculate=function(){
var currDate = new Date();
var prevDate = this.beginDate;
this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
CountUp.prototype.addLeadingZero=function(value){
return value < 10 ? ("0" + value) : value;
}
CountUp.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
CountUp.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML =
" <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? ":" : ":") + "</small>" +
" <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? ":" : ":") + "</small>" +
" <strong>" + this.seconds + "</strong> <small>" + "</small>";
// var self = this;
// setTimeout(function(){self.updateCounter();}, 1000);
}
Here is how I stopped the counter:
I inserted this few lines before "CountUp.prototype.updateCounter=function(){"
var today=new Date();
var start=new Date(2013,10,25,5,35,0); //example: Stop date
diff = start-today;
Then, inside updateCounter function, instead of directly call the setTimeout I added a condition:
if ( ( (this.seconds==0) && (this.minutes==0) (this.hours==0) && (this.days==0) ) || (diff <=0) ) { //on the fly (page is laready open with the counter running) or onload
//Time's up!
} else {
setTimeout(function(){self.updateCounter();}, 1000);
}
So the new code will look like this:
var today=new Date();
var start=new Date(2013,10,25,5,35,0);
diff = start-today;
Counter.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML = " <strong>" + this.seconds + "</strong> " + (this.seconds == 1? ":" : ":")+
" <strong>" + this.minutes + "</strong> " + (this.minutes == 1? ":" : ":")+
" <strong>" + this.hours + "</strong> " + (this.hours == 1? ":" : ":")+
" <strong>" + this.days + "</strong> " + (this.days == 1? ":" : "");
var self = this;
if ( ( (this.seconds==0) && (this.minutes==0) (this.hours==0) && (this.days==0) ) || (diff <=0) ) { //on the fly or onload
//Time's up!
} else {
setTimeout(function(){self.updateCounter();}, 1000);
}
}
Hope that will help.
Shams
I have multiple JavaScript functions to calculate mayan horoscope sign, which I converted to a single PHP class. Everything works well, except some dates. For example, the date 06.10.1977 gives me a NULL result using the PHP class, but this date in the equivalent JavaScript function returns a proper value. Maybe I've got something wrong in PHP so, can somebody check this up for me?
JAVASCRIPT:
function leap_gregorian(year) {
return ((year % 4) == 0) && (!(((year % 100) == 0) && ((year % 400) != 0)));
}
// GREGORIAN_TO_JD -- Determine Julian day number from Gregorian calendar date
var GREGORIAN_EPOCH = 1721425.5;
function gregorian_to_jd(year, month, day) {
return (GREGORIAN_EPOCH - 1) +
(365 * (year - 1)) +
Math.floor((year - 1) / 4) +
(-Math.floor((year - 1) / 100)) +
Math.floor((year - 1) / 400) +
Math.floor((((367 * month) - 362) / 12) +
((month <= 2) ? 0 : (leap_gregorian(year) ? -1 : -2)) +
day);
}
var MAYAN_COUNT_EPOCH = 584282.5;
// JD_TO_MAYAN_COUNT -- Calculate Mayan long count from Julian day
function jd_to_mayan_count(jd) {
var d, baktun, katun, tun, uinal, kin;
jd = Math.floor(jd) + 0.5;
d = jd - MAYAN_COUNT_EPOCH;
baktun = Math.floor(d / 144000);
d = mod(d, 144000);
katun = Math.floor(d / 7200);
d = mod(d, 7200);
tun = Math.floor(d / 360);
d = mod(d, 360);
uinal = Math.floor(d / 20);
kin = mod(d, 20);
return new Array(baktun, katun, tun, uinal, kin);
}
// JD_TO_MAYAN_HAAB -- Determine Mayan Haab "month" and day from Julian day
var MAYAN_HAAB_MONTHS = new Array("Pop", "Uo", "Zip", "Zotz", "Tzec", "Xul",
"Yaxkin", "Mol", "Chen", "Yax", "Zac", "Ceh",
"Mac", "Kankin", "Muan", "Pax", "Kayab", "Cumku", "Uayeb");
function jd_to_mayan_haab(jd) {
var lcount, day;
jd = Math.floor(jd) + 0.5;
lcount = jd - MAYAN_COUNT_EPOCH;
day = mod(lcount + 8 + ((18 - 1) * 20), 365);
return new Array(Math.floor(day / 20) + 1, mod(day, 20));
}
// JD_TO_MAYAN_TZOLKIN -- Determine Mayan Tzolkin "month" and day from Julian day
var MAYAN_TZOLKIN_MONTHS = new Array("Imix", "Ik", "Akbal", "Kan", "Chicchan",
"Cimi", "Manik", "Lamat", "Muluc", "Oc",
"Chuen", "Eb", "Ben", "Ix", "Men",
"Cib", "Caban", "Etznab", "Cauac", "Ahau");
var MAYAN_TZOLKIN_MONTHS_EN = new Array("Crocodile", "Wind", "House", "Lizard", "Serpent",
"Death", "Deer", "Rabbit", "Water", "Dog",
"Monkey", "Grass", "Reed", "Jaguar", "Eagle",
"Vulture", "Earth", "Knife", "Storm", "Flower");
function jd_to_mayan_tzolkin(jd) {
var lcount;
jd = Math.floor(jd) + 0.5;
lcount = jd - MAYAN_COUNT_EPOCH;
return new Array(amod(lcount + 20, 20), amod(lcount + 4, 13));
}
function getMayanSign(sign, month, day, year) {
var isValidated = true;
var result = "";
if (!IsNumeric(month.value) || month.value <= 0 || month.value > 12) {
month.value = "MM";
isValidated = false;
}
if (!IsNumeric(day.value) || day.value <= 0 || day.value > 31) {
day.value = "DD";
isValidated = false;
}
if (!IsNumeric(year.value) || year.value < 1900 ) {
year.value = "YYYY";
isValidated = false;
}
if (isValidated) {
year = new Number(year.value);
mon = new Number(month.value);
mday = new Number(day.value);
hour = min = sec = 0;
// Update Julian day
j = gregorian_to_jd(year, mon + 0, mday) +
(Math.floor(sec + 60 * (min + 60 * hour) + 0.5) / 86400.0);
maytzolkincal = jd_to_mayan_tzolkin(j);
result = MAYAN_TZOLKIN_MONTHS_EN[maytzolkincal[0] - 1];
} else result = "INVALID BIRTHDAY";
sign.value = result;
}
PHP CLASS:
class MayanCalculator {
// JD_TO_MAYAN_TZOLKIN -- Determine Mayan Tzolkin "month" and day from Julian day
private $MAYAN_TZOLKIN_MONTHS = array("Imix", "Ik", "Akbal", "Kan", "Chicchan",
"Cimi", "Manik", "Lamat", "Muluc", "Oc",
"Chuen", "Eb", "Ben", "Ix", "Men",
"Cib", "Caban", "Etznab", "Cauac", "Ahau");
private $MAYAN_TZOLKIN_MONTHS_EN = array("Crocodile", "Wind", "House", "Lizard", "Serpent",
"Death", "Deer", "Rabbit", "Water", "Dog",
"Monkey", "Grass", "Reed", "Jaguar", "Eagle",
"Vulture", "Earth", "Knife", "Storm", "Flower");
private $GREGORIAN_EPOCH = 1721425.5;
private $MAYAN_COUNT_EPOCH = 584282.5;
private $MAYAN_HAAB_MONTHS = array("Pop", "Uo", "Zip", "Zotz", "Tzec", "Xul",
"Yaxkin", "Mol", "Chen", "Yax", "Zac", "Ceh",
"Mac", "Kankin", "Muan", "Pax", "Kayab", "Cumku", "Uayeb");
private $_day;
private $_month;
private $_year;
private $sign;
private $signm;
function __construct($day, $month, $year) {
$this->_day = $day;
$this->_month = $month;
$this->_year = $year;
}
public function getMayanSign() {
$this->sign = $this->getSign();
$this->signm = $this->getMayanSignOnMayan();
$ids = new getIDS(null,null,$this->sign);
$id = $ids->returnIDS();
return array("mayan_sign" => $this->sign, "mayan_sign_on_mayan" => $this->signm, "mayan_sign_id" => $id["mayan_id"]);
}
private function getSign() {
$isValidated = true;
$result = null;
if (!is_numeric($this->_month) || $this->_month <= 0 || $this->_month > 12) :
$isValidated = false;
endif;
if (!is_numeric($this->_day) || $this->_day <= 0 || $this->_day > 31) :
$isValidated = false;
endif;
if (!is_numeric($this->_year) || $this->_year < 1900) :
$isValidated = false;
endif;
if ($isValidated) :
$hour = 0;
$min = 0;
$sec = 0;
//update julian day
$j = $this->gregorian_to_jd($this->_year, $this->_month+0, $this->_day) + (floor($sec + 60 * ($min + 60 * $hour) + 0.5) / 86400.0);
$maytzolkincal = $this->jd_to_mayan_tzolkin($j);
$result = $this->MAYAN_TZOLKIN_MONTHS_EN[$maytzolkincal[0]-1];
else :
$result = 'Wrong date '. $this->_day . '.' . $this->_month . '.' . $this->_year;
endif;
return $result;
}
private function getMayanSignOnMayan() {
$isValidated = true;
$result = null;
if (!is_numeric($this->_month) || $this->_month <= 0 || $this->_month > 12) :
$isValidated = false;
endif;
if (!is_numeric($this->_day) || $this->_day <= 0 || $this->_day > 31) :
$isValidated = false;
endif;
if (!is_numeric($this->_year) || $this->_year < 1900) :
$isValidated = false;
endif;
if ($isValidated) :
$hour = 0;
$min = 0;
$sec = 0;
//update julian day
$j = $this->gregorian_to_jd($this->_year, $this->_month+0, $this->_day) + (floor($sec + 60 * ($min + 60 * $hour) + 0.5) / 86400);
$maytzolkincal = $this->jd_to_mayan_tzolkin($j);
$result = $this->MAYAN_TZOLKIN_MONTHS[$maytzolkincal[0]]-1;
else :
$result = 'Wrong date '. $this->_day . '.' . $this->_month . '.' . $this->_year;
endif;
return $result;
}
private function leap_gregorian($year) {
return (($year % 4) == 0) && (!((($year % 100) == 0) && (($year % 400) != 0)));
}
private function gregorian_to_jd($year, $month, $day) {
$result = ($this->GREGORIAN_EPOCH - 1) +
(365 * ($year - 1)) +
floor(($year - 1) / 4) +
(-floor(($year - 1) / 100)) +
floor(($year - 1) / 400) +
floor((((367 * $month) - 362) / 12) +
(($month <= 2) ? 0 : ($this->leap_gregorian($year) ? -1 : -2)) +
$day);
return $result;
}
private function jd_to_mayan_count($jd) {
$jd = floor($jd) + 0.5;
$d = $jd - $this->MAYAN_COUNT_EPOCH;
$baktun = floor($d / 144000);
$d = $d % 144000;
$katun = floor($d / 7200);
$d = $d % 7200;
$tun = floor($d / 360);
$d = $d % 360;
$uinal = floor($d / 20);
$kin = $d % 20;
return array($baktun, $katun, $tun, $uinal, $kin);
}
private function jd_to_mayan_haab($jd) {
$jd = floor($jd) + 0.5;
$lcount = $jd - $this->MAYAN_COUNT_EPOCH;
$day = ($lcount + 8 + ((18 - 1) * 20)) % 365;
return array(floor($day / 20) + 1, $day % 20);
}
private function jd_to_mayan_tzolkin($jd) {
$jd = floor($jd) + 0.5;
$lcount = $jd - $this->MAYAN_COUNT_EPOCH;
return array(($lcount + 20) % 20, ($lcount + 4) % 13);
}
}
First: Always post all relevant script. Yours was missing the JavaScript function amod() which is crucial to solving your problem, I found it in the original here
Your PHP function jd_to_mayan_tzolkin() ist different from your JavaScript function jd_to_mayan_tzolkin():
While JavaScript uses a separate function amod() to calculate the modulus and returns the numerator if the modulus-result is 0
// AMOD -- Modulus function which returns numerator if modulus is zero
function amod($a, $b) {
return $this->mod($a - 1, $b) + 1;
}
your php function just returns the modulus which can be 0 and therefore the further processing of your PHP fails.
Add the following two functions to your class:
/* MOD -- Modulus function which works for non-integers. */
private function mod($a, $b) {
return $a - ($b * floor($a / $b));
}
// AMOD -- Modulus function which returns numerator if modulus is zero
private function amod($a, $b) {
return $this->mod($a - 1, $b) + 1;
}
And change the PHP method jd_to_mayan_tzolkin() as follows:
private function jd_to_mayan_tzolkin($jd) {
$jd = floor($jd) + 0.5;
$lcount = $jd - $this->MAYAN_COUNT_EPOCH;
return array($this->amod(($lcount + 20),20), $this->amod(($lcount + 4),13));
}
I've been working on getting a Coefficient of Variation equation ported from PHP to Javascript, but can't seem to get it working.
Original PHP script:
// define variables, strip spaces
$weights = $_POST['weights'];
// define coefficient of variation function
function cv($array){
$n = 0;
$mean = 0;
$M2 = 0;
foreach($array as $x){
if ($x != NULL AND $x != '') {
$n++;
$delta = $x - $mean;
$mean = $mean + $delta/$n;
$M2 = $M2 + $delta*($x - $mean);
$total = $total + $x;
}
}
return (((sqrt($M2/($n - 1))) / ($total/$n))*100);
}
$cv = (cv($weights));
This basically takes an array, and figures out the coefficient of variation for it. Now as I try to convert it to Javascript via some Jquery function:
var fields = $('#cvform').serializeArray();
var count = 0;
var num = 0;
var mean = 0;
var m2 = 0;
var total = 0;
var delta = 0;
jQuery.each(fields, function(i, field){
if (field.value > 0) {
num++;
delta=(field.value-mean);
mean=(mean+delta/num);
m2=(m2+delta*(field.value-mean));
total=(total+field.value);
};
});
var cov=(((Math.sqrt(m2/(num-1)))/(total/num))*100);
$("<span>Coefficient of Variation: " + cov + "</span>").appendTo('#cvdisplay');
While the javascript function outputs an answer, it is not correct. If I enter the values "3,3,2,3,3,4" the PHP script gives an output of 21.08, which is correct. The javascript function gives me the value of 0.0011418432035849642.
Can anyone point me to where the equations are differing?
You need to convert your array values to floats via parseFloat() (or integers, parseInt(), whatever suits you):
var fields = $('#cvform').serializeArray();
var count = 0;
var num = 0;
var mean = 0;
var m2 = 0;
var total = 0;
var delta = 0;
$.each(fields, function(i, field) {
alert(field.value);
if (parseFloat(field.value) > 0) {
num++;
delta = (parseFloat(field.value) - mean);
mean = (mean + delta / num);
m2 = (m2 + delta * (parseFloat(field.value) - mean));
total = (total + parseFloat(field.value));
}
});
var cov = (((Math.sqrt(m2 / (num - 1))) / (total / num)) * 100);
$("<span>Coefficient of Variation: " + cov + "</span>").appendTo('#cvdisplay');
The issue is the javascript line
total=(total+field.value); which results in 0332334 instead of 18 as expected. String concatenation is being applied instead of numeric addition.
You can fix this by parsing the integer value: total += parseInt(field.value);
function stDeviation(array){
var L= array.length,
mean= array.reduce(function(a, b){
return a+b;
})/L,
dev= array.map(function(itm){
var tem= itm-mean;
return tem*tem;
});
return Math.sqrt(dev.reduce(function(a, b){
return a+b;
})/L);
}
Math.mean= function(array){
return array.reduce(function(a, b){ return a+b; })/array.length;
}
Math.stDeviation=function(array){
var mean= Math.mean(array);
dev= array.map(function(itm){return (itm-mean)*(itm-mean); });
return Math.sqrt(dev.reduce(function(a, b){ return a+b; })/array.length);
}
var A2= [6.2, 5, 4.5, 6, 6, 6.9, 6.4, 7.5];
alert ('mean: '+Math.mean(A2)+'; deviation: '+Math.stDeviation(A2))
Here, I changed the code around a bit and got it to work. I basically isolated the segments a bit more. Made it more direct.
<?php
$weights = Array(3,3,2,3,3,4);
// define coefficient of variation function
function cv($array) {
$n = 0;
$mean = 0;
$M2 = 0;
$total = 0;
foreach($array as $x) {
if ( !empty($x) ) {
$n++;
$delta = $x - $mean;
$mean = $mean + $delta / $n;
$M2 = $M2 + $delta * ($x - $mean);
$total = $total + $x;
}
}
$sqrt = sqrt( $M2 / ($n - 1) );
$tn = $total / $n;
echo "Sqrt is $sqrt tn is $tn";
return ( $sqrt / $tn ) * 100;
}
$cv = cv($weights);
?>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var fields = Array(3,3,2,3,3,4);
var count = 0;
var n = 0;
var mean = 0;
var m2 = 0;
var total = 0;
var delta = 0;
jQuery.each(fields, function(i, field) {
//var x = field.value;
var x = 1 * field;
if (x > 0) {
n++;
delta = (x - mean);
mean = (mean + (delta / n));
m2 = (m2 + delta * (x - mean));
total = (total + x);
};
});
var sqrt = Math.sqrt(m2 / (n - 1));
var tn = total / n;
var cov = ((sqrt / tn) * 100);
console.log("Total is: "+ total);
console.log("Sqrt is " + sqrt + " tn is " + tn + " cov is " + cov);
$('#js').text("JS Output is: " + cov);
});
</script>
</head>
<body>
<div>
<div>PHP Output: <?=$cv;?></div>
<div id="js"></div>
</div>
</body>
</html>
Here's a direct translation of the function you provided. You have to pass in a javascript array of numbers, and it produces the result you're looking for (at least according to unit tests written in Node.js). You should to the type conversion (string-to-array) in another function to separate your concerns and make the code easier to reason about;
var CoV = function(ary) {
var mean = 0,
n = 0,
m2 = 0,
total = 0,
delta;
for(var i = 0, l = ary.length; i < l; i += 1) {
n += 1;
delta = ary[i] - mean;
mean = mean + delta / n;
m2 = m2 + delta * (ary[i] - mean)
total = total + ary[i]
}
console.log(mean);
console.log(m2);
console.log(total);
return ((Math.sqrt(m2/(i - 1))) / (total / i)) * 100;
};