Beispiel #1
1
 /**
  * Get human readable file size, quick and dirty.
  * 
  * @todo Improve i18n support.
  *
  * @param int $bytes
  * @param string $format
  * @param int|null $decimal_places
  * @return string Human readable string with file size.
  */
 public static function humanReadableBytes($bytes, $format = "en", $decimal_places = null)
 {
     switch ($format) {
         case "sv":
             $dec_separator = ",";
             $thousands_separator = " ";
             break;
         default:
         case "en":
             $dec_separator = ".";
             $thousands_separator = ",";
             break;
     }
     $b = (int) $bytes;
     $s = array('B', 'kB', 'MB', 'GB', 'TB');
     if ($b <= 0) {
         return "0 " . $s[0];
     }
     $con = 1024;
     $e = (int) log($b, $con);
     $e = min($e, count($s) - 1);
     $v = $b / pow($con, $e);
     if ($decimal_places === null) {
         $decimal_places = max(0, 2 - (int) log($v, 10));
     }
     return number_format($v, !$e ? 0 : $decimal_places, $dec_separator, $thousands_separator) . ' ' . $s[$e];
 }
Beispiel #2
0
 /**
  * Get Local routes
  * @return array Array of routes
  */
 public function getRoutes()
 {
     // Return a list of routes the machine knows about.
     $route = fpbx_which('route');
     if (empty($route)) {
         return array();
     }
     exec("{$route} -nv", $output, $retcode);
     if ($retcode != 0 || empty($output)) {
         return array();
     }
     // Drop the first two lines, which are just headers..
     array_shift($output);
     array_shift($output);
     // Now loop through whatever's left
     $routes = array();
     foreach ($output as $line) {
         $arr = preg_split('/\\s+/', $line);
         if (count($arr) < 3) {
             //some strange value we dont understand
             continue;
         }
         if ($arr[2] == "0.0.0.0" || $arr[2] == "255.255.255.255") {
             // Don't care about default or host routes
             continue;
         }
         if (substr($arr[0], 0, 7) == "169.254") {
             // Ignore ipv4 link-local addresses. See RFC3927
             continue;
         }
         $cidr = 32 - log((ip2long($arr[2]) ^ 4294967295.0) + 1, 2);
         $routes[] = array($arr[0], $cidr);
     }
     return $routes;
 }
Beispiel #3
0
function filesize_formatted($path)
{
    $size = filesize($path);
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $power = $size > 0 ? floor(log($size, 1024)) : 0;
    return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}
Beispiel #4
0
 /**
  * Format a filesize
  *
  * @param int $size In bytes
  * @return string
  */
 public function fileSize($size)
 {
     if (!$size) {
         return '0 ' . $this->_sizes[0];
     }
     return round($size / pow(1024, $i = floor(log($size, 1024))), $i > 1 ? 2 : 0) . ' ' . $this->_sizes[$i];
 }
