Ejemplo n.º 1
0
function calcShortestPaths(vertex $start, &$adjLists)
{
    // define an empty queue
    $q = new PriorityQueue();
    // push the starting vertex into the queue
    $q->insert($start, 0);
    $q->rewind();
    // mark the distance to it 0
    $start->distance = 0;
    // the path to the starting vertex
    $start->path = array($start->key);
    while ($q->valid()) {
        $vertex = $q->extract();
        $vertex->visited = 1;
        $list = $adjLists[$vertex->key];
        while ($list->valid()) {
            $item = $list->current();
            if (!$item['vertex']->visited) {
                if ($item['vertex']->distance > $vertex->distance + $item['distance']) {
                    $item['vertex']->distance = $vertex->distance + $item['distance'];
                    $item['vertex']->parent = $vertex;
                }
                $item['vertex']->path = array_merge($vertex->path, array($item['vertex']->key));
                $q->insert($item["vertex"], $item["vertex"]->distance);
            }
            $list->next();
        }
        $q->recoverFromCorruption();
        $q->rewind();
    }
}
Ejemplo n.º 2
0
 public function testQueue()
 {
     $queue = new PriorityQueue();
     $queue->insert('foo', 0);
     $queue->insert('test', 16);
     $queue->insert('bar', 8);
     $this->assertInstanceOf('Countable', $queue);
     $this->assertInstanceOf('IteratorAggregate', $queue);
     $this->assertEquals(3, $queue->count());
     $this->assertEquals(3, count($queue));
     $iterator = $queue->getIterator();
     $this->assertEquals('test', $iterator->current());
     $iterator->next();
     $this->assertEquals('bar', $iterator->current());
     $iterator->next();
     $this->assertEquals('foo', $iterator->current());
     $iterator->next();
     $this->assertEmpty($iterator->current());
 }
 /**
  * {@inheritdoc}
  */
 public function calculate($start, $finish)
 {
     // check if the nodes exist
     if (!isset($this->nodes[$start])) {
         throw new \InvalidArgumentException("The starting node '" . $start . "' is not found");
     }
     if (!isset($this->nodes[$finish])) {
         throw new \InvalidArgumentException("The ending node '" . $finish . "' is not found");
     }
     $distances = [];
     $distances[$start] = 0;
     $visited = [];
     $previous = [];
     $queue = new PriorityQueue();
     $queue->insert($start, $distances[$start]);
     $queue->top();
     while ($queue->valid()) {
         $smallest = $queue->current();
         if ($smallest == $finish) {
             // trying to make path
             $path = array();
             while (isset($previous[$smallest])) {
                 $path[] = $smallest;
                 $smallest = $previous[$smallest];
             }
             $path[] = $start;
             return ['distance' => $distances[$finish], 'path' => array_reverse($path)];
         }
         if (isset($visited[$smallest])) {
             $queue->next();
             continue;
         }
         $visited[$smallest] = true;
         foreach ($this->nodes[$smallest] as $neighbor => $weight) {
             if (isset($visited[$neighbor])) {
                 continue;
             }
             $alt = $distances[$smallest] + $weight;
             if (!isset($distances[$neighbor]) || $alt < $distances[$neighbor]) {
                 $distances[$neighbor] = $alt;
                 $previous[$neighbor] = $smallest;
                 $queue->insert($neighbor, $alt);
             }
         }
         $queue->next();
     }
     // there is no available path if the graph is unconnected
     return null;
 }
Ejemplo n.º 4
0
 /**
  * Add an entry into the queu
  * @param type $datum
  * @param type $priority
  */
 public function insert($name, $callback, $priority)
 {
     $name = trim((string) $name);
     if ('' == $name) {
         throw new \RuntimeException('No name provided for FilterQueue entry');
     }
     if (0 == $priority && $this->hasPriorityZeroFilter) {
         throw new \RuntimeException('Attempt to add duplicate priority-zero filter');
     }
     $datum = array('name' => $name, 'callback' => $callback);
     $this->priorityQueue->insert($datum, $priority);
     if (0 == $priority) {
         $this->hasPriorityZeroFilter = true;
     }
 }
