コード例 #1
0
ファイル: Toys.php プロジェクト: niceforbear/lib
 /**
  * Convert decimal number as a string to binary number
  * For TblUtil in Karate rank
  *
  * Example:
  * Input:  string $uuid = "465827479475458048";
  * Output: string 10101001111100111001111111100000110000000001000000000000
  *
  * @time 2015/08/30 21:45
  *
  * @param $uuid string
  * @param $base string The convert base
  * @return bool
  */
 public static function convertDecimal2Binary($uuid = "", $base = "2")
 {
     if (empty($uuid) || bccomp($uuid, "0", 0) <= 0) {
         return false;
     }
     $binaryResult = "";
     bcscale(0);
     //Set the default precision
     $intBase = (int) $base;
     while (true) {
         if (substr_compare($uuid, "0", 0) == 0) {
             break;
         }
         $last = substr($uuid, -1);
         //Get the last number
         $divFlag = 0;
         if ($last % $intBase == 0) {
             //If $uuid could be divisible
             $binaryResult .= "0";
         } else {
             $binaryResult .= "1";
             $divFlag = 1;
         }
         if ($divFlag == 1) {
             $lastTwo = substr($uuid, -2);
             $replace = (string) ((int) $lastTwo - 1);
             $uuid = substr_replace($uuid, $replace, -2);
         }
         $uuid = bcdiv($uuid, $base);
     }
     $binaryResult = strrev($binaryResult);
     //Reversing the binary sequence to get the right result
     return $binaryResult;
 }
コード例 #2
0
 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;
 }
コード例 #3
0
ファイル: common.lib.php プロジェクト: AmberWish/laba_web
/**
 * Exponential expression / raise number into power
 *
 * @param string $base         base to raise
 * @param string $exp          exponent to use
 * @param mixed  $use_function pow function to use, or false for auto-detect
 *
 * @return mixed string or float
 */
function PMA_pow($base, $exp, $use_function = false)
{
    static $pow_function = null;
    if (null == $pow_function) {
        $pow_function = PMA_detect_pow();
    }
    if (!$use_function) {
        $use_function = $pow_function;
    }
    if ($exp < 0 && 'pow' != $use_function) {
        return false;
    }
    switch ($use_function) {
        case 'bcpow':
            // bcscale() needed for testing PMA_pow() with base values < 1
            bcscale(10);
            $pow = bcpow($base, $exp);
            break;
        case 'gmp_pow':
            $pow = gmp_strval(gmp_pow($base, $exp));
            break;
        case 'pow':
            $base = (double) $base;
            $exp = (int) $exp;
            $pow = pow($base, $exp);
            break;
        default:
            $pow = $use_function($base, $exp);
    }
    return $pow;
}
コード例 #4
0
 function controller_mandelbrot($args)
 {
     bcscale(100);
     $options = $this->options($args);
     $level = any($args["level"], 8);
     $row = any($args["row"], 0);
     $column = any($args["column"], 0);
     $cache = $this->cacheinfo($level, $column, $row, $options);
     if (!file_exists($cache["path"])) {
         $maxlevel = $this->maxlevel($options["maxsize"]);
         $levelinfo = $this->levelinfo($maxlevel - $level, $options);
         $frame = $this->frame($row, $column, $levelinfo, $options);
         //$this->generate_mandelbrot($cache["path"], $levelinfo["tilesize"], $frame["min"], $frame["max"], $options["iterations"]);
         $this->generate_mandelbrot_c($cache["path"], $levelinfo["tilesize"], $options["framemin"], $options["framemax"], $options["iterations"], $level, $row, $column);
         /*
          print_pre($level);
          print_pre("Full size: " . $maxsize[0] . " x " . $maxsize[1]);
          print_pre("Scaled size: $lwidth x $lheight");
          print_pre("$numcolumns x $numrows");
          print_pre($scaledtilesize);
          
          print_pre($min);
          print_pre($max);
          return;
         */
     }
     header("Content-type: image/png");
     print file_get_contents($cache["path"]);
 }
コード例 #5
0
ファイル: JulianDay.php プロジェクト: mjaschen/astrotools
 /**
  * @param \DateTime $dateTime
  */
 public function __construct(\DateTime $dateTime = null)
 {
     bcscale(static::PRECISION_SCALE);
     if ($dateTime instanceof \DateTime) {
         $this->value = $this->dateTimeToJulianDay($dateTime);
     }
 }