Beispiel #5
0
 public function classify($string)
 {
     if ($this->total_samples === 0) {
         return array();
     }
     $tokens = $this->tokenizer->tokenize($string);
     $total_score = 0;
     $scores = array();
     foreach ($this->subjects as $subject => $subject_data) {
         $subject_data['prior_value'] = log($subject_data['count_samples'] / $this->total_samples);
         $this->subjects[$subject] = $subject_data;
         $scores[$subject] = 0;
         foreach ($tokens as $token) {
             $count = isset($this->tokens[$token][$subject]) ? $this->tokens[$token][$subject] : 0;
             $scores[$subject] += log(($count + 1) / ($subject_data['count_tokens'] + $this->total_tokens));
         }
         $scores[$subject] = $subject_data['prior_value'] + $scores[$subject];
         $total_score += $scores[$subject];
     }
     $min = min($scores);
     $sum = 0;
     foreach ($scores as $subject => $score) {
         $scores[$subject] = exp($score - $min);
         $sum += $scores[$subject];
     }
     $total = 1 / $sum;
     foreach ($scores as $subject => $score) {
         $scores[$subject] = $score * $total;
     }
     arsort($scores);
     $max = max($scores);
     $maxs = array_search(max($scores), $scores);
     return $maxs;
 }
 /**
  * @throws RegressionException
  */
 public function calculate()
 {
     if ($this->sourceSequence === null) {
         throw new RegressionException('The input sequence is not set');
     }
     if (count($this->sourceSequence) < $this->dimension) {
         throw new RegressionException(sprintf('The dimension of the sequence of at least %s', $this->dimension));
     }
     $k = 0;
     foreach ($this->sourceSequence as $k => $v) {
         if ($v[1] !== null) {
             $this->sumIndex[0] += log($v[0]);
             $this->sumIndex[1] += log($v[0]) * log($v[1]);
             $this->sumIndex[2] += log($v[1]);
             $this->sumIndex[3] += pow(log($v[0]), 2);
         }
     }
     $k += 1;
     $B = ($k * $this->sumIndex[1] - $this->sumIndex[2] * $this->sumIndex[0]) / ($k * $this->sumIndex[3] - $this->sumIndex[0] * $this->sumIndex[0]);
     $A = exp(($this->sumIndex[2] - $B * $this->sumIndex[0]) / $k);
     foreach ($this->sourceSequence as $i => $val) {
         $coordinate = [$val[0], $A * pow($val[0], $B)];
         $this->resultSequence[] = $coordinate;
     }
     $this->equation = sprintf('y = %s + x^%s', round($A, 2), round($B, 2));
     $this->push();
 }
Beispiel #7
0
 /**
  * Return the literal size of $bytes with the appropriate suffix (bytes, KB, MB, GB)
  *
  * @param integer $bytes
  * @return string
  */
 public static function getLiteralSizeFormat($bytes)
 {
     if (!$bytes) {
         return false;
     }
     $exp = floor(log($bytes, 1024));
     switch ($exp) {
         case 0:
             // bytes
             $suffix = ' bytes';
             break;
         case 1:
             // KB
             $suffix = ' KB';
             break;
         case 2:
             // MB
             $suffix = ' MB';
             break;
         case 3:
             // GB
             $suffix = ' GB';
             break;
     }
     return round($bytes / pow(1024, $exp), 1) . $suffix;
 }
function numbersFormatting($bytes)
{
    $si_prefix = array('B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB');
    $base = 1024;
    $class = min((int) log($bytes, $base), count($si_prefix) - 1);
    return sprintf('%1.2f', $bytes / pow($base, $class)) . ' ' . $si_prefix[$class];
}
Beispiel #9
0
	/**
	 * Converts bytes to more distinguishable formats such as:
	 * kilobytes, megabytes, etc.
	 *
	 * By default, the proper format will automatically be chosen.
	 * However, one of the allowed unit types may also be used instead.
	 *
	 * @param   integer  $bytes      The number of bytes.
	 * @param   string   $unit       The type of unit to return.
	 * @param   integer  $precision  The number of digits to be used after the decimal place.
	 *
	 * @return  string   The number of bytes in the proper units.
	 *
	 * @since   11.1
	 */
	public static function bytes($bytes, $unit = 'auto', $precision = 2)
	{
		$bytes = (int) $bytes;
		$precision = (int) $precision;

		if (empty($bytes))
		{
			return 0;
		}

		$unitTypes = array('b', 'kb', 'MB', 'GB', 'TB', 'PB');

		// Default automatic method.
		$i = floor(log($bytes, 1024));

		// User supplied method:
		if ($unit !== 'auto' && in_array($unit, $unitTypes))
		{
			$i = array_search($unit, $unitTypes, true);
		}

		// TODO Allow conversion of units where $bytes = '32M'.

		return round($bytes / pow(1024, $i), $precision) . ' ' . $unitTypes[$i];
	}
Beispiel #10
0
 function formatBytes($size, $precision = 2)
 {
     //TODO: Scegliere se visualizzare in base binaria o decimale.
     $base = log($size) / log(1024);
     $suffixes = array(' B', ' KiB', ' MiB', ' GiB', ' TiB');
     return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
 }