Ejemplo n.º 5
0
 public function shortest_path($start, $finish)
 {
     $distances = array();
     $previous = array();
     $nodes = new PriorityQueue();
     foreach ($this->verticies as $vertex => $value) {
         if ($vertex === $start) {
             $distances[$vertex] = 0;
             $nodes->insert($vertex, 0);
         } else {
             $distances[$vertex] = PHP_INT_MAX;
             $nodes->insert($vertex, PHP_INT_MAX);
         }
         $previous[$vertex] = null;
     }
     $nodes->top();
     while ($nodes->valid()) {
         $smallest = $nodes->current();
         if ($smallest === $finish) {
             $path = array();
             while ($previous[$smallest]) {
                 $path[] = $smallest;
                 $smallest = $previous[$smallest];
             }
             $path[] = $start;
             $alt = $distances[$finish];
             $path['Разстояние'] = $alt;
             return array_reverse($path);
         }
         if ($smallest === null || $distances[$smallest] === PHP_INT_MAX) {
             break;
         }
         foreach ($this->verticies[$smallest] as $neighbor => $value) {
             $alt = $distances[$smallest] + $this->verticies[$smallest][$neighbor];
             if ($alt < $distances[$neighbor]) {
                 $distances[$neighbor] = $alt;
                 $previous[$neighbor] = $smallest;
                 $nodes->insert($neighbor, $alt);
             }
         }
         $nodes->next();
     }
     return $distances;
 }
 /**
  * @param $transaction_number
  * @param null $terminal_id
  * @return string
  */
 public function getCallnumber($transaction_number, $terminal_id)
 {
     try {
         if (is_null(TerminalTransaction::find($transaction_number))) {
             return json_encode(['error' => 'You have called an invalid input.']);
         }
         $terminal_transaction = TerminalTransaction::find($transaction_number);
         $priority_queue = PriorityQueue::find($transaction_number);
         if ($terminal_transaction->time_called != 0) {
             return json_encode(['error' => 'Number ' . $priority_queue->priority_number . ' has already been called. Please call another number.']);
         } else {
             return ProcessQueue::callTransactionNumber($transaction_number, Helper::userId(), $terminal_id);
         }
     } catch (Exception $e) {
         return json_encode(['error' => $e->getMessage()]);
     }
 }
Ejemplo n.º 7
0
 function Find($NodeStart, $NodeEnd)
 {
     $Queue = new PriorityQueue();
     // Open Nodes ordered based on F cost
     $Queue->setExtractFlags(PriorityQueue::EXTR_DATA);
     $Closed = 0;
     $Found = FALSE;
     $this->Debug = '';
     $this->Cache = array($NodeStart => array('G' => 0, 'F' => 0, 'Parent' => $NodeStart, 'Status' => STATUS_OPEN));
     $Queue->insert($NodeStart, $this->Cache[$NodeStart]['F']);
     while (!$Queue->isEmpty()) {
         $Node = $Queue->extract();
         if ($this->Cache[$Node]['Status'] == STATUS_CLOSED) {
             continue;
         }
         if ($Node == $NodeEnd) {
             $this->Cache[$Node]['Status'] = STATUS_CLOSED;
             $Found = TRUE;
             break;
         }
         if ($Closed > $this->Limit) {
             $this->Debug = 'Hit limit. (' . $this->Limit . ')';
             return NULL;
         }
         $Neighbours = $this->Graph->Neighbours($Node);
         foreach ($Neighbours as $Neighbour) {
             $G = $this->Cache[$Node]['G'] + $this->Graph->G($Node, $Neighbour);
             if (isset($this->Cache[$Neighbour]) && $this->Cache[$Neighbour]['Status'] && $this->Cache[$Neighbour]['G'] <= $G) {
                 continue;
             }
             $F = $G + $this->Graph->H($Neighbour, $NodeEnd);
             $this->Cache[$Neighbour] = array('G' => $G, 'F' => $F, 'Parent' => $Node, 'Status' => STATUS_OPEN);
             $Queue->insert($Neighbour, $F);
         }
         ++$Closed;
         $this->Cache[$Node]['Status'] = STATUS_CLOSED;
     }
     if ($Found) {
         $Path = array();
         $Node = $NodeEnd;
         while ($NodeStart != $Node) {
             $Path[] = $Node;
             $Node = $this->Cache[$Node]['Parent'];
         }
         $Path[] = $Node;
         return array_reverse($Path);
     }
     $this->Debug = 'Path not found, ran out of open nodes.';
     return NULL;
 }
 public function postIssueOther()
 {
     $queue_platform = 'web';
     $terminal_id = 0;
     $business_id = Input::get('business_id');
     $forwarder_id = Input::get('forwarder_id');
     $transaction_number = Input::get('transaction_number');
     if (Business::getForwarderAllowedInBusiness($business_id, $forwarder_id)) {
         $name = PriorityQueue::name($transaction_number);
         $phone = PriorityQueue::phone($transaction_number);
         $email = PriorityQueue::email($transaction_number);
         $service = Service::getFirstServiceOfBusiness($business_id);
         $service_id = $service->service_id;
         $next_number = ProcessQueue::nextNumber(ProcessQueue::lastNumberGiven($service_id), QueueSettings::numberStart($service_id), QueueSettings::numberLimit($service_id));
         $priority_number = $next_number;
         $number = ProcessQueue::issueNumber($service_id, $priority_number, null, $queue_platform, $terminal_id);
         PriorityQueue::updatePriorityQueueUser($number['transaction_number'], $name, $phone, $email);
         return json_encode(['success' => 1, 'number' => $number]);
     }
     return json_encode(['error' => 'You are not allowed to issue a number to this business']);
 }
