Exemplo n.º 1
0
 function parse()
 {
     if ($this->doParseRSS) {
         require_once "include/domit_rss/timer.php";
         $timer = new Timer();
         $success = false;
         $timer->start();
         if (!defined('DOMIT_RSS_INCLUDE_PATH')) {
             define('DOMIT_RSS_INCLUDE_PATH', dirname(__FILE__) . "/");
         }
         switch ($this->rssparser) {
             case "domit_rss_lite":
                 require_once DOMIT_RSS_INCLUDE_PATH . 'xml_domit_rss_lite.php';
                 $this->rssdoc = new xml_domit_rss_document_lite($this->rssurl);
                 break;
             case "domit_rss":
                 require_once DOMIT_RSS_INCLUDE_PATH . 'xml_domit_rss.php';
                 $this->rssdoc = new xml_domit_rss_document($this->rssurl);
                 break;
         }
         // switch
         $timer->stop();
         $this->displayNew();
         echo "<br /><br />Time elapsed: " . $timer->getTime() . "seconds<br /><br />\n";
     }
 }
Exemplo n.º 2
0
 /**
  * Tests duration measuring.
  */
 public function testDuration()
 {
     $mt = microtime(true);
     $name = Timer::start();
     $delta = Timer::stop($name);
     $outerDelta = microtime(true) - $mt;
     // Measured time is greater than 0
     $this->assertGreaterThan(0, $delta);
     // Measured time is less than the time between the two function calls
     $this->assertLessThan($outerDelta, $delta);
     // Non-existent timer
     $this->assertSame(0, Timer::stop('foo'));
     // Start 4 timers
     $names = array('foo', 'bar', 'tmp', 'ohai');
     $times = array_fill_keys($names, 0);
     foreach ($names as $name) {
         Timer::start($name);
     }
     // End them in reverse order
     foreach (array_reverse($names) as $name) {
         $times[$name] = Timer::stop($name);
     }
     // The measured time is supposed to be in descending order
     foreach ($names as $i => $name) {
         $this->assertGreaterThan(0, $times[$name]);
         if ($i > 0) {
             $this->assertLessThan($times[$names[$i - 1]], $times[$name]);
         }
     }
 }
Exemplo n.º 3
0
 public function getSource($pageID)
 {
     Timer::start('LiveFromFileCollection');
     $content = file_get_contents($this->currentArticleFile);
     Timer::stop('LiveFromFileCollection');
     return $content;
 }
Exemplo n.º 4
0
 public function run()
 {
     # Only run once.
     if ($this->result !== null) {
         return $this;
     }
     # It's nice to have this as an implicit condition.
     if ($this->should_except) {
         $this->conditions[] = new Condition(function ($result) {
             return $result->exception() !== null;
         }, 'should throw exception');
     } else {
         $this->conditions[] = new Condition(function ($result) {
             return $result->exception() === null;
         }, 'should not throw exception');
     }
     ob_start();
     $value = null;
     $exception = null;
     $timer = new Timer();
     try {
         $value = call_user_func($this->closure, $this);
     } catch (\Exception $e) {
         $exception = $e;
     }
     $output = ob_get_clean();
     $this->result = new Result($value, $output, $timer->stop(), $exception);
     return $this;
 }