Beispiel #11
0
 public function saveMenuCache()
 {
     try {
         //$defaultStoreId = Mage::app()->getWebsite()->getDefaultGroup()->getDefaultStoreId();
         //Mage::app()->setCurrentStore($defaultStoreId);
         //Mage::getSingleton('core/session', array('name'=>'frontend'));
         //$_layout  = Mage::getSingleton('core/layout');
         //$_block  =	$_layout->createBlock('page/html_topmenu')/*->setTemplate('page/html/topmenu.phtml')*/;
         //$html=$_block->getHtml();
         Mage::app()->loadArea('frontend');
         $layout = Mage::getSingleton('core/layout');
         //load default xml layout handle and generate blocks
         $layout->getUpdate()->load('default');
         $layout->generateXml()->generateBlocks();
         //get the loaded head and header blocks and output
         $headerBlock = $layout->getBlock('header');
         $html = $headerBlock->toHtml();
         $filename = dirname(Mage::getRoot()) . DS . 'media' . DS . 'wp' . DS . 'topmenu';
         file_put_contents($filename, $html);
         //Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
         //Mage::getSingleton('core/session', array('name'=>'admintml'));
     } catch (Exception $e) {
         Mage:
         log($e->getMessage(), null, 'wp_menu_error.log');
     }
 }
function populateParagraphTFs()
{
    $query = "SELECT * from paragraph;";
    $result = mysql_query($query);
    $N = mysql_num_rows($result);
    while ($row = mysql_fetch_array($result)) {
        echo $row['id'];
        $query = "SELECT paragraph_id, COUNT(word_id) as count, word_id FROM sentence, sentence_xref_word WHERE sentence.id = sentence_id AND paragraph_id = " . $row['id'] . " GROUP BY word_id;";
        $counts = mysql_query($query);
        while ($count = mysql_fetch_array($counts)) {
            $query = "SELECT paragraph_frequency, word from word_idf WHERE word_id = " . $count['word_id'] . ";";
            $df = mysql_query($query);
            $df = mysql_fetch_array($df);
            $word = mysql_real_escape_string($df['word']);
            $df = $df['paragraph_frequency'];
            if ($df) {
                $idf = log($N / $df);
                $tf_idf = $count['count'] * $idf;
                $query = "INSERT INTO paragraph_tf (paragraph_id, word_id, tf, tf_idf, word) VALUES (" . $row['id'] . ", " . $count['word_id'] . ", " . $count['count'] . ", " . $tf_idf . ",'" . $word . "');";
                mysql_query($query) or die("<b>A fatal MySQL error occured</b>.\n\t\t\t\t\t<br/> Query: " . $query . "\n\t\t\t\t\t<br/> Error: (" . mysql_errno() . ") " . mysql_error());
            }
        }
        echo "\n";
    }
}
 public function approximate()
 {
     $correlation = $this->getCorrelation();
     $step = $this->getStep();
     $this->_tau = 0;
     for ($i = 0; $i < count($correlation); $i++) {
         if ($correlation[$i] < 0) {
             $p1 = new Model_Coordinate($step * ($i - 1), $correlation[$i - 1]);
             $p2 = new Model_Coordinate($step * $i, $correlation[$i]);
             $k = ($p2->getY() - $p1->getY()) / ($p2->getX() - $p1->getX());
             $b = $p2->getY() - $k * $p2->getX();
             $this->_tau = -$b / $k;
             break;
         }
     }
     $this->_beta = pi() / (2 * $this->_tau);
     $s1 = 0;
     $s2 = 0;
     for ($i = 0; $i * $step < $this->_tau; $i++) {
         $tau = $i * $step;
         $ro_tau = $correlation[$i];
         $s1 += abs($tau * log($ro_tau / cos($this->_beta * $tau)));
         $s2 += $tau * $tau;
     }
     if ($this->_tau < $step) {
         $this->_alpha = 1;
     } else {
         $this->_alpha = $s1 / $s2;
     }
 }