Ejemplo n.º 9
0
<?php

$GLOBALS['client'] = 'Tests';
echo "<p>Starting PriorityQueue test.</p>";
echo "New PriorityQueue, ";
$pq = new PriorityQueue();
echo "done.";
$pq->renderInternalRepresentation();
echo "<br>";
echo "Insert (1, 'one') into pq, ";
$pq->insert(1, 'one');
echo "done.";
$pq->renderInternalRepresentation();
echo "<br>";
echo "Insert (2, 'two') into pq, ";
$pq->insert(2, 'two');
echo "done.";
$pq->renderInternalRepresentation();
echo "<br>";
echo "Insert (0, 'zero') into pq, ";
$pq->insert(0, 'zero');
echo "done.";
$pq->renderInternalRepresentation();
echo "<br>";
echo "Top of pq: ";
var_dump($pq->top());
$pq->renderInternalRepresentation();
echo "<br>";
echo "Pop pq: ";
var_dump($pq->pop());
$pq->renderInternalRepresentation();
Ejemplo n.º 10
0
 public static function buildTree($s)
 {
     $t = new Tree();
     $seenSymbols = array();
     $pq = new PriorityQueue();
     // Add leaf nodes for each symbol to the priority queue.
     for ($i = 0; $i < strlen($s); ++$i) {
         $c = $s[$i];
         if (array_key_exists($c, $seenSymbols)) {
             continue;
         }
         $occurrences = 0;
         for ($j = $i; $j < strlen($s); ++$j) {
             if ($s[$j] != $c) {
                 continue;
             }
             $occurrences++;
         }
         $node = new Node($c, $occurrences);
         $pq->enqueue($node);
         $t->leaves[$c] = $node;
         $seenSymbols[$c] = true;
     }
     if ($pq->size() == 0) {
         return $t;
     }
     // While there is more than one node left in the priority queue:
     while ($pq->size() > 1) {
         // Remove the two nodes of highest priority (lowest probability).
         $node1 = $pq->dequeue();
         $node2 = $pq->dequeue();
         // Create a new internal node with the two nodes as children with
         // p_total = p_1 + p_2
         $newNode = new Node(null, $node1->weight + $node2->weight);
         $newNode->left = $node1;
         $newNode->right = $node2;
         $node1->parent = $newNode;
         $node2->parent = $newNode;
         // Add the new node to the queue.
         $pq->enqueue($newNode);
     }
     // The final node in the priority queue is the root.
     $t->root = $pq->dequeue();
     return $t;
 }
