Пример #1
0
 /**
  * @covers Fisharebest\PhpPolyfill\Php::inf
  * @covers Fisharebest\PhpPolyfill\Php::isLittleEndian
  * @runInSeparateProcess
  */
 public function testInf()
 {
     $this->assertTrue(is_float(Php::inf()));
     $this->assertTrue(is_double(Php::inf()));
     $this->assertTrue(is_infinite(Php::inf()));
     $this->assertFalse(is_finite(Php::inf()));
 }
Пример #2
0
 /**
  * 与えられた値を整数型に変換して返します。
  * @link http://www.hcn.zaq.ne.jp/___/WEB/WebIDL-ja.html#es-integers Web IDL (第2版 — 日本語訳)
  * @param boolean|integer|float|string|resource|\GMP|\SplInt $value
  * @param string $type byte、octet、short、unsigned short、long、unsigned long、long long、unsigned long long
  * @param integer|float $min 浮動小数点型で正確に扱える整数の範囲よりも、整数型で扱える整数の範囲が狭ければ (整数型が32bitである環境なら) 浮動小数点数。
  * @param integer|float $max 浮動小数点型で正確に扱える整数の範囲よりも、整数型で扱える整数の範囲が狭ければ (整数型が32bitである環境なら) 浮動小数点数。
  * @param integer $bits
  * @param booelan $signed
  * @param string $extendedAttribute 拡張属性。[EnforceRange] か [Clamp] のいずれか。
  * @return integer|float 整数型の範囲を超える場合は浮動小数点数。
  * @throws \InvalidArgumentException 配列、NULL が与えられた場合。または、GMP、SplInt 以外のオブジェクトが与えられた場合。
  * @throws \DomainException $extendedAttribute が [EnforceRange]、かつ与えられたの値が $min 〜 $max に収まらなかった場合。
  */
 private static function toInteger($value, $type, $min, $max, $bits, $signed, $extendedAttribute = null)
 {
     /** @var string 要求される型。 */
     $expectedType = sprintf('%s (an integer in the range of %s to %s)', $type, is_float($min) ? number_format($min, 0, '', '') : $min, is_float($max) ? number_format($max, 0, '', '') : $max);
     if (!self::isIntegerCastable($value)) {
         throw new \InvalidArgumentException(ErrorMessageCreator::create($value, $expectedType));
     }
     if ($value instanceof \GMP || is_resource($value) && get_resource_type($value) === 'GMP integer') {
         // GMP数であれば、あらかじめ文字列に変換しておく
         $value = gmp_strval($value);
     }
     /** @var integer|float 与えられた値の数値表現。整数型の範囲を超える場合は浮動小数点数。整数値となる場合、小数部があれば0方向へ丸められる。 */
     $number = is_float($value) || (double) $value < self::$phpIntMin || (double) $value > PHP_INT_MAX ? (double) $value : (int) $value;
     if ($extendedAttribute === '[EnforceRange]') {
         /** @var integer|float 与えられた値の整数表現。整数型の範囲を超える場合は浮動小数点数。 */
         $integer = self::roundTowardZero($number);
         if (!is_finite($number) || $integer < $min || $integer > $max) {
             throw new \DomainException(ErrorMessageCreator::create($value, $expectedType));
         }
     } elseif (!is_nan($number) && $extendedAttribute === '[Clamp]') {
         $number = min(max($number, $min), $max);
         $integer = is_float($number) ? round($number, 0, PHP_ROUND_HALF_EVEN) : $number;
     } elseif (!is_finite($number)) {
         $integer = 0;
     } else {
         $integer = self::modulo(self::roundTowardZero($number), pow(2, $bits));
         if ($signed && $integer >= pow(2, $bits - 1)) {
             $integer -= pow(2, $bits);
         }
     }
     return is_float($integer) && $integer >= self::$phpIntMin && $integer <= PHP_INT_MAX ? (int) $integer : $integer;
 }
Пример #3
0
 protected function matches($actual)
 {
     $asserter = new asserters\boolean();
     try {
         $asserter->setWith(is_finite($actual))->isTrue();
     } catch (exception $exception) {
         throw new exception($asserter, $this->analyzer->getTypeOf($actual) . ' is not finite');
     }
 }