Beispiel #14
0
function _DEBUG($b_valAll = 0, $s_msgtype = 'both|con|ech|printr|vardump', $s_msg = '', $s_default = '')
{
    if ($b_valAll === 1 && $s_msgtype != '') {
        if ($s_msgtype === 'both') {
            echo '<br />===DEBUG===<br />' . $s_msg . '<br />===DEBUG===<br />';
            console . log($s_msg) . '<br />';
        } else {
            if ($s_msgtype === 'ech') {
                echo '<br />===DEBUG===<br />' . $s_msg . '<br />===DEBUG===<br />';
            } else {
                if ($s_msgtype === 'con') {
                    '<br />===DEBUG===<br />' . console . log($s_msg) . '<br />===DEBUG===<br />';
                } else {
                    if ($s_msgtype === 'printr') {
                        '<br />===DEBUG===<br />' . print_r($s_msg) . '<br />===DEBUG===<br />';
                    } else {
                        if ($s_msgtype === 'vardump') {
                            '<br />===DEBUG===<br />' . var_dump($s_msg) . '<br />===DEBUG===<br />';
                        }
                    }
                }
            }
        }
    } else {
        if ($b_valAll === 0 && $s_msgtype != '') {
            echo $s_default;
        }
    }
}
Beispiel #15
0
 public static function getRounds($tour_id)
 {
     global $conn;
     $sql = "SELECT team_count,tournament_type as tour_type from event_tournament WHERE id=:tour_id";
     $sth = $conn->prepare($sql);
     $sth->bindValue('tour_id', $tour_id);
     try {
         $sth->execute();
     } catch (Exception $e) {
     }
     $result = $sth->fetchAll(PDO::FETCH_ASSOC);
     $team_count = $result[0]['team_count'];
     $tour_type = $result[0]['tour_type'];
     /*if($team_count>2 && $team_count<=4)
     		$rounds=2;
     	elseif($team_count>4 && $team_count<=8)
     		$rounds=3;
     	elseif ($team_count>8 && $team_count<=16)
     		$rounds=4;
     	elseif ($team_count>16 && $team_count<=32)
     		$rounds=5;
     	else
     		$rounds=6;*/
     if ($tour_type == 1) {
         $rounds = ceil(log($team_count, 2));
     } else {
         $rounds = ceil(log($team_count, 2)) + ceil(log(log($team_count, 2), 2));
     }
     return $rounds;
 }
Beispiel #16
0
 protected function _parse(&$variable)
 {
     if (!is_string($variable) || !preg_match('[0\\.[0-9]{8} [0-9]{10}]', $variable)) {
         return false;
     }
     list($usec, $sec) = explode(" ", $variable);
     $time = (double) $usec + (double) $sec;
     if (KINT_PHP53) {
         $size = memory_get_usage(true);
     }
     # '@' is used to prevent the dreaded timezone not set error
     $this->value = @date('Y-m-d H:i:s', $sec) . '.' . substr($usec, 2, 4);
     $numberOfCalls = count(self::$_times);
     if ($numberOfCalls > 0) {
         # meh, faster than count($times) > 1
         $lap = $time - end(self::$_times);
         self::$_laps[] = $lap;
         $this->value .= "\n<b>SINCE LAST CALL:</b> <b class=\"kint-microtime\">" . round($lap, 4) . '</b>s.';
         if ($numberOfCalls > 1) {
             $this->value .= "\n<b>SINCE START:</b> " . round($time - self::$_times[0], 4) . 's.';
             $this->value .= "\n<b>AVERAGE DURATION:</b> " . round(array_sum(self::$_laps) / $numberOfCalls, 4) . 's.';
         }
     }
     $unit = array('B', 'KB', 'MB', 'GB', 'TB');
     if (KINT_PHP53) {
         $this->value .= "\n<b>MEMORY USAGE:</b> " . $size . " bytes (" . round($size / pow(1024, $i = floor(log($size, 1024))), 3) . ' ' . $unit[$i] . ")";
     }
     self::$_times[] = $time;
     $this->type = 'Stats';
 }
 /**
  * Prosty "algorytm" do generowania rankingu danego wpisu na podstawie ocen i czasu dodania
  *
  * @param $votes
  * @param $bonus
  * @param $timestamp
  * @return int
  */
 public static function getScore($votes, $bonus, $timestamp)
 {
     $log = $votes || $bonus ? log($votes + $bonus, 2) : 0;
     // magia dzieje sie tutaj :) ustalanie "mocy" danego wpisu. na tej podstawie wyswietlane
     // sa wpisy na stronie glownej. liczba glosow swiadczy o ich popularnosci
     return (int) ($log + $timestamp / 45000);
 }
