How do I call go-code with a cmd command in PHP? - php

I have a .go code that I want to run and get the return value in PHP.
The line I use in CMD is "go run test.go map.csv" and I want to run it through a PHP script and get whatever the code returns on my website.
Right now I don't get anything to my variable in the PHP-code.
GO-code
package main
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"log"
"math/bits"
"math/rand"
"os"
"runtime"
"strconv"
"strings"
"time"
)
const MaxInt = int(^uint(0) >> 1)
// IntSet
type IntSet struct {
Storage uint
}
func (vs IntSet) Contains(value int) bool {
return (vs.Storage & (1 << uint(value))) != 0
}
func (vs IntSet) Count() int {
return bits.OnesCount(vs.Storage)
}
func (vs *IntSet) Insert(value int) {
vs.Storage |= 1 << uint(value)
}
func (vs *IntSet) Remove(value int) {
vs.Storage &= ^(1 << uint(value))
}
func (vs IntSet) Value() int {
return int(vs.Storage >> 1)
}
func (vs IntSet) Iter() []int {
n := vs.Count()
v := make([]int, n)
for c, i := 0, 0; c < n; i++ {
if vs.Contains(i) {
v[c] = i
c++
}
}
return v
}
func (vs IntSet) String() string {
buf := bytes.Buffer{}
buf.WriteString("{")
delim := ""
for c, i := 0, 0; c < vs.Count(); i++ {
if vs.Contains(i) {
buf.WriteString(fmt.Sprintf("%s%v", delim, i))
delim = ","
c++
}
}
buf.WriteString("}")
return buf.String()
}
// Combinations 'k' integers from a serie '1..n'
type Combs []IntSet
func combWithLen(n, k, first int, vs IntSet, acc Combs) Combs {
if k > vs.Count() {
for x := first; x <= n; x++ {
s := vs
s.Insert(x)
acc = combWithLen(n, k, x+1, s, acc)
}
} else {
acc = append(acc, vs)
}
return acc
}
func Comb(n, k int) Combs {
return combWithLen(n, k, 1, IntSet{}, Combs{})
}
// Held Karp
type Path struct {
Cost int
From int
}
func minPath(paths []Path) Path {
m := paths[0]
for i := 1; i < len(paths); i++ {
if m.Cost > paths[i].Cost {
m = paths[i]
}
}
return m
}
func pathFromTo(from, to int, c [][]Path, dists CostMatrix, prev IntSet) Path {
p := Path{}
p.Cost = c[prev.Value()][from-1].Cost + dists[from][to]
p.From = from
return p
}
func reverse(a []int) []int {
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
return a
}
// CostMatrix
type CostMatrix [][]int
func (dists CostMatrix) CalcCostToSubsets(c [][]Path, edges, subsetSz int) {
maxWorkers := runtime.NumCPU()
workers := 0
done := make(chan bool)
for _, visited := range Comb(edges, subsetSz) {
if workers == maxWorkers {
<-done
} else {
workers += 1
}
go func(vs IntSet) {
subset := vs.Iter()
// Find the lowest cost to get to this subset
for _, k := range subset {
prev := vs
prev.Remove(k)
res := []Path{}
for _, m := range subset {
if m != k {
res = append(res, pathFromTo(m, k, c, dists, prev))
}
}
if len(res) > 0 {
c[vs.Value()][k-1] = minPath(res)
}
}
done <- true
}(visited)
}
// Wait for all workers to finish
for ; workers > 0; workers -= 1 {
<-done
}
}
func (dists CostMatrix) ShortestPath() (int, []int) {
n := len(dists)
c := make([][]Path, 1<<uint(n-1))
for i := 0; i < len(c); i++ {
c[i] = make([]Path, n-1)
}
// Add paths from start to first steps
for k := 1; k < n; k++ {
c[1<<uint(k-1)][k-1] = Path{dists[0][k], 0}
}
for s := 2; s < n; s++ {
dists.CalcCostToSubsets(c, n-1, s)
}
visited := IntSet{}
for k := 1; k < n; k++ {
visited.Insert(k)
}
// Add path back to start and calculate optimal cost
res := []Path{}
for k := 1; k < n; k++ {
res = append(res, pathFromTo(k, 0, c, dists, visited))
}
p := minPath(res)
cost := p.Cost
// Backtrack to find path
steps := make([]int, n+1)
for i := 1; i < n; i++ {
steps[i] = p.From
from := p.From
p = c[visited.Value()][p.From-1]
visited.Remove(from)
}
return cost, reverse(steps)
}
func (c CostMatrix) MaxDigitWidth() (width int) {
for row := 0; row < len(c); row++ {
for col := 0; col < len(c[row]); col++ {
w := 0
for d := c[row][col]; d > 0; d /= 10 {
w += 1
}
if width < w {
width = w
}
}
}
return
}
func (c CostMatrix) String() string {
fmtstr := fmt.Sprintf("%%%vv", c.MaxDigitWidth())
buf := bytes.Buffer{}
for row := 0; row < len(c); row++ {
if row == 0 {
buf.WriteString("{\n")
}
buf.WriteString(" { ")
for col := 0; col < len(c[row]); col++ {
buf.WriteString(fmt.Sprintf(fmtstr, c[row][col]))
if col != len(c[row])-1 {
buf.WriteString(", ")
}
}
buf.WriteString(" },\n")
if row == len(c)-1 {
buf.WriteString("}")
} else {
}
}
return buf.String()
}
func Abs(n int) int {
if n < 0 {
return -n
}
return n
}
func Max(a, b int) int {
if a < b {
return b
}
return a
}
type Location struct {
shelf int
level int
}
func cost(from, to Location) int {
dx := Abs(from.shelf - to.shelf)
dy := Abs(from.level-to.level) * 2
return Max(dx, dy)
}
func zeroMatrix(dim int) CostMatrix {
var c CostMatrix = make([][]int, dim)
for i := range c {
c[i] = make([]int, dim)
}
return c
}
func genMatrix(nodes, depth, height int) CostMatrix {
rand.Seed(time.Now().UnixNano())
c := zeroMatrix(nodes)
l := make([]Location, nodes)
for i := range l {
l[i] = Location{rand.Intn(depth), rand.Intn(height)}
}
for row := 0; row < nodes; row++ {
for col := row + 1; col < nodes; col++ {
c[row][col] = cost(l[row], l[col])
c[col][row] = c[row][col]
}
}
return c
}
func readMatrix(r io.Reader) CostMatrix {
cr := csv.NewReader(r)
rec, err := cr.ReadAll()
if err != nil {
log.Fatalln(err)
}
M := zeroMatrix(len(rec))
for row, line := range rec {
for col, str := range line {
v, err := strconv.ParseInt(strings.TrimSpace(str), 10, 32)
if err != nil {
log.Fatalln(err)
}
M[row][col] = int(v)
}
}
return M
}
func GetCostMatrix() CostMatrix {
if len(os.Args) == 1 {
return readMatrix(os.Stdin)
}
arg := os.Args[1]
if strings.HasSuffix(arg, ".csv") {
file, err := os.Open(arg)
if err != nil {
log.Fatalln(err)
}
return readMatrix(file)
}
dim, err := strconv.ParseInt(arg, 10, 32)
if err != nil {
log.Fatalln(err)
}
return genMatrix(int(dim), 50, 9)
}
// Program entrypoint
func main() {
start := time.Now()
time.Sleep(time.Second * 2)
c := GetCostMatrix()
fmt.Println(c)
fmt.Println(c.ShortestPath())
elapsed := time.Since(start)
fmt.Printf("Processen tog %s sekunder", elapsed)
}
I want to catch what the GO-code main() returns in PHP:
<?php
$cmdOutput = exec('go run c:/Go/src/hello/test.go c:/Go/src/hello/map.csv');
var_dump($cmdOutput);
?>
but it says $cmdOutput is 0.