コード例 #6
0
 /**
  * @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;
 }
コード例 #7
0
 /**
  * @param Collection $paid
  * @param Collection $unpaid
  *
  * @return array
  */
 public function frontpage(Collection $paid, Collection $unpaid)
 {
     $paidDescriptions = [];
     $paidAmount = 0;
     $unpaidDescriptions = [];
     $unpaidAmount = 0;
     bcscale(2);
     /** @var TransactionJournal $entry */
     foreach ($paid as $entry) {
         // loop paid and create single entry:
         $paidDescriptions[] = $entry->description;
         $paidAmount = bcadd($paidAmount, $entry->amount_positive);
     }
     /** @var Bill $entry */
     foreach ($unpaid as $entry) {
         // loop unpaid:
         $description = $entry[0]->name . ' (' . $entry[1]->format('jS M Y') . ')';
         $amount = bcdiv(bcadd($entry[0]->amount_max, $entry[0]->amount_min), 2);
         $unpaidDescriptions[] = $description;
         $unpaidAmount = bcadd($unpaidAmount, $amount);
         unset($amount, $description);
     }
     $data = [['value' => $unpaidAmount, 'color' => 'rgba(53, 124, 165,0.7)', 'highlight' => 'rgba(53, 124, 165,0.9)', 'label' => trans('firefly.unpaid')], ['value' => $paidAmount, 'color' => 'rgba(0, 141, 76, 0.7)', 'highlight' => 'rgba(0, 141, 76, 0.9)', 'label' => trans('firefly.paid')]];
     return $data;
 }
コード例 #8
0
ファイル: BC.php プロジェクト: danhunsaker/bcmath
 public static function scale($scale)
 {
     if ($retval = bcscale($scale)) {
         static::$scale = $scale;
     }
     return $retval;
 }
コード例 #9
0
ファイル: Util.class.php プロジェクト: altesien/FinalProject
 /**
  * Exponential expression / raise number into power
  *
  * @param string $base         base to raise
  * @param string $exp          exponent to use
  * @param string $use_function pow function to use, or false for auto-detect
  *
  * @return mixed string or float
  */
 public static function pow($base, $exp, $use_function = '')
 {
     static $pow_function = null;
     if ($pow_function == null) {
         $pow_function = self::detectPow();
     }
     if (!$use_function) {
         if ($exp < 0) {
             $use_function = 'pow';
         } else {
             $use_function = $pow_function;
         }
     }
     if ($exp < 0 && $use_function != 'pow') {
         return false;
     }
     switch ($use_function) {
         case 'bcpow':
             // bcscale() needed for testing pow() with base values < 1
             bcscale(10);
             $pow = bcpow($base, $exp);
             break;
         case 'gmp_pow':
             $pow = gmp_strval(gmp_pow($base, $exp));
             break;
         case 'pow':
             $base = (double) $base;
             $exp = (int) $exp;
             $pow = pow($base, $exp);
             break;
         default:
             $pow = $use_function($base, $exp);
     }
     return $pow;
 }
コード例 #10
0
ファイル: Client.php プロジェクト: imvkmark/l5-chinapay
 function __construct()
 {
     bcscale(0);
     $this->setEnv('test');
     $this->transDate = date('Ymd');
     $this->orderId = "00" . date('YmdHis');
 }
コード例 #11
0
 /**
  * Handle the event when journal is saved.
  *
  * @param  JournalCreated $event
  *
  * @return boolean
  */
 public function handle(JournalCreated $event)
 {
     /** @var TransactionJournal $journal */
     $journal = $event->journal;
     $piggyBankId = $event->piggyBankId;
     /** @var PiggyBank $piggyBank */
     $piggyBank = Auth::user()->piggybanks()->where('piggy_banks.id', $piggyBankId)->first(['piggy_banks.*']);
     if (is_null($piggyBank)) {
         return false;
     }
     // update piggy bank rep for date of transaction journal.
     $repetition = $piggyBank->piggyBankRepetitions()->relevantOnDate($journal->date)->first();
     if (is_null($repetition)) {
         return false;
     }
     bcscale(2);
     $amount = $journal->amount_positive;
     // if piggy account matches source account, the amount is positive
     if ($piggyBank->account_id == $journal->source_account->id) {
         $amount = $amount * -1;
     }
     $repetition->currentamount = bcadd($repetition->currentamount, $amount);
     $repetition->save();
     PiggyBankEvent::create(['piggy_bank_id' => $piggyBank->id, 'transaction_journal_id' => $journal->id, 'date' => $journal->date, 'amount' => $amount]);
     return true;
 }
