Example #1
0
 private function register($loop, $me)
 {
     $buffer = '';
     // Launching the linker
     $this->process = new \React\ChildProcess\Process('exec php linker.php', null, array('sid' => $this->sid, 'baseuri' => $this->baseuri));
     $this->process->start($loop);
     // Buffering the incoming data and fire it once its complete
     $this->process->stdout->on('data', function ($output) use($me, &$buffer) {
         if (substr($output, -1) == "") {
             $out = $buffer . substr($output, 0, -1);
             $buffer = '';
             $me->messageOut($out);
         } else {
             $buffer .= $output;
         }
     });
     // The linker died, we close properly the session
     $this->process->on('exit', function ($output) use($me) {
         echo colorize($this->sid, 'yellow') . " : " . colorize("linker killed \n", 'red');
         $me->process = null;
         $me->closeAll();
         $sd = new \Modl\SessionxDAO();
         $sd->delete($this->sid);
     });
     // Debug only, if the linker output some errors
     $this->process->stderr->on('data', function ($output) use($me) {
         echo $output;
     });
 }
function fail($msg = null)
{
    $fail_msg = colorize(" [✗] \n" . $msg, 'red', true);
    if ($msg) {
        $fail_msg .= "\n";
    }
    return $fail_msg;
}
/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    global $credentialsPath;
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(GAPI_SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');


    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        $authUrl = $client->createAuthUrl();
        $authCode = false;
        if (isset($_POST['authCode']) && $_POST['authCode']) {
            $authCode = $_POST['authCode'];
        }

        if (!$authCode) {
            printf("Open the following link in your browser:\n<a href='%s' target='_blank'>link</a>\n", $authUrl);
            echo "<form method='post'><input name='authCode'><input type='submit' name='Check auth code'></form>";
            die;
        }

        if ($authCode) {
            // Exchange authorization code for an access token.
            $accessToken = $client->authenticate($authCode);
            if (file_put_contents($credentialsPath, $accessToken)) {
                printf("Credentials saved to %s: " . colorize("SUCCESS", "SUCCESS") . "<br>", $credentialsPath);
            } else {
                printf("Credentials saved to %s: " . colorize("FAILED", "FAILURE") . "<br>", $credentialsPath);
                die;
            }
        } else {
            die("No authCode");
        }
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        echo "Token is Expired. Trying to refresh.. <br>";
        $client = refreshToken($client);
    } else {
        echo "Everything fine<br>";
    }

    return $client;
}
Example #4
0
function output_error_cache()
{
    global $error_cache, $error_abort;
    if (count($error_cache)) {
        echo colorize(TYPE_ERROR, "Failed");
        if (PHP_SAPI == 'cli') {
            echo "\n\n";
        } else {
            echo "<br /><ol>\n";
        }
        foreach ($error_cache as $error_msg) {
            if (PHP_SAPI == 'cli') {
                echo "\n";
            } else {
                echo "<li>";
            }
            switch ($error_msg['t']) {
                case TYPE_NOTICE:
                    $msg = 'NOTICE';
                    break;
                case TYPE_WARNING:
                    $msg = 'WARNING';
                    break;
                case TYPE_ERROR:
                    $msg = 'ERROR';
                    break;
            }
            echo colorize($error_msg['t'], $msg);
            if (PHP_SAPI == 'cli') {
                echo "\t" . $error_msg['m'];
            } else {
                echo " " . $error_msg['m'] . "</li>";
            }
        }
        if (PHP_SAPI == 'cli') {
            echo "\n";
        } else {
            echo "</ol>\n";
        }
    } else {
        echo colorize(TYPE_OK, "OK");
        if (PHP_SAPI == 'cli') {
            echo "\n";
        } else {
            echo "\n<br />";
        }
    }
    echo "\n";
    $error_cache = array();
}
function show_menu()
{
    echo colorize("\nWhat would you like to do:\n", 'blue', true);
    echo colorize("1> Create A User And A Tweet\n", 'blue', false);
    echo colorize("2> Read A User Record\n", 'blue', false);
    echo colorize("3> Batch Read Tweets For A User\n", 'blue', false);
    echo colorize("4> Scan All Tweets For All Users\n", 'blue', false);
    echo colorize("5> Check and Set -- Update User Password\n", 'blue', false);
    echo colorize("6> Query Tweets By Username And Users By Tweet Count Range\n", 'blue', false);
    echo colorize("7> Stream UDF -- Aggregation Based on Tweet Count By Region\n", 'blue', false);
    echo colorize("0> Exit\n", 'blue', false);
    echo colorize("\nSelect 0-7 and hit enter: ", 'blue', false);
    return intval(trim(readline()));
}
Example #6
0
function checkBOM($filename)
{
    global $auto;
    $contents = file_get_contents($filename);
    $charset[1] = substr($contents, 0, 1);
    $charset[2] = substr($contents, 1, 1);
    $charset[3] = substr($contents, 2, 1);
    if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
        if ($auto == 1) {
            $rest = substr($contents, 3);
            rewrite($filename, $rest);
            return colorize("BOM found, automatically removed.", "NOTE");
        } else {
            return colorize("BOM found", "WARNING");
        }
    } else {
        return colorize("BOM Not Found.", "WARNING");
    }
}
Example #7
0
 public function setWebsocket($baseuri, $port)
 {
     $explode = parse_url($baseuri);
     echo "\n" . "--- " . colorize("Server Configuration - Apache", 'purple') . " ---" . "\n";
     echo colorize("Enable the Secure WebSocket to WebSocket tunneling", 'yellow') . "\n# a2enmod proxy_wstunnel \n";
     echo colorize("Add this in your configuration file (default-ssl.conf)", 'yellow') . "\nProxyPass /ws/ ws://localhost:{$port}/\n";
     echo "\n" . "--- " . colorize("Server Configuration - nginx", 'purple') . " ---" . "\n";
     echo colorize("Add this in your configuration file", 'yellow') . "\n";
     echo "location /ws/ {\n    proxy_pass http://localhost:{$port}/;\n    proxy_http_version 1.1;\n    proxy_set_header Upgrade \$http_upgrade;\n    proxy_set_header Connection \"Upgrade\";\n    proxy_set_header Host \$host;\n    proxy_set_header X-Real-IP \$remote_addr;\n    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;\n    proxy_set_header X-Forwarded-Proto https;\n    proxy_redirect off;\n}\n\n";
     $path = $explode['host'] . $explode['path'];
     if ($explode['scheme'] == 'https') {
         $ws = 'wss://' . $path . 'ws/';
         $secured = 'true';
         echo colorize("Encrypted ", 'green') . "\n";
     } else {
         $ws = 'ws://' . $path . 'ws/';
         $secured = 'false';
         echo colorize("Unencrypted ", 'red') . "\n";
     }
     file_put_contents(CACHE_PATH . 'websocket', $secured);
     return $ws;
 }
 /**
  * Updates the user with the tweet count and latest tweet info
  * @param string $username
  * @param int $ts
  * @param int $tweet_count
  * @return boolean whether the update succeeded
  * @throws \Aerospike\Training\Exception
  */
 private function updateUser($username, $ts, $tweet_count)
 {
     $key = $this->getUserKey($username);
     $bins = array('tweetcount' => $tweet_count, 'lasttweeted' => $ts);
     echo colorize("Updating the user record ≻", 'black', true);
     if ($this->annotate) {
         display_code(__FILE__, __LINE__, 6);
     }
     $status = $this->client->put($key, $bins);
     if ($status !== Aerospike::OK) {
         echo fail();
         // throwing an \Aerospike\Training\Exception
         throw new Exception($this->client, "Failed to get the user {$username}");
     }
     echo success();
     return true;
 }