To capture the output, you need to provide extra parameters.
$cmdOutput = []; // Variabled passed by reference.
exec('go run c:/Go/src/hello/test.go c:/Go/src/hello/map.csv', $cmdOutput);
var_dump($cmdOutput); // Will be an array of all printed lines.
documentation exec function

$cmd = '/usr/local/go/bin/go /path/to/test.go map.csv 2>&1';
exec($cmd, $output, $return_var);
var_dump($output);
just make sure your web server user has permissions (e.g www-data).

Related

C function substr, PHP extension, strncpy wrong length

My php_substr function should set kpart to a33c5b4b58b26d9f however it instead sets it to a33c5b4b58b26d9fìÿ?꬯wÿÿÿÿ®w.
Any ideas?
long ks;
char *kpart1;
ks = 16;
php_substr("a33c5b4b58b26d9f78293df1c5d5a3bf", &kpart1, 0, ks); // a33c5b4b58b26d9fìÿ?꬯wÿÿÿÿ®w
char *php_substr(char *str, char **ptr, long f, long l)
{
int str_len = strlen(str);
if (!l) {
l=0;
}
if (l!=0) {
if ((l < 0 && -l > str_len)) {
return FALSE;
} else if (l > str_len) {
l = str_len;
}
} else {
l = str_len;
}
if (f > str_len) {
return FALSE;
} else if (f < 0 && -f > str_len) {
f = 0;
}
if (l < 0 && (l + str_len - f) < 0) {
return FALSE;
}
if (f < 0) {
f = str_len + f;
if (f < 0) {
f = 0;
}
}
if (l < 0) {
l = (str_len - f) + l;
if (l < 0) {
l = 0;
}
}
if (f >= str_len) {
return FALSE;
}
if ((f + l) > str_len) {
l = str_len - f;
}
strncpy(*ptr,str+f,l);
return 0;
}
Edited to use malloc and included full working code!
I tried the zend engine emalloc however this didn't seem to work
long ks;
char *kpart1;
ks = 16;
kpart1 = php_substr("a33c5b4b58b26d9f78293df1c5d5a3bf", 0, ks); // a33c5b4b58b26d9f
char *php_substr(char *str, long f, long l)
{
int str_len = strlen(str);
unsigned char *buffer;
if (l!=0) {
if ((l < 0 && -l > str_len)) {
return FALSE;
} else if (l > str_len) {
l = str_len;
}
} else {
l = str_len;
}
if (f > str_len) {
return FALSE;
} else if (f < 0 && -f > str_len) {
f = 0;
}
if (l < 0 && (l + str_len - f) < 0) {
return FALSE;
}
if (f < 0) {
f = str_len + f;
if (f < 0) {
f = 0;
}
}
if (l < 0) {
l = (str_len - f) + l;
if (l < 0) {
l = 0;
}
}
if (f >= str_len) {
return FALSE;
}
if ((f + l) > str_len) {
l = str_len - f;
}
buffer = (char*)malloc(l+1);
strncpy(buffer,str+f,l);
buffer[l]='\0';
return buffer;
}
After trimming out all the testing of the parameters
After editing into a file that compiles/links/runs
this is the resulting code:
#include <stdio.h>
#include <string.h>
#define FALSE (0)
char *php_substr(char *str, char **ptr, long f, long l)
{
strncpy(*ptr,str+f,(size_t)l);
return 0;
}
int main( void )
{
long int ks = 16;
char *kpart1;
php_substr("a33c5b4b58b26d9f78293df1c5d5a3bf", &kpart1, 0, ks); // a33c5b4b58b26d9fìÿ?꬯wÿÿÿÿ®w
printf( "%s\n", kpart1);
}
Notice that the char pointer: kpart1 is not initialized to point to any specific location.
(in this case it contains whatever trash was on the stack. If it were a global variable, it would contian NULL.)
The call to strncpy() is trying to copy the first 16 bytes of the passed in constant to where ever kpart1 happens to be pointing.
The strncpy() results in undefined behaviour and can lead to a seg fault event.
I did not perform an analysis on the manipulation of the passed in variables f and l.
Suggest, as you found, that the pointer: kpart1 needs to be initialized to point to some allocated memory, where that allocated memory needs to be at least l-f+1 in length.