Exemplo n.º 5
0
 public function extractPage($pageID, $pageTitle, $pageSource)
 {
     $this->extractor->setPageURI($pageID);
     if (!$this->extractor->isActive()) {
         return $result = new ExtractionResult($pageID, $this->extractor->getLanguage(), $this->getExtractorID());
     }
     Timer::start($this->extractor->getExtractorID());
     $result = $this->extractor->extractPage($pageID, $pageTitle, $pageSource);
     Timer::stop($this->extractor->getExtractorID());
     Timer::start('validation');
     //$this->extractor->check();
     if (Options::getOption('validateExtractors')) {
         ValidateExtractionResult::validate($result, $this->extractor);
     }
     Timer::stop('validation');
     Statistics::increaseCount($this->extractor->getExtractorID(), 'created_Triples', count($result->getTriples()));
     Statistics::increaseCount('Total', 'created_Triples', count($result->getTriples()));
     if ($this->extractor->isGenerateOWLAxiomAnnotations()) {
         $triples = $result->getTriples();
         if (count($triples) > 0) {
             foreach ($triples as $triple) {
                 $triple->addDCModifiedAnnotation();
                 $triple->addExtractedByAnnotation($this->extractor->getExtractorID());
             }
         }
     }
     return $result;
 }
 private static function populateCharacters($db)
 {
     global $baseDir;
     $timer = new Timer();
     $maxTime = 65 * 1000;
     // Reset 222's that are over a week old
     $db->execute("update zz_api set errorCode = 0 where errorCode = 222 and lastValidation <= date_sub(now(), interval 7 day)");
     $apiCount = $db->queryField("select count(*) count from zz_api where errorCode not in (203, 220, 222) and lastValidation <= date_add(now(), interval 1 minute)", "count", array(), 0);
     if ($apiCount == 0) {
         return;
     }
     $fetchesPerSecond = 25;
     $iterationCount = 0;
     while ($timer->stop() < $maxTime) {
         $keyIDs = $db->query("select distinct keyID from zz_api where errorCode not in (203, 220, 222) and lastValidation < date_sub(now(), interval 2 hour)\r\n\t\t\t\t\torder by lastValidation, dateAdded desc limit 100", array(), 0);
         foreach ($keyIDs as $row) {
             if (Util::isMaintenanceMode()) {
                 return;
             }
             $keyID = $row["keyID"];
             $m = $iterationCount % $fetchesPerSecond;
             $db->execute("update zz_api set lastValidation = date_add(lastValidation, interval 5 minute) where keyID = :keyID", array(":keyID" => $keyID));
             $command = "flock -w 60 {$baseDir}/cache/locks/populate.{$m} php5 {$baseDir}/cli.php apiFetchCharacters " . escapeshellarg($keyID);
             //Log::log("$command");
             exec("{$command} >/dev/null 2>/dev/null &");
             $iterationCount++;
             if ($iterationCount % $fetchesPerSecond == 0) {
                 sleep(1);
             }
         }
         sleep(1);
     }
 }
Exemplo n.º 7
0
 public static function initResource($inifile)
 {
     //Timer::start("a");
     $arr = parse_ini_file($inifile);
     /*
     		Timer::stop("a");
     		Timer::start("b");
     		$p = new Properties();
     		$fp = fopen($inifile.'2','r');
     		$p->load($fp);
     		
     		//print_r($p->propertyNames());
     		Timer::stop("b");
     		Timer::printTime(10);
     		die();
     */
     if (!is_array($arr) || !count($arr) > 0) {
         die("core/ResourcePool : inifile " . $inifile . " not found\n");
     }
     Timer::start('ResourcePool::init::' . $class);
     $class = new ReflectionClass($arr['className']);
     $resourceInstance = $class->newInstance($arr);
     $resourceInstance->init();
     self::$resources = $resourceInstance;
     Timer::stop('ResourcePool::init::' . $class);
     //$resourceInstance
     //$resourceInstance->setStatus($status);
 }
Exemplo n.º 8
0
 public function elapsedTimeGreaterThanZeroUsingStartAndStop()
 {
     $fixture = new Timer();
     $fixture->start();
     usleep(100 * 1000);
     $fixture->stop();
     $elapsed = $fixture->elapsedTime();
     $this->assertTrue($elapsed > 0.0, 'Elapsed time should be greater than zero');
 }
Exemplo n.º 9
0
 /**
  * Add execution time to response
  *
  * @return void
  */
 public static function showExecutionTime()
 {
     $time = Timer::stop();
     if (Response::$outJson) {
         Response::add(['executionTime' => $time . 'ms']);
     } else {
         Response::add("<!-- executionTime {$time}ms -->");
     }
 }
Exemplo n.º 10
0
 /**
  * @param \CEvent $event
  * @param string $action
  */
 private function handleEnd(\CEvent $event, $action)
 {
     if ($timer = $this->popTimer($event, $action)) {
         if ($event->params) {
             Timer::dataMerge($timer, $event->params);
         }
         Timer::stop($timer);
     }
 }