Пример #4
0
 /**
  * Dumps information about a variable in readable format.
  * @param  mixed  variable to dump
  * @return string
  */
 public static function toLine($var)
 {
     static $table;
     if ($table === NULL) {
         foreach (array_merge(range("", ""), range("", "ÿ")) as $ch) {
             $table[$ch] = '\\x' . str_pad(dechex(ord($ch)), 2, '0', STR_PAD_LEFT);
         }
         $table['\\'] = '\\\\';
         $table["\r"] = '\\r';
         $table["\n"] = '\\n';
         $table["\t"] = '\\t';
     }
     if (is_bool($var)) {
         return $var ? 'TRUE' : 'FALSE';
     } elseif ($var === NULL) {
         return 'NULL';
     } elseif (is_int($var)) {
         return "{$var}";
     } elseif (is_float($var)) {
         if (!is_finite($var)) {
             return str_replace('.0', '', var_export($var, TRUE));
             // workaround for PHP 7.0.2
         }
         $var = str_replace(',', '.', "{$var}");
         return strpos($var, '.') === FALSE ? $var . '.0' : $var;
         // workaround for PHP < 7.0.2
     } elseif (is_string($var)) {
         if (preg_match('#^(.{' . self::$maxLength . '}).#su', $var, $m)) {
             $var = "{$m['1']}...";
         } elseif (strlen($var) > self::$maxLength) {
             $var = substr($var, 0, self::$maxLength) . '...';
         }
         return preg_match('#[^\\x09\\x0A\\x0D\\x20-\\x7E\\xA0-\\x{10FFFF}]#u', $var) || preg_last_error() ? '"' . strtr($var, $table) . '"' : "'{$var}'";
     } elseif (is_array($var)) {
         $out = '';
         $counter = 0;
         foreach ($var as $k => &$v) {
             $out .= $out === '' ? '' : ', ';
             if (strlen($out) > self::$maxLength) {
                 $out .= '...';
                 break;
             }
             $out .= ($k === $counter ? '' : self::toLine($k) . ' => ') . (is_array($v) && $v ? 'array(...)' : self::toLine($v));
             $counter = is_int($k) ? max($k + 1, $counter) : $counter;
         }
         return "array({$out})";
     } elseif ($var instanceof \Exception || $var instanceof \Throwable) {
         return 'Exception ' . get_class($var) . ': ' . ($var->getCode() ? '#' . $var->getCode() . ' ' : '') . $var->getMessage();
     } elseif (is_object($var)) {
         return self::objectToLine($var);
     } elseif (is_resource($var)) {
         return 'resource(' . get_resource_type($var) . ')';
     } else {
         return 'unknown type';
     }
 }
Пример #5
0
 function __toString()
 {
     $sql = "";
     foreach ($this as $column => $value) {
         if (isset($this->{$column})) {
             $sql = ($sql ? "{$sql}, " : "") . "{$column}=" . (is_double($value) && !is_finite($value) ? "NULL" : "'" . (self::$db ? self::$db->escape($value) : $value) . "'");
         }
     }
     return $sql;
 }
Пример #6
0
 private function XNPV($rate, $values, $dates)
 {
     if (!is_array($values) || !is_array($dates)) {
         return null;
     }
     if (count($values) != count($dates)) {
         return null;
     }
     $xnpv = 0.0;
     for ($i = 0; $i < count($values); $i++) {
         $xnpv += $values[$i] / pow(1 + $rate, $this->DATEDIFF('day', $dates[0], $dates[$i]) / 365);
     }
     return is_finite($xnpv) ? $xnpv : null;
 }
Пример #7
0
 /**
  * 与えられた値を、NAN、INFを含まない浮動小数点型に変換して返します。
  * @link https://heycam.github.io/webidl/#idl-double Web IDL (Second Edition)
  * @link http://www.w3.org/TR/WebIDL/#idl-double Web IDL
  * @param boolean|integer|float|string|resource|\GMP|\SplFloat $value
  * @throws \InvalidArgumentException 配列、NULL が与えられた場合。または、GMP、SplFloat 以外のオブジェクトが与えられた場合。
  * @throws \DomainException 変換後の値が、NAN、INF、-INF のいずれかになった場合。
  * @return float
  */
 public static function toDouble($value)
 {
     $expectedType = 'double (a float not NAN or INF)';
     try {
         $float = self::toUnrestrictedDouble($value);
     } catch (\InvalidArgumentException $exeception) {
         throw new \InvalidArgumentException(ErrorMessageCreator::create($value, $expectedType));
     }
     if (is_finite($float)) {
         return $float;
     } else {
         throw new \DomainException(ErrorMessageCreator::create($value, $expectedType));
     }
 }
Пример #8
0
 public function execute()
 {
     $src = FileBackendGroup::singleton()->get($this->getOption('src'));
     $dst = FileBackendGroup::singleton()->get($this->getOption('dst'));
     $posDir = $this->getOption('posdir');
     $posFile = $posDir ? $posDir . '/' . wfWikiID() : false;
     $start = $this->getOption('start', 0);
     if (!$start && $posFile && is_dir($posDir)) {
         $start = is_file($posFile) ? (int) trim(file_get_contents($posFile)) : 0;
         ++$start;
         // we already did this ID, start with the next one
         $startFromPosFile = true;
     } else {
         $startFromPosFile = false;
     }
     $end = $this->getOption('end', INF);
     $this->output("Synchronizing backend '{$dst->getName()}' to '{$src->getName()}'...\n");
     $this->output("Starting journal position is {$start}.\n");
     if (is_finite($end)) {
         $this->output("Ending journal position is {$end}.\n");
     }
     // Actually sync the dest backend with the reference backend
     $lastOKPos = $this->syncBackends($src, $dst, $start, $end);
     // Update the sync position file
     if ($startFromPosFile && $lastOKPos >= $start) {
         // successfully advanced
         if (file_put_contents($posFile, $lastOKPos, LOCK_EX) !== false) {
             $this->output("Updated journal position file.\n");
         } else {
             $this->output("Could not update journal position file.\n");
         }
     }
     if ($lastOKPos === false) {
         if (!$start) {
             $this->output("No journal entries found.\n");
         } else {
             $this->output("No new journal entries found.\n");
         }
     } else {
         $this->output("Stopped synchronization at journal position {$lastOKPos}.\n");
     }
     if ($this->isQuiet()) {
         print $lastOKPos;
         // give a single machine-readable number
     }
 }