Example #9
0
if (isset($args['a']) || isset($args['annotate'])) {
    display_code(__FILE__, $start, __LINE__);
}
if (isset($args['a']) || isset($args['clean'])) {
    $start = __LINE__;
    echo colorize("Removing the records ≻", 'black', true);
    for ($i = 4; $i < 10; $i++) {
        $key = $db->initKey("test", "characters", $i);
        $db->remove($key);
    }
    if ($status == Aerospike::OK) {
        echo success();
    } else {
        echo standard_fail($db);
    }
    if (isset($args['a']) || isset($args['annotate'])) {
        display_code(__FILE__, $start, __LINE__);
    }
    $start = __LINE__;
    echo colorize("Dropping the index ≻", 'black', true);
    $status = $db->dropIndex("test", "age_index");
    if ($status == Aerospike::OK) {
        echo success();
    } else {
        echo standard_fail($db);
    }
    if (isset($args['a']) || isset($args['annotate'])) {
        display_code(__FILE__, $start, __LINE__);
    }
}
$db->close();
            // roll back the test value
            $kv['v']--;
        }
    } else {
        $res = $db->get($key, $r);
        $reads++;
        if ($res != Aerospike::OK) {
            $read_fails++;
        } elseif ($r['bins']['v'] != $kv['v']) {
            $read_fails++;
        }
    }
}
$end = microtime(true);
if ($read_fails == 0 && $write_fails == 0) {
    echo success();
} else {
    echo standard_fail($db);
}
echo colorize("{$num_ops} serial operations, {$reads} reads, {$writes} writes (every {$write_every} records)\n", 'green', true);
$color = $read_fails > 0 ? 'red' : 'green';
echo colorize("Failed reads: {$read_fails}\n", $color, true);
$color = $write_fails > 0 ? 'red' : 'green';
echo colorize("Failed writes: {$write_fails}\n", $color, true);
$delta = $end - $begin;
$tps = $num_ops / $delta;
echo colorize("Total time: {$delta}s TPS:{$tps}\n", 'purple', true);
$db->close();
?>