Beispiel #18
0
 /**
  * Строит логарифмическое облако - расчитывает значение size в зависимости от count
  * У объектов в коллекции обязательно должны быть методы getCount() и setSize()
  *
  * @param array $aCollection   Список тегов
  * @param int  $iMinSize       Минимальный размер
  * @param int  $iMaxSize       Максимальный размер
  *
  * @return array
  */
 public function MakeCloud($aCollection, $iMinSize = 1, $iMaxSize = 10)
 {
     if (count($aCollection)) {
         $iSizeRange = $iMaxSize - $iMinSize;
         $iMin = 10000;
         $iMax = 0;
         foreach ($aCollection as $oObject) {
             if ($iMax < $oObject->getCount()) {
                 $iMax = $oObject->getCount();
             }
             if ($iMin > $oObject->getCount()) {
                 $iMin = $oObject->getCount();
             }
         }
         $iMinCount = log($iMin + 1);
         $iMaxCount = log($iMax + 1);
         $iCountRange = $iMaxCount - $iMinCount;
         if ($iCountRange == 0) {
             $iCountRange = 1;
         }
         foreach ($aCollection as $oObject) {
             $iTagSize = $iMinSize + (log($oObject->getCount() + 1) - $iMinCount) * ($iSizeRange / $iCountRange);
             $oObject->setSize(round($iTagSize));
         }
     }
     return $aCollection;
 }
Beispiel #19
0
 public static function getInteger($min = 0, $max = 0x7fffffff)
 {
     $bytes_required = min(4, ceil(log($max - $min, 2) / 8) + 1);
     $bytes = self::getBinary($bytes_required);
     $offset = abs(hexdec(bin2hex($bytes)) % ($max - $min + 1));
     return intval($min + $offset);
 }
/**
 * Smarty replace modifier plugin
 * 
 * Type:     modifier<br>
 * Name:     filesize<br>
 * Purpose:  show the filesize of a file in kb, mb, gb etc...
 * 
 * @param string $ 
 * @return string 
*/
function smarty_modifier_filesize($size)
{
    $size = max(0, (int) $size);
    $units = array('بایت', 'کیلوبایت', 'مگابایت', 'گیگابایت', 'ترابایت', 'پتابایت', 'اتابایت', 'زتابایت', 'یتابایت');
    $power = $size > 0 ? floor(log($size, 1024)) : 0;
    return number_format($size / pow(1024, $power), 2, '.', ',') . $units[$power];
}
Beispiel #21
0
function geoToPixel($lat, $lon, $zoomLevel)
{
    $mapSize = TILE_SIZE << $zoomLevel;
    $latitude = min(1, max(0, 0.5 - log(tan(M_PI / 4 + M_PI / 2 * $lat / 180)) / M_PI / 2));
    $longitude = $lon / 360 + 0.5;
    return array("x" => intval($longitude * $mapSize), "y" => intval($latitude * $mapSize));
}
Beispiel #22
0
 public function calcWeight()
 {
     $tags = $this->doctrine->getRepository('AppBundle:Tag')->findAllTags();
     $tagWeights = array();
     foreach ($tags as $tag) {
         $tagWeights[] = array('tag' => $tag->getTitle(), 'count' => count($tag->getArticles()));
     }
     $threshold = 0;
     $maxsize = 10;
     $minsize = 1;
     $counts = $tagcount = $tagcloud = array();
     foreach ($tagWeights as $tag) {
         if ($tag['count'] >= $threshold) {
             $counts[] = $tag['count'];
             $tagcount += array($tag['tag'] => $tag['count']);
         }
     }
     $maxcount = max($counts);
     $mincount = min($counts);
     $constant = log($maxcount - ($mincount - 1)) / ($maxsize - $minsize == 0 ? 1 : $maxsize - $minsize);
     foreach ($tagcount as $tag => $count) {
         $size = log($count - ($mincount - 1)) / $constant + $minsize;
         $tagcloud[] = array('tag' => $tag, 'count' => $count, 'size' => round($size));
     }
     return $tagcloud;
 }