Пример #9
0
 static function convertBeforeEncode($val)
 {
     $arr = null;
     if (is_object($val)) {
         $_g = get_class($val);
         switch ($_g) {
             case "_hx_anonymous":
             case "stdClass":
                 $arr = php_Lib::associativeArrayOfObject($val);
                 break;
             case "_hx_array":
                 $arr = php_Lib::toPhpArray($val);
                 break;
             case "Date":
                 return Std::string($val);
                 break;
             case "HList":
                 $arr = php_Lib::toPhpArray(Lambda::harray($val));
                 break;
             case "_hx_enum":
                 $e = $val;
                 return $e->index;
                 break;
             case "StringMap":
             case "IntMap":
                 $arr = php_Lib::associativeArrayOfHash($val);
                 break;
             default:
                 $arr = php_Lib::associativeArrayOfObject($val);
                 break;
         }
     } else {
         if (is_array($val)) {
             $arr = $val;
         } else {
             if (is_float($val) && !is_finite($val)) {
                 $val = null;
             }
             return $val;
         }
     }
     return array_map(isset(haxe_Json::$convertBeforeEncode) ? haxe_Json::$convertBeforeEncode : array("haxe_Json", "convertBeforeEncode"), $arr);
 }
Пример #10
0
 /**
  * Returns the prime factors of a number.
  * More info (http://bateru.com/news/2012/05/code-of-the-day-javascript-prime-factors-of-a-number/)
  * Taken from Ratio.js
  *
  * @param number $number
  * @return array an array of numbers
  * @example prime.factorization(20).join(',') === "2,2,5"
  **/
 public static function factorization($number = 0)
 {
     $number = floor($number);
     $continue = 1 < $number && is_finite($number);
     $factors = array();
     while ($continue) {
         $sqrt = sqrt($number);
         $x = 2;
         if (fmod($number, $x) != 0) {
             $x = 3;
             while (fmod($number, $x) != 0 && ($x += 2) < $sqrt) {
             }
         }
         $x = $sqrt < $x ? $number : $x;
         $factors[] = $x;
         $continue = $x != $number;
         $number /= $x;
     }
     return $factors;
 }
Пример #11
0
 /**
  * Parses string representing degrees/minutes/seconds into numeric degrees.
  *
  * This is very flexible on formats, allowing signed decimal degrees, or deg-min-sec optionally
  * suffixed by compass direction (NSEW). A variety of separators are accepted (eg 3° 37′ 09″W).
  * Seconds and minutes may be omitted.
  *
  * @param   string|number $dmsStr - Degrees or deg/min/sec in variety of formats.
  * @returns number Degrees as decimal number.
  */
 public static function parseDMS($dmsStr)
 {
     // check for signed decimal degrees without NSEW, if so return it directly
     if (is_numeric($dmsStr) && is_finite($dmsStr)) {
         return (double) $dmsStr;
     }
     // strip off any sign or compass dir'n & split out separate d/m/s
     $dms = preg_split('/[^0-9.,]+/', preg_replace(['/^-/', '/[NSEW]$/i'], '', trim((string) $dmsStr)));
     if ($dms[count($dms) - 1] == '') {
         array_splice($dms, count($dms) - 1);
     }
     // from trailing symbol
     if ($dms == '') {
         return NAN;
     }
     // and convert to decimal degrees...
     switch (count($dms)) {
         case 3:
             // interpret 3-part result as d/m/s
             $deg = $dms[0] / 1 + $dms[1] / 60 + $dms[2] / 3600;
             break;
         case 2:
             // interpret 2-part result as d/m
             $deg = $dms[0] / 1 + $dms[1] / 60;
             break;
         case 1:
             // just d (possibly decimal) or non-separated dddmmss
             $deg = $dms[0];
             // check for fixed-width unseparated format eg 0033709W
             //if (/[NS]/i.test(dmsStr)) deg = '0' + deg;  // - normalise N/S to 3-digit degrees
             //if (/[0-9]{7}/.test(deg)) deg = deg.slice(0,3)/1 + deg.slice(3,5)/60 + deg.slice(5)/3600;
             break;
         default:
             return NAN;
     }
     if (preg_match('/^-|[WS]$/i', trim($dmsStr))) {
         $deg = -$deg;
     }
     // take '-', west and south as -ve
     return (double) $deg;
 }
Пример #12
0
 public static function whatIs($what)
 {
     $type = gettype($what);
     switch ($type) {
         case "double":
         case "integer":
             if (is_finite($what)) {
                 return $what % 1 === 0 ? "integer" : "number";
             }
             if (is_nan($what)) {
                 return "not-a-number";
             }
             return "unknown-number";
         case "NULL":
             return "null";
         case "boolean":
         case "object":
         case "array":
         case "string":
             return $type;
         default:
             return "unknown-type";
     }
 }