Exemplo n.º 11
0
 /**
  * Triggers the ExtractionJob
  * @param $job: An ExtractionJob
  */
 public function execute($job)
 {
     $language = $job->getPageCollection()->getLanguage();
     // Initialize Extractors and Destination
     foreach (new ArrayObject($job->getExtractionGroups()) as $group) {
         $group->getDestination()->start();
         foreach (new ArrayObject($group->getExtractors()) as $extractor) {
             $extractor->start($language);
         }
     }
     $this->log(DEBUG, "extractors started");
     // Extract content from WikiPedia Pages
     // The PageTitleIterator loops over all pages from a PageCollection
     foreach ($job->getPageTitleIterator() as $pageTitle) {
         Timer::start(get_class($job->getPageCollection()) . '::getSource');
         $pageSource = $job->getPageCollection()->getSource($pageTitle);
         Timer::stop(get_class($job->getPageCollection()) . '::getSource');
         $pageID = $this->getPageID($pageTitle, $pageSource, $language);
         if ($pageID === false || $pageID == NULL) {
             continue;
         }
         $this->log(DEBUG, "begin page extraction");
         // Extract the content and pass it to the Destination
         foreach (new ArrayObject($job->getExtractionGroups()) as $group) {
             $destination = $group->getDestination();
             foreach (new ArrayObject($group->getExtractors()) as $extractor) {
                 $this->log(DEBUG, "extractPage: " . $extractor->getExtractorID());
                 $result = $extractor->extractPage($pageID, $pageTitle, $pageSource);
                 Timer::start('destination:accept');
                 $destination->accept($result);
                 Timer::stop('destination:accept');
             }
             //end foreach
         }
         //end outer foreach
     }
     // Close Destinations and Extractors
     foreach (new ArrayObject($job->getExtractionGroups()) as $group) {
         Timer::start('destination:finish');
         $group->getDestination()->finish();
         Timer::stop('destination:finish');
         // Optional MetaInformation is stored in MetaDestination
         // Currently only used for InfoboxExtraction for predicates
         $metaDestination = $group->getMetaDestination();
         if ($metaDestination != null) {
             $metaDestination->start();
             foreach (new ArrayObject($group->getExtractors()) as $extractor) {
                 $result = $extractor->finish();
                 if ($result != null) {
                     $metaDestination->accept($result);
                 }
             }
             $metaDestination->finish();
         }
     }
 }
Exemplo n.º 12
0
Arquivo: Xml.php Projeto: rajnishp/bjs
 /**
  * Try to emulate SAX type serialization, because otherwise it goes out of memory
  * @param $data
  * @param $output Sets the output to this variable
  * @param $clear_data If set, $data is cleared once serialization is done
  * @return unknown_type
  */
 function serializeLowMemory(&$data, &$output, $clear_data = false, $batch_size = 1000)
 {
     if ($this->serializer == false) {
         $serializer_options = array('addDecl' => FALSE, 'encoding' => 'ISO-8859-1', 'indent' => '  ', 'rootName' => 'item', 'defaultTagName' => 'item');
         $this->serializer = new XML_Serializer($serializer_options);
     }
     list($temp_file_name, $http) = Util::getTemporaryFile('xml-serialize', 'xml');
     $this->logger->debug("Using temporary file for XML Serialization: {$temp_file_name}");
     $fh = fopen($temp_file_name, 'w');
     fwrite($fh, "<?xml version='1.0' encoding='ISO-8859-1'?>\n<root>\n");
     if (Util::is_assoc($data)) {
         foreach ($data as $top_level_tag_key => &$data_value) {
             $first = true;
             fwrite($fh, "<{$top_level_tag_key}>\n");
             if (is_array($data_value)) {
                 $count = 0;
                 $string = "";
                 $timer = new Timer('SerializationTimer');
                 $timer->start();
                 foreach ($data_value as $second_level_key => &$second_level_value) {
                     $string .= $this->serializeXml($second_level_value) . "\n";
                     $count++;
                     if ($count % $batch_size == 0) {
                         $timer->stop();
                         fwrite($fh, $string);
                         $string = "";
                         $this->logger->debug("{$top_level_tag_key} > Serialized upto row - " . $count++ . ". Time Taken : " . $timer->getLastLapTime() . "s. Current Memory usage: " . memory_get_usage() / 1000000 . "MB");
                         $timer->start();
                     }
                     if ($first) {
                         $this->logger->debug("{$top_level_tag_key} > XML Serialization Sample Data : Key is {$second_level_key}\nValue is " . print_r($second_level_value, true));
                         $first = false;
                     }
                     //if clear data is set, clear the second level value
                     if ($clear_data) {
                         $second_level_value = false;
                     }
                     //fflush($fh);
                 }
                 //the last batch might not be complete
                 if ($string != "") {
                     $timer->stop();
                     fwrite($fh, $string);
                     $string = "";
                 }
             }
             fwrite($fh, "</{$top_level_tag_key}>\n");
             if ($clear_data) {
                 $data_value = false;
             }
         }
     }
     fwrite($fh, "\n</root>");
     fclose($fh);
     $output = file_get_contents($temp_file_name);
 }
