Exemple #1
0
// メモ化していないパーサ
$a = PEG::ref($a_ref);
$p = PEG::ref($p_ref);
$a_ref = PEG::choice(PEG::seq($p, '+', $a), PEG::seq($p, '-', $a), $p);
$p_ref = PEG::choice(PEG::seq('(', $a, ')'), '1');
$a->parse(PEG::context($str));
$t->setMarker('no memoize');
// メモ化しているパーサ
$a = PEG::ref($a_ref);
$p = PEG::ref($p_ref);
$a_ref = PEG::memo(PEG::choice(PEG::seq($p, '+', $a), PEG::seq($p, '-', $a), $p));
$p_ref = PEG::memo(PEG::choice(PEG::seq('(', $a, ')'), '1'));
$a->parse($c = PEG::context($str));
$t->setMarker('memoize');
$t->stop();
$t->display();
/* 結果
---------------------------------------------------------
marker       time index            ex time         perct   
---------------------------------------------------------
Start        1242400475.10093900   -                0.00%
---------------------------------------------------------
no memoize   1242400476.30805000   1.207111        99.74%
---------------------------------------------------------
memoize      1242400476.31115500   0.003105         0.26%
---------------------------------------------------------
Stop         1242400476.31117700   0.000022         0.00%
---------------------------------------------------------
total        -                     1.210238       100.00%
---------------------------------------------------------
 */