Пример #13
0
 /**
  * Cast an value to a specific type.
  *
  * Public calls should be made to "cast" which then delegates to this method.
  *
  * @param mixed $value        Value to be casted and returned by reference.
  * @param mixed $defaultValue Value to be returned if not set.
  *
  * @return mixed New value (or default value if unmatched).
  * @throws \TypeError If defaultValue is of invalid type.
  */
 public function doCast($value, $defaultValue = null)
 {
     if (false === is_float($defaultValue) && null !== $defaultValue) {
         throw new \TypeError('DefaultValue must be a float for AsFloat casts');
     }
     if (false === is_string($value) && false === is_numeric($value)) {
         $this->setError(self::ONLY_STRINGS_NUMERICS);
         return $defaultValue;
     }
     if (false === is_float($value)) {
         $options = ['options' => ['default' => null, 'decimal' => $this->decimalSeparator]];
         // remove thousands separator
         $value = str_replace($this->digitsSeparator, '', strval($value));
         $value = filter_var($value, FILTER_VALIDATE_FLOAT, $options);
     }
     if (false === is_float($value) || true === is_nan($value) || false === is_finite($value)) {
         $this->setError(self::FLOAT_MUST_BE_ACCEPTED_FORMAT, ['decimalSeparator' => $this->decimalSeparator, 'digitsSeparator' => $this->digitsSeparator]);
         return $defaultValue;
     }
     if (null !== $this->precision) {
         $value = round($value, $this->precision);
     }
     return $value;
 }
Пример #14
0
 /**
  * @return mixed
  */
 private static function toJson(&$var, $options, $level = 0)
 {
     if (is_bool($var) || is_null($var) || is_int($var)) {
         return $var;
     } elseif (is_float($var)) {
         return is_finite($var) ? strpos($tmp = json_encode($var), '.') ? $var : array('number' => "{$tmp}.0") : array('type' => (string) $var);
     } elseif (is_string($var)) {
         return self::encodeString($var, $options[self::TRUNCATE]);
     } elseif (is_array($var)) {
         static $marker;
         if ($marker === NULL) {
             $marker = uniqid("", TRUE);
         }
         if (isset($var[$marker]) || $level >= $options[self::DEPTH]) {
             return array(NULL);
         }
         $res = array();
         $var[$marker] = TRUE;
         foreach ($var as $k => &$v) {
             if ($k !== $marker) {
                 $k = preg_match('#^\\w{1,50}\\z#', $k) ? $k : '"' . self::encodeString($k, $options[self::TRUNCATE]) . '"';
                 $res[] = array($k, self::toJson($v, $options, $level + 1));
             }
         }
         unset($var[$marker]);
         return $res;
     } elseif (is_object($var)) {
         $obj =& self::$liveStorage[spl_object_hash($var)];
         if ($obj && $obj['level'] <= $level) {
             return array('object' => $obj['id']);
         }
         if ($options[self::LOCATION] & self::LOCATION_CLASS) {
             $rc = $var instanceof \Closure ? new \ReflectionFunction($var) : new \ReflectionClass($var);
             $editor = Helpers::editorUri($rc->getFileName(), $rc->getStartLine());
         }
         static $counter = 1;
         $obj = $obj ?: array('id' => self::$livePrefix . '0' . $counter++, 'name' => Helpers::getClass($var), 'editor' => empty($editor) ? NULL : array('file' => $rc->getFileName(), 'line' => $rc->getStartLine(), 'url' => $editor), 'level' => $level, 'object' => $var);
         if ($level < $options[self::DEPTH] || !$options[self::DEPTH]) {
             $obj['level'] = $level;
             $obj['items'] = array();
             foreach (self::exportObject($var, $options[self::OBJECT_EXPORTERS]) as $k => $v) {
                 $vis = 0;
                 if (isset($k[0]) && $k[0] === "") {
                     $vis = $k[1] === '*' ? 1 : 2;
                     $k = substr($k, strrpos($k, "") + 1);
                 }
                 $k = preg_match('#^\\w{1,50}\\z#', $k) ? $k : '"' . self::encodeString($k, $options[self::TRUNCATE]) . '"';
                 $obj['items'][] = array($k, self::toJson($v, $options, $level + 1), $vis);
             }
         }
         return array('object' => $obj['id']);
     } elseif (is_resource($var)) {
         $obj =& self::$liveStorage[(string) $var];
         if (!$obj) {
             $type = get_resource_type($var);
             $obj = array('id' => self::$livePrefix . (int) $var, 'name' => $type . ' resource');
             if (isset(self::$resources[$type])) {
                 foreach (call_user_func(self::$resources[$type], $var) as $k => $v) {
                     $obj['items'][] = array($k, self::toJson($v, $options, $level + 1));
                 }
             }
         }
         return array('resource' => $obj['id']);
     } else {
         return array('type' => 'unknown type');
     }
 }
 public function newPagerForSavedQuery(PhabricatorSavedQuery $saved)
 {
     if ($this->shouldUseOffsetPaging()) {
         $pager = new PHUIPagerView();
     } else {
         $pager = new AphrontCursorPagerView();
     }
     $page_size = $this->getPageSize($saved);
     if (is_finite($page_size)) {
         $pager->setPageSize($page_size);
     } else {
         // Consider an INF pagesize to mean a large finite pagesize.
         // TODO: It would be nice to handle this more gracefully, but math
         // with INF seems to vary across PHP versions, systems, and runtimes.
         $pager->setPageSize(0xffff);
     }
     return $pager;
 }