Example #11
0
$un = trim(fgets(STDIN));
if (empty($un)) {
    $un = 'username';
}
$config['username_property'] = $un;
unset($un);
// A property of the above model to use for passwords.
echo colorize('Model property for hashed password', 'cyan', true) . ' [password]: ';
$pw = trim(fgets(STDIN));
if (empty($pw)) {
    $pw = 'password';
}
$config['password_property'] = $pw;
unset($pw);
// Get a unique password salt. Generate a random one if the user doesn't specify one.
echo colorize('Unique password salt', 'cyan', true) . ' [' . colorize('Randomly Generated', 'green') . ']: ';
$salt = trim(fgets(STDIN));
if (empty($salt)) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
    $salt = '';
    for ($i = 0; $i < 72; $i++) {
        $salt .= substr($chars, rand(0, strlen($chars) - 1), 1);
    }
}
$config['auth_salt'] = $salt;
unset($salt, $chars, $i);
echo "Installing configuration profile...\n";
// Write the new configuration to the config file
$installationValues = <<<EOF
<?php
/**
 * @param string $value
 * @return string
 */
function convertForOutput($value, $color = COLOR_PURPLE)
{
    if ($GLOBALS['ricegrain-validator-colorize'] == true) {
        return colorize(var_export($value, true), $color);
    } else {
        return var_export($value, true);
    }
}
 /**
  * Create database schema
  */
 public function create_schema()
 {
     if (!$this->tables) {
         die('No tables given');
     }
     // Create each table
     foreach ($this->tables as $table => $schema) {
         // Report status to user
         print 'Dropping table ' . colorize($table, 'yellow') . "\n";
         // Remove table
         $this->db->query("DROP TABLE IF EXISTS \"{$table}\"");
         $sql = "CREATE TABLE \"{$table}\" (\n";
         $index = array();
         $unique = array();
         // Defaults for columns
         $defaults = array('type' => 'string', 'length' => NULL, 'index' => FALSE, 'null' => TRUE, 'default' => '', 'unique' => FALSE, 'precision' => 0, 'scale' => 0);
         foreach ($schema as $column => $data) {
             $data = $data + $defaults;
             $type = $data['type'];
             // Integer?
             if ($type == 'primary' or $type == 'integer') {
                 // Default to int
                 $length = $data['length'] ? $data['length'] : 2147483647;
                 if ($length <= 32767) {
                     $type = 'smallint';
                 } elseif ($length <= 2147483647) {
                     $type = 'integer';
                 } else {
                     $type = 'bigint';
                 }
                 // Is this the primary column?
                 if ($data['type'] == 'primary') {
                     $primary = $column;
                     // Primary keys are special
                     $sql .= "\t\"{$column}\" serial primary key,\n";
                     continue;
                 }
             } elseif ($type == 'string') {
                 // Even if "text" isn't a valid type in SQL
                 // PostgreSQL treats it the same as "character varying" (i.e. "varchar")
                 $type = 'text';
             } elseif ($type == 'boolean') {
                 $type = 'boolean';
             } elseif ($type == 'decimal') {
                 $type = 'decimal(' . $data['precision'] . ',' . $data['scale'] . ')';
             } else {
                 $type = 'timestamp without time zone';
             }
             // Build Column Definition
             $sql .= "\t\"{$column}\" {$type}";
             // NULL and FALSE are both valid defaults
             if ($data['default'] !== '') {
                 if (is_bool($data['default']) or $data['default'] === NULL) {
                     $sql .= ' DEFAULT ' . $data['default'];
                 } else {
                     $sql .= ' DEFAULT \'' . $data['default'] . "'";
                 }
             }
             // Add NULL
             if (!$data['null']) {
                 $sql .= ' NOT NULL';
             }
             $sql .= ",\n";
             // Is the column unique?
             if ($data['unique']) {
                 $unique[] = $column;
             }
             // Index the column?
             if ($data['index']) {
                 $index[] = $column;
             }
         }
         foreach ($unique as $column) {
             $key = $table . '_' . $column . '_u';
             //.chr(mt_rand(65,90));
             $sql .= "CONSTRAINT {$key} UNIQUE ({$column}),\n";
             // Creating a unique constraint automattically creates an index
             foreach ($index as $id => $field) {
                 if ($field === $column) {
                     unset($index[$id]);
                 }
             }
         }
         // Remove ending comma and close table
         $sql = substr($sql, 0, -2) . "\n);";
         // Create table
         print $sql . "\n";
         $this->db->query($sql);
         // Create any indexes
         foreach ($index as $column) {
             $key = $table . '_' . $column . '_i';
             //.chr(mt_rand(65,90));
             $sql = "CREATE INDEX {$key} ON \"{$table}\" USING btree ({$column})";
             print $sql . "\n";
             $this->db->query($sql);
         }
         // Report status to user
         print 'Created table ' . colorize($table, 'green') . "\n\n";
     }
     print colorize('Schema Created', 'blue') . "\n\n";
 }