Beispiel #23
0
    function freeStorage()
    {
        $bytes = disk_free_space(".");
        $si_prefix = array('B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB');
        $base = 1024;
        $class = min((int) log($bytes, $base), count($si_prefix) - 1);
        $free = sprintf('%1.2f', $bytes / pow($base, $class));
        $bytes = disk_total_space(".");
        $si_prefix = array('B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB');
        $base = 1024;
        $class = min((int) log($bytes, $base), count($si_prefix) - 1);
        $total = sprintf('%1.2f', $bytes / pow($base, $class));
        $used = $total - $free;
        $percentage = round($used / $total * 100);
        if ($percentage > '80') {
            echo '
				<div style="float:left"><img src="app/images/sd.png" align="middle"> SD Card <font color="red"> (Warning)</font>:
				<br/><br/><div class="graph"><strong class="barGreen" style="width:' . $percentage . '%;">' . $percentage . '%</strong></div> &nbsp; &nbsp;  <div class="clear"></div>; ';
        } else {
            echo '
				 <div style="float:left"><img src="app/images/sd.png" align="middle"> SD Card <font color="green"> (OK)</font>:
				 <br/><div class="graph"><strong class="barGreen" style="width:' . $percentage . '%;">' . $percentage . '%</strong></div> &nbsp; &nbsp;  <div class="clear"></div>';
        }
        echo "<br/>Total: <strong>" . $total . "</strong> GB &middot ";
        echo "Free: <strong>" . $free . "</strong> GB";
        echo "</div>";
    }
 public function parseQuery($query)
 {
     parse_str($query, $args);
     if (isset($args['transparent'])) {
         $this->transparent = $args['transparent'] == 'true';
     }
     if (isset($args['format'])) {
         $this->imageFormat = $args['format'];
     }
     if (isset($args['size'])) {
         $sizeParts = explode(',', $args['size']);
         $this->imageWidth = $sizeParts[0];
         $this->imageHeight = $sizeParts[1];
     }
     if (isset($args['imageSR'])) {
         $this->setMapProjection($args['imageSR']);
     }
     if (isset($args['bbox'])) {
         list($xmin, $ymin, $xmax, $ymax) = explode(',', $args['bbox']);
         $zoom = log($this->globeWidth() / ($xmax - $xmin), 2);
         $northeast = array('lat' => $ymax, 'lon' => $xmax);
         $southwest = array('lat' => $ymin, 'lon' => $xmin);
         if ($this->mapProjector) {
             $northeast = $this->mapProjector->reverseProject($northeast);
             $southwest = $this->mapProjector->reverseProject($southwest);
         }
         $this->setBoundingBox($southwest['lon'], $southwest['lat'], $northeast['lon'], $northeast['lat']);
     }
     // TODO read layerDefs and layers
 }
 static function latLonToMeters($lat, $lng)
 {
     $mx = $lng * self::originShift() / 180;
     $my = log(tan((90 + $lat) * pi() / 360.0)) / (pi() / 180);
     $my = $my * self::originShift() / 180;
     return new GoogleMapPoint($mx, $my);
 }