Пример #16
0
 public static function MIRR($values, $finance_rate, $reinvestment_rate)
 {
     if (!is_array($values)) {
         return self::$_errorCodes['value'];
     }
     $values = self::flattenArray($values);
     $finance_rate = self::flattenSingleValue($finance_rate);
     $reinvestment_rate = self::flattenSingleValue($reinvestment_rate);
     $n = count($values);
     $rr = 1.0 + $reinvestment_rate;
     $fr = 1.0 + $finance_rate;
     $npv_pos = $npv_neg = 0.0;
     foreach ($values as $i => $v) {
         if ($v >= 0) {
             $npv_pos += $v / pow($rr, $i);
         } else {
             $npv_neg += $v / pow($fr, $i);
         }
     }
     if ($npv_neg == 0 || $npv_pos == 0 || $reinvestment_rate <= -1) {
         return self::$_errorCodes['value'];
     }
     $mirr = pow(-$npv_pos * pow($rr, $n) / ($npv_neg * $rr), 1.0 / ($n - 1)) - 1.0;
     return is_finite($mirr) ? $mirr : self::$_errorCodes['value'];
 }
Пример #17
0
 /**
  * Validate a value for addition to the result
  * @param mixed $value
  * @return array|mixed|string
  */
 private static function validateValue($value)
 {
     global $wgContLang;
     if (is_object($value)) {
         // Note we use is_callable() here instead of instanceof because
         // ApiSerializable is an informal protocol (see docs there for details).
         if (is_callable(array($value, 'serializeForApiResult'))) {
             $oldValue = $value;
             $value = $value->serializeForApiResult();
             if (is_object($value)) {
                 throw new UnexpectedValueException(get_class($oldValue) . "::serializeForApiResult() returned an object of class " . get_class($value));
             }
             // Recursive call instead of fall-through so we can throw a
             // better exception message.
             try {
                 return self::validateValue($value);
             } catch (Exception $ex) {
                 throw new UnexpectedValueException(get_class($oldValue) . "::serializeForApiResult() returned an invalid value: " . $ex->getMessage(), 0, $ex);
             }
         } elseif (is_callable(array($value, '__toString'))) {
             $value = (string) $value;
         } else {
             $value = (array) $value + array(self::META_TYPE => 'assoc');
         }
     }
     if (is_array($value)) {
         foreach ($value as $k => $v) {
             $value[$k] = self::validateValue($v);
         }
     } elseif (is_float($value) && !is_finite($value)) {
         throw new InvalidArgumentException("Cannot add non-finite floats to ApiResult");
     } elseif (is_string($value)) {
         $value = $wgContLang->normalize($value);
     } elseif ($value !== null && !is_scalar($value)) {
         $type = gettype($value);
         if (is_resource($value)) {
             $type .= '(' . get_resource_type($value) . ')';
         }
         throw new InvalidArgumentException("Cannot add {$type} to ApiResult");
     }
     return $value;
 }
Пример #18
0
 static function isFinite($f)
 {
     return is_finite($f);
 }
 /**
  * Returns true if object is a finite number.
  *
  * @category Object Functions
  *
  * @param mixed $object the object
  *
  * @return bool
  */
 public static function isFinite($object)
 {
     return is_finite($object);
 }
Пример #20
0
 /**
  * Get the backlinks for a given table. Cached in process memory only.
  * @param string $table
  * @param int|bool $startId
  * @param int|bool $endId
  * @param int|INF $max
  * @param string $select 'all' or 'ids'
  * @return ResultWrapper
  */
 protected function queryLinks($table, $startId, $endId, $max, $select = 'all')
 {
     wfProfileIn(__METHOD__);
     $fromField = $this->getPrefix($table) . '_from';
     if (!$startId && !$endId && is_infinite($max) && isset($this->fullResultCache[$table])) {
         wfDebug(__METHOD__ . ": got results from cache\n");
         $res = $this->fullResultCache[$table];
     } else {
         wfDebug(__METHOD__ . ": got results from DB\n");
         $conds = $this->getConditions($table);
         // Use the from field in the condition rather than the joined page_id,
         // because databases are stupid and don't necessarily propagate indexes.
         if ($startId) {
             $conds[] = "{$fromField} >= " . intval($startId);
         }
         if ($endId) {
             $conds[] = "{$fromField} <= " . intval($endId);
         }
         $options = array('ORDER BY' => $fromField);
         if (is_finite($max) && $max > 0) {
             $options['LIMIT'] = $max;
         }
         if ($select === 'ids') {
             // Just select from the backlink table and ignore the page JOIN
             $res = $this->getDB()->select($table, array($this->getPrefix($table) . '_from AS page_id'), array_filter($conds, function ($clause) {
                 // kind of janky
                 return !preg_match('/(\\b|=)page_id(\\b|=)/', $clause);
             }), __METHOD__, $options);
         } else {
             // Select from the backlink table and JOIN with page title information
             $res = $this->getDB()->select(array($table, 'page'), array('page_namespace', 'page_title', 'page_id'), $conds, __METHOD__, array_merge(array('STRAIGHT_JOIN'), $options));
         }
         if ($select === 'all' && !$startId && !$endId && $res->numRows() < $max) {
             // The full results fit within the limit, so cache them
             $this->fullResultCache[$table] = $res;
         } else {
             wfDebug(__METHOD__ . ": results from DB were uncacheable\n");
         }
     }
     wfProfileOut(__METHOD__);
     return $res;
 }
Пример #21
0
function _hx_mod($x, $y)
{
    if (is_int($x) && is_int($y)) {
        if ($y == 0) {
            return 0;
        }
        return $x % $y;
    }
    if (!is_nan($x) && !is_nan($y) && !is_finite($y) && is_finite($x)) {
        return $x;
    }
    return fmod($x, $y);
}
Пример #22
0
 /**
  * Evaluates the constraint for parameter $other. Returns true if the
  * constraint is met, false otherwise.
  *
  * @param  mixed $other Value or object to evaluate.
  * @return bool
  */
 protected function matches($other)
 {
     return is_finite($other);
 }