Example #14
0
function liveExecuteCommand($cmd)
{
    echo "<pre>";
    while (@ob_end_flush()) {
    }
    // end all output buffers if any
    //	$process = popen("$cmd 2>&1 ; echo Exit status : $?", 'r');
    $process = popen("{$cmd} 2>&1", 'r');
    $complete_output = "";
    while (!feof($process)) {
        $live_output = fread($process, 100);
        $complete_output = $complete_output . $live_output;
        $live_output = colorize(str_replace(chr(10), '<br />', $live_output));
        echo "{$live_output}";
        @ob_flush();
        @flush();
    }
    pclose($process);
    // get exit status
    preg_match('/[0-9]+$/', $complete_output, $matches);
    echo "</pre>";
    // return exit status and intended output
    if (isset($matches[0])) {
        return array('exit_status' => $matches[0], 'output' => str_replace("Exit status : " . $matches[0], '', $complete_output));
    }
}
Example #15
0
function comploc()
{
    echo colorize("Locales compiler\n", 'green');
    $folder = CACHE_PATH . '/locales/';
    if (!file_exists($folder)) {
        $bool = mkdir($folder);
        if (!$bool) {
            echo colorize("The locales cache folder can't be created", 'red');
            exit;
        }
    } else {
        echo colorize("Folder already exist, don't re-create it\n", 'red');
    }
    $langs = loadLangArray();
    foreach ($langs as $key => $value) {
        $langarr = parseLangFile(DOCUMENT_ROOT . '/locales/' . $key . '.po');
        $out = '<?php global $translations;
        $translations = array(';
        foreach ($langarr as $msgid => $msgstr) {
            if ($msgid != '') {
                $out .= '"' . $msgid . '" => "' . $msgstr . '",' . "\n";
            }
        }
        $out .= ');';
        $fp = fopen($folder . $key . '.php', 'w');
        fwrite($fp, $out);
        fclose($fp);
        echo "- {$key} compiled\n";
    }
}
echo "\n";
echo 'Printing csv...';
echo "\n";
echo "\n";
$file = fopen('results.csv', 'w');
function cmp($a, $b)
{
    if ($a['points'] > $b['points']) {
        return $a;
    } else {
        return $b;
    }
}
//usort($memo_array,'cmp');
//$count = 250;
//while($count > 0){
foreach ($memo_array as $row) {
    if ($row['points'] > 250) {
        fputcsv($file, $row);
    }
    //$count = $count-1;
}
//}
echo colorize(" Done! ", "SUCCESS");
echo "\n";
echo "\n";
echo " Check your desktop for ";
echo colorize(" results.csv ", "FAILURE");
echo "\n";
echo "\n";
exit;
Example #17
0
function download_composer($url)
{
    echo 'Downloading composer...';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $binary = curl_exec($ch);
    if (curl_errno($ch)) {
        echo colorize('FAILED!' . PHP_EOL . curl_error($ch), 'FAILURE');
        curl_close($ch);
        return false;
    }
    $fp = fopen(ROOT_PATH . 'composer.phar', 'wb');
    fputs($fp, $binary);
    fclose($fp);
    curl_close($ch);
    echo 'Done!' . PHP_EOL;
}
 /**
  * Create database schema
  */
 public function create_schema()
 {
     if (!$this->tables) {
         die('No tables given');
     }
     // First force the schema to use UTF-8
     //$this->db->query("ALTER DATABASE `micromvc` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
     // Create each table
     foreach ($this->tables as $table => $schema) {
         // Report status to user
         print 'Dropping table ' . colorize($table, 'green') . "\n";
         // Remove table
         $this->db->query("DROP TABLE IF EXISTS `{$table}`");
         $sql = "CREATE TABLE `{$table}` (\n";
         $index = array();
         $unique = array();
         $primary = NULL;
         // Defaults for columns
         $defaults = array('type' => 'string', 'length' => NULL, 'index' => FALSE, 'null' => TRUE, 'default' => NULL, 'unique' => FALSE, 'precision' => 0, 'scale' => 0);
         foreach ($schema as $column => $data) {
             $data = $data + $defaults;
             $type = $data['type'];
             // Integer?
             if ($type == 'primary' or $type == 'integer') {
                 // Default to int
                 $length = $data['length'] ? $data['length'] : 2147483647;
                 if ($length <= 127) {
                     $type = 'TINYINT';
                 } elseif ($length <= 32767) {
                     $type = 'SMALLINT';
                 } elseif ($length <= 8388607) {
                     $type = 'MEDIUMINT';
                 } elseif ($length <= 2147483647) {
                     $type = 'INT';
                 } else {
                     $type = 'BIGINT';
                 }
                 // Is this the primary column?
                 if ($data['type'] == 'primary') {
                     $primary = $column;
                     // Primary keys are special
                     $sql .= "\t`{$column}` {$type} unsigned NOT NULL AUTO_INCREMENT,\n";
                     continue;
                 }
             } elseif ($type == 'string') {
                 // Default to text
                 $length = $data['length'] ? $data['length'] : 65535;
                 if ($length <= 255) {
                     $type = 'VARCHAR(' . $length . ')';
                 } elseif ($length <= 65535) {
                     $type = 'TEXT';
                 } elseif ($length <= 16777215) {
                     $type = 'MEDIUMTEXT';
                 } else {
                     $type = 'LONGTEXT';
                 }
             } elseif ($type == 'boolean') {
                 $type = 'TINYINT(1)';
             } elseif ($type == 'decimal') {
                 $type = 'DECIMAL(' . $data['precision'] . ',' . $data['scale'] . ')';
             } else {
                 $type = 'DATETIME';
             }
             // Build Column Definition
             $sql .= "\t`{$column}` {$type}";
             if (!$data['null']) {
                 $sql .= ' NOT NULL';
             }
             if ($data['default']) {
                 $sql .= ' DEFAULT \'' . $data['default'] . "'";
             }
             $sql .= ",\n";
             // Is the column unique?
             if ($data['unique']) {
                 $unique[] = $column;
             }
             // Index the column?
             if ($data['index']) {
                 $index[] = $column;
             }
         }
         if ($primary) {
             $sql .= "PRIMARY KEY (`{$primary}`),\n";
         }
         foreach ($unique as $column) {
             $sql .= "UNIQUE KEY `{$column}` (`{$column}`),\n";
         }
         foreach ($index as $column) {
             $sql .= "KEY `{$column}` (`{$column}`),\n";
         }
         // Remove ending comma
         $sql = substr($sql, 0, -2) . "\n";
         $sql .= ') ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
         //$sql .=') ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci';
         // Create table
         $this->db->query($sql);
         // Report status to user
         print 'Created table ' . colorize($table, 'green') . "\n";
     }
     print colorize('Schema Created', 'blue') . "\n\n";
 }
Example #19
0
/**
 * Uses getWeatherXML to retrieve TAF info, then parses it and returns array
 *
 * @param int $altn
 * @return array
 */
function getTafs($altn = 0)
{
    $tafs = array();
    $wx = new phpweather();
    $xml = getWeatherXml('tafs', $altn);
    $ap_array = getAirportArray($altn);
    $severe_wx = getSevereWxSettings();
    foreach ($xml->data->TAF as $taf) {
        $metCondition = 1;
        $decoded_taf = $wx->decode_taf($taf->raw_text);
        $station_id = (string) $taf->station_id;
        foreach ($decoded_taf['periods1'] as $period) {
            if (isset($period['desc']['clouds'])) {
                foreach ($period['desc']['clouds'] as $clouds) {
                    if ($clouds['condition'] == 'BKN' || $clouds['condition'] == 'OVC' || $clouds['condition'] == 'VV') {
                        if ($clouds['ft'] < $ap_array[$station_id]['2_ceil']) {
                            if ($clouds['ft'] < $ap_array[$station_id]['3_ceil']) {
                                $metCondition = 3;
                                $decoded_taf['taf'] = colorize($clouds['coded'], $decoded_taf['taf'], 'red');
                            } else {
                                if ($metCondition == 1) {
                                    $metCondition = 2;
                                }
                                $decoded_taf['taf'] = colorize($clouds['coded'], $decoded_taf['taf']);
                            }
                        }
                    }
                }
            }
            if (isset($period['desc']['visibility'])) {
                foreach ($period['desc']['visibility'] as $vis) {
                    if ($vis['meter'] < $ap_array[$station_id]['2_vis']) {
                        if ($vis['meter'] < $ap_array[$station_id]['3_vis']) {
                            $metCondition = 3;
                            $decoded_taf['taf'] = colorize($vis['coded'], $decoded_taf['taf'], 'red');
                        } else {
                            if ($metCondition == 1) {
                                $metCondition = 2;
                            }
                            $decoded_taf['taf'] = colorize($vis['coded'], $decoded_taf['taf']);
                        }
                    }
                }
            }
            if (isset($period['desc']['weather'])) {
                foreach ($period['desc']['weather'] as $sigwx) {
                    if (in_array($sigwx['coded'], $severe_wx['yellow'])) {
                        if ($metCondition == 1) {
                            $metCondition = 2;
                        }
                        $decoded_taf['taf'] = colorize($sigwx['coded'], $decoded_taf['taf']);
                    }
                    if (in_array($sigwx['coded'], $severe_wx['red'])) {
                        $metCondition = 3;
                        $decoded_taf['taf'] = colorize($sigwx['coded'], $decoded_taf['taf'], 'red');
                    }
                }
            }
        }
        $tafs[$station_id] = array('station_id' => $station_id, 'raw' => (string) $decoded_taf['taf'], 'metCondition' => $metCondition);
    }
    return $tafs;
}
Example #20
0
function dev_GenericEventPrinter($arg1, $arg2, $arg3, $arg4, $arg5, $arg6, $arg7, $arg8)
{
    global $dial_events_log;
    if (!empty($dial_events_log)) {
        $s = getTimeStamp() . " ";
        $s .= str_pad($arg1, 8, " ", STR_PAD_BOTH);
        $s .= str_pad($arg2, 6, " ", STR_PAD_BOTH);
        $s .= str_pad($arg3, 16, " ", STR_PAD_BOTH);
        $s .= str_pad($arg4, 16, " ", STR_PAD_BOTH);
        $s .= str_pad($arg5, 55, " ", STR_PAD_BOTH);
        $s .= str_pad($arg6, 55, " ", STR_PAD_BOTH);
        $s .= str_pad($arg7, 17, " ", STR_PAD_BOTH);
        $s .= str_pad($arg8, 20, " ", STR_PAD_BOTH);
        logLine($s, $dial_events_log . ".txt");
        $s = '<div style="font-size:90%;white-space:nowrap;"><span style="font-family:monospace;">' . date('[H:i:s]') . "</span>";
        $s .= colorize(str_pad($arg1, 8, "_", STR_PAD_BOTH));
        $s .= colorize(str_pad($arg2, 6, "_", STR_PAD_BOTH));
        $s .= colorize(str_pad($arg3, 16, "_", STR_PAD_BOTH));
        $s .= colorize(str_pad($arg4, 16, "_", STR_PAD_BOTH));
        $s .= colorize(str_pad($arg5, 55, "_", STR_PAD_BOTH));
        $s .= colorize(str_pad($arg6, 55, "_", STR_PAD_BOTH));
        $s .= colorize(str_pad($arg7, 17, "_", STR_PAD_BOTH));
        $s .= colorize(str_pad($arg8, 20, "_", STR_PAD_BOTH));
        $s = preg_replace("/_/", "&nbsp;", $s);
        $s = logLine($s . "</div>", $dial_events_log);
    }
}
Example #21
0
function status($type, $text = '')
{
    switch ($type) {
        case 'write':
        case 'create':
        case 'prepare':
            action('green', $type, $text);
            break;
        case 'empty':
        case 'remove':
            action('red', $type, $text);
            break;
        case 'move':
        case 'rename':
            action('cyan', $type, $text);
            break;
        case 'copy':
        case 'update':
        case 'hydrate':
            action('brown', $type, $text);
            break;
        default:
            $text = str_replace(APP_PATH . DIRECTORY_SEPARATOR, '', $text);
            $prefix = str_pad("\\bwhite({$type})\\b", 25, ' ', STR_PAD_LEFT);
            writeln(colorize("{$prefix}  {$text}"));
            break;
    }
}
Example #22
0
function handleSSLErrors($errno, $errstr)
{
    fwrite(STDERR, colorize(getenv('sid'), 'yellow') . " : " . colorize($errstr, 'red') . "\n");
}
Example #23
0
    var_dump($response);
}
if (isset($args['a']) || isset($args['annotate'])) {
    display_code(__FILE__, $start, __LINE__);
}
echo colorize("Using infoMany() to get the build of each Aerospike cluster node ≻", 'black', true);
$start = __LINE__;
$response = $db->infoMany('build');
if ($response == NULL) {
    echo $db->errorno();
    echo standard_fail($db);
} else {
    echo success();
    var_dump($response);
}
if (isset($args['a']) || isset($args['annotate'])) {
    display_code(__FILE__, $start, __LINE__);
}
echo colorize("Using getNodes() to fetch the address of all the cluster nodes ≻", 'black', true);
$start = __LINE__;
$nodes = $db->getNodes();
if ($nodes == NULL) {
    echo standard_fail($db);
} else {
    echo success();
    var_dump($nodes);
}
if (isset($args['a']) || isset($args['annotate'])) {
    display_code(__FILE__, $start, __LINE__);
}
$db->close();
        echo success();
    } else {
        echo standard_fail($db);
    }
    if (isset($args['a']) || isset($args['annotate'])) {
        display_code(__FILE__, $start, __LINE__);
    }
    $start = __LINE__;
    echo colorize("Dropping the index ≻", 'black', true);
    $status = $db->dropIndex("test", "age_index");
    if ($status == Aerospike::OK) {
        echo success();
    } else {
        echo standard_fail($db);
    }
    if (isset($args['a']) || isset($args['annotate'])) {
        display_code(__FILE__, $start, __LINE__);
    }
    echo colorize("De-Registering the UDF module ≻", 'black', true);
    $start = __LINE__;
    $status = $db->deregister("example_aggregate_udf.lua");
    if ($status == Aerospike::OK) {
        echo success();
    } else {
        echo standard_fail($db);
    }
    if (isset($args['a']) || isset($args['annotate'])) {
        display_code(__FILE__, $start, __LINE__);
    }
}
$db->close();
Example #25
0
$booted = $bootstrap->boot();
$argsize = count($argv);
if ($argsize == 1) {
    echo colorize("Please specify a base uri eg.", "red") . colorize(" http://myhost.com/movim/\n", 'yellow');
    exit;
}
if ($argsize == 2) {
    echo colorize("Please specify a port eg.", "red") . colorize(" 8080\n", 'yellow');
    exit;
}
$md = Modl\Modl::getInstance();
$infos = $md->check();
if ($infos != null) {
    echo colorize("The database need to be updated before running the daemon\n", 'green');
    foreach ($infos as $i) {
        echo colorize($i . "\n", 'blue');
    }
    echo colorize("\nTo update the database run\n", 'green');
    echo colorize("php mud.php db --set\n", 'purple');
    exit;
}
$loop = Factory::create();
$core = new Core($loop, $argv[1], $argv[2]);
$app = new HttpServer(new WsServer($core));
$socket = new Reactor($loop);
$socket->listen($argv[2], '127.0.0.1');
$socketApi = new Reactor($loop);
new Api($socketApi, $core);
$socketApi->listen(1560);
$server = new IoServer($app, $socket, $loop);
$server->run();
function adaptResults ( $oldName, $oldCountry, $newName, $newCountry, $newId ) {
#----------------------------------------------------------------------

  #--- Mysql-ify.
  $oldName    = mysqlEscape( $oldName );
  $oldCountry = mysqlEscape( $oldCountry );
  $newName    = mysqlEscape( $newName );
  $newCountry = mysqlEscape( $newCountry );
  $newId      = mysqlEscape( $newId );

  #--- Build the command.  
  $command = "
    UPDATE Results
    SET personName='$newName', countryId='$newCountry', personId='$newId'
    WHERE personName='$oldName' AND countryId='$oldCountry' AND personId=''
  ";
  
  #--- Show the command.
  echo colorize( $command );
  
  #--- Execute the command.
  dbCommand( $command );
}
Example #27
0
$start = __LINE__;
$status = $db->scan("test", null, function ($record) {
    if (array_key_exists('email', $record['bins']) && !is_null($record['bins']['email']) && array_key_exists('name', $record['bins']) && !is_null($record['bins']['name'])) {
        echo "\n({$record['key']['ns']},{$record['key']['set']}," . base64_encode($record['key']['digest']) . ")";
    }
});
if ($status != AEROSPIKE::OK) {
    echo standard_fail($db);
} else {
    echo success();
}
if (isset($args['a']) || isset($args['annotate'])) {
    display_code(__FILE__, $start, __LINE__);
}
if (isset($args['a']) || isset($args['clean'])) {
    $start = __LINE__;
    echo colorize("Removing the record ≻", 'black', true);
    $key = $db->initKey("test", "users", 1234);
    $status = $db->remove($key);
    $key = $db->initKey("test", "users", 2345);
    $status = $db->remove($key);
    if ($status == Aerospike::OK) {
        echo success();
    } else {
        echo standard_fail($db);
    }
    if (isset($args['a']) || isset($args['annotate'])) {
        display_code(__FILE__, $start, __LINE__);
    }
}
$db->close();
 /**
  * Updates the user with the tweet count and latest tweet info
  * @param string $username
  * @param int $ts
  * @param int $tweet_count
  * @return boolean whether the update succeeded
  * @throws \Aerospike\Training\Exception
  */
 private function updateUser($username, $ts, $tweet_count)
 {
     // @todo make sure the getUserKey() method of BaseService.php is working
     $key = $this->getUserKey($username);
     $bins = array('tweetcount' => $tweet_count, 'lasttweeted' => $ts);
     echo colorize("Updating the user record ≻", 'black', true);
     // @todo write the user record to the database
     //$status = ...
     if ($status !== Aerospike::OK) {
         echo fail();
         // throwing an \Aerospike\Training\Exception
         throw new Exception($this->client, "Failed to get the user {$username}");
     }
     echo success();
     return true;
 }