I would like to compare to set of text and get how similar/relevant they are to each other, I use similar_text(), but i found out its not as accurate

I would like to compare to set of text and get how similar/relevant they are to each other, I use similar_text(), but i found out its not as accurate. Thank you.
For example the following text gives me 66%
Text1: Innovation game, eat, sleep, breathe innovation. It love creativity & passion power Internet drives . We understand time greatest asset, challege meet deadline.
Text2: Soviet union communist policy; Germany league organization disguise enermies beaten wanted.
My code is as below:
echo $student_answer = removeCommonWords($answer)."<br><br>";
$student_answer = strip_tags($student_answer);
echo $memo = removeCommonWords2($memo)."<br><br>";
echo similar_text($memo, $student_answer);
You can use the JS version:
http://phpjs.org/functions/similar_text/
The JS code shows you the precent code (you can modify the code):
return (sum * 200) / (firstLength + secondLength);
I hope this will help you!
EDIT:
How to use similar_text in JS?
Create a file named similar_text.js and copy&paste this code in it:
function similar_text (first, second, percent) {
// http://kevin.vanzonneveld.net
// + original by: Rafał Kukawski (http://blog.kukawski.pl)
// + bugfixed by: Chris McMacken
// + added percent parameter by: Markus Padourek (taken from http://www.kevinhq.com/2012/06/php-similartext-function-in-javascript_16.html)
// * example 1: similar_text('Hello World!', 'Hello phpjs!');
// * returns 1: 7
// * example 2: similar_text('Hello World!', null);
// * returns 2: 0
// * example 3: similar_text('Hello World!', null, 1);
// * returns 3: 58.33
if (first === null || second === null || typeof first === 'undefined' || typeof second === 'undefined') {
return 0;
}
first += '';
second += '';
var pos1 = 0,
pos2 = 0,
max = 0,
firstLength = first.length,
secondLength = second.length,
p, q, l, sum;
max = 0;
for (p = 0; p < firstLength; p++) {
for (q = 0; q < secondLength; q++) {
for (l = 0;
(p + l < firstLength) && (q + l < secondLength) && (first.charAt(p + l) === second.charAt(q + l)); l++);
if (l > max) {
max = l;
pos1 = p;
pos2 = q;
}
}
}
sum = max;
if (sum) {
if (pos1 && pos2) {
sum += this.similar_text(first.substr(0, pos2), second.substr(0, pos2));
}
if ((pos1 + max < firstLength) && (pos2 + max < secondLength)) {
sum += this.similar_text(first.substr(pos1 + max, firstLength - pos1 - max), second.substr(pos2 + max, secondLength - pos2 - max));
}
}
if (!percent) {
return sum;
} else {
return (sum * 200) / (firstLength + secondLength);
}
}
In your put the following line:
<script type="text/JavaScript" src="YOUR_PATH/similar_text.js"></script>
Now you can use it in your body:
<script>
similar_text('Hello World!', 'Hello phpjs!');
</script>
It will output 7.
Hope this wil help you!