Ejemplo n.º 11
0
    function extract()
    {
        array_shift($this->dataStore);
        return parent::extract();
    }
    function toString()
    {
        $retStr = "";
        $cnt = count($this->dataStore);
        for ($i = 0; $i < $cnt; ++$i) {
            $retStr .= $this->dataStore[$i]->name . " номер: " . $this->dataStore[$i]->priority . "\n";
        }
        return $retStr . "\n";
    }
}
$bank = new PriorityQueue();
$clients = ["Пупкин", "Сумкин", "Корзинкина", "Морковкин", "Зайцев"];
shuffle($clients);
foreach ($clients as $p => $client) {
    $bank->insert(new Client($client, $p + 1), $p + 1);
}
print $bank->toString();
$current = $bank->extract();
print "Обслуживается: " . $current->name . "\n";
print "Ожидают очереди:\n";
print $bank->toString();
exit;
$current = $bank->extract();
print "Обслуживается: " . $current->name . "\n";
print "Ожидают очереди:\n";
print $bank->toString();
 /**
  * @param $service_id
  * @param $name
  * @param $phone
  * @param $email
  * @return JSON-formatted queued number
  */
 public function getQueueNumber($service_id, $name, $phone, $email)
 {
     try {
         $next_number = ProcessQueue::nextNumber(ProcessQueue::lastNumberGiven($service_id), QueueSettings::numberStart($service_id), QueueSettings::numberLimit($service_id));
         $priority_number = $next_number;
         $queue_platform = 'kiosk';
         $number = ProcessQueue::issueNumber($service_id, $priority_number, null, $queue_platform);
         PriorityQueue::updatePriorityQueueUser($number['transaction_number'], $name, $phone, $email);
         $details = ['number_assigned' => $priority_number];
         return Response::json($details, 200, array(), JSON_PRETTY_PRINT);
     } catch (Exception $e) {
         return json_encode(['error' => 'Something went wrong!']);
     }
 }
Ejemplo n.º 13
0
/** get the group of words most similar to this word **/
function old_synset($id, $word, $pos)
{
    $query = "SELECT * from word where word = '" . $word . "' and pos = '" . $pos . "';";
    if ($id) {
        $query = "SELECT * from word where id = " . $id . ";";
    }
    $result = mysql_query($query);
    $row = array();
    $friends = array();
    $similarities = array();
    $ids = array();
    $poss = array();
    $best = new PriorityQueue();
    $best->clear();
    $row;
    $word;
    $pos;
    $friend;
    $friends_of_friends;
    while ($row = mysql_fetch_array($result)) {
        $id = $row['id'];
        $word = $row['word'];
        $_GET['word'] = $word;
        $pos = $row['pos'];
        $_GET['pos'] = $pos;
        $friends = getMostSimilar($id);
        foreach ($friends as $friend) {
            if ($friend['word'] != $word) {
                if (!array_key_exists($friend['id'], $similarities)) {
                    $similarities[$friend['id']] = 0;
                    $ids[$friend['id']] = $friend['word'];
                    $poss[$friend['id']] = $friend['pos'];
                }
                $similarities[$friend['id']] += $friend['similarity'];
                $friends_of_friends = getMostSimilar($friend['id']);
                foreach ($friends_of_friends as $ff) {
                    if ($ff['word'] != $word) {
                        if (!array_key_exists($ff['id'], $similarities)) {
                            $similarities[$ff['id']] = 0;
                            $ids[$ff['id']] = $ff['word'];
                            $poss[$ff['id']] = $ff['pos'];
                        }
                        $similarities[$ff['id']] += $ff['similarity'] * $friend['similarity'];
                    }
                }
            }
        }
    }
    foreach (array_keys($similarities) as $id) {
        $best->push($id, $similarities[$id]);
    }
    $answer = array();
    $max = 0;
    $next;
    $w;
    $pos;
    $sim;
    while (!$best->IsEmpty()) {
        $next = $best->pop();
        $w = $ids[$next];
        $pos = $poss[$next];
        $sim = $similarities[$next];
        if ($sim > $max) {
            $max = $sim;
        }
        if ($sim >= $max / 2) {
            array_push($answer, array("word" => $w, "id" => $next, "similarity" => $sim, "pos" => $pos));
        }
    }
    return $answer;
}
Ejemplo n.º 14
0
    goto end;
}
$status = socket_bind($sock, "/private/tmp/classmate{$argv['1']}.sock");
if (!$status) {
    Error::generate('debug', "Error in classmate{$argv['1']}: " . socket_strerror(socket_last_error()));
    goto end;
}
$status = socket_listen($sock, 100);
if (!$status) {
    Error::generate('debug', "Error in classmate{$argv['1']}: " . socket_strerror(socket_last_error()));
    goto end;
}
$clients = array();
$data = array();
$completed = new PriorityQueue();
$curl_stack = new PriorityQueue();
$in_progress = array();
$mch = curl_multi_init();
$mcr = null;
$active = 0;
$locked = false;
$blocking = false;
// set to false to potentially have multiple concurrent queries from 1 source
$max_simult_queries = 2;
// max no. of simultaneous outgoing connections
// stats
$logpath = "{$ROOT}/admin/daemon_stats.log";
$fp = fopen($logpath, "a");
date_default_timezone_set('America/New_York');
$start_time = date(DATE_RFC822);
$n_reqs_recvd = 0;
 public function getServiceKeyDetails($service, $branch_id)
 {
     $service->current_number = PriorityQueue::currentNumber($service->service_id, $branch_id);
     $service->last_number_given = PriorityQueue::lastNumberGiven($service->service_id, $branch_id);
     $service->terminals = $this->getTerminalCurrentNumber($service->service_id, $branch_id);
     $service->called_numbers = PriorityQueue::calledNumbers($service->service_id, $branch_id);
     return $service;
 }