Example #29
0
 if (!empty($message)) {
     $restart = false;
     if ($message == '</stream:stream>') {
         $conn->close();
         $loop->stop();
     } elseif ($message == "<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>" || $message == '<proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>') {
         stream_set_blocking($conn->stream, 1);
         $out = stream_socket_enable_crypto($conn->stream, 1, STREAM_CRYPTO_METHOD_TLS_CLIENT);
         $restart = true;
     }
     #fwrite(STDERR, colorize($message, 'yellow')." : ".colorize('received', 'green')."\n");
     #fwrite(STDERR, colorize(getenv('sid'), 'yellow')." widgets : ".\sizeToCleanSize(memory_get_usage())."\n");
     \Moxl\API::clear();
     \RPC::clear();
     if (!$parser->parse($message)) {
         fwrite(STDERR, colorize(getenv('sid'), 'yellow') . " " . $parser->getError() . "\n");
     }
     if ($restart) {
         $session = \Sessionx::start();
         \Moxl\Stanza\Stream::init($session->host);
         stream_set_blocking($conn->stream, 0);
         $restart = false;
     }
     $msg = \RPC::commit();
     \RPC::clear();
     if (!empty($msg)) {
         echo base64_encode(gzcompress(json_encode($msg), 9)) . "";
         #fwrite(STDERR, colorize($msg.' '.strlen($msg), 'yellow')." : ".colorize('sent to browser', 'green')."\n");
     }
     $xml = \Moxl\API::commit();
     \Moxl\API::clear();
 /**
  * Asks the developer for input and finds the aggregated users by region
  * that fit a tweet count range
  * @throws \Aerospike\Training\Exception
  */
 public function aggregateUsersByRegion()
 {
     echo colorize("\nAggregate user's by region whose tweet count is in a given range", 'blue', true) . "\n";
     echo colorize("This is part of the Aggregations exercises", 'red', true) . "\n";
 }