Exemplo n.º 13
0
 public function runPlugin($input = array())
 {
     $badContent = 1;
     $goodContent = 1;
     if (!isset($input['tracerouteFailDomain'])) {
         $input['tracerouteFailDomain'] = '';
     }
     if (!isset($input['followRedirects'])) {
         $input['followRedirects'] = 1;
     }
     $input['followRedirects'] = (bool) $input['followRedirects'];
     for ($i = $input['attempts']; $i <= $input['attempts']; $i++) {
         $output = Plugin::$output;
         ///set defaults for all output
         $t = new Timer();
         $t->start();
         $output['returnContent'] = HttpContentPlugin::doHTTPGet($input['url'], $input['maxConnectTimeoutSeconds'], $input['maxRequestTimeoutSeconds'], $input['followRedirects']);
         //			echo $output['returnContent'];
         $output['responseTimeMs'] = (int) $t->stop();
         $output['measuredValue'] = $output['returnContent'];
         if (trim($input['goodContent']) != '') {
             $goodContent = strpos($output['returnContent'], $input['goodContent']) === false ? 0 : 1;
         }
         if (trim($input['badContent']) != '') {
             $badContent = strpos($output['returnContent'], $input['badContent']) === false ? 1 : 0;
         }
         //default to down
         $output['currentStatus'] = 0;
         //if its already bad, then its bad.
         if ($goodContent + $badContent == 2) {
             $output['currentStatus'] = 1;
         }
         if ($output['currentStatus'] == 1) {
             //we've got what we wanted
             break;
         } else {
             //else keep going till we do or hit max attempts
             if (isset($input['attemptWait']) && $input['attemptWait'] !== 0) {
                 usleep($input['attemptWait'] * 1000);
             }
         }
     }
     //html email
     $output['htmlEmail'] = 1;
     if ($output['currentStatus'] == 0 && $input['tracerouteFailDomain'] != '') {
         $tmpfname = tempnam("/tmp", "phpMonitorHTTPContent");
         // do here something
         $cmd = '/usr/sbin/mtr --report --report-cycles 5 ' . $input['tracerouteFailDomain'] . ' > ' . $tmpfname . ' 2>&1';
         exec($cmd);
         $return = file_get_contents($tmpfname);
         unlink($tmpfname);
         //			echo $cmd;
         $output['returnContent'] = $output['returnContent'] . "\n\n<pre>{$return}</pre>";
     }
     return $output;
 }