Exemple #2
0
    PublisherPeer::doDelete($morrow_id);
    print boolTest(true);
    print "Attempting to delete publisher [id = {$penguin_id}]: ";
    PublisherPeer::doDelete($penguin_id);
    print boolTest(true);
    print "Attempting to delete publisher [id = {$vintage_id}]: ";
    $vintage->delete();
    print boolTest(true);
    // These have to be deleted manually also since we have onDelete
    // set to SETNULL in the foreign keys in book. Is this correct?
    print "Attempting to delete author [lastname = 'Rowling']: ";
    $rowling->delete();
    print boolTest(true);
    print "Attempting to delete publisher [lastname = 'Scholastic']: ";
    $scholastic->delete();
    print boolTest(true);
    print "Attempting to delete BookClubList 1: ";
    $blc1->delete();
    print boolTest(true);
    print "Attempting to delete BookClubList 2: ";
    $blc2->delete();
    print boolTest(true);
} catch (Exception $e) {
    die("Error deleting book: " . $e->__toString());
}
// Check again to make sure that tables are empty
// ----------------------------------------------
check_tables_empty();
$timer->stop();
print $timer->display();
Exemple #3
0
 function viewUpload()
 {
     $form = new SessionUploadForm();
     $view = Core_View::factory('sessionsfileupload');
     $view->UploadStatusMsg = "";
     $view->UploadStatus = "Error";
     if ($form->validate()) {
         $timer = new Benchmark_Timer();
         $timer->start();
         $upload = $form->getSubmitValue('upload');
         $timer->setMarker('Decode Sessions - Start');
         exec('/usr/local/bin/fitdecode -s ' . $upload['tmp_name'], $xml_session);
         $xml_session = implode("\n", $xml_session);
         $sessions = parseSessions($xml_session);
         $timer->setMarker('Decode Sessions - End');
         /* There should only be one session */
         if (is_array($sessions)) {
             $session = $sessions[0];
             unset($sessions);
         }
         $db = Zend_Registry::get('db');
         $db->beginTransaction();
         try {
             $api = new Module_Sessions_API();
             /* Insert the session data into the database */
             $api->createSessionFull($session->start_time, 'E1', 'Untitled', $session->total_timer_time, $session->total_distance, $session->total_calories, $session->avg_heart_rate, $session->max_heart_rate, $session->avg_speed, $session->max_speed, $session->total_ascent, $session->total_descent, '');
             /* Find the seconds since epoch so we can do simple maths */
             $ftime = strptime($session->start_time, '%FT%T%z');
             $session_epoch = mktime($ftime['tm_hour'], $ftime['tm_min'], $ftime['tm_sec'], 1, $ftime['tm_yday'] + 1, $ftime['tm_year'] + 1900);
             $session_timestamp = $session->start_time;
             unset($session);
             unset($sessions);
             $timer->setMarker('Decode Records - Start');
             exec('/usr/local/bin/fitdecode -r ' . $upload['tmp_name'], $xml_records);
             $xml_records = implode("\n", $xml_records);
             $records_input = parseRecords($xml_records, $session_epoch);
             $timer->setMarker('Decode Records - End');
             if (is_array($records_input)) {
                 $record_prev = $records_input[0];
             }
             /* Get the array of records, removing duplicates */
             $records = array();
             foreach ($records_input as $record) {
                 if (!isset($record_last) || $record_last->interval != $record->interval) {
                     $records[] = $record;
                 }
                 $record_last = $record;
             }
             unset($records_input);
             unset($record_last);
             $UserAPI = Module_UserManagement_API::getInstance();
             $user = $UserAPI->getUser();
             /* Add the matching data points */
             foreach ($records as $record) {
                 /* Skip duplicates, they will cause issues in graphs */
                 if (!isset($record->power)) {
                     $record->power = $api->getPower($record->gradient, $record->temperature, $record->altitude, $record->speed, $record->speed - $record_prev->speed, $record->interval - $record_prev->interval, $user['rider_weight'], $user['bike_weight']);
                 }
                 $record_prev = $record;
             }
             unset($user);
             unset($UserAPI);
             $timer->setMarker('Record insertion - start');
             $api->insertAllSessionData($session_timestamp, $records);
             /* Insert all the data */
             $timer->setMarker('Record insertion - end');
             /* Calculate the climbs */
             $climbs = $api->getClimbCategories();
             $timer->setMarker('Climb - Start');
             $min_climb = $climbs[0];
             /* 500m with an average gradient of more than 3% (cat 5)*/
             /* Find the points that have a distance of 500m */
             $window_distance = 0;
             $window_altitude = 0;
             $cat = -1;
             $climb_num = 1;
             $num_records = count($records);
             $num_climbs = count($climbs);
             for ($front = 0, $back = 0; $front < $num_records; $front++) {
                 $window_distance += $records[$front]->delta_distance * 1000;
                 $window_altitude += $records[$front]->delta_altitude;
                 if ($window_distance > $min_climb['min_distance']) {
                     $window_gradient = $window_altitude / $window_distance * 100;
                     /* Check if we have found the start of a climb */
                     if ($cat == -1 && $window_gradient >= $climbs[$cat + 1]['min_gradient']) {
                         $cat++;
                         /* Go through and find the minimum height */
                         $min = $back;
                         for ($i = $back; $i < $front; $i++) {
                             if ($records[$i]->altitude <= $records[$min]->altitude) {
                                 $min = $i;
                             }
                         }
                         $climb['bottom'] = $records[$min]->interval;
                         $climb['min_altitude'] = $records[$min]->altitude;
                     }
                     /* Check if we have finished the climb */
                     if ($cat != -1 && $window_gradient < $climbs[$cat]['min_gradient']) {
                         /* Need to go back and find the maximum altitude */
                         $max = $back;
                         for ($i = $back; $i < $front; $i++) {
                             if ($records[$i]->altitude > $records[$max]->altitude) {
                                 $max = $i;
                             }
                         }
                         $climb['top'] = $records[$max]->interval;
                         $climb['max_altitude'] = $records[$max]->altitude;
                         /* Get the max gradient */
                         $climb['gradient_max'] = $records[$min]->gradient;
                         for ($i = $min; $i <= $max; $i++) {
                             if ($climb['gradient_max'] < $records[$i]->gradient) {
                                 $climb['gradient_max'] = $records[$i]->gradient;
                             }
                         }
                         /* Tally the totals */
                         $climb['total_climbed'] = 0;
                         for ($i = $min + 1; $i <= $max; $i++) {
                             $climb['total_climbed'] += $records[$i]->delta_altitude;
                         }
                         $climb['total_distance'] = round($records[$max]->distance - $records[$min]->distance, 2);
                         $climb['gradient_avg'] = round($climb['total_climbed'] / ($climb['total_distance'] * 1000) * 100, 2);
                         /* Find the category of the climb */
                         $cat = -1;
                         while ($cat + 1 < $num_climbs && $climb['gradient_avg'] >= $climbs[$cat + 1]['min_gradient'] && $climb['total_distance'] * 1000 >= $climbs[$cat + 1]['min_distance'] && $climb['total_climbed'] >= $climbs[$cat + 1]['min_height']) {
                             $cat++;
                         }
                         $climb['cat'] = $cat;
                         if ($cat != -1) {
                             /* Store it into the database */
                             $api->insertClimb($session_timestamp, $climb_num++, $climb['bottom'], $climb['top'], $climb['gradient_avg'], $climb['gradient_max'], $climb['total_distance'], $climb['total_climbed'], $climb['min_altitude'], $climb['max_altitude']);
                             /* Start search for the next climb */
                             $front = $max;
                             $back = $max;
                             $window_distance = 0;
                             $window_altitude = 0;
                         } else {
                             /* It was a false climb, either not steep enough, 
                              * too short, and the window just masked this 
                              * Keep searching for the next climb
                              */
                         }
                         $cat = -1;
                     }
                     /* Move the back of the window up */
                     while ($window_distance > $min_climb['min_distance'] && $back < $num_records) {
                         $window_distance -= $records[$back]->delta_distance * 1000;
                         $window_altitude -= $records[$back]->delta_altitude;
                         $back++;
                     }
                 }
             }
             $timer->setMarker('Climb - End');
             /*
              * Bikes
              * userid
              * name
              * description
              * type, TT or Road
              * weight
              * picture?
              * Assign a bike to an exercise session at creation time?
              */
             unset($records);
             $timer->setMarker('Laps - Start');
             exec('/usr/local/bin/fitdecode -l ' . $upload['tmp_name'], $xml_laps);
             $xml_laps = implode("\n", $xml_laps);
             $laps = parseLaps($xml_laps);
             $timer->setMarker('Laps - End');
             $lap_num = 1;
             foreach ($laps as $lap) {
                 $ftime = strptime($lap->start_time, '%FT%T%z');
                 $start_epoch = mktime($ftime['tm_hour'], $ftime['tm_min'], $ftime['tm_sec'], 1, $ftime['tm_yday'] + 1, $ftime['tm_year'] + 1900);
                 $lap_start = $start_epoch - $session_epoch;
                 $api->insertLap($session_timestamp, $lap_num, $lap_start, $lap->start_position_lat, $lap->start_position_long, $lap->total_timer_time, $lap->total_elapsed_time, $lap->total_calories, $lap->avg_heart_rate, $lap->max_heart_rate, $lap->avg_speed, $lap->max_speed, $lap->total_ascent, $lap->total_descent, $lap->total_distance);
                 $lap_num++;
             }
             //$timer->display();
             $db->commit();
             $plans = Module_Plans_API::getInstance();
             $view->planned = $plans->getClosestPlan($session_timestamp);
             $view->session_timestamp = $session_timestamp;
             $view->UploadStatusMsg = "Is this session the planned exercise session on at ere";
             $view->UploadStatus = "Success";
         } catch (Exception $e) {
             $db->rollback();
             $view->UploadStatusMsg = "Failed to upload";
             $view->UploadStatus = "Error";
             echo $e->getMessage();
         }
         $timer->display();
     }
     $view->addForm($form);
     $view->subTemplate = 'genericForm.tpl';
     echo $view->render();
 }