コード例 #12
0
 public function execute($image)
 {
     bcscale(20);
     $curves = $this->argument(0)->value();
     $numPoints = count($curves);
     $img = $image->getCore();
     $gradient = new Imagick();
     $gradient->newImage(255, 1, new ImagickPixel('white'));
     $regression = new PolynomialRegression($numPoints);
     foreach ($curves as $point) {
         $regression->addData($point[0], $point[1]);
     }
     $coefficients = $regression->getCoefficients();
     for ($x = 0; $x < 255; ++$x) {
         $y = (int) max(0, min(255, $regression->interpolate($coefficients, $x)));
         $r = $g = $b = $y;
         $pixel = new ImagickPixel('rgb(' . $r . ',' . $g . ',' . $b . ')');
         $draw = new ImagickDraw();
         $draw->setFillColor($pixel);
         $draw->rectangle($x, 0, $x + 1, 1);
         $gradient->drawImage($draw);
     }
     $gradient->setImageInterpolateMethod(Imagick::INTERPOLATE_BILINEAR);
     $img->clutImage($gradient);
     return $image;
 }
コード例 #13
0
 /**
  * @param AccountRepositoryInterface $repository
  *
  * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
  */
 public function index(AccountRepositoryInterface $repository)
 {
     $types = Config::get('firefly.accountTypesByIdentifier.asset');
     $count = $repository->countAccounts($types);
     bcscale(2);
     if ($count == 0) {
         return redirect(route('new-user.index'));
     }
     $title = 'Firefly';
     $subTitle = trans('firefly.welcomeBack');
     $mainTitleIcon = 'fa-fire';
     $transactions = [];
     $frontPage = Preferences::get('frontPageAccounts', []);
     $start = Session::get('start', Carbon::now()->startOfMonth());
     $end = Session::get('end', Carbon::now()->endOfMonth());
     $showTour = Preferences::get('tour', true)->data;
     $accounts = $repository->getFrontpageAccounts($frontPage);
     $savings = $repository->getSavingsAccounts();
     $piggyBankAccounts = $repository->getPiggyBankAccounts();
     $savingsTotal = 0;
     foreach ($savings as $savingAccount) {
         $savingsTotal = bcadd($savingsTotal, Steam::balance($savingAccount, $end));
     }
     $sum = $repository->sumOfEverything();
     if ($sum != 0) {
         Session::flash('error', 'Your transactions are unbalanced. This means a' . ' withdrawal, deposit or transfer was not stored properly. ' . 'Please check your accounts and transactions for errors.');
     }
     foreach ($accounts as $account) {
         $set = $repository->getFrontpageTransactions($account, $start, $end);
         if (count($set) > 0) {
             $transactions[] = [$set, $account];
         }
     }
     return view('index', compact('count', 'showTour', 'title', 'savings', 'subTitle', 'mainTitleIcon', 'transactions', 'savingsTotal', 'piggyBankAccounts'));
 }
