Converting Python Code to PHP [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
Is there a software converter out there that can automatically convert this python code to PHP?
#!/usr/bin/python
import math
def calcNumEntropyBits(s):
if len(s) <= 0: return 0.0
symCount = {}
for c in s:
if c not in symCount: symCount[c] = 1
else: symCount[c] += 1
entropy = 0.0
for c,n in symCount.iteritems():
prob = n / float(len(s))
entropy += prob * (math.log(prob)/math.log(2))
if entropy >= 0.0: return 0.0
else: return -(entropy*len(s))
def testEntropy(s):
print "Bits of entropy in '%s' is %.2f" % (s, calcNumEntropyBits(s))
testEntropy('hello world')
testEntropy('bubba dubba')
testEntropy('aaaaaaaaaaa')
testEntropy('aaaaabaaaaa')
testEntropy('abcdefghijk')

I'm not aware of any Python-to-PHP converter in the wild, but it should be a trivial task to port and the similarities are quite easy to spot:
function calcNumEntropyBits($s) {
if (strlen($s) <= 0) return 0.0;
$symCount = array();
foreach (str_split($s) as $c) {
if (!in_array($c,$symCount)) $symCount[$c] = 1;
else $symCount[$c] ++;
}
$entropy = 0.0;
foreach ($symCount as $c=>$n) {
$prob = $n / (float)strlen($s);
$entropy += $prob * log($prob)/log(2);
}
if ($entropy >= 0.0) return 0.0;
else return -($entropy*strlen($s));
}
function testEntropy($s):
printf("Bits of entropy in '%s' is %.2f",$s,calcNumEntropyBits($s));
testEntropy('hello world');
testEntropy('bubba dubba');
testEntropy('aaaaaaaaaaa');
testEntropy('aaaaabaaaaa');
testEntropy('abcdefghijk');
The last few lines in the first function could have also been written as a standard PHP ternary expression:
return ($entropy >= 0.0)? 0.0: -($entropy*strlen($s));

I created a python-to-php converter called py2php. It can auto-translate the basic logic and then you will need to tweak library calls, etc. Still experimental.
Here is auto-generated PHP from the python provided by the OP.
<?php
require_once('py2phplib.php');
require_once( 'math.php');
function calcNumEntropyBits($s) {
if ((count($s) <= 0)) {
return 0.0;
}
$symCount = array();
foreach( $s as $c ) {
if (!$symCount.__contains__($c)) {
$symCount[$c] = 1;
}
else {
$symCount[$c] += 1;
}
}
$entropy = 0.0;
foreach( $symCount->iteritems() as $temp_c ) {
$prob = ($n / float(count($s)));
$entropy += ($prob * (math::log($prob) / math::log(2)));
}
if (($entropy >= 0.0)) {
return 0.0;
}
else {
return -($entropy * count($s));
}
}
function testEntropy($s) {
pyjslib_printFunc(sprintf('Bits of entropy in \'%s\' is %.2f', new pyjslib_Tuple([$s, calcNumEntropyBits($s)])));
}
testEntropy('hello world');
testEntropy('bubba dubba');
testEntropy('aaaaaaaaaaa');
testEntropy('aaaaabaaaaa');
testEntropy('abcdefghijk');
It would not run correctly due to the math import and __contains__, but those would be easy enough to fix by hand.

I am about 1/2 way done making a PHP interpreter in Python and I can tell you flat out that there are literally dozens of major edge cases that play out to thousands of possibilities that would make it almost impossible to port Python to PHP. Python has a much more robust grammar then PHP while further foward in the language, Python's stdlib is probably one of the most advanced in comparison to any other language in it's class.
My recommendation is to take your question one step further back, to why do you need a set of Python based logic in PHP. Alternatives to attempting to port/translate your code could include subprocessing from PHP to Python, using Gearman to have Python do work in the backend while PHP handles view logic, or a much more involved solution would be to implement a service bus or message queue between a PHP application and Python services.
PS. Apologies for any readability issues, finishing a 2 day sprint just now.

No such tool exists, you'll have to port the code yourself

I changed the library py2php from https://github.com/dan-da/py2php and forked it into a new repository at https://github.com/bunkahle/py2php
You now can also use the python math library which is translated to PHP code. Still you have to do adaptations to your code in order to get it to work.

I wondered myself that same question, and I found this PyToPhp.py file in the GitHubGist site. It is simple, and seem an start point for the begining.
I'm going to take a look to it!!!

Related

Arithmetic on large numbers

I've been thinking about ways to program for exteme distances, in the game Hellion for example, orbits could be near to scale in the ranges of millions of kilometers. However there was a common glitch where movement would be very choppy the further you were from the object you were orbiting. I might be wrong in my speculation to why that was, but my best guess was that it was down to loss of precision at that distance.
As a little exercise I've been thinking about ways to solve that problem and what I currently have is a a pretty basic unit staged distance system.
class Distance
{
public const MAX_AU = 63018.867924528;
public const MAX_MM = 149598000000000;
private $ly = 0;
private $au = 0;
private $mm = 0;
public function add(Distance $add): Distance
{
$distance = new Distance();
$distance->mm = $this->mm + $add->mm;
if ($distance->mm > self::MAX_MM) {
$distance->mm-= self::self::MAX_MM;
$distance->au++;
}
$distance->au+= $this->au + $add->au;
if ($distance->au > self::MAX_AU) {
$distance->au-= self::self::MAX_AU;
$distance->ly++;
}
$distance->ly+= $this->ly + $add->ly;
return $distance;
}
}
I put in the addition method, which is written as though by hand. I didn't want to use arbitary precision because it would have been too extreme for calculating the smaller distances a player would normally interact with.
My question is; is this how something like this is normally done? and if not, could someone please explain what is wrong with this (inefficient for example), and how it could be done better?
Thanks
PS. I am aware that in the context of a game, this is normally handled with sub-grids, but to simulate how objects in orbit would drift apart, thats what this is for.
You can use the BCMath functions. BCMath supports numbers of any size and precision.
Example:
$mm = "149598000000000";
$au = "63018.867924528";
$sum = bcadd($mm,$au,10);
echo $sum;
//149598000063018.8679245280

Array Insert Time Jump

During deep researching about hash and zval structure and how arrays are based on it, faced with strange insert time.
Here is example:
$array = array();
$someValueToInsert = 100;
for ($i = 0; $i < 10000; ++$i) {
$time = microtime(true);
array_push($array, $someValueToInsert);
echo $i . " : " . (int)((microtime(true) - $time) * 100000000) . "</br>";
}
So, I found that every 1024, 2024, 4048... element will be inserted using much more time(>~x10).
It doesn't depends will I use array_push, array_unshift, or simply $array[] = someValueToInsert.
I'm thinking about that in Hash structure:
typedef struct _hashtable {
...
uint nNumOfElements;
...
} HashTable;
nNumOfElements has default max value, but it doesn't the answer why does it took more time to insert in special counters(1024, 2048...).
Any thoughts ?
While I would suggest double checking my answer on the PHP internals list, I believe the answer lay in zend_hash_do_resize(). When more elements are needed in the hash table, this function is called and the extant hash table is doubled in size. Since the table starts life at 1024, this doubling explains the results you've observed. Code:
} else if (ht->nTableSize < HT_MAX_SIZE) { /* Let's double the table size */
void *old_data = HT_GET_DATA_ADDR(ht);
Bucket *old_buckets = ht->arData;
HANDLE_BLOCK_INTERRUPTIONS();
ht->nTableSize += ht->nTableSize;
ht->nTableMask = -ht->nTableSize;
HT_SET_DATA_ADDR(ht, pemalloc(HT_SIZE(ht), ht->u.flags & HASH_FLAG_PERSISTENT));
memcpy(ht->arData, old_buckets, sizeof(Bucket) * ht->nNumUsed);
pefree(old_data, ht->u.flags & HASH_FLAG_PERSISTENT);
zend_hash_rehash(ht);
HANDLE_UNBLOCK_INTERRUPTIONS();
I am uncertain if the remalloc is the performance hit, or if the rehashing is the hit, or the fact that the whole block is uninterruptable. Would be interesting to put a profiler on it. I think some might have already done that for PHP 7.
Side note, the Thread Safe version does things differently. I'm not overly familiar with that code, so there may be a different issue going on if your using ZTS.
I think it is related to implementation of dynamic arrays.
See here "Geometric expansion and amortized cost" http://en.wikipedia.org/wiki/Dynamic_array
To avoid incurring the cost of resizing many times, dynamic arrays resize by a large amount, **such as doubling in size**, and use the reserved space for future expansion
You can read about arrays in PHP here as well https://nikic.github.io/2011/12/12/How-big-are-PHP-arrays-really-Hint-BIG.html
It is a standard practice for dynamic arrays. E.g. check here C++ dynamic array, increasing capacity
capacity = capacity * 2; // doubles the capacity of the array

Point in Polygon algorithm giving wrong results sometimes [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I saw on StackOverflow a "point in polygon" raytracing algorithm that I implemented in my PHP Code. Most of the time, it works well, but in some complicated cases, with complex polygons and vicious points, it fails and it says that point in not in polygon when it is.
For example:
You will find here my Polygon and Point classes: pointInPolygon method is in Polygon class. At the end of the file, there are two points that are supposed to lie inside the given polygon (True on Google Earth). The second one works well, but the first one is buggy :( .
You can easily check the polygon on Google Earth using this KML file.
Have been there :-) I also travelled through Stackoverflow's PiP-suggestions, including your reference and this thread. Unfortunately, none of the suggestions (at least those I tried) were flawless and sufficient for a real-life scenario: like users plotting complex polygons on a Google map in freehand, "vicious" right vs left issues, negative numbers and so on.
The PiP-algorithm must work in all cases, even if the polygon consists of hundreds of thousands of points (like a county-border, nature park and so on) - no matter how "crazy" the polygon is.
So I ended up building a new algorithm, based on some source from an astronomy-app:
//Point class, storage of lat/long-pairs
class Point {
public $lat;
public $long;
function Point($lat, $long) {
$this->lat = $lat;
$this->long = $long;
}
}
//the Point in Polygon function
function pointInPolygon($p, $polygon) {
//if you operates with (hundred)thousands of points
set_time_limit(60);
$c = 0;
$p1 = $polygon[0];
$n = count($polygon);
for ($i=1; $i<=$n; $i++) {
$p2 = $polygon[$i % $n];
if ($p->long > min($p1->long, $p2->long)
&& $p->long <= max($p1->long, $p2->long)
&& $p->lat <= max($p1->lat, $p2->lat)
&& $p1->long != $p2->long) {
$xinters = ($p->long - $p1->long) * ($p2->lat - $p1->lat) / ($p2->long - $p1->long) + $p1->lat;
if ($p1->lat == $p2->lat || $p->lat <= $xinters) {
$c++;
}
}
$p1 = $p2;
}
// if the number of edges we passed through is even, then it's not in the poly.
return $c%2!=0;
}
Illustrative test :
$polygon = array(
new Point(1,1),
new Point(1,4),
new Point(4,4),
new Point(4,1)
);
function test($lat, $long) {
global $polygon;
$ll=$lat.','.$long;
echo (pointInPolygon(new Point($lat,$long), $polygon)) ? $ll .' is inside polygon<br>' : $ll.' is outside<br>';
}
test(2, 2);
test(1, 1);
test(1.5333, 2.3434);
test(400, -100);
test(1.01, 1.01);
Outputs :
2,2 is inside polygon
1,1 is outside
1.5333,2.3434 is inside polygon
400,-100 is outside
1.01,1.01 is inside polygon
It is now more than a year since I switched to the above algorithm on several sites. Unlike the "SO-algorithms" there have not been any complaints so far. See it in action here (national mycological database, sorry for the Danish). You can plot a polygon, or select a "kommune" (a county) - ultimately compare a polygon with thousands of points to thousands of records).
Update
Note, this algorithm is targeting geodata / lat,lngs which can be very precise (n'th decimal), therefore considering "in polygon" as inside polygon - not on border of polygon. 1,1 is considered outside, since it is on the border. 1.0000000001,1.01 is not.

PHP and Windows WMI, CPU Temperature and false readings?

I wrote this PHP function:
<?php
//windows cpu temperature
function win_cpu_temp(){
$wmi = new COM("winmgmts://./root\WMI");
$cpus = $wmi->execquery("SELECT * FROM MSAcpi_ThermalZoneTemperature");
foreach ($cpus as $cpu) {
$cpupre = $cpu->CurrentTemperature;
}
$cpu_temp = ($cpupre/10)-273.15 . ' C';
return $cpu_temp;
}
echo win_cpu_temp();
?>
My problem, is that the script displays 59.55 C which I had thought was correct. I checked this value several hours later, and it's exactly the same. I just put the CPU to work at 90% compressing video for ten minutes, and this value is the same still.
Can anyone help me find the "true" value for this function?
I've read (to no avail):
MSAcpi_ThermalZoneTemperature class not showing actual temperature
How is, say, "Core Temp" getting its values? Same computer, it reports between 49 and 53 Celsius.
With a little digging around I found the common issue with using MSAcpi_ThermalZoneTemperature was that it is dependent upon being implemented on your system.
You could try querying Win32_TemperatureProbe and see if you have any luck there.
Neither MSAcpi_ThermalZoneTemperature or Win32_TemperatureProbe worked on my system, although if you have admin access, you can use http://openhardwaremonitor.org/ which provides a WMI interface for all available sensor data.
This worked great for me and I was able to accurately report CPU Core temp from a PHP script:
function report_cpu_temp(){
$wmi = new COM('winmgmts://./root/OpenHardwareMonitor');
$result = $wmi->ExecQuery("SELECT * FROM Sensor");
foreach($result as $obj){
if($obj->SensorType == 'Temperature' && strpos($obj->Parent, 'cpu') > 0)
echo "$obj->Name ($obj->Value C)"; // output cpu core temp
else
echo 'skipping ' . $obj->Identifier ;
echo '<br />';
}
}
Hope this helps.

Generating PHP code (from Parser Tokens)

Is there any available solution for (re-)generating PHP code from the Parser Tokens returned by token_get_all? Other solutions for generating PHP code are welcome as well, preferably with the associated lexer/parser (if any).
From my comment:
Does anyone see a potential problem,
if I simply write a large switch
statement to convert tokens back to
their string representations (i.e.
T_DO to 'do'), map that over the
tokens, join with spaces, and look for
some sort of PHP code pretty-printing
solution?
After some looking, I found a PHP homemade solution in this question, that actually uses the PHP Tokenizer interface, as well as some PHP code formatting tools which are more configurable (but would require the solution as described above).
These could be used to quickly realize a solution. I'll post back here when I find some time to cook this up.
Solution with PHP_Beautifier
This is the quick solution I cooked up, I'll leave it here as part of the question. Note that it requires you to break open the PHP_Beautifier class, by changing everything (probably not everything, but this is easier) that is private to protected, to allow you to actually use the internal workings of PHP_Beautifier (otherwise it was impossible to reuse the functionality of PHP_Beautifier without reimplementing half their code).
An example usage of the class would be:
file: main.php
<?php
// read some PHP code (the file itself will do)
$phpCode = file_get_contents(__FILE__);
// create a new instance of PHP2PHP
$php2php = new PHP2PHP();
// tokenize the code (forwards to token_get_all)
$phpCode = $php2php->php2token($phpCode);
// print the tokens, in some way
echo join(' ', array_map(function($token) {
return (is_array($token))
? ($token[0] === T_WHITESPACE)
? ($token[1] === "\n")
? "\n"
: ''
: token_name($token[0])
: $token;
}, $phpCode));
// transform the tokens back into legible PHP code
$phpCode = $php2php->token2php($phpCode);
?>
As PHP2PHP extends PHP_Beautifier, it allows for the same fine-tuning under the same API that PHP_Beautifier uses. The class itself is:
file: PHP2PHP.php
class PHP2PHP extends PHP_Beautifier {
function php2token($phpCode) {
return token_get_all($phpCode);
}
function token2php(array $phpToken) {
// prepare properties
$this->resetProperties();
$this->aTokens = $phpToken;
$iTotal = count($this->aTokens);
$iPrevAssoc = false;
// send a signal to the filter, announcing the init of the processing of a file
foreach($this->aFilters as $oFilter)
$oFilter->preProcess();
for ($this->iCount = 0;
$this->iCount < $iTotal;
$this->iCount++) {
$aCurrentToken = $this->aTokens[$this->iCount];
if (is_string($aCurrentToken))
$aCurrentToken = array(
0 => $aCurrentToken,
1 => $aCurrentToken
);
// ArrayNested->off();
$sTextLog = PHP_Beautifier_Common::wsToString($aCurrentToken[1]);
// ArrayNested->on();
$sTokenName = (is_numeric($aCurrentToken[0])) ? token_name($aCurrentToken[0]) : '';
$this->oLog->log("Token:" . $sTokenName . "[" . $sTextLog . "]", PEAR_LOG_DEBUG);
$this->controlToken($aCurrentToken);
$iFirstOut = count($this->aOut); //5
$bError = false;
$this->aCurrentToken = $aCurrentToken;
if ($this->bBeautify) {
foreach($this->aFilters as $oFilter) {
$bError = true;
if ($oFilter->handleToken($this->aCurrentToken) !== FALSE) {
$this->oLog->log('Filter:' . $oFilter->getName() , PEAR_LOG_DEBUG);
$bError = false;
break;
}
}
} else {
$this->add($aCurrentToken[1]);
}
$this->controlTokenPost($aCurrentToken);
$iLastOut = count($this->aOut);
// set the assoc
if (($iLastOut-$iFirstOut) > 0) {
$this->aAssocs[$this->iCount] = array(
'offset' => $iFirstOut
);
if ($iPrevAssoc !== FALSE)
$this->aAssocs[$iPrevAssoc]['length'] = $iFirstOut-$this->aAssocs[$iPrevAssoc]['offset'];
$iPrevAssoc = $this->iCount;
}
if ($bError)
throw new Exception("Can'process token: " . var_dump($aCurrentToken));
} // ~for
// generate the last assoc
if (count($this->aOut) == 0)
throw new Exception("Nothing on output!");
$this->aAssocs[$iPrevAssoc]['length'] = (count($this->aOut) -1) - $this->aAssocs[$iPrevAssoc]['offset'];
// post-processing
foreach($this->aFilters as $oFilter)
$oFilter->postProcess();
return $this->get();
}
}
?>
In the category of "other solutions", you could try PHP Parser.
The parser turns PHP source code into an abstract syntax tree....Additionally, you can convert a syntax tree back to PHP code.
If I'm not mistaken http://pear.php.net/package/PHP_Beautifier uses token_get_all() and then rewrites the stream. It uses heaps of methods like t_else and t_close_brace to output each token. Maybe you can hijack this for simplicity.
See our PHP Front End. It is a full PHP parser, automatically building ASTs, and a matching prettyprinter that regenerates compilable PHP code complete with the original commments. (EDIT 12/2011:
See this SO answer for more details on what it takes to prettyprint from ASTs, which are just an organized version of the tokens: https://stackoverflow.com/a/5834775/120163)
The front end is built on top of our DMS Software Reengineering Toolkit, enabling the analysis and transformation of PHP ASTs (and then via the prettyprinter code).

Categories