Exemplo n.º 14
0
 /**
  * Run benchmark.
  *
  * @throws BenchEx
  *
  * @return Bench
  */
 public function run()
 {
     foreach ($this->benchmarks as $name => $benchmark) {
         $this->timer->start($name);
         $benchmark($this->iterations);
         $this->timer->stop($name);
     }
     $this->createSummary();
     return $this;
 }
 function parse()
 {
     if ($this->xmlaction != null) {
         require_once "timer.php";
         $timer = new Timer();
         $success = false;
         $this->saxparser == "saxy" ? $parseSAXY = true : ($parseSAXY = false);
         $timer->start();
         switch ($this->domparser) {
             case "domit":
                 //change this to the domit path
                 require_once 'xml_domit_parser.php';
                 $this->xmldoc =& new DOMIT_Document();
                 $this->xmldoc->expandEmptyElementTags(true);
                 $this->xmldoc->setNamespaceAwareness(true);
                 break;
             case "domitlite":
                 //change this to the domit lite path
                 require_once 'xml_domit_lite_parser.php';
                 $this->xmldoc =& new DOMIT_Lite_Document();
                 break;
         }
         // switch
         switch ($this->xmlaction) {
             case "parsefile":
                 $success = $this->xmldoc->loadXML($this->xmlfile, $parseSAXY);
                 break;
             case "parseurl":
                 $success = $this->xmldoc->loadXML("http://" . $this->xmlurl, $parseSAXY);
                 break;
             case "parsetext":
                 $success = $this->xmldoc->parseXML($this->xmltext, $parseSAXY);
                 break;
         }
         $timer->stop();
         if ($success) {
             echo "<br /><br />Time elapsed: " . $timer->getTime() . "seconds<br /><br />\n";
             if ($this->xmloutput == "tostring") {
                 echo $this->xmldoc->toString(true);
             } else {
                 if ($this->xmloutput == "tonormalizedstring") {
                     echo $this->xmldoc->toNormalizedString(true);
                 } else {
                     if ($this->xmloutput == "toarray") {
                         echo "<pre>\n";
                         print_r($this->xmldoc->toArray());
                         echo "</pre>\n";
                     }
                 }
             }
         } else {
             echo "<br /><br />Parsing error: xml document may be invalid or malformed.\n";
         }
     }
 }
Exemplo n.º 16
0
 public function testToString()
 {
     $this->object->start();
     $this->object->stop();
     ob_start();
     echo $this->object;
     $content = ob_get_contents();
     ob_end_clean();
     $this->assertInternalType("string", $content);
     $this->assertNotEmpty($content);
 }
 public function testSaveSimple()
 {
     //Logger::getInstance()->on();
     YuppLoader::load('core.support', 'Timer');
     $timer = new Timer();
     $timer->start();
     $bot = new Botella(array("material" => "vidrio", "capacidad" => 1.5, "tapaRosca" => true));
     $this->assert($bot->save(), 'Test guardar 1 ' . print_r($bot->getErrors(), true));
     $timer->stop();
     echo 'Time: ' . $timer->getElapsedTime() . '<br/>';
     //Logger::getInstance()->off();
 }
Exemplo n.º 18
0
 /**
  * Main program.
  *
  * @param array $args Command-line arguments.
  * @return integer Zero on success; non-zero on failure.
  */
 public static function main($args)
 {
     $status = 0;
     printf("3\n");
     printf("n\n");
     printf("fib1 s\n");
     printf("fib2 s\n");
     for ($i = 0; $i < 48; ++$i) {
         $timer = new Timer();
         $timer->start();
         $result = fibonacci($i);
         $timer->stop();
         $time1 = $timer->getElapsedTime();
         $timer->start();
         $result = fibonacci2($i);
         $timer->stop();
         $time2 = $timer->getElapsedTime();
         printf("%d\t%f\t%f\n", $i, $time1, $time2);
     }
     return $status;
 }
Exemplo n.º 19
0
 public function testStopChildren()
 {
     // Init
     $timer = new Timer();
     // Process
     $timer->start('mysql.sql.query.response.parsing', true);
     usleep(50000);
     $timer->stop('mysql.sql');
     usleep(50000);
     $value = $timer('mysql.sql.query.response.parsing');
     // Assert
     $this->assertEquals(true, $value > 0.045 && $value < 0.55);
 }
Exemplo n.º 20
0
        public function query($query){
            if(!$this->wasInititialized){
                $this->log('warn', $this->id." mysql resource was not intialized");
                }
            Timer::start(get_class($this)."");
            $now = microtime(true);
            $result = mysql_query($query, $this->connection);
            $needed = (microtime(true)-$now);
            $this->log('debug', "query needed ".$needed. " msec : ".$query);
            Timer::stop(get_class($this)."");

            return $result;
        }