コード例 #14
0
 /**
  * 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();
 }
コード例 #15
0
ファイル: unionpay.php プロジェクト: noikiy/Ecstore-to-odoo
 public function dopay($payment)
 {
     $merId = $this->getConf('mer_id', __CLASS__);
     //客户号
     $mer_key = $this->getConf('mer_key', __CLASS__);
     //私钥
     bcscale(2);
     //组织给银联打过去要签名的数据 $args
     $args = array("version" => "1.0.0", "charset" => "UTF-8", "transType" => '01', "merAbbr" => $payment['shopName'], "merId" => $merId, "merCode" => "", "backEndUrl" => $this->notify_url, "frontEndUrl" => $this->callback_url, "acqCode" => "", "orderTime" => date('YmdHis', $payment['t_begin']), "orderNumber" => $payment['payment_id'], "commodityName" => "", "commodityUrl" => "", "commodityUnitPrice" => "", "commodityQuantity" => "", "transferFee" => "", "commodityDiscount" => "", "orderAmount" => bcadd($payment['cur_money'], 0) * 100, "orderCurrency" => 156, "customerName" => "", "defaultPayType" => "", "defaultBankNumber" => "", "transTimeout" => "", "customerIp" => $_SERVER['REMOTE_ADDR'], "origQid" => "", "merReserved" => "");
     //生成签名
     $chkvalue = $this->sign($args, 'MD5', $mer_key);
     //循环给表单赋值
     foreach ($args as $key => $val) {
         $this->add_field($key, $val);
     }
     //再往表单里面添加签名方法,签名
     $this->add_field('signMethod', 'MD5');
     $this->add_field('signature', $chkvalue);
     if ($this->is_fields_valiad()) {
         echo $this->get_html();
         exit;
     } else {
         return false;
     }
 }
コード例 #16
0
function load_config()
{
    $CI =& get_instance();
    foreach ($CI->Appconfig->get_all()->result() as $app_config) {
        $CI->config->set_item($CI->security->xss_clean($app_config->key), $CI->security->xss_clean($app_config->value));
    }
    //Set language from config database
    $language = $CI->config->item('language');
    //Loads all the language files from the language directory
    if (!empty($language)) {
        // fallback to English if language folder does not exist
        if (!file_exists('./application/language/' . $language)) {
            $language = 'en';
        }
        $CI->config->set_item('language', $language);
        $map = directory_map('./application/language/' . $language);
        foreach ($map as $file) {
            if (!is_array($file) && substr(strrchr($file, '.'), 1) == "php") {
                $CI->lang->load(strtr($file, '', '_lang.php'), $language);
            }
        }
    }
    //Set timezone from config database
    if ($CI->config->item('timezone')) {
        date_default_timezone_set($CI->config->item('timezone'));
    } else {
        date_default_timezone_set('America/New_York');
    }
    bcscale($CI->config->item('currency_decimals') + $CI->config->item('tax_decimals'));
}
コード例 #17
0
ファイル: Decimal.php プロジェクト: cubiche/cubiche
 /**
  * @param int $scale
  *
  * @throws \InvalidArgumentException
  */
 public static function setDefaultScale($scale)
 {
     if (!is_int($scale) || $scale < 0) {
         throw new \InvalidArgumentException('The scale must be a positive integer');
     }
     self::$defaultScale = $scale;
     \bcscale(self::$defaultScale);
 }
コード例 #18
0
ファイル: Math.php プロジェクト: poef/ariadne
 /**
  * Restores the state of precision setting
  *
  */
 public static function restore()
 {
     if (self::$oldPrecision !== null && function_exists('ini_set')) {
         ini_set('precision', self::$oldPrecision[0]);
         ini_set('bcmath.scale', self::$oldPrecision[1]);
         bcscale(self::$oldPrecision[1]);
     }
     self::$setup = false;
 }
コード例 #19
0
 function __construct()
 {
     bcscale(4);
     foreach (self::$variable as $key => $value) {
         $this->{$key} = 0;
     }
     $this->order = 0;
     $this->check = true;
 }
コード例 #20
0
ファイル: pi.php プロジェクト: philum/cms
function plug_pi($p)
{
    bcscale(20);
    //nb after comma
    //$pi=msql_read('','public_pi','1',1); $pi=substr($pi,0,$p);
    //$math=bcdiv(bcadd(bcsqrt(5),1),2);//phi
    $pi4 = pi1($p ? $p : 40000);
    $ret = $pi4 * 4;
    return $ret;
}
コード例 #21
0
ファイル: Time.php プロジェクト: sergeylunev/astrolib
 public function numberOfHours()
 {
     bcscale(6);
     $seconds = $this->date->format('s');
     $minutes = $this->date->format('i');
     $hours = $this->date->format('G');
     $numberOfSeconds = bcdiv($seconds, '60.0');
     $numberOfMinutes = bcdiv(bcadd($minutes, $numberOfSeconds), 60);
     $numberOfHours = bcadd($hours, $numberOfMinutes);
     return (double) $numberOfHours;
 }
コード例 #22
0
ファイル: ArkWorker.php プロジェクト: uafrica/delayed-jobs
 protected function _bcpi($precision)
 {
     $num = 0;
     $k = 0;
     bcscale($precision + 3);
     $limit = ($precision + 3) / 14;
     while ($k < $limit) {
         $num = bcadd($num, bcdiv(bcmul(bcadd('13591409', bcmul('545140134', $k)), bcmul(bcpow(-1, $k), $this->_bcfact(6 * $k))), bcmul(bcmul(bcpow('640320', 3 * $k + 1), bcsqrt('640320')), bcmul($this->_bcfact(3 * $k), bcpow($this->_bcfact($k), 3)))));
         ++$k;
     }
     return bcdiv(1, bcmul(12, $num), $precision);
 }
