function oldTextual($steamid) { $result = 'Invalid input.'; if (!preg_match('([a-zA-Z])', $steamid) && strlen($steamid) === 17) { // 64-bit int $acc_id = bcsub($steamid, '76561197960265728'); $result = 'STEAM_0:'; if ($acc_id % 2 === 0) { $result .= '0:'; } else { $result .= '1:'; } $result .= bcdiv($acc_id, '2', 0); } if (substr($steamid, 0, 2) === "[U") { // New textual format str_replace("[", "", str_replace("]", "", $steamid)); $split = explode(':', $steamid); $result = 'STEAM_0:'; $z = (int) $split[2]; if ($z % 2 === 0) { $result .= '0:'; } else { $result .= '1:'; } $acc_id = bcdiv($z, '2', 0); $result .= $acc_id; } if (substr($steamid, 0, 6) === 'STEAM_') { $result = $steamid; } return $result; }
function GetAuthID($i64friendID) { $tmpfriendID = $i64friendID; $iServer = "1"; if (extension_loaded('bcmath') == 1) { //decode communityid with bcmath if (bcmod($i64friendID, "2") == "0") { $iServer = "0"; } $tmpfriendID = bcsub($tmpfriendID, $iServer); if (bccomp("76561197960265728", $tmpfriendID) == -1) { $tmpfriendID = bcsub($tmpfriendID, "76561197960265728"); } $tmpfriendID = bcdiv($tmpfriendID, "2"); return "STEAM_0:" . $iServer . ":" . $tmpfriendID; } else { if (extension_loaded('gmp') == 1) { //decode communityid with gmp if (gmp_mod($i64friendID, "2") == "0") { $iServer = "0"; } $tmpfriendID = gmp_sub($tmpfriendID, $iServer); if (gmp_cmp("76561197960265728", $tmpfriendID) == -1) { $tmpfriendID = gmp_sub($tmpfriendID, "76561197960265728"); } $tmpfriendID = gmp_div($tmpfriendID, "2"); return "STEAM_0:" . $iServer . ":" . gmp_strval($tmpfriendID); } } return false; }
function G($start = '', $end = '', $dec = 3) { if (empty($_GET['need_stat'])) { //return false; } static $_info = array(); if (is_float($end)) { $info[$start] = $end; } elseif (!empty($end)) { if (!isset($_info[$end])) { $_info[$end] = my_microtime_float($dec); } return number_format($_info[$end] - $_info[$start], $dec); } elseif (!empty($start)) { $_info[$start] = my_microtime_float($dec); } else { $temp = array(); $findFirst = true; foreach ($_info as $key => $value) { if ($findFirst) { $baseTime = $value; $lastTime = 0; $findFirst = false; } $currTime = bcsub($value, $baseTime, 3); $currCostTime = bcsub($currTime, $lastTime, 3); $lastTime = $currTime; $temp[$key] = $currTime . ' [' . $currCostTime . ']'; } return $temp; } }
function bcfact($fact, $scale = 100) { if ($fact == 1) { return 1; } return bcmul($fact, bcfact(bcsub($fact, '1'), $scale), $scale); }
/** * Handle the event. * * @param JournalSaved $event * * @return void */ public function handle(JournalSaved $event) { $journal = $event->journal; // get the event connected to this journal: /** @var PiggyBankEvent $event */ $event = PiggyBankEvent::where('transaction_journal_id', $journal->id)->first(); if (is_null($event)) { return; } $piggyBank = $event->piggyBank()->first(); $repetition = null; if ($piggyBank) { /** @var PiggyBankRepetition $repetition */ $repetition = $piggyBank->piggyBankRepetitions()->relevantOnDate($journal->date)->first(); } if (is_null($repetition)) { return; } bcscale(2); $amount = $journal->amount; $diff = bcsub($amount, $event->amount); // update current repetition $repetition->currentamount = bcadd($repetition->currentamount, $diff); $repetition->save(); $event->amount = $amount; $event->save(); }
function internal_to_numstr($num, $precision = -1, $round = true) { if ($precision == -1) { $precision = 8; $tidy = true; } else { $tidy = false; } if (!is_string($num) && !is_resource($num)) { throw new Error('Coding error!', "internal_to_numstr argument has type '" . gettype($num) . "'"); } $repr = gmp_strval($num); if ($round) { if ($repr > 0) { $repr = bcadd($repr, pow(10, 8 - $precision) / 2); } else { $repr = bcsub($repr, pow(10, 8 - $precision) / 2); } } $repr = bcdiv($repr, pow(10, 8), $precision); // now tidy output... if ($tidy) { return clean_sql_numstr($repr); } return sprintf("%.{$precision}f", $repr); }
function frame($row, $column, $levelinfo, $options) { $scaledtilesize = array(bcdiv(bcsub($options["framemax"][0], $options["framemin"][0]), $levelinfo["columns"]), bcdiv(bcsub($options["framemax"][1], $options["framemin"][1]), $levelinfo["rows"])); $ret["min"] = array(bcadd(bcmul($scaledtilesize[0], $column), $options["framemin"][0]), bcadd(bcmul($scaledtilesize[1], $row), $options["framemin"][1])); $ret["max"] = array(bcadd($ret["min"][0], $scaledtilesize[0]), bcadd($ret["min"][1], $scaledtilesize[1])); return $ret; }
function revalue($data, &$errors = array()) { if (empty($data['transaction_date'])) { $data['transaction_date'] = date(DATE_FORMAT); } $glperiod = GLPeriod::getPeriod(fix_date($data['transaction_date'])); if (!$glperiod || count($glperiod) == 0) { $errors[] = 'No period exists for this date'; return false; } $data['value'] = bcsub($this->glbalance(), $data['new_balance']); $data['glperiods_id'] = $glperiod['id']; $data['source'] = 'C'; $data['type'] = 'V'; $data['glaccount_id'] = $this->currency_detail->writeoff_glaccount_id; $data['glcentre_id'] = $this->currency_detail->glcentre_id; GLTransaction::setTwinCurrency($data); $gl_trans[] = GLTransaction::Factory($data, $errors); $data['value'] = bcmul($data['value'], -1); $data['glaccount_id'] = $this->glaccount_id; $data['glcentre_id'] = $this->glcentre_id; GLTransaction::setTwinCurrency($data); $gl_trans[] = GLTransaction::Factory($data, $errors); $db = DB::Instance(); $db->StartTrans(); if (count($errors) == 0 && GLTransaction::saveTransactions($gl_trans, $errors)) { return $db->CompleteTrans(); } $errors[] = 'Failed to save GL Transaction'; $db->FailTrans(); $db->CompleteTrans(); return false; }
function checkGlobeadmin($nuConfigDBHost, $nuConfigDBName, $nuConfigDBUser, $nuConfigDBPassword) { $login = false; $session_id = $_REQUEST['sessid']; $db = new PDO("mysql:host={$nuConfigDBHost};dbname={$nuConfigDBName};charset=utf8", $nuConfigDBUser, $nuConfigDBPassword, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $values = array($session_id, 'globeadmin'); $sql = "SELECT * FROM zzzsys_session WHERE zzzsys_session_id = ? AND sss_zzzsys_user_id = ?"; $obj = $db->prepare($sql); $obj->execute($values); $recordObj = $obj->fetch(PDO::FETCH_OBJ); $result = $obj->rowCount(); if ($result == 1) { $then = $recordObj->sss_timeout; $now = time(); $diff = bcsub($now, $then, 0); if ($diff < 1800) { $login = true; } } if (!$login) { setError("Not Logged in as globeadmin"); } unset($obj); unset($db); return $login; }
function fiat_and_btc_to_price($fiat, $btc, $round = 'round') { $fiat = gmp_strval($fiat); $btc = gmp_strval($btc); if (gmp_cmp($btc, "0") == 0) { return ""; } else { if ($round == 'round') { $price = bcdiv($fiat, $btc, PRICE_PRECISION + 1); return sprintf("%." . PRICE_PRECISION . "f", $price); } else { if ($round == 'down') { $price = bcdiv($fiat, $btc, PRICE_PRECISION); // echo "rounding $fiat / $btc = " . bcdiv($fiat, $btc, 8) . " down to $price<br/>\n"; return $price; } else { if ($round == 'up') { $raw = bcdiv($fiat, $btc, 8); $adjust = bcsub(bcdiv(1, pow(10, PRICE_PRECISION), 8), '0.00000001', 8); $price = bcadd($raw, $adjust, PRICE_PRECISION); // echo "rounding $fiat / $btc = $raw up to $price<br/>\n"; return $price; } else { throw new Error("Bad Argument", "fiat_and_btc_to_price() has round = '{$round}'"); } } } } }
/** * Replace bcpowmod() * * @category PHP * @package PHP_Compat * @license LGPL - http://www.gnu.org/licenses/lgpl.html * @copyright 2004-2007 Aidan Lister <*****@*****.**>, Arpad Ray <*****@*****.**> * @link http://php.net/function.bcpowmod * @author Sara Golemon <*****@*****.**> * @version $Revision: 1.1 $ * @since PHP 5.0.0 * @require PHP 4.0.0 (user_error) */ function php_compat_bcpowmod($x, $y, $modulus, $scale = 0) { // Sanity check if (!is_scalar($x)) { user_error('bcpowmod() expects parameter 1 to be string, ' . gettype($x) . ' given', E_USER_WARNING); return false; } if (!is_scalar($y)) { user_error('bcpowmod() expects parameter 2 to be string, ' . gettype($y) . ' given', E_USER_WARNING); return false; } if (!is_scalar($modulus)) { user_error('bcpowmod() expects parameter 3 to be string, ' . gettype($modulus) . ' given', E_USER_WARNING); return false; } if (!is_scalar($scale)) { user_error('bcpowmod() expects parameter 4 to be integer, ' . gettype($scale) . ' given', E_USER_WARNING); return false; } $t = '1'; while (bccomp($y, '0')) { if (bccomp(bcmod($y, '2'), '0')) { $t = bcmod(bcmul($t, $x), $modulus); $y = bcsub($y, '1'); } $x = bcmod(bcmul($x, $x), $modulus); $y = bcdiv($y, '2'); } return $t; }
public function getSteamID3() { $authserver = bcsub($this->steamID64, '76561197960265728') & 1; $authid = (bcsub($this->steamID64, '76561197960265728') - $authserver) / 2; $authid = 2 * intval($authid) + intval($authserver); return "U:1:{$authid}"; }
function bcinvert($a, $n) { // Sanity check if (!is_scalar($a)) { user_error('bcinvert() expects parameter 1 to be string, ' . gettype($a) . ' given', E_USER_WARNING); return false; } if (!is_scalar($n)) { user_error('bcinvert() expects parameter 2 to be string, ' . gettype($n) . ' given', E_USER_WARNING); return false; } $u1 = $v2 = '1'; $u2 = $v1 = '0'; $u3 = $n; $v3 = $a; while (bccomp($v3, '0')) { $q0 = bcdiv($u3, $v3); $t1 = bcsub($u1, bcmul($q0, $v1)); $t2 = bcsub($u2, bcmul($q0, $v2)); $t3 = bcsub($u3, bcmul($q0, $v3)); $u1 = $v1; $u2 = $v2; $u3 = $v3; $v1 = $t1; $v2 = $t2; $v3 = $t3; } if (bccomp($u2, '0') < 0) { return bcadd($u2, $n); } else { return bcmod($u2, $n); } }
/** * Handle the event. * * @param TransactionJournalUpdated $event * @SuppressWarnings(PHPMD.CyclomaticComplexity) // it's exactly 5. * * @return bool */ public function handle(TransactionJournalUpdated $event) : bool { $journal = $event->journal; if (!$journal->isTransfer()) { return true; } // get the event connected to this journal: /** @var PiggyBankEvent $event */ $event = PiggyBankEvent::where('transaction_journal_id', $journal->id)->first(); if (is_null($event)) { return false; } $piggyBank = $event->piggyBank()->first(); $repetition = null; if (!is_null($piggyBank)) { /** @var PiggyBankRepetition $repetition */ $repetition = $piggyBank->piggyBankRepetitions()->relevantOnDate($journal->date)->first(); } if (is_null($repetition)) { return false; } $amount = TransactionJournal::amount($journal); $diff = bcsub($amount, $event->amount); // update current repetition $repetition->currentamount = bcadd($repetition->currentamount, $diff); $repetition->save(); $event->amount = $amount; $event->save(); return true; }
/** * Returns profiling information. */ function get_profiling($group_name = 'default') { $i = 0; $total = 0; $result = array(); $markers = $this->group_markers[$group_name]; foreach ($markers as $marker => $index) { $time = $this->markers[$index]; if ($i == 0) { $diff = 0; } else { $temp = $this->markers[$index - 1]; if (extension_loaded('bcmath')) { $diff = bcsub($time, $temp, 6); $total = bcadd($total, $diff, 6); } else { $diff = $time - $temp; $total = $total + $diff; } } $result[$i]['name'] = $marker; $result[$i]['time'] = $time; $result[$i]['diff'] = $diff; $result[$i]['total'] = $total; $i++; } return $result; }
public function sub($decimal) { if (!$decimal instanceof Decimal) { $decimal = new Decimal($decimal); } return new Decimal(bcsub($this->amount, $decimal->getAmount(), self::$scale)); }
/** * Execute the console command. * * @return mixed */ public function handle() { $this->info('Downloading the full ROA cert list'); $roas = json_decode(file_get_contents($this->rpkiServer)); $ipv4AmountCidrArray = $this->ipUtils->IPv4cidrIpCount(); $ipv6AmountCidrArray = $this->ipUtils->IPv6cidrIpCount(); $mysqlTime = '"' . date('Y-m-d H:i:s') . '"'; $this->info('Creating the insert query'); DB::statement('DROP TABLE IF EXISTS roa_table_temp'); DB::statement('DROP TABLE IF EXISTS backup_roa_table'); DB::statement('CREATE TABLE roa_table_temp LIKE roa_table'); $roaInsert = ''; foreach ($roas->roas as $roa) { $roaParts = explode('/', $roa->prefix); $roaCidr = $roaParts[1]; $roaIP = $roaParts[0]; $roaAsn = str_ireplace('as', '', $roa->asn); $startDec = $this->ipUtils->ip2dec($roaIP); if ($this->ipUtils->getInputType($roaIP) == 4) { $ipAmount = $ipv4AmountCidrArray[$roaCidr]; } else { $ipAmount = $ipv6AmountCidrArray[$roaCidr]; } $endDec = bcsub(bcadd($startDec, $ipAmount), 1); $roaInsert .= '("' . $roaIP . '",' . $roaCidr . ',' . $startDec . ',' . $endDec . ',' . $roaAsn . ',' . $roa->maxLength . ',' . $mysqlTime . ',' . $mysqlTime . '),'; } $this->info('Processing the insert query'); $roaInsert = rtrim($roaInsert, ',') . ';'; DB::statement('INSERT INTO roa_table_temp (ip,cidr,ip_dec_start,ip_dec_end,asn,max_length,updated_at,created_at) VALUES ' . $roaInsert); $this->info('Hot Swapping the ROA list table'); DB::statement('RENAME TABLE roa_table TO backup_roa_table, roa_table_temp TO roa_table;'); DB::statement('DROP TABLE IF EXISTS backup_roa_table'); }
public function sortRentalPayment($data) { // Put into new array and order data by date, type $paymentData = array(); foreach ($data as $key => $val) { // Add data to new array $paymentData["id_{$key}"] = $val; // Generate a sortable date field if ($val['date_due'] != 'N/A') { // Sort by date due $sortDate = $val['date_due']; } else { // Sort by date received $sortDate = $val['date_paid']; } $day = substr($sortDate, 0, 2); $month = substr($sortDate, 3, 2); $year = substr($sortDate, 6, 4); $paymentData["id_{$key}"]['sortableDate'] = mktime(0, 0, 0, $month, $day, $year); } uasort($paymentData, array('Datasource_Insurance_RentGuaranteeClaim_RentalPayment', '_actualSortRentalPayment')); // Add in arrears values to results array - now uses BC Math to prevent // stuffs like '-0.00' from appearing. True story. $accumulator = '0.00'; bcscale(2); foreach ($paymentData as $key => $data) { $accumulator = bcadd($accumulator, bcsub($data['amount_due'], $data['amount_paid'])); $paymentData[$key]['arrear_amount'] = $accumulator; } return $paymentData; }
/** * @param Collection $accounts * @param Carbon $start * @param Carbon $end * * @return array */ public function expenseAccounts(Collection $accounts, Carbon $start, Carbon $end) { $data = ['count' => 1, 'labels' => [], 'datasets' => [['label' => trans('firefly.spent'), 'data' => []]]]; bcscale(2); $start->subDay(); $ids = $this->getIdsFromCollection($accounts); $startBalances = Steam::balancesById($ids, $start); $endBalances = Steam::balancesById($ids, $end); $accounts->each(function (Account $account) use($startBalances, $endBalances) { $id = $account->id; $startBalance = $this->isInArray($startBalances, $id); $endBalance = $this->isInArray($endBalances, $id); $diff = bcsub($endBalance, $startBalance); $account->difference = round($diff, 2); }); $accounts = $accounts->sortByDesc(function (Account $account) { return $account->difference; }); foreach ($accounts as $account) { if ($account->difference > 0) { $data['labels'][] = $account->name; $data['datasets'][0]['data'][] = $account->difference; } } return $data; }
public function subtract(Number $precision, $scale = null) { $scale = $this->scale($scale); $result = bcsub($this->value, $precision->getValue(), self::MAX_PRECISION); $diff = $this->round($result, $scale); return new self($diff, $scale); }
/** * generate a single unique id * when generating ids using unixtime as the prefix, subtract the ID_OFFSET amount from * the start time. gives us more breathing room for using serial numbers. * unix_timestamp of 1000000000 == 2001/09/08 18:46:40 * since the current time won't ever be that number, it is a safe point to go back to. * shouldn't hit big int max for 80 years. at that point we'll rewrite our app :) */ public function id() { $prefix = bcsub(self::time(), self::ID_OFFSET); if ($prefix < 1) { throw new Exception('invalid serial generated', $prefix); } return $prefix . str_pad(mt_rand(0, 9999999999.0), 10, '0', STR_PAD_LEFT); }
/** * Subtract two numbers that are represented as a string. * Numbers will not be rounded but floored instead! So 10.0 - 0.1 with a precision of 0 will result in 9! * @param string $amountA first operand * @param string $amountB second operand * @return string the result as a string */ public static function subtract($amountA, $amountB) { $precision = (int) \Config::inst()->get('SilverStripe\\Omnipay\\PaymentMath', 'precision'); if (function_exists('bcsub') && \Config::inst()->get('SilverStripe\\Omnipay\\PaymentMath', 'useBcMath')) { return bcsub($amountA, $amountB, $precision); } return self::formatFloat((double) $amountA - (double) $amountB, $precision); }
function getStateAnnualTaxableIncome() { $annual_income = $this->getAnnualTaxableIncome(); $allowance = $this->getStateAllowanceAmount(); $income = bcsub($annual_income, $allowance); Debug::text('State Annual Taxable Income: ' . $income, __FILE__, __LINE__, __METHOD__, 10); return $income; }
/** * Helper to do floating point modulus with bcmath. * * @param string $left_operand * @param string $modulus * @param int $scale * * @return string * * @see bcmod() */ protected static function bcfmod($left_operand, $modulus, $scale = NULL) { if (!isset($scale)) { $scale = ini_get('bcmath.scale'); } $div = bcdiv($left_operand, $modulus, 0); return bcsub($left_operand, bcmul($div, $modulus, $scale), $scale); }
function getDistrictAnnualTaxableIncome() { $annual_income = $this->getAnnualTaxableIncome(); $state_allowance = $this->getStateAllowanceAmount(); $state_dependant_allowance = $this->getStateDependantAllowanceAmount(); $income = bcsub(bcsub($annual_income, $state_allowance), $state_dependant_allowance); Debug::text('District Annual Taxable Income: ' . $income, __FILE__, __LINE__, __METHOD__, 10); return $income; }
function GetSteamNorm($Steam64) { $authserver = bcsub($Steam64, '76561197960265728') & 1; //Get the third number of the steamid $authid = (bcsub($Steam64, '76561197960265728') - $authserver) / 2; //Concatenate the STEAM_ prefix and the first number, which is always 0, as well as colons with the other two numbers $steamid = "STEAM_0:{$authserver}:{$authid}"; return $steamid; }
public static function encode($number, $encode = '') { while ($number > 0) { $mod = bcmod($number, 62); $encode .= self::$base62[$mod]; $number = bcdiv(bcsub($number, $mod), 62); } return strrev($encode); }
/** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index() { $billingDetails = $this->getAccountBillingDetails(); $values = ['amount_due' => $billingDetails->balance_due, 'next_bill_date' => $billingDetails->next_bill_date, 'next_bill_amount' => $billingDetails->next_recurring_charge_amount, 'total_balance' => $billingDetails->total_balance, 'available_funds' => $billingDetails->available_funds, 'payment_past_due' => $this->isPaymentPastDue(), 'balance_minus_funds' => bcsub($billingDetails->total_balance, $billingDetails->available_funds, 2)]; $invoices = $this->getInvoices(); $transactions = $this->getTransactions(); $paymentMethods = $this->getPaymentMethods(); return view("pages.billing.index", compact('values', 'invoices', 'transactions', 'paymentMethods')); }
function getDistrictAnnualTaxableIncome() { $annual_income = $this->getAnnualTaxableIncome(); $standard_deduction = $this->getDistrictStandardDeductionAmount(); $district_allowance = $this->getDistrictAllowanceAmount(); $income = bcsub(bcsub($annual_income, $standard_deduction), $district_allowance); Debug::text('District Annual Taxable Income: ' . $income, __FILE__, __LINE__, __METHOD__, 10); return $income; }
public function bcpow_($num, $power) { $awnser = "1"; while ($power) { $awnser = bcmul($awnser, $num, 100); $power = bcsub($power, "1"); } return rtrim($awnser, '0.'); }