Пример #23
0
 public static function encode($value, $type, $format)
 {
     if ($value) {
         // Empty values return empty string
         $formater[self::TYPE_DATE][self::FORMAT_EDITOR] = function ($value) {
             return date('Y-m-d', $value);
         };
         $formater[self::TYPE_DATE_RANGE][self::FORMAT_EDITOR] = function ($aValue) {
             $result = [ValueFormater::PERIOD_OF_VALIDITY_START => '', ValueFormater::PERIOD_OF_VALIDITY_END => ''];
             foreach ($aValue as $attributeName => $value) {
                 if ($value && is_finite($value)) {
                     $result[$attributeName] = date('Y-m-d', $value);
                 }
             }
             //$result = array_pad($result, 2, '');
             return $result;
         };
         $formater[self::TYPE_DATE_TIME][self::FORMAT_EDITOR] = function ($value) {
             return date('Y-m-d\\TH:i:s\\Z', $value);
         };
         $formater[self::TYPE_DATE_TIME_RANGE][self::FORMAT_EDITOR] = function ($aValue) {
             $result = [ValueFormater::PERIOD_OF_VALIDITY_START => '', ValueFormater::PERIOD_OF_VALIDITY_END => ''];
             foreach ($aValue as $attributeName => $value) {
                 if ($value && is_finite($value)) {
                     $result[$attributeName] = date('Y-m-d\\TH:i:s\\Z', $value);
                 }
             }
             //$result = array_pad($result, 2, '');
             return $result;
         };
         $formater[self::TYPE_TAGS][self::FORMAT_EDITOR] = function ($value) {
             return implode(',', $value);
         };
         $formater[self::TYPE_BOOLEAN][self::FORMAT_EDITOR] = function ($value) {
             return $value ? ' checked="checked"' : '';
         };
         $formater[self::TYPE_DATE_RANGE][self::FORMAT_HUMAN] = function ($aValue) {
             $result = [ValueFormater::PERIOD_OF_VALIDITY_START => '∞', ValueFormater::PERIOD_OF_VALIDITY_END => '∞'];
             $bModified = false;
             foreach ($aValue as $attributeName => $value) {
                 if ($value && is_finite($value)) {
                     $result[$attributeName] = date('j M G:i\\h', $value);
                     $bModified = true;
                 }
             }
             //$result = array_pad($result, 2, '');
             return $bModified ? implode(' - ', $result) : '';
         };
         if (isset($formater[$type][$format])) {
             return $formater[$type][$format]($value);
         } else {
             return $value;
         }
     }
 }
Пример #24
0
 /**
  * Validate that a number is in specified range.
  * if $lower and $upper are not set, will return true if
  * $check is a legal finite on this platform
  *
  * @param string $check Value to check
  * @param integer $lower Lower limit
  * @param integer $upper Upper limit
  * @return boolean Success
  */
 public static function range($check, $lower = null, $upper = null)
 {
     if (!is_numeric($check)) {
         return false;
     }
     if (isset($lower) && isset($upper)) {
         return $check > $lower && $check < $upper;
     }
     return is_finite($check);
 }
Пример #25
0
echo sqrt(-2354) . " " . sqrt("foo") . " " . sqrt(0) . " " . sqrt(5) . sqrt(1.2345) . "\n";
echo "srand\n";
srand(12);
echo "(no output)\n";
echo "tan\n";
echo tan(-2354) . " " . tan("foo") . " " . tan(0) . " " . tan(5) . tan(1.2345) . "\n";
echo "tanh\n";
echo tanh(-2354) . " " . tanh("foo") . " " . tanh(0) . " " . tanh(5) . tanh(1.2345) . "\n";
echo "is_finite\n";
if (is_finite(1)) {
    echo "works.";
}
if (is_finite(log(0))) {
    echo " broken";
}
if (is_finite(sqrt(-1))) {
    echo " brokener";
}
echo "\n";
echo "is_infinite\n";
if (is_infinite(1)) {
    echo "broken.";
}
if (is_infinite(log(0))) {
    echo " works";
}
if (is_infinite(sqrt(-1))) {
    echo " brokener";
}
echo "\n";
echo "is_nan\n";
Пример #26
0
 /**
  * @param number $value
  *
  * @return bool
  */
 public static function isInfinite($value)
 {
     return !is_finite($value);
 }