Ejemplo n.º 16
0
 /**
  * Handles downloaded data.
  * The function name is a bit of a misnomer, as it does not actually fetch the contents when using api_multi. This has been done ahead of time (unless we're using the old api() calls).
  * This function writes the downloaded content (json-ified, if it's not a Picture) into its respective output file, causes the new object to create its connections and add them to the queue.
  * @param $facebook A Facebook instance to use for fetching data.
  */
 public function fetch($facebook)
 {
     // If the folder for our output files doesn't exist yet, create it
     if (!is_dir("../tmp/" . $facebook->getUnique())) {
         mkdir("../tmp/" . $facebook->getUnique());
     }
     // Create a safe file name. Simply replaces all slashes, actually.
     //TODO: Write this platform-independent-safe
     $fname = Connection::createSafeName($facebook, $this->url);
     //$fname = $facebook->getUnique() . "/" .strtr($this->url, "/", "~") . ".request";
     // Is this a Picture? If so, we don't process the content but simply write it into a file that has base64($url) as its filename.
     if ($this->type == 'Picture') {
         fprintf($facebook->getLogFd(), "Writing picture with filesize " . strlen($this->json) . "\n");
         if (!file_exists("../tmp/" . $facebook->getUnique() . "/" . base64_encode($this->url))) {
             file_put_contents("../tmp/" . $facebook->getUnique() . "/" . base64_encode($this->url), $this->json);
         }
         return new Picture("", 0);
     }
     try {
         // Check if the file already exists; if so, throw an exception
         if (file_exists($fname)) {
             throw new Exception("File " . $fname . " already exists.");
         }
         // If json is empty, we haven't fetched any content yet, which means that we're using the old API.
         // So let's just use the old api() call. This one also does an implicit json_decode(), so we don't have to perform that anymore.
         if (strlen($this->json) < 1) {
             $this->json = $facebook->api($this->url);
         } else {
             $facebook->log("[RESPONSE] Response's json is larger than 0");
             $this->json = json_decode($this->json, true);
         }
         // Check if the Graph API returned an error.
         if (isset($this->json['error'])) {
             //echo "fetch() FB Error:<br />";
             //print_r($this->json);
             throw new Exception("fb error: " . json_encode($this->json['error']));
         }
     } catch (Exception $e) {
         //echo "fetch() Exception occurred (" . $e->getMessage()  . "), continuing anyway, handling as empty Picture";
         //ob_flush();
         //flush()
         $facebook->log("[ERROR] fetch() Exception occurred (" . $e->getMessage() . "), continuing anyway, handling as empty Picture");
         // This "empty picture" is nearly an empty object. It has no connections and should therefore be completely neutral to the rest of the process.
         return new Picture("", 0);
     }
     // Open the output file for writing
     $facebook->log("[FILE] Creating file " . $fname);
     $fp = fopen($fname, "w");
     // Write the json data - in text form - to the file
     //fwrite($fp, print_r($this->json, TRUE));
     fwrite($fp, json_encode($this->json));
     // Close the output file again.
     fclose($fp);
     if (isset($this->json['paging']) && isset($this->json['paging']['next'])) {
         $queue = new PriorityQueue();
         $url = substr($this->json['paging']['next'], strpos($this->json['paging']['next'], "com/") + 4);
         $facebook->log("[DEBUG] Adding paging URL " . $url);
         $queue->unshift(new Connection($url, $this->depth, $this->type, true), 100);
         Facebook::getQueue()->merge($queue);
     } else {
         $facebook->log("[DEBUG] No paging or next");
     }
     // If the data is not "right there" at the topmost level but nested in the data part, replace our internal variable with the actual payload.
     if (isset($this->json['data'])) {
         $this->json = $this->json['data'];
     }
     // Check if there are multiple objects stored in the received json
     if ($this->multiplicity) {
         $retval = array();
         // Handle each object in json
         foreach ($this->json as $item) {
             // First, the two "meta-types" Profile and Taggable; they're not actual types, but they can determine which of their subtypes is the appropriate one with their static getInstance() method.
             if ($this->type == 'Profile') {
                 array_push($retval, Profile::getInstance($item, $this->depth));
             } else {
                 if ($this->type == 'Taggable') {
                     array_push($retval, Taggable::getInstance($item, $this->depth));
                 } else {
                     // Slight PHP magic: $this->type is a string that contains a class name, i.e. we construct an object whose class name is specified by that field.
                     array_push($retval, new $this->type($item, $this->depth));
                 }
             }
             if ($this->type == 'User') {
                 $facebook->log('Created a user.');
             }
             //$facebook->log(print_r($item));
         }
         $fullnull = true;
         //Performing getConnections() now, adding everything into the big static queue
         // Also, we check if all getConnections() return NULL
         foreach ($retval as $item) {
             if (NULL != $item->getConnections()) {
                 $fullnull = false;
             }
         }
         // All getConnections() have returned NULL, which means that the depth is too high (or deep?). So it's time for us to return NULL, too, in order to let the recursion end at this point (actually, it doesn't end, it just switches to a different part of the recursion tree).
         if ($fullnull) {
             return NULL;
         }
         // Return the array with all parsed objects
         return $retval;
     } else {
         // Same as before: Call getInstance for the meta-types, otherwise create an object with the type $this->type.
         if ($this->type == 'Profile') {
             $retval = Profile::getInstance($this->json, $this->depth);
         } else {
             if ($this->type == 'Taggable') {
                 $retval = Taggable::getInstance($this->json, $this->depth);
             } else {
                 $retval = new $this->type($this->json, $this->depth);
             }
         }
         //Performing getConnections() now, adding this element's connection into the big static queue
         if (NULL == $retval->getConnections()) {
             return NULL;
         }
         // Return the parsed object
         return $retval;
     }
 }
Ejemplo n.º 17
0
 function calcDistances($start)
 {
     // define an empty queue
     $q = new PriorityQueue();
     // push the starting vertex into the queue
     $q->insert($start, 0);
     $q->rewind();
     // mark the distance to it 0
     $start->distance = 0;
     while ($q->valid()) {
         $t = $q->extract();
         $t->visited = 1;
         foreach ($t->getRelations() as $key => $relation) {
             foreach ($relation as $object) {
                 if (!$object->visited) {
                     if ($object->distance > $t->distance + 1) {
                         $object->distance = $t->distance + 1;
                         $object->parent = $t;
                     }
                     $q->insert($object, $object->distance);
                 }
             }
         }
         $q->recoverFromCorruption();
         $q->rewind();
     }
 }