Exemple #4
0
                    id = 'Submit1' onclick = 'nCumulativeTime = 0; nTrips=0; xajax_roundTrip(0); return false;' />
            </p>

            <p>
                <input type = 'submit'
                    value = 'Compress' name = 'compress' id = 'compress' onclick = 'xajax_compress(); return false;' />
            </p>

            <p>
                <input type = 'submit'
                    value = 'Compile' name = 'compile' id = 'compile' onclick = 'xajax_compile(); return false;' />
            </p>
        </form>

        <div id = "submittedDiv">
        </div>

        <div id = "result">
        </div>

        <?php 
$timer->stop();
$timer->display();
if (function_exists('xdebug_get_code_coverage')) {
    var_dump(xdebug_get_code_coverage());
}
?>
    </body>
</html>

Exemple #5
0
 /**
  * Perform mySQL query and try to determine result value
  *
  * @param string $query
  * @param string $output
  * @param string $index_field    if set, the resulting array will have the value
  *                               of the $index_field as a key
  *                               (use with caution if a get_row() call will follow!)
  * @return bool|int
  */
 public function query($query, $output = OBJECT, $index_field = null)
 {
     global $MODULE_VARS;
     // Keep track of the time the query took?
     $sql_time = is_array($MODULE_VARS['default']) && array_key_exists('NC_DEBUG_SQL_TIME', $MODULE_VARS['default']) && $MODULE_VARS['default']['NC_DEBUG_SQL_TIME'];
     // Keep track of from where the method was executed?
     $sql_func = is_array($MODULE_VARS['default']) && array_key_exists('NC_DEBUG_SQL_FUNC', $MODULE_VARS['default']) && $MODULE_VARS['default']['NC_DEBUG_SQL_FUNC'];
     if ($sql_time && !class_exists('Benchmark_Timer')) {
         require_once "Benchmark/Timer.php";
     }
     if ($this->benchmark || $sql_time) {
         $timer = new Benchmark_Timer();
         $timer->start();
     }
     // For reg expressions
     $query = trim($query);
     // Initialise return
     $return_val = 0;
     $this->is_error = 0;
     $func = '';
     $this->errno = 0;
     // Flush cached values..
     $this->flush();
     // Log how the function was called
     //        $this->func_call = "\$db->query(\"$query\")";
     // Keep track of the last query for debug..
     $this->last_query = $query;
     // Perform the query via std mysql_query function..
     $this->result = @mysql_query($query, $this->dbh);
     $this->num_queries++;
     $q = ['query' => $query];
     // таймер
     if ($this->benchmark || $sql_time) {
         $timer->stop();
         if ($this->benchmark) {
             $timer->display();
         }
         $sql_time = $timer->timeElapsed();
         $q['sql_time'] = $sql_time;
     }
     if ($sql_func) {
         $backtrace = debug_backtrace();
         $func = ($backtrace[2]['class'] ? $backtrace[2]['class'] . '::' : '') . $backtrace[2]['function'];
         $q['sql_func'] = $func;
     }
     $this->queries_arr[] = $q;
     // If there is an error then take note of it..
     if ($str = @mysql_error($this->dbh)) {
         $this->register_error($str);
         $this->is_error = 1;
         $this->show_errors ? trigger_error($str, E_USER_WARNING) : null;
         $this->errno = mysql_errno();
         if ($this->debug_all || $this->trace) {
             echo "<div style='border: 2pt solid red; margin: 10px; padding:10px; font-size:13px; color:black;'><br/>\n";
             echo "Query: <b>" . $query . "</b><br/>\n";
             echo "Error: <b>" . $str . "</b><br/>\n";
             echo "</div>\n";
         }
     }
     $this->debugMessage($this->num_queries . ". " . $query, $func, $sql_time, $this->is_error ? 'error' : 'ok');
     if ($this->is_error) {
         return false;
     }
     // Query was an insert, delete, update, replace
     if (preg_match("/^(insert|delete|update|replace)\\s+/i", $query)) {
         $this->rows_affected = @mysql_affected_rows($this->dbh);
         // Take note of the insert_id
         // NB: не нужно заменять на nc_preg_match(), поскольку запрос не обязательно
         // является корректной UTF строкой - в этом случае условие не будет выполнено!
         if (preg_match("/^(insert|replace)\\s+/i", $query)) {
             $this->insert_id = @mysql_insert_id($this->dbh);
         }
         // Return number of rows affected
         $return_val = $this->rows_affected;
     } else {
         // Take note of column info
         if ($this->fill_col_info) {
             $this->col_info = array();
             $i = 0;
             while ($i < @mysql_num_fields($this->result)) {
                 $this->col_info[$i] = @mysql_fetch_field($this->result);
                 $i++;
             }
         } else {
             $this->col_info = false;
         }
         // mysql_query returns TRUE for INSERT/UPDATE/DROP queries and FALSE on error
         if (!is_bool($this->result)) {
             // Store Query Results
             $this->result_output_type = $output;
             if ($output == ARRAY_N) {
                 $fetch_function = 'mysql_fetch_row';
             } elseif ($output == ARRAY_A) {
                 $fetch_function = 'mysql_fetch_assoc';
             } else {
                 $fetch_function = 'mysql_fetch_object';
             }
             // Store results as an objects within main array
             $num_rows = 0;
             while ($row = $fetch_function($this->result)) {
                 $key = $index_field !== null ? is_array($row) ? $row[$index_field] : $row->{$index_field} : $num_rows;
                 $this->last_result[$key] = $row;
                 $num_rows++;
             }
             mysql_free_result($this->result);
             // Log number of rows the query returned
             $this->num_rows = $num_rows;
         }
         // Return number of rows selected
         $return_val = $this->num_rows;
     }
     // If debug ALL queries
     $this->trace || $this->debug_all ? $this->debug() : null;
     if (1 || $this->debug_all) {
         preg_match("/(from\\s+\\w+)/si", $query, $regs);
         $from = preg_replace("/\\s+/s", " ", $regs[1]);
         $from = preg_replace("/from /i", "FROM ", $from);
         $this->groupped_queries[$from][$this->num_queries] = $query;
     }
     if ($this->benchmark && $GLOBALS["nccttimer"] instanceof Benchmark_Timer) {
         $GLOBALS["nccttimer"]->setMarker("QRY {$this->num_queries}<br />");
     }
     return $return_val;
 }