Exemplo n.º 21
0
 public static function getGlobalDbObj(array $args = array())
 {
     global $_DB_OBJ;
     $prefix = $args['prefix'];
     if (isset($_DB_OBJ[$prefix]) == false) {
         // requirePackage('mysqli', 2);
         $timer = Timer::start('Mysqli Loading ... ' . $prefix . '_HOST');
         $databaseInterfaceClass = 'MysqliConnect';
         $params = array('host' => constant($prefix . '_HOST'), 'username' => constant($prefix . '_USER'), 'password' => constant($prefix . '_PASS'), 'database' => constant($prefix . '_DB'));
         $_DB_OBJ[$prefix] = new $databaseInterfaceClass($params);
         Timer::stop($timer);
         // echo 'Getting new db connection. ' . $prefix . ', ' . print_r($params, true) . "\n";
     }
     return $_DB_OBJ[$prefix];
 }
Exemplo n.º 22
0
 public function httpget($url)
 {
     $s = curl_init();
     Timer::start(get_class($this) . "");
     curl_setopt($s, CURLOPT_URL, $url);
     curl_setopt($s, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($s, CURLOPT_BINARYTRANSFER, true);
     $result = curl_exec($s);
     if ($result === false) {
         Logger::warn($url . ' returned faulty result ' . curl_error());
     }
     Timer::stop(get_class($this) . "");
     //echo $result;
     return $result;
 }
Exemplo n.º 23
0
function calcTop($row)
{
    global $mdb;
    $timer = new Timer();
    $currentSum = (int) @$row['shipsDestroyed'];
    $parameters = [$row['type'] => $row['id']];
    $parameters['limit'] = 10;
    $parameters['kills'] = true;
    $topLists[] = array('type' => 'character', 'data' => Stats::getTop('characterID', $parameters));
    $topLists[] = array('type' => 'corporation', 'data' => Stats::getTop('corporationID', $parameters, true));
    $topLists[] = array('type' => 'alliance', 'data' => Stats::getTop('allianceID', $parameters, true));
    $topLists[] = array('type' => 'faction', 'data' => Stats::getTop('factionID', $parameters, true));
    $topLists[] = array('type' => 'ship', 'data' => Stats::getTop('shipTypeID', $parameters, true));
    $topLists[] = array('type' => 'system', 'data' => Stats::getTop('solarSystemID', $parameters, true));
    $mdb->set('statistics', $row, ['topAllTime' => $topLists, 'allTimeSum' => $currentSum]);
    if ($timer->stop() > 60000) {
        exit;
    }
}
Exemplo n.º 24
0
 public function executeCount($query, $logComponent, $defaultGraphURI = null, $format = null)
 {
     Timer::start($logComponent . '::http::count');
     $json = $this->executeQuery($query, $logComponent, $defaultGraphURI, $format);
     $jarr = json_decode($json, true);
     Timer::stop($logComponent . '::http::count');
     /*
                     "results": { "distinct": false, "ordered": true, "bindings": [
         { "count": { "type": "typed-literal", "datatype": "http://www.w3.org/2001/XMLSchema#integer", "value": "30" }} ] } }
     */
     if (isset($jarr['results']) && isset($jarr['results']['bindings'])) {
         $bindings = $jarr['results']['bindings'];
         foreach ($bindings as $one) {
             $count = $one['count'];
             return $count['value'];
         }
     } else {
         return 0;
     }
 }
Exemplo n.º 25
0
 public function execute($parameters, $db)
 {
     global $stompServer, $stompUser, $stompPassword;
     // Ensure the class exists
     if (!class_exists("Stomp")) {
         die("ERROR! Stomp not installed!  Check the README to learn how to install Stomp...\n");
     }
     $stomp = new Stomp($stompServer, $stompUser, $stompPassword);
     $stompKey = "StompSend::lastFetch";
     $lastFetch = date("Y-m-d H:i:s", time() - 12 * 3600);
     $lastFetch = Storage::retrieve($stompKey, $lastFetch);
     $stompCount = 0;
     $timer = new Timer();
     while ($timer->stop() < 60000) {
         if (Util::isMaintenanceMode()) {
             return;
         }
         $result = $db->query("SELECT killID, insertTime, kill_json FROM zz_killmails WHERE insertTime > :lastFetch AND processed > 0 ORDER BY killID limit 1000", array(":lastFetch" => $lastFetch), 0);
         foreach ($result as $kill) {
             $lastFetch = max($lastFetch, $kill["insertTime"]);
             if (!empty($kill["kill_json"])) {
                 if ($kill["killID"] > 0) {
                     $stompCount++;
                     $destinations = self::getDestinations($kill["kill_json"]);
                     foreach ($destinations as $destination) {
                         $stomp->send($destination, $kill["kill_json"]);
                     }
                 }
                 $data = json_decode($kill["kill_json"], true);
                 $json = json_encode(array("solarSystemID" => $data["solarSystemID"], "killID" => $data["killID"], "characterID" => $data["victim"]["characterID"], "corporationID" => $data["victim"]["corporationID"], "allianceID" => $data["victim"]["allianceID"], "shipTypeID" => $data["victim"]["shipTypeID"], "killTime" => $data["killTime"]));
                 $stomp->send("/topic/starmap.systems.active", $json);
             }
         }
         Storage::store($stompKey, $lastFetch);
         sleep(5);
     }
     if ($stompCount > 0) {
         Log::log("Stomped {$stompCount} killmails");
     }
 }
Exemplo n.º 26
0
 /**
  * @param array $parameters
  * @param Database $db
  */
 public function execute($parameters, $db)
 {
     $timer = new Timer();
     do {
         $crests = Db::query("select * from zz_crest_killmail where processed = 0 order by killID limit 30", array(), 0);
         foreach ($crests as $crest) {
             try {
                 $killID = $crest["killID"];
                 $hash = trim($crest["hash"]);
                 $url = "http://public-crest.eveonline.com/killmails/{$killID}/{$hash}/";
                 $perrymail = \Perry\Perry::fromUrl($url);
                 $killmail = array();
                 $killmail["killID"] = (int) $killID;
                 $killmail["solarSystemID"] = (int) $perrymail->solarSystem->id;
                 $killmail["killTime"] = str_replace(".", "-", $perrymail->killTime);
                 $killmail["moonID"] = (int) @$perrymail->moon->id;
                 $victim = array();
                 $killmail["victim"] = self::getVictim($perrymail->victim);
                 $killmail["attackers"] = self::getAttackers($perrymail->attackers);
                 $killmail["items"] = self::getItems($perrymail->victim->items);
                 $json = json_encode($killmail);
                 $killmailHash = Util::getKillHash(null, json_decode($json));
                 Db::execute("insert ignore into zz_killmails (killID, hash, source, kill_json) values (:killID, :hash, :source, :json)", array(":killID" => $killID, ":hash" => $hash, ":source" => "crest:{$killID}", ":json" => $json));
                 Db::execute("update zz_crest_killmail set processed = 1 where killID = :killID", array(":killID" => $killID));
                 // Write this file to eve-kill's parse directory
                 $xml = Util::xmlOut(array($killmail), array());
                 $file = "/var/killboard/zkb_killlogs/0_0_{$killID}.xml";
                 @unlink($file);
                 @error_log($xml, 3, $file);
             } catch (Exception $ex) {
                 Db::execute("update zz_crest_killmail set processed = -1 where killID = :killID", array(":killID" => $killID));
             }
         }
         if (count($crests) == 0) {
             sleep(1);
         }
     } while ($timer->stop() < 65000);
 }
Exemplo n.º 27
0
 public function runPlugin($input = array())
 {
     $output = Plugin::$output;
     ///set defaults for all output
     $t = new Timer();
     $t->start();
     try {
         $mysql = new MySQL($input['mysqlConnection']);
         $rs = $mysql->runQuery($input['testQuery']);
         if ($row = mysql_fetch_array($rs, MYSQL_NUM)) {
             $output['currentStatus'] = 1;
             $output['returnContent'] = "All normal\n" . $row[0];
             $output['measuredValue'] = $row[0];
         } else {
             $output['currentStatus'] = 0;
             $output['returnContent'] = "no results were returned for the query" . $input['testQuery'];
         }
     } catch (Exception $e) {
         $output['currentStatus'] = 0;
         $output['returnContent'] = "Query {$input['testQuery']} errored:\n" . $e->getMessage();
     }
     $output['responseTimeMs'] = (int) $t->stop();
     return $output;
 }
Exemplo n.º 28
0
<?php

require_once '../init.php';
global $beSocial;
if ($beSocial != true) {
    $redis->del("queueSocial");
    exit;
}
$queueSocial = new RedisQueue('queueSocial');
$timer = new Timer();
while ($timer->stop() < 59000) {
    $killID = $queueSocial->pop();
    if ($killID != null) {
        beSocial($killID);
    }
}
function beSocial($killID)
{
    global $beSocial, $mdb;
    if (!isset($beSocial)) {
        $beSocial = false;
    }
    if ($beSocial === false) {
        return;
    }
    if ($killID < 0) {
        return;
    }
    $ircMin = 10000000000.0;
    $twitMin = 10000000000.0;
    $kill = $mdb->findDoc('killmails', ['killID' => $killID]);
Exemplo n.º 29
0
 /**
  * Sorter test method.
  *
  * @param object ISorter $sorter The sorter to test.
  * @param integer $n The length of array to test.
  * @param integer $seed A seed for the random number generator.
  * @param integer $m If given, data values are restricted to [0,m-1].
  * (Optional).
  */
 public static function test(ISorter $sorter, $n, $seed, $m = 0)
 {
     //printf("AbstractSorter test program.\n");
     RandomNumberGenerator::setSeed($seed);
     $data = new BasicArray($n);
     for ($i = 0; $i < $n; ++$i) {
         $datum = intval(RandomNumberGenerator::next() * Limits::MAXINT);
         if ($m != 0) {
             $datum = $datum % $m;
         }
         $data[$i] = $datum;
     }
     $timer = new Timer();
     $timer->start();
     $sorter->sort($data);
     $timer->stop();
     $datum = sprintf("%s %d %d %f", $sorter->getClass()->getName(), $n, $seed, $timer->getElapsedTime());
     fprintf(STDOUT, "%s\n", $datum);
     fprintf(STDERR, "%s\n", $datum);
     for ($i = 1; $i < $n; ++$i) {
         if ($data[$i] < $data[$i - 1]) {
             printf("FAILED\n");
             break;
         }
     }
 }
Exemplo n.º 30
0
	function query($sql, $verbose=false){
		return new TestPostgrResult(array());
		
		$sql = trim($sql);
		if($this->_postgr_link === false){
			$this->_postgr_link = pg_connect("host=" . $this->host . " user="******" password="******" dbname=" . $this->database);
			pg_query($this->_postgr_link, "SET NAMES 'utf8'");
		}
		if($this->_postgr_link === false){
			throw new DatabaseException("could not connect to MySQL");
		};

		if($this->_query_cache->get($sql)){
			if($verbose)echo "found in cache<br>";
			$result = $this->_query_cache->get($sql);
			if(pg_num_rows($result)){
				if($verbose) echo ": seeking to 0";
				pg_result_seek($result, 0);
			}
			$ret = new PostgrResult($this->_postgr_link, $result);
			if($verbose) echo "<br>";
		}else{
			if($verbose) echo "not in cache";
			$this->_query_count++;
			/**
			 * this following line should be run once per connection to postgres
			 *
			 * i'm running it before every query. I can probably optimize this
			 * to run once per connection, but I need to do some thorough testing...
			 *
			 * http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html
			 */
			pg_query($this->_postgr_link, "SET NAMES 'utf8'");
			$timer = new Timer();
			$timer->start();
			$result = pg_query($this->_postgr_link, $sql);
			$ret = new PostgrResult($this->_postgr_link, $result);
			$timer->stop();
			$time = $timer->read();
			
			if(is_object($this->logger)){
				$this->logger->log($this, ALogger::$LOW, $sql);
			}
			
			/**
			 * the query is too long! oh noes!
			 */
			if($time > .1){
				/**
				 * save the query to the DB, so I can look at it later
				 */
				if(is_object($this->logger)){
					$this->logger->longQuery($time, $sql);
				}
			}
			
			if(pg_last_error($this->_postgr_link)){
				if($verbose) echo "postgr_error: " . pg_last_error($this->_postgr_link) . "<br>";
				throw new DatabaseException(pg_last_error($this->_postgr_link));
			}
			if(strpos($sql, "SELECT") === 0){
				if($verbose) echo ": select: $sql<br><br>";
				$this->_query_cache->put($sql, $result);
			}else{
				if($verbose) echo ": not select: $sql<br>";
				if($verbose) echo "clearing cache<br>";
				$this->_query_cache->reset();
			}

		}
		return $ret;
	}