How can I get the offsets of all set bits in a bitarray?

In C, Ruby or PHP, how can I get the offsets of all set bits in an bitarray. E.g.:
Bitarray: 1 0 0 1 0
Offset: 5 4 3 2 1
Yields 2 and 5.
10001 => {1,5}
11 => {1,2}
1001001 => {1,4,7}
The most obvious solution would be to first do a reversed Find first set to know the length and then loop through the bits, saving the offset/index. However this does not seem very smart. Something like FFSR multiple times with subtraction might be better.
I came up with this. I've used binary shift operation to find out if there is binary "1" or "0". Probably you could use this code as your starting point.
#include <stdio.h>
int main()
{
int number;
int counter = 1;
printf("Please input the number to get the offsets: ");
scanf("%d", &number);
printf("The required positions of ones: ");
while ((number != 0))
{
if ((number % 2) != 0)
{
number = number >> 1;
printf("%d", counter);
}
else
{
number = number >> 1;
}
counter++;
}
return 0;
}
Here is an extended version that prints binary representation as well:
#include <stdio.h>
#include <strings.h>
char* rev(char* str);
int main()
{
int number, temp;
int counter = 1;
char str[32] = "";
printf("Please input the number to get the offsets: ");
scanf("%d", &number);
temp = number;
printf("Binary representation: ");
while ((temp != 0))
{
if ((temp % 2) != 0)
{
temp = temp >> 1;
strncat(str, "1", 1);
}
else
{
temp = temp >> 1;
strncat(str, "0", 1);
}
}
printf("%s", rev(str));
printf("\nThe required positions of ones: ");
while ((number != 0))
{
if ((number % 2) != 0)
{
number = number >> 1;
printf("%d", counter);
}
else
{
number = number >> 1;
}
counter++;
}
getch();
getch();
return 0;
}
char* rev(char* str)
{
int end= strlen(str) - 1;
int start = 0;
while( start<end )
{
str[start] ^= str[end];
str[end] ^= str[start];
str[start]^= str[end];
++start;
--end;
}
return str;
}

