Converting Python Code to PHP

Converting Python Code to PHP

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('Converting Python Code to PHPaaa');
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));

is there any way to convert this python code into php

OpenAI has an AI to convert code from one language to another. I believe it supports PHP and Python. I have used this tool and it converts the code very accuratly.
Here's a link to an example OpenAI has on their website: https://beta.openai.com/examples/default-translate-code

Need help converting a Python script to PHP

The Python script doesn't send the POST request body as JSON. It uses data= rather than json=, which sends it as a URL-encoded data=value, where the value is a JSON-encoded object.

You need to do it similarly in the PHP version. Only the data parameter should be encoded as JSON, not the entire request.

<?php

$dir = __DIR__;
include $dir .'/vendor/autoload.php';

$tracking_number = '123456789';

$url = 'https://www.fedex.com/trackingCal/track';

$headers = [];

$data = [
"data" => json_encode([
"TrackPackagesRequest" => [
"appType" => "wtrk",
"uniqueKey" => "",
"processingParameters" => [
"anonymousTransaction" => true,
"clientId" => "WTRK",
"returnDetailedErrors" => true,
"returnLocalizedDateTime" => false
],
"trackingInfoList" => [[
"trackNumberInfo" => [
"trackingNumber" => $tracking_number,
"trackingQualifier" => "",
"trackingCarrier" => ""
]
]]
]

]),
"action" => "trackpackages",
"locale" => "en_US",
"format" => "json",
"version" => 99
];

$response = Requests::post($url, $headers, $data);

print_r($response);

Convert python code to php

In PHP I think regular expressions need to be inside 2 x / e.g.

$a = preg_replace('/"[ \t]*"/', '":"', $a);

Edit: As André mentioned, the delimiter does not necessarily need to be forward slashes, however I think the double quotes you're using are meant to be used as part of the regular expression rather than the delimiters.

Convert Python code to PHP/Laravel (Gate.io signature)

i got the answer, i hope it will helps:

public function buildSignHeaders($method, $resourcePath, $queryParams = [], $payload = null)
{
$fullPath = parse_url(config('gate-io.host'), PHP_URL_PATH) . $resourcePath;
$fmt = "%s\n%s\n%s\n%s\n%s";
$timestamp = time();
$hashedPayload = hash("sha512", ($payload !== null) ? $payload : "");
$signatureString = sprintf(
$fmt,
$method,
$fullPath,
GuzzleHttp\Psr7\build_query($queryParams, false),
$hashedPayload,
$timestamp
);
$signature = hash_hmac("sha512", $signatureString, config('gate-io.apiSecretKey'));
return [
"KEY" => config('gate-io.apiKey'),
"SIGN" => $signature,
"Timestamp" => $timestamp
];
}

Convert python code with sha to php

I saw few errors in your PHP code.

This is a python snippet:

>>> sha = hashlib.sha256()
>>> sha.update(user)
>>> sha.update(passing)
>>> sha_A = [ord(x) for x in sha.digest()]
[135, 146, 107, 215, 70, 126, 179, 21, 19, 177, 191, 236, 182, 136, 192, 53, 148, 42, 160, 24, 63, 224, 170, 211, 32, 131, 59, 146, 60, 162, 77, 2]

And the PHP version, corrected:

$ctx = hash_init('sha256');
hash_update($ctx, $user);
hash_update($ctx, $passing);
$digest = hash_final($ctx, true);

$sha_A = [];
foreach (str_split($digest) as $x) {
$sha_A[] = ord($x);
}
[135, 146, 107, 215, 70, 126, 179, 21, 19, 177, 191, 236, 182, 136, 192, 53, 148, 42, 160, 24, 63, 224, 170, 211, 32, 131, 59, 146, 60, 162, 77, 2]

In your PHP version, $sha = hash_update($sha, $user); was bad because hash_update returns a boolean. The first argument is called the context and is the result of hash_init, the second one is the data to hash. Finally, you call hash_final with the last parameter (raw_output) to true to get binary data.

Last error, using openssl_digest on the SHA result's was computing the digest of the SHA digest's. Funny, isn't it? :).



Related Topics



Leave a reply



Submit