Пример #27
0
 /**
  * Initializes the list of default validation rules.
  *
  * @return void
  */
 public static function __init()
 {
     $alnum = '[A-Fa-f0-9]';
     $class = get_called_class();
     static::$_methodFilters[$class] = array();
     static::$_rules = array('alphaNumeric' => '/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{Lt}\\p{Lu}\\p{Nd}]+$/mu', 'blank' => '/[^\\s]/', 'creditCard' => array('amex' => '/^3[4|7]\\d{13}$/', 'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/', 'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/', 'disc' => '/^(?:6011|650\\d)\\d{12}$/', 'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/', 'enroute' => '/^2(?:014|149)\\d{11}$/', 'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/', 'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/', 'mc' => '/^5[1-5]\\d{14}$/', 'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/', 'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})' . '\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4]' . '[0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/', 'visa' => '/^4\\d{12}(\\d{3})?$/', 'voyager' => '/^8699[0-9]{11}$/', 'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3' . '(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'), 'date' => array('dmy' => '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)' . '(\\/|-|\\.|\\x20)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?' . '\\d{2})$|^(?:29(\\/|-|\\.|\\x20)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?' . '(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])' . '00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.|\\x20)(?:(?:0?[1-9])|' . '(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%', 'mdy' => '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|' . '1[0-2])(\\/|-|\\.|\\x20)(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d' . '{2})$|^(?:0?2(\\/|-|\\.|\\x20)29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?' . '(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])' . '00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\\/|-|\\.|\\x20)(?:0?[1-9]|1' . '\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%', 'ymd' => '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579]' . '[26])|(?:(?:16|[2468][048]|[3579][26])00)))(\\/|-|\\.|\\x20)' . '(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})(\\/|-|\\.|' . '\\x20)(?:(?:(?:0?[13578]|1[02])\\2(?:31))|(?:(?:0?[1,3-9]|1[0-2])' . '\\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\\2(?:0?[1-9]|1\\d|2[0-8]' . '))))$%', 'dMy' => '/^((31(?!\\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\\b|t)t?|Nov)' . '(ember)?)))|((30|29)(?!\\ Feb(ruary)?))|(29(?=\\ Feb(ruary)?\\ ' . '(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468]' . '[048]|[3579][26])00)))))|(0?[1-9])|1\\d|2[0-8])\\ (Jan(uary)?|' . 'Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|' . 'Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]|[2-9]' . '\\d)\\d{2})$/', 'Mdy' => '/^(?:(((Jan(uary)?|Ma(r(ch)?|y)|Jul(y)?|Aug(ust)?|Oct(ober)?' . '|Dec(ember)?)\\ 31)|((Jan(uary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)' . '|(ne?))|Aug(ust)?|Oct(ober)?|(Sept|Nov|Dec)(ember)?)\\ (0?[1-9]' . '|([12]\\d)|30))|(Feb(ruary)?\\ (0?[1-9]|1\\d|2[0-8]|(29(?=,?\\ ' . '((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468]' . '[048]|[3579][26])00)))))))\\,?\\ ((1[6-9]|[2-9]\\d)\\d{2}))$/', 'My' => '%^(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|' . 'Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)[ /]((1[6-9]' . '|[2-9]\\d)\\d{2})$%', 'my' => '%^(((0[123456789]|10|11|12)([- /.])(([1][9][0-9][0-9])|([2][0-9]' . '[0-9][0-9]))))$%'), 'ip' => function ($value, $format = null, array $options = array()) {
         $options += array('flags' => array());
         return (bool) filter_var($value, FILTER_VALIDATE_IP, $options);
     }, 'money' => array('right' => '/^(?!0,?\\d)(?:\\d{1,3}(?:([, .])\\d{3})?(?:\\1\\d{3})*|(?:\\d+))' . '((?!\\1)[,.]\\d{2})?(?<!\\x{00a2})\\p{Sc}?$/u', 'left' => '/^(?!\\x{00a2})\\p{Sc}?(?!0,?\\d)(?:\\d{1,3}(?:([, .])\\d{3})?' . '(?:\\1\\d{3})*|(?:\\d+))((?!\\1)[,.]\\d{2})?$/u'), 'notEmpty' => '/[^\\s]+/m', 'phone' => '/^\\+?[0-9\\(\\)\\-]{10,20}$/', 'postalCode' => '/(^|\\A\\b)[A-Z0-9\\s\\-]{5,}($|\\b\\z)/i', 'regex' => '/^(?:([^[:alpha:]\\\\{<\\[\\(])(.+)(?:\\1))|(?:{(.+)})|(?:<(.+)>)|' . '(?:\\[(.+)\\])|(?:\\((.+)\\))[gimsxu]*$/', 'time' => '%^((0?[1-9]|1[012])(:[0-5]\\d){0,2}([AP]M|[ap]m))$|^([01]\\d|2[0-3])' . '(:[0-5]\\d){0,2}$%', 'boolean' => function ($value) {
         $bool = is_bool($value);
         $filter = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
         return $bool || $filter !== null || empty($value);
     }, 'decimal' => function ($value, $format = null, array $options = array()) {
         if (isset($options['precision'])) {
             $precision = strlen($value) - strrpos($value, '.') - 1;
             if ($precision !== (int) $options['precision']) {
                 return false;
             }
         }
         return filter_var($value, FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE) !== null;
     }, 'inList' => function ($value, $format, $options) {
         $options += array('list' => array());
         return in_array($value, $options['list']);
     }, 'lengthBetween' => function ($value, $format, $options) {
         $length = strlen($value);
         $options += array('min' => 1, 'max' => 255);
         return $length >= $options['min'] && $length <= $options['max'];
     }, 'luhn' => function ($value) {
         if (empty($value) || !is_string($value)) {
             return false;
         }
         $sum = 0;
         $length = strlen($value);
         for ($position = 1 - $length % 2; $position < $length; $position += 2) {
             $sum += $value[$position];
         }
         for ($position = $length % 2; $position < $length; $position += 2) {
             $number = $value[$position] * 2;
             $sum += $number < 10 ? $number : $number - 9;
         }
         return $sum % 10 == 0;
     }, 'numeric' => function ($value) {
         return is_numeric($value);
     }, 'inRange' => function ($value, $format, $options) {
         $defaults = array('upper' => null, 'lower' => null);
         $options += $defaults;
         if (!is_numeric($value)) {
             return false;
         }
         switch (true) {
             case !is_null($options['upper']) && !is_null($options['lower']):
                 return $value > $options['lower'] && $value < $options['upper'];
             case !is_null($options['upper']):
                 return $value < $options['upper'];
             case !is_null($options['lower']):
                 return $value > $options['lower'];
         }
         return is_finite($value);
     }, 'uuid' => "/^{$alnum}{8}-{$alnum}{4}-{$alnum}{4}-{$alnum}{4}-{$alnum}{12}\$/", 'email' => function ($value) {
         return filter_var($value, FILTER_VALIDATE_EMAIL);
     }, 'url' => function ($value, $format = null, array $options = array()) {
         $options += array('flags' => array());
         return (bool) filter_var($value, FILTER_VALIDATE_URL, $options);
     });
     $isEmpty = function ($self, $params, $chain) {
         extract($params);
         return empty($value) && $value != '0' ? false : $chain->next($self, $params, $chain);
     };
     static::$_methodFilters[$class]['alphaNumeric'] = array($isEmpty);
     static::$_methodFilters[$class]['notEmpty'] = array($isEmpty);
     static::$_methodFilters[$class]['creditCard'] = array(function ($self, $params, $chain) {
         extract($params);
         $options += array('deep' => false);
         if (strlen($value = str_replace(array('-', ' '), '', $value)) < 13) {
             return false;
         }
         if (!$chain->next($self, compact('value') + $params, $chain)) {
             return false;
         }
         return $options['deep'] ? Validator::isLuhn($value) : true;
     });
     static::$_methodFilters[$class]['email'] = array(function ($self, $params, $chain) {
         extract($params);
         $defaults = array('deep' => false);
         $options += $defaults;
         if (!$chain->next($self, $params, $chain)) {
             return false;
         }
         if (!$options['deep']) {
             return true;
         }
         list($prefix, $host) = explode('@', $params['value']);
         if (getmxrr($host, $mxhosts)) {
             return is_array($mxhosts);
         }
         return false;
     });
 }