Beispiel #26
0
 function Generate($level)
 {
     $start = rand(4 * $level, 5 * $level) * 100;
     $end = rand(1 * $level, 3 * $level) * 100;
     $rate = rand(75, 95) / 100;
     // // Original exercise
     // $start	= 3600;
     // $end	= 900;
     // $rate	= 0.854;
     $x = (log($end) / log(10) - log($start) / log(10)) / (log($rate) / log(10));
     $correct = 2014 + ceil($x);
     $question = 'Egy $2014$ végén készült előrejelzés szerint az Indiában élő tigrisek $t$ száma az elkövetkező években (az egyes évek végén) megközelítőleg a következő összefüggés szerint alakul: $t(x) = ' . $start . ' \\cdot ' . round2($rate, 3) . '^x$, ahol $x$ a $2014$ óta eltelt évek számát jelöli. Melyik évben várható, hogy a tigrisek száma $' . $end . '$ alá csökken?';
     $page[] = 'A feladat lényegében azt kérdi, hogy melyik az az $x$, amit ha behelyettesítünk a képletbe, $' . $end . '$-' . By($end) . ' kisebb lesz az eredmény.';
     $page[] = 'Írjuk fel ezt az egyenlőtlenséget:$$' . $start . '\\cdot ' . round2($rate, 3) . '^x<' . $end . '$$';
     $page[] = 'Osszuk el mindkét oldalt $' . $start . '$-' . With($start) . ':$$' . round2($rate, 3) . '^x<\\frac{' . $end . '}{' . $start . '}$$';
     $page[] = 'Vegyük mindkét oldal $10$-es alapú logaritmusát:$$\\lg\\left(' . round2($rate, 3) . '^x\\right)<\\lg\\left(\\frac{' . $end . '}{' . $start . '}\\right)$$';
     $hints[] = $page;
     $page = [];
     $page[] = '<div class="alert alert-info"><strong>Logaritmus azonosság:</strong><br />Egy hányados logaritmusát úgy kapjuk meg, hogy a számláló logaritmusából kivonjuk a nevező logaritmusát:$$\\lg\\left(\\frac{a}{b}\\right)=\\lg a - \\lg b$$</div>';
     $page[] = 'A fenti azonosságot felhasználva írjuk a jobb oldalt:$$\\lg\\left(' . round2($rate, 3) . '^x\\right)<\\lg' . $end . '-\\lg' . $start . '$$';
     $hints[] = $page;
     $page = [];
     $page[] = '<div class="alert alert-info"><strong>Logaritmus azonosság:</strong><br />Ha egy hatványnak vesszük a logaritmusát, akkor a kitevőt a kifejezés elé írhatjuk:$$\\lg\\left(a^b\\right)=b\\cdot\\lg a$$</div>';
     $page[] = 'A fenti azonosságot felhasználva írjuk az $x$-et a bal oldali kifejezés elé:$$x\\cdot\\lg' . round2($rate, 3) . '<\\lg' . $end . '-\\lg' . $start . '$$';
     $page[] = 'Osszuk el mindkét oldalt $\\lg' . round2($rate, 3) . '$-' . With(round($rate * 1000)) . '!<div class="alert alert-danger"><b>Figyelem!</b><br />Az $1$-nél kisebb számok logaritmusa <b>negatív</b> lesz, ezért a relációs jel iránya megfordul!$$x>\\frac{\\lg' . $end . '-\\lg' . $start . '}{\\lg' . round2($rate, 3) . '}\\approx{' . round2($x) . '}$$</div>';
     $page[] = 'A fenti kifejezés azt jelenti, hogy a $2014$ után legalább $' . ceil($x) . '$ évnek kell eltelnie ahhoz, hogy a tigrisek száma $' . $end . '$ alá csökkenjen, vagyis a megoldás $2014+' . ceil($x) . '=$<span class="label label-success">$' . $correct . '$</span>.';
     $hints[] = $page;
     $solution = '$' . $correct . '$';
     return array('question' => $question, 'correct' => $correct, 'solution' => $solution, 'hints' => $hints);
 }
