I am producing an rrd graph and I am facing 2 problems.
Problem 1: The numbers that I am printing they are integers without decimals, although when they are printed decimals appear. It is really confusing. So I looked online on the rrdgraph_graph and although that I am using the correct syntax and I am not applying any calculations I still do get floating values instead of integers.
According to the official website: %s place this after %le, %lf or %lg. This will be replaced by the appropriate SI magnitude unit and the value will be scaled accordingly (123456 -> 123.456 k).
I have attached a photo as sample of the output. I have also provide a working example code so if anyone understands the RRD's can view possible the error.
Problem 2: I was trying to add on my graph the VRULE:time#color[:legend][:dashes[=on_s[,off_s[,on_s,off_s]...]][:dash-offset=offset]] function and based on the online instructions I can supply the time. Since my graph is shifting I was planning to do time (value) - 1800 sec. I wanted to place a vertical line in the middle of the graph so I could view approximately an average on 30 minutes values. When I am applying such a format I get this error:
<b>Graph error: </b>parameter '1400274668-1800' does not represent time in line VRULE:1400274668-1800#0000CD:Half way values
When I remove the subtraction everything work fine. Is there a way to produce this line in the middle of my graph?
<?php
$file = "snmp";
$rrdFile = dirname(__FILE__) . "/".$file.".rrd";
$in = "losses";
$png = "/home/linux/Desktop/";
$in_min = "vdef_in_min";
$in_max = "vdef_in_max";
$in_lst = "vdef_in_lst";
$in_av = "vdef_in_av";
$title = "Losses RRD::Graph";
$output = array("1h","1d");
$step = 5;
$heartbeat = 2 * $step;
while (1) {
sleep (1);
$options = array(
"--start","now -15s",
"--step", "".$step."",
"DS:".$in.":GAUGE:".$heartbeat.":0:U",
"RRA:LAST:0.5:1:3600",
"RRA:MIN:0.5:1:3600",
"RRA:MAX:0.5:1:3600",
"RRA:AVERAGE:0.5:6:600",
"RRA:LAST:0.5:300:288",
"RRA:MIN:0.5:300:288",
"RRA:MAX:0.5:300:288`",
"RRA:AVERAGE:0.5:600:144"
);
if ( !isset( $create ) ) {
$create = rrd_create(
"".$rrdFile."",
$options
);
if ( $create === FALSE ) {
echo "Creation error: ".rrd_error()."\n";
}
}
$t = time();
$losses = rand(0, 150);
$update = rrd_update(
"".$rrdFile."",
array(
"".$t.":".$losses.""
)
);
if ($update === FALSE) {
echo "Update error: ".rrd_error()."\n";
}
date_default_timezone_set('Europe/Stockholm');
$timezone = new DateTime(NULL, new DateTimeZone('Europe/Stockholm'));
$date = date('l jS \of F Y h\\:i\\:s A' , $timezone->format('U'));
$comment = "RRD last updated:".$date;
$comment = str_replace( ":", "\\:", $comment );
$graph = "Graph last updated:".$date;
$graph = str_replace( ":", "\\:", $graph );
foreach ($output as $test) {
$final = array(
"--start","end - ".$test."",
"--end", "".$t."",
"--title=".$file." RRD::Graph with - ".$test." Periods",
"--vertical-label=Bytes(s)/sec",
"--right-axis-label=latency(ms)",
"--alt-y-grid", "--rigid",
"--width", "800", "--height", "500",
"--lower-limit=0",
"--no-gridfit",
"--slope-mode",
"DEF:".$in."_def=".$file.".rrd:".$in.":LAST",
"CDEF:inbytes=".$in."_def",
"VDEF:".$in_lst."=inbytes,LAST",
"VDEF:".$in_min."=inbytes,MINIMUM",
"VDEF:".$in_max."=inbytes,MAXIMUM",
"VDEF:".$in_av."=inbytes,AVERAGE",
"COMMENT:\\n",
"LINE2:".$in."_def#FF0000:".$in."",
"GPRINT:".$in_min.": Minimum\:%6.2lf %S",
"GPRINT:".$in_max.":Maximum\:%6.2lf %S",
"GPRINT:".$in_lst.":Last\:%6.2lf %s",
"GPRINT:".$in_av.":Average\:%6.2lf %s",
"COMMENT:\\n",
"VRULE:".$t."#0000CD:Half way values",
"COMMENT:\\n",
"HRULE:50#FFFF00:Maximum value",
"COMMENT:\\n",
"COMMENT: ",
"COMMENT:\\n",
"COMMENT:".$comment."\\r",
"COMMENT:".$graph."\\r"
);
$outputPngFile = rrd_graph(
"".$png."".$test.".png",
$final
);
if ($outputPngFile === FALSE) {
echo "<b>Graph error: </b>".rrd_error()."\n";
}
}
$debug = rrd_lastupdate (
"".$rrdFile.""
);
if ($debug === FALSE) {
echo "<b>Graph result error: </b>".rrd_error()."\n";
}
var_dump ($debug);
}
?>
The answer to your first problem is almost certainly Data Normalisation. Since you are not updating the RRD precisely on the Step boundary every time, the submitted data values are normalised to a step boundary, resulting in the decimal values. To understand this, read Alex van den Bogeardt's excellent article on the subject.
Your second problem is that you simply cannot use the VRULE declaration in that way. The first parameter to VRULE may be either a number or a VDEF variable, but it cannot be a formula. Therefore, VRULE:12345678#0000CD:Foo is fine, as is VRULE:vdefname#FF00FF:Bar. However you may not use VRULE:123456-123#0000CD:No. Do the calculation before, like this:
"VRULE:".($t-1800)."#0000CD:Half way values",
... and this should result in a valid syntax.
Related
I'm trying to calculate the RSI using the Poloniex API and PHP Trader EXtension. Here is what i have so far.
date_default_timezone_set( 'UTC' );
$api = new poloniex( 'xxxxxxx', 'xxxxx' );
$data = $api->getChartValues( 'BTC_LTC', strtotime( "-21 hours" ), time(), 300 );
print_r( $data);
$rsi = array();
foreach ( $data as $a )
{
$rsi[] = $a['close'];
}
$rsi = trader_rsi( array_reverse($rsi) , 14 );
The getChartValues calls the returnChartData API Function from Poloniex API.
After running the script, the output RSI is completely different than the valid one.
What i'm doing wrong?
maybe there is no need to reverse, here is my code that works fine
$rsi = array();
foreach ( $data as $a )
{
$rsi[] = $a['close'];
}
$rsi = trader_rsi( $rsi , 14 );
print_r( $rsi );
According to the RSI definition:
The relative strength index is calculated using the following formula:
RSI = 100 - 100 / (1 + RS)
Where RS = Average gain of up periods during the specified time frame / Average loss of down periods during the specified time frame/
[...]
The default time frame for comparing up periods to down periods is 14, as in 14 trading days.
Are you sure that the RS parameter in your computation is exactly the same than in "the valid one" ? And according to you what is "the valid one" source ?
I want to get specific content of a website into an array.
I have approx 20 sites to fetch the content and output in other ways i like.Only the port is always changing (not 27015, its than 27016 or so...)
This is just one: SOURCE-URL of Content
For now, i use this code in PHP to fetch the Gameicon "cs.png", but the icon varies in length - so it isn't the best way, or? :-/
$srvip = '148.251.78.214';
$srvlist = array('27015');
foreach ($srvlist as $srvport) {
$source = file_get_contents('http://www.gametracker.com/server_info/'.$srvip.':'.$srvport.'/');
$content = array(
"icon" => substr($source, strpos($source, 'game_icons64')+13, 6),
);
echo $content[icon];
}
Thanks for helping, some days are passed from my last PHP work :P
You just need to look for the first " that comes after the game_icons64 and read up to there.
$srvip = '148.251.78.214';
$srvlist = array('27015');
foreach ($srvlist as $srvport) {
$source = file_get_contents('http://www.gametracker.com/server_info/'.$srvip.':'.$srvport.'/');
// find the position right after game_icons64/
$first_occurance = strpos($source, 'game_icons64')+13;
// find the first occurance of " after game_icons64, where the src ends for the img
$second_occurance = strpos($source, '"', $first_occurance);
$content = array(
// take a substring starting at the end of game_icons64/ and ending just before the src attribute ends
"icon" => substr($source, $first_occurance, $second_occurance-$first_occurance),
);
echo $content['icon'];
}
Also, you had an error because you used [icon] and not ['icon']
Edit to match the second request involving multiple strings
$srvip = '148.251.78.214';
$srvlist = array('27015');
$content_strings = array( );
// the first 2 items are the string you are looking for in your first occurrence and how many chars to skip from that position
// the third is what should be the first char after the string you are looking for, so the first char that will not be copied
// the last item is how you want your array / program to register the string you are reading
$content_strings[] = array('game_icons64', 13, '"', 'icon');
// to add more items to your search, just copy paste the line above and change whatever you need from it
foreach ($srvlist as $srvport) {
$source = file_get_contents('http://www.gametracker.com/server_info/'.$srvip.':'.$srvport.'/');
$content = array();
foreach($content_strings as $k=>$v)
{
$first_occurance = strpos($source, $v[0])+$v[1];
$second_occurance = strpos($source, $v[2], $first_occurance);
$content[$v[3]] = substr($source, $first_occurance, $second_occurance-$first_occurance);
}
print_r($content);
}
I'm working on mining tweets using some text processing (with PHP) like removing html tags, mention / username, link, non-alphanumeric, repeating syllable n character, noise word
When I get search results and directly perform all processing mentioned above, my app does not give resulti. The app just can show results when do processing on
removing tag html, mentions, links, nonalphanum, n repeating character (not all textprocessing steps).
I want to ask why that in problems come, is PHP code has specific criteria in the process?
In PHP, is it possible to define order time text to be longer processing ? (so I can use all my process step)
Any help will be greatly appreciated. Thanks
I add all preprocessing line of codes. hope you can analyze if there any problem guys. Thanks
function addspaces($value){
return " ".$value." "; }
function containsTLD($string) {
preg_match(
"/(AC($|\/)|\.AD($|\/)|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\.QA($|\/)|\.RE($|\/)|\.RO($|\/)|\.RS($|\/)|\.RU($|\/)|\.RW($|\/)|\.SA($|\/)|\.SB($|\/)|\.SC($|\/)|\.SD($|\/)|\.SE($|\/)|\.SG($|\/)|\.SH($|\/)|\.SI($|\/)|\.SJ($|\/)|\.SK($|\/)|\.SL($|\/)|\.SM($|\/)|\.SN($|\/)|\.SO($|\/)|\.SR($|\/)|\.ST($|\/)|\.SU($|\/)|\.SV($|\/)|\.SY($|\/)|\.SZ($|\/)|\.TC($|\/)|\.TD($|\/)|\.TEL($|\/)|\.TF($|\/)|\.TG($|\/)|\.TH($|\/)|\.TJ($|\/)|\.TK($|\/)|\.TL($|\/)|\.TM($|\/)|\.TN($|\/)|\.TO($|\/)|\.TP($|\/)|\.TR($|\/)|\.TRAVEL($|\/)|\.TT($|\/)|\.TV($|\/)|\.TW($|\/)|\.TZ($|\/)|\.UA($|\/)|\.UG($|\/)|\.UK($|\/)|\.US($|\/)|\.UY($|\/)|\.UZ($|\/)|\.VA($|\/)|\.VC($|\/)|\.VE($|\/)|\.VG($|\/)|\.VI($|\/)|\.VN($|\/)|\.VU($|\/)|\.WF($|\/)|\.WS($|\/)|\.XN--0ZWM56D($|\/)|\.XN--11B5BS3A9AJ6G($|\/)|\.XN--80AKHBYKNJ4F($|\/)|\.XN--9T4B11YI5A($|\/)|\.XN--DEBA0AD($|\/)|\.XN--G6W251D($|\/)|\.XN--HGBK6AJ7F53BBA($|\/)|\.XN--HLCJ6AYA9ESC7A($|\/)|\.XN--JXALPDLP($|\/)|\.XN--KGBECHTV($|\/)|\.XN--ZCKZAH($|\/)|\.YE($|\/)|\.YT($|\/)|\.YU($|\/)|\.ZA($|\/)|\.ZM($|\/)|\.ZW)/i",
$string,
$M);
$has_tld = (count($M) > 0) ? true : false;
return $has_tld;
}
function cleaner($url) {
$U = explode(' ',$url);
$W =array();
foreach ($U as $k => $u) {
if (stristr($u,".")) {
if (containsTLD($u) === true) {
unset($U[$k]);
return cleaner( implode(' ',$U));
}
}
}
return implode(' ',$U);
}
$regexmention = "/(?<=^|(?<=[^a-zA-Z0-9-_\.]))#([A-Za-z-_\.]+[A-Za-z0-9]+)/i";
$reject = strtolower(implode(" ",file("file.txt")));//bikin deretan kata yg direject, mis: smartfren ga iya gue gw
$rejectarray = array_map('addspaces',explode(" ", $reject) );
$removehtmltag=strip_tags($tweet,"");
$removemention=strtolower(preg_replace($regexmention, "",$removehtmltag));
$removeurl=cleaner($removemention);
$removenonalfa = preg_replace("/[^A-Za-z0-9 ]/", " ",$removeurl );
$removerepeatchar = preg_replace("/(.)\\1+/", "$1", $removerepeatchar);
$removedigit = preg_replace('/\d/', " ", preg_replace("/(.)\\1+/", "$1", $removerepeatchar));
$removerepeatword = implode(' ',array_unique(preg_split('/[\s?:;,.]+/', $removedigit, -1, PREG_SPLIT_NO_EMPTY)));
$removedoublesyllable=preg_replace("/(.*)(\\1+)/", "", $removerepeatword ); //wkwk hahaha
$removeminimumthreechar = preg_replace("/\b\w{1,3}\b/", " ", $removedoublesyllable);
$removenoiseword = addspaces( $removeminimumthreechar ); // " saya ... bb "
$final=trim( str_replace($rejectarray, " ",$removenoiseword) );
//say
echo $final;
It seems that you are passing the maximum time allowed by the web server
Try to use set_time_limit
set_time_limit(0);
Or using too much memory, in this case modify php.ini memory_limit to something reasonable for your case like
memory_limit = 128M
I have to create an automatic weather including rain, snow, clouds, fog and sunny.
Depending on the season I need to set a percentage for all weather: the forecast will be updated 3 or 4 times during a day.
Example:
Winter | Rain: 30% Snow: 30% Sunny: 10% Cloudy: 10%, Fog: 20%
I do not know how to implement a random condition based on percentages. Some help?
Many thanks and sorry for my bad English.
Well, you can use:
$location = 'Rome';
$document = file_get_contents(str_replace(" ", "+", "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=".$location));
$xml = new SimpleXMLElement($document);
echo "$location: ".$xml->temp_c."° C";
Just take a look on the XML and see what data you have available.
EDIT
I didn't understand what the OP wanted the first time. Basically, it's even easier.
$weather = mt_rand(0,100);
$season = 'winter';
switch($season) {
case 'winter': {
if ($weather < 30) {
$output = 'Rainy';
} else if ($weather >=30 && $weather < 60) {
$output = 'Snowy';
}
// goes on on the same ideea of testing the value of $weather
break;
}
// other seasons
}
echo $output;
What I suggest tough, is to keep your values in arrays (for example the seasons) as well as the values for chances to have one type of weather or another.
array (
[winter] => array (
[30] => 'Rainy',
[60] => 'Snowy',
... // the other chances of weather
),
[spring] => array (
...
),
... // and so on
)
Use mt_rand(0,100) to get a random value and the array above to determine the weather.
Please let me know if this works for you.
Great answer by Claudiu but if you want to view with Fahrenheit (F) that possible example Below:
<?php
$location = 'Washington';
$document = file_get_contents(str_replace(" ", "+", "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" . $location));
$xml = new SimpleXMLElement($document);
echo $xml->temp_f . "° F";
?>
I have a question about str_replace in PHP. When I do:
$latdir = $latrichting.$Lat;
If (preg_match("/N /", $latdir)) {
$Latcoorl = str_replace(" N ", "+",$latdir);
}
else {
$Latcoorl = str_replace ("S ", "-",$latdir);
}
print_r($latdir);
print_r($Latcoorl);
print_r($latdir); gives :N52.2702777778
but print_r ($Latcoorl); gives :N52.270277777800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Yes, it adds a lot of zeros. Can someone explane this behavior just for the fun of it?
print_r ($latrichting);
give's: N
print_r ($Lat);
This give's the weird long number.
So its probably not the str_replace command, you think ?
$latmin2 = bcdiv($latsec, 60, 20);
$latmin_total = $latmin + $latmin2;
$lat = bcdiv($latmin_total, 60, 20);
$latdir = array("N" => 1, "S" => -1);
$latcoorl = $latdir * $latdir[$latrichting];
Happy New Year.
Your string replace search string has a space before the 'N' while the dumped value looks like it's N:
Not sure what it has to do with all the zeros though.
On my system this code fragment:
<?php
$latdir = ':N52.2702777778';
If (preg_match("/N /", $latdir)) {
$Latcoorl = str_replace(" N ", "+",$latdir);
}
else {
$Latcoorl = str_replace ("S ", "-",$latdir);
}
print_r($latdir);
print_r($Latcoorl);
?>
gives the following result:
:N52.2702777778:N52.2702777778
My best guess is you have something after this code that prints out a serie of 0.
How I would do it; just a variation of Anthony's original answer that keeps everything as numeric and doesn't lapse into string mode.
$Latcoorl = ($latrichting == "N") ? ($Lat) : (-1 * $Lat);
The string operations you did won't generate any 0s.
The 0s have to come from $lat. What did you do with $lat? any division by pi? PHP will try to store the most accurate possible float number in $lat. That's not really a problem, its a correct behavior. Just truncate the number when displayed, or round it up.