javascript equivalent of bcpowmod

I'm coding a javascript version that can decode a RSA encryption I made in PHP.
everything works fine except I don't have a javascript equivalent of bcpowmod.
I used the PHP JS library for the other functions but it doesn't have bcpowmod.
If I use default math operators like: (pow(block,q)) % r I get NAN.
Is there a way or js library that can work for me?
bcpowmod is very tuff tough in javascript. Here's the code to do it. I just posted an entire library for anyone to use to employ RSA RC4 encryption in their web sites, but was promptly shot down by a moderator, Brad Larson. He said, they don't want this kind of stuff at Stack Overflow. Anyway here's the code for you.
Java script is slow at this. So I do it in multiple steps so javascript has time to show a progress bar or something. I had to write my own bcmath package to do it. You can see the whole library of encryption functions ready to go at http://jerrywickey.com/test/testJerrysLibrary.php
You need arbitrary precision multiply, divide, subtract and compare. So they are all here. the actual bcpowmod is done in multiple steps because it just takes so long.
When the calculations are done, it calls the function named in the callback parameter with the result. Swap a and b back and forth to get it to work for you, just incase we are using different terms for the RSA public, private and modulo values. Use just the alphanumeric name for the callback function. Don't use the parenthesis.
bcpowmod( 'plain text', RSAp, RSAq, 'myCallBackForResult');
function myCallBackForResult( result){
alert ( result + ' of powmod');
}
function bcpowmod( str, a, b, callback){
RSAencryptStep( (''+str), (''+a), (''+b), '1', callback, 0);
}
function RSAencryptStep( str, a, b, result, callback, count){
count++;
if ( JL_bccomp( JL_bcmod( a, '2'), '1')==0) {
result = JL_bcmod( JL_bcmul( result, str), b);
}
str= JL_bcmod( JL_bcmul( str, str), b);
a= JL_bcdiv( a, '2');
if ( JL_bccomp( a, '0')!=0){
var e= "RSAencryptStep('" +str+"','" +a+"','" +b+"','" +result+"','" +callback +"'," +count+")";
setTimeout( e, 10);
clearTimeout( JL_crytime);
try{
ge('cryptocount').innerHTML= ( 60 - count);
}catch(e){}
}else{
eval( callback+'("'+ result+'")' );
}
}
function JL_bccomp( a, b){
if (a.length > b.length){ return 1; }
if (a.length < b.length){ return -1; }
var i= 0; while ( a.charAt(i)==b.charAt(i) && ++i<a.length){ }
if ( i==a.length){ return 0; }
if ( parseInt( a.charAt(i)) > parseInt( b.charAt(i))){ return 1; }
return -1;
}
function JL_bcadd( a, b){
var zero= '00000000000000000000'; while ( zero.length < a.length + b.length){ zero+= ''+zero; }
if ( a.length < b.length){ a= ''+ zero.substring( 0, ( b.length - a.length )) + a; }
if ( b.length < a.length){ b= ''+ zero.substring( 0, ( a.length - b.length )) + b; }
var s= ('0'+a).split('');
var t= 0;
for (var i=0; i<a.length; i++){
t= parseInt( s[s.length-i-1]) + parseInt( b.charAt( b.length-i-1));;
if (t > 9){
s[s.length-i-1]= t - 10;
s[s.length-i-2]= parseInt( s[s.length-i-2]) + 1;
}else{
s[s.length-i-1]= t;
}
}
return trim( trim(( s.join('')+' '), '0'), '');
}
function JL_bcsub( a, b){
var x= JL_bccomp( a, b);
if ( x==0){
return '0';
}
var minus= '';
if ( x < 0){
var x= a;
a= b;
b= x;
minus= '-';
}
var s= a.split('');
var t= 0;
for (var i=0; i<s.length; i++){
t= parseInt(s[s.length-i-1]);
if ( i<b.length){ t= t - parseInt( b.charAt( b.length-i-1)); }
if ( t<0){
s[s.length-i-1]= t + 10;
s[s.length-i-2]= s[s.length-i-2] - 1;
}else{
s[s.length-i-1]= parseInt( t);
}
}
return minus + trim( trim(( s.join('')+' '), '0'), '');
}
function JL_bcmul( a, b){
var s= [];
for (var i=0; i < a.length + b.length; i++){ s[i]= 0; }
var t= 0;
for (i=0; i<b.length; i++){
for (var j=0; j<a.length; j++){
t= s[i+j] + ( parseInt( a.charAt( a.length - j - 1)) * parseInt( b.charAt( b.length - i - 1)));
s[i+j]= t % 10;
s[i+j+1]= s[i+j+1] + Math.floor( t / 10);
}
}
s.reverse();
return trim( trim(( s.join('')+' '), '0'), '');
}
function JL_bcdiv( a, b){
var r= '0';
var rr= '1';
var e= b;
var rrs= [];
var es= [];
var i= 0;
while( JL_bccomp( a, b) >= 0){
rr= '1';
e= b;
i= 0;
while( JL_bccomp( a, e) >= 0){
a= JL_bcsub( a, e);
r= JL_bcadd( r, rr);
if ( typeof es[i] == 'undefined'){
es[i]= JL_bcmul( e, '2');
rrs[i]= JL_bcmul( rr, '2');
}
e= es[i];
rr= rrs[i];
i++;
}
}
// a is the remainder
return r;
}
function JL_bcmod( a, m){
var s= [];
var e= m;
var i= 0;
while( JL_bccomp( a, m) >= 0){
e= m;
i= 0;
while( JL_bccomp( a, e) >= 0){
a= JL_bcsub( a, e);
if ( typeof s[i] == 'undefined'){
s[i]= JL_bcmul( e, '2');
}
e= s[i];
i++;
}
}
return a;
}