function compute_ratio($stimulus_word, $cooccurring_word)
{
    $result = array();
    $window_frequency_sql = "SELECT COUNT(keywords) FROM keywords_from_userinfo WHERE keywords LIKE '% " . $stimulus_word . " %' and keywords LIKE '% " . $cooccurring_word . " %';";
    $window_frequency = query_count($window_frequency_sql);
    $cooccurring_word_total_frequency_sql = "SELECT COUNT(keywords) FROM keywords_from_userinfo WHERE keywords LIKE '% " . $cooccurring_word . " %';";
    $cooccurring_word_total_frequency = query_count($cooccurring_word_total_frequency_sql);
    $residual_frequency = $cooccurring_word_total_frequency - $window_frequency;
    $total_window_size_sql = "SELECT COUNT(keywords) FROM keywords_from_userinfo WHERE keywords LIKE '% " . $stimulus_word . " %';";
    $total_window_size = query_count($total_window_size_sql);
    $residual_window_size = $total_window_size - $window_frequency;
    $total_corpus_size_sql = "SELECT COUNT(keywords) FROM keywords_from_userinfo";
    $total_corpus_size = query_count($total_corpus_size_sql);
    $residual_corpus_size = $total_corpus_size - $total_window_size - $cooccurring_word_total_frequency + $window_frequency;
    $ratio = 0;
    if ($window_frequency == 0) {
        $ratio = 0;
    } else {
        if ($residual_frequency == 0 || $residual_window_size == 0) {
            $ratio = 1000;
            // represent infinite
        } else {
            $ratio = 2 * ($window_frequency * log($window_frequency) + $residual_window_size * log($residual_window_size) + $residual_frequency * log($residual_frequency) + $residual_corpus_size * log($residual_corpus_size) + $total_corpus_size * log($total_corpus_size) - ($window_frequency + $residual_window_size) * log($window_frequency + $residual_window_size) - ($window_frequency + $residual_frequency) * log($window_frequency + $residual_frequency) - ($residual_window_size + $residual_corpus_size) * log($residual_window_size + $residual_corpus_size) - ($residual_frequency + $residual_corpus_size) * log($residual_frequency + $residual_corpus_size));
        }
    }
    $result['window_frequency'] = $window_frequency;
    $result['total_window_size'] = $total_window_size;
    $result['residual_window_size'] = $residual_window_size;
    $result['cooccurring_word_total_frequency'] = $cooccurring_word_total_frequency;
    $result['residual_frequency'] = $residual_frequency;
    $result['residual_corpus_size'] = $residual_corpus_size;
    $result['total_corpus_size'] = $total_corpus_size;
    $result['ratio'] = $ratio;
    return $result;
}
Beispiel #28
0
function get_max_zoom_level($img_wid, $img_hei, $t_wid, $t_hei)
{
    $largest_dim = $img_wid > $img_hei ? $img_wid : $img_hei;
    $t_dim = $img_wid > $img_hei ? $t_wid : $t_hei;
    $zoom_levels = ceil(log(($largest_dim + 1) / ($t_dim + 1), 2));
    return intval($zoom_levels);
}
Beispiel #29
0
 public function moveFile($destPath)
 {
     console . log($destPath);
     if (!move_uploaded_file($this->tempFileName, $destPath)) {
         throw new UploadException("uploaded file ({$this->origFileName}) could not be moved to file storage", 2009);
     }
 }
Beispiel #30
0
 /**
  *
  * @param TrainingSet $tset
  *        	The set of documents for which we will compute the idf
  * @param FeatureFactoryInterface $ff
  *        	A feature factory to translate the document data to single tokens
  */
 public function __construct(TrainingSet $tset, FeatureFactoryInterface $ff = null)
 {
     if ($ff === null) {
         $ff = new DataAsFeatures();
     }
     $tset->setAsKey(TrainingSet::CLASS_AS_KEY);
     foreach ($tset as $class => $doc) {
         $tokens = $ff->getFeatureArray($class, $doc);
         // extract tokens from the document
         $tokens = array_fill_keys($tokens, 1);
         // make them occur once
         foreach ($tokens as $token => $v) {
             if (isset($this->idf[$token])) {
                 $this->idf[$token]++;
             } else {
                 $this->idf[$token] = 1;
             }
         }
     }
     // this idf so far contains the doc frequency
     // we will now inverse it and take the log
     $D = count($tset);
     foreach ($this->idf as &$v) {
         $v = log($D / $v);
     }
     $this->logD = log($D);
 }