Пример #28
0
 /**
  * Validate that a number is in specified range.
  * if $lower and $upper are not set, will return true if
  * $check is a legal finite on this platform
  *
  * @param string $check Value to check
  * @param integer $lower Lower limit
  * @param integer $upper Upper limit
  * @return boolean Success
  * @access public
  */
 function range($check, $lower = null, $upper = null)
 {
     if (!is_numeric($check)) {
         return false;
     }
     if (isset($lower) && isset($upper)) {
         if ($lower > $upper) {
             return false;
         }
         if ($check > $lower && $check < $upper) {
             return true;
         }
     } elseif (is_finite($check)) {
         return true;
     }
     return false;
 }
Пример #29
0
 /**
  * XNPV
  *
  * Returns the net present value for a schedule of cash flows that is not necessarily periodic.
  * To calculate the net present value for a series of cash flows that is periodic, use the NPV function.
  *
  * Excel Function:
  *		=XNPV(rate,values,dates)
  *
  * @param	float			$rate		The discount rate to apply to the cash flows.
  * @param	array of float	$values		A series of cash flows that corresponds to a schedule of payments in dates. The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment. If the first value is a cost or payment, it must be a negative value. All succeeding payments are discounted based on a 365-day year. The series of values must contain at least one positive value and one negative value.
  * @param	array of mixed	$dates		A schedule of payment dates that corresponds to the cash flow payments. The first payment date indicates the beginning of the schedule of payments. All other dates must be later than this date, but they may occur in any order.
  * @return	float
  */
 public static function XNPV($rate, $values, $dates)
 {
     $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
     if (!is_numeric($rate)) {
         return PHPExcel_Calculation_Functions::VALUE();
     }
     if (!is_array($values) || !is_array($dates)) {
         return PHPExcel_Calculation_Functions::VALUE();
     }
     $values = PHPExcel_Calculation_Functions::flattenArray($values);
     $dates = PHPExcel_Calculation_Functions::flattenArray($dates);
     $valCount = count($values);
     if ($valCount != count($dates)) {
         return PHPExcel_Calculation_Functions::NaN();
     }
     if (min($values) > 0 || max($values) < 0) {
         return PHPExcel_Calculation_Functions::VALUE();
     }
     $xnpv = 0.0;
     for ($i = 0; $i < $valCount; ++$i) {
         if (!is_numeric($values[$i])) {
             return PHPExcel_Calculation_Functions::VALUE();
         }
         $xnpv += $values[$i] / pow(1 + $rate, PHPExcel_Calculation_DateTime::DATEDIF($dates[0], $dates[$i], 'd') / 365);
     }
     return is_finite($xnpv) ? $xnpv : PHPExcel_Calculation_Functions::VALUE();
 }
Пример #30
0
 /**
  * Finds whether a value is a legal finite number.
  * @link http://php.net/manual/en/function.is-finite.php
  * @param float $number <p>The value to check</p>
  * @return bool true if <i>number</i> is a legal finite
  * number within the allowed range for a PHP float on this platform,
  * else false.
  */
 public static function isFinite($number)
 {
     return is_finite($number);
 }