コード例 #23
0
ファイル: LineItemTest.php プロジェクト: imosnet/invoice
 public function testLineTotals()
 {
     bcscale(10);
     $item = (new LineItem())->setUnitPrice('25');
     $this->assertEquals('25', $item->getTotal());
     $item->setTaxRate(19);
     $this->assertEquals('25', $item->getTotal());
     $item->setQuantity(2);
     $this->assertEquals('50', $item->getTotal());
     $item->setDiscount(25);
     $this->assertEquals('37.5', $item->getTotal());
 }
コード例 #24
0
ファイル: Expense.php プロジェクト: leander091/firefly-iii
 /**
  * @param $add
  */
 public function addToTotal($add)
 {
     bcscale(2);
     $add = strval(round($add, 2));
     if (bccomp('0', $add) === -1) {
         $add = bcmul($add, '-1');
     }
     // if amount is positive, the original transaction
     // was a transfer. But since this is an expense report,
     // that amount must be negative.
     $this->total = bcadd($this->total, $add);
 }
コード例 #25
0
ファイル: phi.php プロジェクト: philum/cms
function plug_phi($d)
{
    $float = $d ? $d : 100;
    bcscale($float);
    //$ret=(sqrt(5)+1)/2;
    //$math=bcdiv(bcadd(bcsqrt(5),1),2);
    $phi = phi($float);
    //$fibo=fibo();
    //$comp=bccomp($phi,$fibo);
    //$ret=$math.br().$phi.br().$fibo.br().$comp;
    return $phi;
}
コード例 #26
0
 /**
  * @param string $amount
  * @param string $iban
  * @param string $name
  */
 public function __construct($amount, $iban, $name)
 {
     $amount += 0;
     if (is_float($amount)) {
         if (!function_exists('bcscale')) {
             throw new InvalidArgumentException('Using floats for amount is only possible with bcmath enabled');
         }
         bcscale(2);
         $amount = (int) bcmul($amount, 100);
     }
     $this->transferAmount = $amount;
     $this->iban = $iban;
     $this->name = StringHelper::sanitizeString($name);
 }
コード例 #27
0
 /**
  * @param Collection $set
  *
  * @return array
  */
 public function history(Collection $set)
 {
     $chart = new GChart();
     $chart->addColumn(trans('firefly.date'), 'date');
     $chart->addColumn(trans('firefly.balance'), 'number');
     $sum = '0';
     bcscale(2);
     foreach ($set as $entry) {
         $sum = bcadd($sum, $entry->sum);
         $chart->addRow(new Carbon($entry->date), $sum);
     }
     $chart->generate();
     return $chart->getData();
 }
コード例 #28
0
ファイル: PhpBenchmark.php プロジェクト: smuuf/phpcb
 public function run($count = 1000000)
 {
     // Make sure the output of benchmarked code is not displayed.
     ob_start();
     // Set BC scale
     bcscale(self::BC_SCALE);
     // Limit the iterations count
     $count = min(max($count, self::MIN_COUNT), self::MAX_COUNT);
     $this->results = $this->engine->run($count, $this->closures);
     // Save the total count of iterations for the template
     $this->template['count'] = $count;
     // Render the output
     $this->renderResults();
 }
コード例 #29
0
ファイル: PiggybankPart.php プロジェクト: zetaron/firefly-iii
 /**
  * @return float|int
  */
 public function percentage()
 {
     bcscale(2);
     if ($this->getCurrentamount() < $this->getCumulativeAmount()) {
         $pct = 0;
         // calculate halfway point?
         if (bcsub($this->getCumulativeAmount(), $this->getCurrentamount()) < $this->getAmountPerBar()) {
             $left = $this->getCurrentamount() % $this->getAmountPerBar();
             $pct = round($left / $this->getAmountPerBar() * 100);
         }
         return $pct;
     } else {
         return 100;
     }
 }
コード例 #30
0
 /**
  * @param Collection $set
  *
  * @return array
  */
 public function history(Collection $set)
 {
     // language:
     $format = (string) trans('config.month_and_day');
     $data = ['count' => 1, 'labels' => [], 'datasets' => [['label' => 'Diff', 'data' => []]]];
     $sum = '0';
     bcscale(2);
     foreach ($set as $entry) {
         $date = new Carbon($entry->date);
         $sum = bcadd($sum, $entry->sum);
         $data['labels'][] = $date->formatLocalized($format);
         $data['datasets'][0]['data'][] = round($sum, 2);
     }
     return $data;
 }