Converting a hexadecimal string into binary in Objective-C

What's an equivalent of the PHP function pack:
pack('H*', '01234567989abcdef' );
in Objective-C?
Assuming that you want the results as an NSData, you can use a function similar to this:
NSData *CreateDataWithHexString(NSString *inputString)
{
NSUInteger inLength = [inputString length];
unichar *inCharacters = alloca(sizeof(unichar) * inLength);
[inputString getCharacters:inCharacters range:NSMakeRange(0, inLength)];
UInt8 *outBytes = malloc(sizeof(UInt8) * ((inLength / 2) + 1));
NSInteger i, o = 0;
UInt8 outByte = 0;
for (i = 0; i < inLength; i++) {
UInt8 c = inCharacters[i];
SInt8 value = -1;
if (c >= '0' && c <= '9') value = (c - '0');
else if (c >= 'A' && c <= 'F') value = 10 + (c - 'A');
else if (c >= 'a' && c <= 'f') value = 10 + (c - 'a');
if (value >= 0) {
if (i % 2 == 1) {
outBytes[o++] = (outByte << 4) | value;
outByte = 0;
} else if (i == (inLength - 1)) {
outBytes[o++] = value << 4;
} else {
outByte = value;
}
} else {
if (o != 0) break;
}
}
return [[NSData alloc] initWithBytesNoCopy:outBytes length:o freeWhenDone:YES];
}
See the -scanHex... methods of NSScanner.

Categories