问:
Laravel filter by many to many relation of a relation
I'm writing a movie and serie database. I want to make it possible to filter by genre.

For the movie part it's quite easy. In my movie model I just could add a genre scope:

```<code>public function scopeGenres($query, $genres)
{
    return $query->whereHas('genres', function($q) use ($genres){
        $q->whereIn('genres.genre_id', $genres);
    });
}
</code>```

Now I want to include it with the series model. The problem: I display the seasons and not the series and the genres are attached to the series.

It's like:

```<code>Season belongsTo Serie morphToMany Genre
</code>```

I already tried to make it like:

```<code>$seasons->with('serie' => function($query) use ($genre_ids){
    $query->whereHas('genres', function($q) use ($genre_ids){
        $q->whereIn('genres.genre_id', $genres);
    });
});
</code>```

but with no success.

How can I filter the season by Genre?

答:
You just have to replace with function with another whereHas

```<code>$seasons->whereHas('serie', function($query) use ($genre_ids) {
    $query->whereHas('genres', function($q) use ($genre_ids){
        $q->whereIn('genres.genre_id', $genres);
    });
});
</code>```

Body:
I'm writing a movie and serie database. I want to make it possible to filter by genre.

For the movie part it's quite easy. In my movie model I just could add a genre scope:

public function scopeGenres($query, $genres)
{
    return $query->whereHas('genres', function($q) use ($genres){
        $q->whereIn('genres.genre_id', $genres);
    });
}

Now I want to include it with the series model. The problem: I display the seasons and not the series and the genres are attached to the series.

It's like:

Season belongsTo Serie morphToMany Genre

I already tried to make it like:

$seasons->with('serie' => function($query) use ($genre_ids){
    $query->whereHas('genres', function($q) use ($genre_ids){
        $q->whereIn('genres.genre_id', $genres);
    });
});

but with no success.

How can I filter the season by Genre?

Body:
You just have to replace with function with another whereHas

$seasons->whereHas('serie', function($query) use ($genre_ids) {
    $query->whereHas('genres', function($q) use ($genre_ids){
        $q->whereIn('genres.genre_id', $genres);
    });
});


来源: stackexchange

问:
Convert [Float] to variables arguments
I'm trying to use NSString(format: , arg...) to update a UILabel by incrementing one or more values in this label.

To do that, I have a function where I am receiving the args as Float... (which is what I want) and the only solution I found to store them is by using an array [Float] (which is not what I want).
Then, I'm modifying each value of my array to display it.

To modify the text of my UILabel, I am using label.text = NSString(format: "%f and %f", myArrayOfFloat) and it does not work. NSString takes the array as a single value, not as an array.

If anyone has a solution, I'm all ears.

答:
There is a

```<code>NSString(format: String, arguments argList: CVaListPointer)
</code>```

initializer which takes the substitution values as a CVaListPointer
(which is the Swift equivalent of va_list in C). Example:

```<code>let myArrayOfFloat: [Float] = [1.2, 3.4]
let text = withVaList(myArrayOfFloat) {
    NSString(format: "%f and %f", arguments: $0)
}
print(text) // 1.200000 and 3.400000
</code>```

However, it is simpler to create a  String, using the

```<code>String(format: String, arguments: [CVarArg])
</code>```

initializer, which takes the substitution values as a single array parameter. Example:

```<code>let myArrayOfFloat: [Float] = [1.2, 3.4]
let text = String(format: "%f and %f", arguments: myArrayOfFloat)
print(text) // 1.200000 and 3.400000
</code>```

ContentLicense: CC BY-SA 3.0

Title: Convert [Float] to variables arguments

Body:
There is a

NSString(format: String, arguments argList: CVaListPointer)

initializer which takes the substitution values as a CVaListPointer
(which is the Swift equivalent of va_list in C). Example:

let myArrayOfFloat: [Float] = [1.2, 3.4]
let text = withVaList(myArrayOfFloat) {
    NSString(format: "%f and %f", arguments: $0)
}
print(text) // 1.200000 and 3.400000

However, it is simpler to create a  String, using the

String(format: String, arguments: [CVarArg])

initializer, which takes the substitution values as a single array parameter. Example:

let myArrayOfFloat: [Float] = [1.2, 3.4]
let text = String(format: "%f and %f", arguments: myArrayOfFloat)
print(text) // 1.200000 and 3.400000


问:
How to Redirect all IE users to a new page
My programmer is on vacation so I need your help!  I discovered a page that has a bug for IE users.  I want to redirect all IE users to a different page.

How can I do this?  I searched all through Google and Stackoverflow and cannot find an answer.   (I found some scripts, and tried them, but none worked).

答:
Support for conditional comments has been removed in Internet Explorer 10 standards

I'm use this dirty hack for redirecting IE10+ users

```<code><script type="text/javascript">
    var check = true;
</script>
<!--[if lte IE 9]>
<script type="text/javascript">
    var check = false;
</script>
<![endif]-->
<script type="text/javascript">
    if (check) {
        window.location = "page_for_ie10+.html";
    }
</script>
</code>```

Body:
Support for conditional comments has been removed in Internet Explorer 10 standards

I'm use this dirty hack for redirecting IE10+ users

<script type="text/javascript">
    var check = true;
</script>
<!--[if lte IE 9]>
<script type="text/javascript">
    var check = false;
</script>
<![endif]-->
<script type="text/javascript">
    if (check) {
        window.location = "page_for_ie10+.html";
    }
</script>


问:
C++ - constant variable, is it a correct term?
At the end of the artile here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/

It mentions the following sentence:

Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

Is "constant variables" a correct term to use? Aren't constants different from variables?

Thanks.

答:
Yes, it's a bit of a contradiction in terms. Variables are things that vary by definition, and constants are things that don't vary by definition.

That aside, in C++ (and other languages), people still call them constant variables because we essentially think of any value with a name as a variable.

Feel free to just say 'constant' though.

ContentLicense: CC BY-SA 2.5


问:
Graphic counter correction
I have a chart and my system that I need it to report the exact value of the search results.

Due to many data, the results come out so 1.1K.

In the place that 1.1K wanted it shows the exact value that would be 1057.
Here is the graph function in JS:

```<code>function Post(url, param, title, totalText) {
    totalText = totalText || "Total";

    $.ajax({
        method: "POST",
        url: "/Graficos/" + url,
        data: param,
        beforeSend: function () {
            showLoader();
        },
        success: function (data) {
            ChartConstructor(title, JSON.stringify(data), totalText);
        },
        complete: function () {
            hideLoader();
        }
    });
}

    function ChartConstructor(title, dados, totalText) {
        window.google.charts.load('current', { 'packages': ['bar'] });
        window.google.charts.setOnLoadCallback(drawStuff);

        function drawStuff() {
            var table = JSON.parse(dados);
            var rows = "";

            var array = [["", "Total"]];

            for (var i = 0; i < table.length; i++) {
                array.push([table[i].Title, table[i].Count]);
            }

            var data = new google.visualization.arrayToDataTable(array);

            var options = {
                width: '100%',
                height: 400,
                chart: {
                    title: title,
                },
                bar: { groupWidth: '95%' },
                bars: 'horizontal',
                series: {
                    0: { axis: 'distance' },
                }
            };

            var chart = new google.charts.Bar(document.getElementById("chart-content"));
            chart.draw(data, options);

            $("#chart-type").val("");
        }
    }
</code>```

答:
According to the documentation, you can set the format of hAxis or vAxis to 'none' to display the full number.

Example:

```<code>        var options = {
            width: '100%',
            height: 400,
            chart: {
                title: title,
            },
            bar: { groupWidth: '95%' },
            bars: 'horizontal',
            series: {
                0: { axis: 'distance' },
            },
            vAxis: {
                format: 'none'
            }
        };
</code>```

Title: Graphic counter correction

Body:
I have a chart and my system that I need it to report the exact value of the search results.

Due to many data, the results come out so 1.1K.

In the place that 1.1K wanted it shows the exact value that would be 1057.
Here is the graph function in JS:

function Post(url, param, title, totalText) {
    totalText = totalText || "Total";

    $.ajax({
        method: "POST",
        url: "/Graficos/" + url,
        data: param,
        beforeSend: function () {
            showLoader();
        },
        success: function (data) {
            ChartConstructor(title, JSON.stringify(data), totalText);
        },
        complete: function () {
            hideLoader();
        }
    });
}

    function ChartConstructor(title, dados, totalText) {
        window.google.charts.load('current', { 'packages': ['bar'] });
        window.google.charts.setOnLoadCallback(drawStuff);

        function drawStuff() {
            var table = JSON.parse(dados);
            var rows = "";

            var array = [["", "Total"]];

            for (var i = 0; i < table.length; i++) {
                array.push([table[i].Title, table[i].Count]);
            }

            var data = new google.visualization.arrayToDataTable(array);

            var options = {
                width: '100%',
                height: 400,
                chart: {
                    title: title,
                },
                bar: { groupWidth: '95%' },
                bars: 'horizontal',
                series: {
                    0: { axis: 'distance' },
                }
            };

            var chart = new google.charts.Bar(document.getElementById("chart-content"));
            chart.draw(data, options);

            $("#chart-type").val("");
        }
    }

Body:
According to the documentation, you can set the format of hAxis or vAxis to 'none' to display the full number.

Example:

        var options = {
            width: '100%',
            height: 400,
            chart: {
                title: title,
            },
            bar: { groupWidth: '95%' },
            bars: 'horizontal',
            series: {
                0: { axis: 'distance' },
            },
            vAxis: {
                format: 'none'
            }
        };


问:
Byte conversion from hash string, java vs python
I have issue with converting a pure java Curve25519 function to Python equivalent, the specific problem is related to digest function that convert hash string to byte equivalent, the java implementation :

Data example :

sP = "this is a sample of secret pass phrase for test purpose"

```<code>/**
 * Calculate the SHA-256 hash of a string
 *
 * @param       input           Data to be hashed
 * @return                      The hash digest
 */
public static byte[] singleDigest(String input) {
    byte[] bytes;
    try {
        bytes = singleDigest(input.getBytes("UTF-8"));
        System.out.println("bytes"+bytes);
        System.out.println("before singleDigest"+input);
    } catch (UnsupportedEncodingException exc) {
        bytes = null;
    }
    return bytes;
}

/**
 * Calculate the SHA-256 hash of a byte array
 *
 * @param       input           Data to be hashed
 * @return                      The hash digest
 */
public static byte[] singleDigest(byte[] input) {
    byte[] bytes;
    synchronized (digest) {
        digest.reset();
        bytes = digest.digest(input);

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
            sb.append(String.format("%02x", bytes[i] & 0xFF));
        }
        System.out.println(sb.toString());
    }
    return bytes;
}
</code>```

Generate this byte output :

byteOutput :82, -57, 124, 58, -105, 76, 123, 3, 119, -21, 121, 71, -54, 73, -75, 54, 31, -33, -49, -68, -16, -19, 125, -61, -116, -82, 96, 50, -35, -119, -28, 25

with positive and negative numbers, on python side, I use this function to convert a hashed string to byte :

```<code>secret = sha256(sP.encode('utf-8')).hexdigest()
sct = ParseHexString(secret).getData()

class ParseHexString(object):

    def __init__(self, hex):
        """

        """
        if not isinstance(hex, str):
            return None
        else:

            self.hex = hex
            self.listOfByte = None

        self.run()

    def run(self):

        if len(self.hex)&0x01 == 1:
            return None

        lbytes = []
        for i in range(0, len(self.hex), 2):
            op1, op2 = self.hex[i:i + 2]
            oop1 = ord(op1)
            oop2 = ord(op2)

            char1 = oop1 - 0x57 if oop1 > 0x60 else oop1 - 0x30
            char2 = oop2 - 0x57 if oop2 > 0x60 else oop2 - 0x30

            if (char1 < 0 or char2 < 0 or char1 > 15 or char2 > 15):
                print("Invalid hex number ",op1,op2)

            lbytes.append(((char1 << 4) + char2))

        self.listOfByte = lbytes

    def getData(self):
        return self.listOfByte
</code>```

I used lists here instead of mutable bytearray because of internal representation of bytearray (0 - 256), and the output for some hashed string
is different and is only positive integers :

82, 199, 124, 58, 151, 76, 123, 3, 119, 235, 121, 71, 202, 73, 181, 54, 31, 217, 207, 188, 240, 237, 125, 196, 140, 174, 96, 50, 221, 137, 228, 25

I noticed that (256 - JavaByteOutput[x] == PythonByteOtput[x]) when JavaByteOutput is a negative number, the question is, how I can modify my ParseHexString class to have equivalent positive/negative output, and I want pure python code and no libraries.

Thanks for any kind answer.
Regards
Alex

答:
The whole point here: Java only knows signed types.

This means: although the Java byte is also about 8 bits, the range is from -128 to 127. Unsigned bytes go from 0 to 255.

That is all there is to this. The only thing that really matters is that you are consistent about how the values dealt with. See here for some further thoughts on this topic.

Body:
I have issue with converting a pure java Curve25519 function to Python equivalent, the specific problem is related to digest function that convert hash string to byte equivalent, the java implementation :

Data example :

sP = "this is a sample of secret pass phrase for test purpose"

/**
 * Calculate the SHA-256 hash of a string
 *
 * @param       input           Data to be hashed
 * @return                      The hash digest
 */
public static byte[] singleDigest(String input) {
    byte[] bytes;
    try {
        bytes = singleDigest(input.getBytes("UTF-8"));
        System.out.println("bytes"+bytes);
        System.out.println("before singleDigest"+input);
    } catch (UnsupportedEncodingException exc) {
        bytes = null;
    }
    return bytes;
}

/**
 * Calculate the SHA-256 hash of a byte array
 *
 * @param       input           Data to be hashed
 * @return                      The hash digest
 */
public static byte[] singleDigest(byte[] input) {
    byte[] bytes;
    synchronized (digest) {
        digest.reset();
        bytes = digest.digest(input);

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
            sb.append(String.format("%02x", bytes[i] & 0xFF));
        }
        System.out.println(sb.toString());
    }
    return bytes;
}

Generate this byte output :

byteOutput :82, -57, 124, 58, -105, 76, 123, 3, 119, -21, 121, 71, -54, 73, -75, 54, 31, -33, -49, -68, -16, -19, 125, -61, -116, -82, 96, 50, -35, -119, -28, 25

with positive and negative numbers, on python side, I use this function to convert a hashed string to byte :

secret = sha256(sP.encode('utf-8')).hexdigest()
sct = ParseHexString(secret).getData()

class ParseHexString(object):

    def __init__(self, hex):
        """

        """
        if not isinstance(hex, str):
            return None
        else:

            self.hex = hex
            self.listOfByte = None

        self.run()

    def run(self):

        if len(self.hex)&0x01 == 1:
            return None

        lbytes = []
        for i in range(0, len(self.hex), 2):
            op1, op2 = self.hex[i:i + 2]
            oop1 = ord(op1)
            oop2 = ord(op2)

            char1 = oop1 - 0x57 if oop1 > 0x60 else oop1 - 0x30
            char2 = oop2 - 0x57 if oop2 > 0x60 else oop2 - 0x30

            if (char1 < 0 or char2 < 0 or char1 > 15 or char2 > 15):
                print("Invalid hex number ",op1,op2)

            lbytes.append(((char1 << 4) + char2))

        self.listOfByte = lbytes

    def getData(self):
        return self.listOfByte

I used lists here instead of mutable bytearray because of internal representation of bytearray (0 - 256), and the output for some hashed string
is different and is only positive integers :

82, 199, 124, 58, 151, 76, 123, 3, 119, 235, 121, 71, 202, 73, 181, 54, 31, 217, 207, 188, 240, 237, 125, 196, 140, 174, 96, 50, 221, 137, 228, 25

I noticed that (256 - JavaByteOutput[x] == PythonByteOtput[x]) when JavaByteOutput is a negative number, the question is, how I can modify my ParseHexString class to have equivalent positive/negative output, and I want pure python code and no libraries.

Thanks for any kind answer.
Regards
Alex


问:
Spring boot deployment
I am developing a spring boot rest API for mobile application (without view or JSP pages) , I am deploying the API on a windows server (dedicated) , I installed the tomcat server and MySQL server on the server , when I am trying to access the application from the server localhost everything is ok , ex:  localhost:8080/api/users, but when I am trying to access it from another pc using my server IP  I get cannot reach ex:  162.144.188.112:8080/api/users
the same thing happens when I want to access MySQL server using server IP.

so I do not  know is there any issue in my server , or I just miss something in the  configuration for MySQL and tomcat server ?

答:
If you can access it locally but not remotely, it has to be a missing firewall rule in your Windows Server or there is an additional firewall between your remote desktop and your server.

For the firewall of your Windows Server:

In the Start menu, type Windows Firewall with Advanced Security and then...

Right click on Inbound Rules and select New Rule...

For the rule type, take Port then click Next >

Select TCP and Specific local ports with 8080 filled in the text box, then click Next >

Allow the connection, then click Next >

Keep the default for the next page (Profile), click Next >

Give a name to your rule and click Finish

As said before, as long as your MySQL server is on the same server than your application, do not expose its port (3306).

Title: Spring boot deployment


问:
laravel curl not working on azure
I am connecting my two apps (laravel with python) using curl command. It is working absolutely fine on my local server without changing a single line but when it gives me following error when on azure server

POST https://myweb.com/searchJobs 500 ()

my code is

```<code>$ch = curl_init();

    //URL to send the request to

    curl_setopt($ch, CURLOPT_URL, 'http://python-scrapper-python001.azurewebsites.net/myfunction');

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));

    //We are doing a post request
    curl_setopt($ch, CURLOPT_POST, 1);

    //adding the post data to request
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);

    //Return instead of outputting directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $output = curl_exec($ch);
        curl_close($ch);
</code>```

is there any security protocol that I need to update on azure or what can be possible issue?

答:
Since you are using the default domain provided by azure appservice. Instead of just using the HTTP protocol try to use the HTTPS since this is already free on the default domain provided. in this case try this changes.</p>

```<code>$ch = curl_init();

    //URL to send the request to

    curl_setopt($ch, CURLOPT_URL, 'https://python-scrapper-python001.azurewebsites.net/myfunction');

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));

    //We are doing a post request
    curl_setopt($ch, CURLOPT_POST, 1);

    //adding the post data to request
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);

    //Return instead of outputting directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $output = curl_exec($ch);
        curl_close($ch);
</code>```

Title: laravel curl not working on azure

Body:
I am connecting my two apps (laravel with python) using curl command. It is working absolutely fine on my local server without changing a single line but when it gives me following error when on azure server

POST https://myweb.com/searchJobs 500 ()

my code is

$ch = curl_init();

    //URL to send the request to

    curl_setopt($ch, CURLOPT_URL, 'http://python-scrapper-python001.azurewebsites.net/myfunction');

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));

    //We are doing a post request
    curl_setopt($ch, CURLOPT_POST, 1);

    //adding the post data to request
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);

    //Return instead of outputting directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $output = curl_exec($ch);
        curl_close($ch);

is there any security protocol that I need to update on azure or what can be possible issue?

Body:
Since you are using the default domain provided by azure appservice. Instead of just using the HTTP protocol try to use the HTTPS since this is already free on the default domain provided. in this case try this changes.

$ch = curl_init();

    //URL to send the request to

    curl_setopt($ch, CURLOPT_URL, 'https://python-scrapper-python001.azurewebsites.net/myfunction');

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));

    //We are doing a post request
    curl_setopt($ch, CURLOPT_POST, 1);

    //adding the post data to request
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);

    //Return instead of outputting directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $output = curl_exec($ch);
        curl_close($ch);


问:
Replicate Remote DB Mysql
I´m following this tutorial (http://www.linux-party.com/42-mysql/8628-como-replicar-una-de-base-de-datos-de-mysql-2-de-2)..

When I configure slave (my.cnf) with this parameters:

```<code>server-id=2
master-host=xxx.xxx.xxx.xxx
master-user=root
master-password=xxxxxxxxx
master-connect-retry=60
replicate-do-db=db_mirror
</code>```

And restart mysql, I get the following error:

```<code>ERROR! MySQL server PID file could not be found!
Starting MySQL.. ERROR! The server quit without updating PID file
(/var/lib/mysql/xxxxxxxxx.com.pid)
</code>```

Any suggestions?

Thanks

答: File my.cnf was bad configurated....</p>

Title: Replicate Remote DB Mysql

Body:
I´m following this tutorial (http://www.linux-party.com/42-mysql/8628-como-replicar-una-de-base-de-datos-de-mysql-2-de-2)..

When I configure slave (my.cnf) with this parameters:

server-id=2
master-host=xxx.xxx.xxx.xxx
master-user=root
master-password=xxxxxxxxx
master-connect-retry=60
replicate-do-db=db_mirror

And restart mysql, I get the following error:

ERROR! MySQL server PID file could not be found!
Starting MySQL.. ERROR! The server quit without updating PID file
(/var/lib/mysql/xxxxxxxxx.com.pid)

Any suggestions?

Thanks

Body: File my.cnf was bad configurated....


问:
php - array map using public function callback within class
```<code>class something{
    public function add_val( $val ){
    $array = array();
    foreach( $val as $value ) {
        $array[] = static::$post[${$value}];
    }
    return $array;
    }
    pulblic function somethingelse(){
       ....
       ....
       $optionsArray['value'] = array_map( 'add_val', array_chunk( $drop_val, count( $optionsArray['heading_x'] ) ) );
       ....
       ....
    }
}
</code>```

how can i call the add_val method within the other using array_map()??

答:
Use an array that contains the object, and the method name:

```<code>$optionsArray['value'] = array_map(array($this, 'add_val'), array_chunk($drop_val, count($optionsArray['heading_x'])));
</code>```

You do the same for most other functions that take in callbacks as parameters, like array_walk(), call_user_func(), call_user_func_array(), and so on.

How does it work? Well, if you pass an array to the callback parameter, PHP does something similar to this (for array_map()):

```<code>if (is_array($callback)) {         // array($this, 'add_val')
    if (is_object($callback[0])) {
        $object = $callback[0];    // The object ($this)
        $method = $callback[1];    // The object method name ('add_val')

        foreach ($array as &$v) {
            // This is how you call a variable object method in PHP
            // You end up doing something like $this->add_val($v);
            $v = $object->$method($v);
        }
    }
}

// ...

return $array;
</code>```

Here you can see that PHP just loops through your array, calling the method on each value. Nothing complicated to it; again just basic object-oriented code.

This may or may not be how PHP does it internally, but conceptually it's the same.

Body:
class something{
    public function add_val( $val ){
    $array = array();
    foreach( $val as $value ) {
        $array[] = static::$post[${$value}];
    }
    return $array;
    }
    pulblic function somethingelse(){
       ....
       ....
       $optionsArray['value'] = array_map( 'add_val', array_chunk( $drop_val, count( $optionsArray['heading_x'] ) ) );
       ....
       ....
    }
}

how can i call the add_val method within the other using array_map()??

Body:
Use an array that contains the object, and the method name:

$optionsArray['value'] = array_map(array($this, 'add_val'), array_chunk($drop_val, count($optionsArray['heading_x'])));

You do the same for most other functions that take in callbacks as parameters, like array_walk(), call_user_func(), call_user_func_array(), and so on.

How does it work? Well, if you pass an array to the callback parameter, PHP does something similar to this (for array_map()):

if (is_array($callback)) {         // array($this, 'add_val')
    if (is_object($callback[0])) {
        $object = $callback[0];    // The object ($this)
        $method = $callback[1];    // The object method name ('add_val')

        foreach ($array as &$v) {
            // This is how you call a variable object method in PHP
            // You end up doing something like $this->add_val($v);
            $v = $object->$method($v);
        }
    }
}

// ...

return $array;

Here you can see that PHP just loops through your array, calling the method on each value. Nothing complicated to it; again just basic object-oriented code.

This may or may not be how PHP does it internally, but conceptually it's the same.


问:
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other.

Here is the result I would like

Here is what I am getting (fail)

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
  padding-top: 25px;
  padding-bottom: 95px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="primary-content">
  <p class="intro">
  Austin, Texas is not only the capital.<br>It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.
  </p>
  <div id="container2">
    <div id="container1">
      <div id="About">
        <h2>About</h2>
        <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum.
        </p>
      <!-- Column one end -->
      </div>
      <div id="Capitalbuilding">
      <!-- Column two start -->
        <img src="https://image.ibb.co/e90Vhw/419796506_db7f02aedd_b.jpg" alt="picture of the Capital Building">
      <!-- Column two end -->
      </div>
    </div>
  </div>
</div><!-- End .primary-content --></code>```

答:
Flexbox is a good solution to this. Just set the container1 to display: flex

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
    padding-top: 25px;
  padding-bottom: 95px;
}
#container1 {
  display: flex;
  background-color: #E9CCA9;

}
#Capitalbuilding {
  background-color: #4e4e4e;
  width: 40%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="primary-content">
     <p class="intro">
                Austin, Texas is not only the capital.<br>It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.
            </p>
    <div id="container2">
    <div id="container1">
        <div id="About">
            <h2>About</h2>
        <p>
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum.  .
        </p>
            <!-- Column one end -->
        </div>
        <div id="Capitalbuilding">
            <!-- Column two start -->
        <img src="https://image.ibb.co/e90Vhw/419796506_db7f02aedd_b.jpg" alt="picture of the Capital Building">
            <!-- Column two end -->
        </div>
    </div>
</div>

        </div><!-- End .primary-content --></code>```

Body:
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other.

Here is the result I would like

Here is what I am getting (fail)

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
  padding-top: 25px;
  padding-bottom: 95px;
}

  Austin, Texas is not only the capital.
It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.

About

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum.

Body:
Flexbox is a good solution to this. Just set the container1 to display: flex

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
    padding-top: 25px;
  padding-bottom: 95px;
}
#container1 {
  display: flex;
  background-color: #E9CCA9;

}
#Capitalbuilding {
  background-color: #4e4e4e;
  width: 40%;
}

<div class="primary-content">
     <p class="intro">
                Austin, Texas is not only the capital.<br>It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.
            </p>
    <div id="container2">
    <div id="container1">
        <div id="About">
            <h2>About</h2>
        <p>
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum.  .
        </p>
            <!-- Column one end -->
        </div>
        <div id="Capitalbuilding">
            <!-- Column two start -->
        <img src="https://image.ibb.co/e90Vhw/419796506_db7f02aedd_b.jpg" alt="picture of the Capital Building">
            <!-- Column two end -->
        </div>
    </div>
</div>

        </div><!-- End .primary-content -->


问:
Determine Collection type in Swift
I've a function whose header looks like this

```<code>func doSomethingOnCollection<T:Collection>(_ array: T) -> [T]
</code>```

as you can see it takes Collection as a parameter, meaning it can be Array, Set or Dictionary, how can I check type of parameter passed in this function at runtime ?

答:
Swift documentation says:

Use the type check operator (is) to check whether an instance is of a
  certain subclass type. The type check operator returns true if the
  instance is of that subclass type and false if it is not.

```<code>func doSomethingOnCollection<T: Collection>(_ param: T) -> [T] {
    if param is Array<Any> {
        print("Array")
    }
    // We can't say 'Set<Any>', since type of set should conform
    // protocol 'Hashable'
    else if param is Set<Int> {
        print("Set")
    }
    // For the same reason above, we can't say 'Dictionary<Any, Any>'
    else if param is Dictionary<Int, Any> {
        print("Dictionary")
    }
    return []
}
</code>```

Title: Determine Collection type in Swift

Body:
I've a function whose header looks like this

func doSomethingOnCollection<T:Collection>(_ array: T) -> [T]

as you can see it takes Collection as a parameter, meaning it can be Array, Set or Dictionary, how can I check type of parameter passed in this function at runtime ?

Body:
Swift documentation says:

Use the type check operator (is) to check whether an instance is of a
  certain subclass type. The type check operator returns true if the
  instance is of that subclass type and false if it is not.

func doSomethingOnCollection<T: Collection>(_ param: T) -> [T] {
    if param is Array<Any> {
        print("Array")
    }
    // We can't say 'Set<Any>', since type of set should conform
    // protocol 'Hashable'
    else if param is Set<Int> {
        print("Set")
    }
    // For the same reason above, we can't say 'Dictionary<Any, Any>'
    else if param is Dictionary<Int, Any> {
        print("Dictionary")
    }
    return []
}


问:
Enabling ProGuard in Eclipse for Android
The new documentation on ProGuard for Android says to add a line to the default.properties file in the project home directory. However, on opening this file, I read at the top:

```<code># This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
</code>```

Am I missing something?

Also, is there a way to enable ProGuard only for a production build from Eclipse (i.e., when exporting the finished product)?

答: You can add the line to build.properties, as mentioned in default.properties.

Body:
The new documentation on ProGuard for Android says to add a line to the default.properties file in the project home directory. However, on opening this file, I read at the top:

# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!

Am I missing something?

Also, is there a way to enable ProGuard only for a production build from Eclipse (i.e., when exporting the finished product)?


问:
Alternative to Concat on MySql
With the following query:

```<code>"SELECT
'Week' `key`
,concat("KW-" ,WEEK(current_date - INTERVAL 1 WEEK) ) as value"
</code>```

I get :

```<code>Key Value
Week KW-48
</code>```

However when I transform this query to Talend for an automation, it gives me error. Is there any alternative to concat function in Mysql? Thank you.

答:
There is also CONCAT_WS():

```<code>SELECT CONCAT_WS(SPACE(1), 'Name:','jhon') AS result
</code>```

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_concat-ws

Title: Alternative to Concat on MySql

Body:
With the following query:

"SELECT
'Week' `key`
,concat("KW-" ,WEEK(current_date - INTERVAL 1 WEEK) ) as value"

I get :

Key Value
Week KW-48

However when I transform this query to Talend for an automation, it gives me error. Is there any alternative to concat function in Mysql? Thank you.

Body:
There is also CONCAT_WS():

SELECT CONCAT_WS(SPACE(1), 'Name:','jhon') AS result

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_concat-ws


问:
Why does ffmpeg never finish when converting a video from my web app?
I am trying to convert a video when the user submits a form.  It seems to convert ok but the file "is being used by another proccess" when I try to do anything with it.  It looks like ffmpeg.exe never exits.  My code is below is there anything I should be doing different to allow the process to release the file?  If I run this manually it exits fine.</p>

```<code>internal class ConversionUtility : Utility
{
    public void Convert(string videoFileName)
    {
        var video = new VideoFile(videoFileName);

        if (!video.infoGathered)
            GetVideoInfo(video);

        var Params = string.Format("-y -i \"{0}\" -coder ac -me_method full -me_range 16 -subq 5 -sc_threshold 40 -vcodec libx264 -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -i_qfactor 0.71 -keyint_min 25 -b_strategy 1 -g 250 -r 20 \"{1}\"", video.Path, Path.ChangeExtension(videoFileName,".mp4"));
        //var Params = string.Format("-y -i \"{0}\" -acodec libfaac -ar 44100 -ab 96k -coder ac -me_method full -me_range 16 -subq 5 -sc_threshold 40 -vcodec libx264 -s 1280x544 -b 1600k -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -i_qfactor 0.71 -keyint_min 25 -b_strategy 1 -g 250 -r 20 c:\\output3.mp4", video.Path, videoFileName);
        //var Params = String.Format(" {0} \"{1}\"",this.FFmpegLocation, video.Path);

        var threadStart = new ParameterizedThreadStart(del => RunProcess(Params));
        var thread = new Thread(threadStart);
        thread.Start();
        //RunProcess(Params);
    }
}

internal class Utility
{
    public string FFmpegLocation { get; set; }
    private string WorkingPath { get { return Path.GetDirectoryName(FFmpegLocation); } }

    protected string RunProcess(string Parameters)
    {
        //create a process info
        var oInfo = new ProcessStartInfo(this.FFmpegLocation, Parameters)
        {
            UseShellExecute = false,
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };

        //Create the output and streamreader to get the output
        string output = null; StreamReader srOutput = null;

        //try the process
        try
        {
            //run the process
            Process proc = System.Diagnostics.Process.Start(oInfo);

            proc.WaitForExit();
            //if (!proc.WaitForExit(10000))
            //    proc.Kill();

            //get the output
            srOutput = proc.StandardError;

            //now put it in a string
            output = srOutput.ReadToEnd();

            proc.Close();
        }
        catch (Exception)
        {
            output = string.Empty;
        }
        finally
        {
            //now, if we succeded, close out the streamreader
            if (srOutput != null)
            {
                srOutput.Close();
                srOutput.Dispose();
            }
        }
        return output;
    }
</code>```

答:
You should always read the StandardOutput and the StandardError buffers while the process is running. Whenever the buffers reach their limits, the process will literally hang until you read the buffers to end.

FFMpeg constantly reports information about the conversion. Every update of the information you see in the bottom of the Command Prompt is added to the StandardOutput buffer, thus filling up the buffer. The buffer is likely to fill up quickly when converting large files.

Body:
I am trying to convert a video when the user submits a form.  It seems to convert ok but the file "is being used by another proccess" when I try to do anything with it.  It looks like ffmpeg.exe never exits.  My code is below is there anything I should be doing different to allow the process to release the file?  If I run this manually it exits fine.

internal class ConversionUtility : Utility
{
    public void Convert(string videoFileName)
    {
        var video = new VideoFile(videoFileName);

        if (!video.infoGathered)
            GetVideoInfo(video);

        var Params = string.Format("-y -i \"{0}\" -coder ac -me_method full -me_range 16 -subq 5 -sc_threshold 40 -vcodec libx264 -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -i_qfactor 0.71 -keyint_min 25 -b_strategy 1 -g 250 -r 20 \"{1}\"", video.Path, Path.ChangeExtension(videoFileName,".mp4"));
        //var Params = string.Format("-y -i \"{0}\" -acodec libfaac -ar 44100 -ab 96k -coder ac -me_method full -me_range 16 -subq 5 -sc_threshold 40 -vcodec libx264 -s 1280x544 -b 1600k -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -i_qfactor 0.71 -keyint_min 25 -b_strategy 1 -g 250 -r 20 c:\\output3.mp4", video.Path, videoFileName);
        //var Params = String.Format(" {0} \"{1}\"",this.FFmpegLocation, video.Path);

        var threadStart = new ParameterizedThreadStart(del => RunProcess(Params));
        var thread = new Thread(threadStart);
        thread.Start();
        //RunProcess(Params);
    }
}

internal class Utility
{
    public string FFmpegLocation { get; set; }
    private string WorkingPath { get { return Path.GetDirectoryName(FFmpegLocation); } }

    protected string RunProcess(string Parameters)
    {
        //create a process info
        var oInfo = new ProcessStartInfo(this.FFmpegLocation, Parameters)
        {
            UseShellExecute = false,
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };

        //Create the output and streamreader to get the output
        string output = null; StreamReader srOutput = null;

        //try the process
        try
        {
            //run the process
            Process proc = System.Diagnostics.Process.Start(oInfo);

            proc.WaitForExit();
            //if (!proc.WaitForExit(10000))
            //    proc.Kill();

            //get the output
            srOutput = proc.StandardError;

            //now put it in a string
            output = srOutput.ReadToEnd();

            proc.Close();
        }
        catch (Exception)
        {
            output = string.Empty;
        }
        finally
        {
            //now, if we succeded, close out the streamreader
            if (srOutput != null)
            {
                srOutput.Close();
                srOutput.Dispose();
            }
        }
        return output;
    }


问:
Transpose columns to rows in Scala
Need to transpose the dataframe and save it as external table using Scala.
Tried to do using pivot but no luck, need to transpose all the columns in a DF to rows and corresponding values as sample_value columns.
My DF

```<code>A B C D
1 2 3 4
1 2 3 4
2 3 4 1
2 3 4 1
</code>```

Need final output as:

```<code>col_name  sample_value1 sample_value2
A         1             2
B         2             3
C         3             4
D         4             1
</code>```

答:
Before I proceed to answer your question, I would like to stress on the fact that this is a very expensive solution and should be used only when you don't have an alternative.

Given a dataframe as

```<code>+---+---+---+---+
|A  |B  |C  |D  |
+---+---+---+---+
|1  |2  |3  |4  |
|1  |2  |3  |4  |
|2  |3  |4  |1  |
|2  |3  |4  |1  |
+---+---+---+---+
</code>```

You can do the following to get a new column for headernames for the final dataframe as

```<code>import org.apache.spark.sql.functions.lit
import org.apache.spark.sql.functions.concat
import org.apache.spark.sql.functions.rank
import org.apache.spark.sql.expressions.Window
val tempdf = df.distinct().withColumn("new", concat(lit("sample_value"), rank.over(Window.partitionBy().orderBy("A")))).cache()
</code>```

which should give you

```<code>+---+---+---+---+-------------+
|A  |B  |C  |D  |new          |
+---+---+---+---+-------------+
|1  |2  |3  |4  |sample_value1|
|2  |3  |4  |1  |sample_value2|
+---+---+---+---+-------------+
</code>```

Now final expensive part is to use pivot, union, withColumn, groupBy and aggregations to get the desired output

```<code>val firstCol = df.schema.fieldNames.head
val restOfCol = df.schema.fieldNames.tail
import org.apache.spark.sql.functions.first
var finaldf = tempdf.groupBy().pivot("new").agg(first(firstCol)).withColumn("col_name", lit(firstCol))

for(column <- restOfCol) {
  finaldf = finaldf.union(tempdf.groupBy().pivot("new").agg(first(column)).withColumn("col_name", lit(column)))
}

finaldf.show(false)
</code>```

finaldf should be

```<code>+-------------+-------------+--------+
|sample_value1|sample_value2|col_name|
+-------------+-------------+--------+
|1            |2            |A       |
|2            |3            |B       |
|3            |4            |C       |
|4            |1            |D       |
+-------------+-------------+--------+
</code>```

ContentLicense: CC BY-SA 4.0

Title: Transpose columns to rows in Scala

Body:
Need to transpose the dataframe and save it as external table using Scala.
Tried to do using pivot but no luck, need to transpose all the columns in a DF to rows and corresponding values as sample_value columns.
My DF

A B C D
1 2 3 4
1 2 3 4
2 3 4 1
2 3 4 1

Need final output as:

col_name  sample_value1 sample_value2
A         1             2
B         2             3
C         3             4
D         4             1

Body:
Before I proceed to answer your question, I would like to stress on the fact that this is a very expensive solution and should be used only when you don't have an alternative.

Given a dataframe as

+---+---+---+---+
|A  |B  |C  |D  |
+---+---+---+---+
|1  |2  |3  |4  |
|1  |2  |3  |4  |
|2  |3  |4  |1  |
|2  |3  |4  |1  |
+---+---+---+---+

You can do the following to get a new column for headernames for the final dataframe as

import org.apache.spark.sql.functions.lit
import org.apache.spark.sql.functions.concat
import org.apache.spark.sql.functions.rank
import org.apache.spark.sql.expressions.Window
val tempdf = df.distinct().withColumn("new", concat(lit("sample_value"), rank.over(Window.partitionBy().orderBy("A")))).cache()

which should give you

+---+---+---+---+-------------+
|A  |B  |C  |D  |new          |
+---+---+---+---+-------------+
|1  |2  |3  |4  |sample_value1|
|2  |3  |4  |1  |sample_value2|
+---+---+---+---+-------------+

Now final expensive part is to use pivot, union, withColumn, groupBy and aggregations to get the desired output

val firstCol = df.schema.fieldNames.head
val restOfCol = df.schema.fieldNames.tail
import org.apache.spark.sql.functions.first
var finaldf = tempdf.groupBy().pivot("new").agg(first(firstCol)).withColumn("col_name", lit(firstCol))

for(column <- restOfCol) {
  finaldf = finaldf.union(tempdf.groupBy().pivot("new").agg(first(column)).withColumn("col_name", lit(column)))
}

finaldf.show(false)

finaldf should be

+-------------+-------------+--------+
|sample_value1|sample_value2|col_name|
+-------------+-------------+--------+
|1            |2            |A       |
|2            |3            |B       |
|3            |4            |C       |
|4            |1            |D       |
+-------------+-------------+--------+


问:
Fastest way to subtract pointer array by a constant
I have a very large array of type (short*). How do I subtract all values by a constant in the fastest manner? </p>

答:
Using a for loop is indeed the most efficient way to do this

```<code>short *arr = new short[1000000];
const short c = 8504;

//populate the array
     Populate(arr); //just some method to populate the array

    for(int i=0;i<1000000;i++){
      arr[i] = c - arr[i] ;//subtract from the constant
    //or even
    //*arr = c - *arr++ ;
    }
</code>```

This code doesn't check for type overflows though.

Body:
Using a for loop is indeed the most efficient way to do this

short *arr = new short[1000000];
const short c = 8504;

//populate the array
     Populate(arr); //just some method to populate the array

    for(int i=0;i<1000000;i++){
      arr[i] = c - arr[i] ;//subtract from the constant
    //or even
    //*arr = c - *arr++ ;
    }

This code doesn't check for type overflows though.


问:
Why Assembly x86_64 syscall parameters are not in alphabetical order like i386
There is that one question that troubles me.

So ... Why in x86_32 the parameters are passed in registers that I feel are in alphabetically (eax, ecx, edx, esi) and ranked order (esi, edi, ebp)

```<code>+---------+------+------+------+------+------+------+
| syscall | arg0 | arg1 | arg2 | arg3 | arg4 | arg5 |
+---------+------+------+------+------+------+------+
|   %eax  | %ebx | %ecx | %edx | %esi | %edi | %ebp |
+---------+------+------+------+------+------+------+

section .text
    global _start
_start:
    mov eax, 1     ; x86_64 opcode for sys_exit
    mov ebx, 0     ; first argument
    int 0x80
</code>```

While in x86_64 syscall's parameters are passed in registers that look a little bit randomly arranged:

```<code>+---------+------+------+------+------+------+------+
| syscall | arg0 | arg1 | arg2 | arg3 | arg4 | arg5 |
+---------+------+------+------+------+------+------+
|   %rax  | %rdi | %rsi | %rdx | %r10 | %r8  | %r9  |
+---------+------+------+------+------+------+------+

section .text
    global _start
_start:
    mov eax, 1     ; x86_64 opcode for sys_exit
    mov edi, 0     ; first argument
    syscall
</code>```

Did they do that for a specific reason? Am I not seeing something here?

答:
The x86-64 System V ABI was designed to minimize instruction-count (and to some degree code-size) in SPECint as compiled by the version of gcc that was current before the first AMD64 CPUs were sold.  See this answer for some history and list-archive links.

Since 5 minutes before I thought all registers were the same but they were used differently because of a convention. Now all things changed for me

x86-64 is not fully orthogonal.  Some instructions implicitly use specific registers.  e.g. push implicitly uses rsp as the stack pointer, shl edx, cl is only usable with a shift count in cl (until BMI2 shlx).

More rarely used: widening mul rdi does rdx:rax = rax*rdi.  The rep-string instructions implicitly use RDI, RSI, and RCX, although they're often not worth using.

It turns out that choosing the arg-passing registers so that functions that passed their args to memcpy could inline it as rep movs was useful in the metric Jan Hubicka was using, thus rdi and rsi were chosen as the first two args.  But that leaving rcx unused until the 4th arg was better, because cl is needed for variable-count shift.  (And most functions don't happen to use their 3rd arg as a shift count.)  (Probably older GCC versions inlined memcpy or memset as rep movs more aggressively; it's usually not worth it vs. SIMD for small arrays these days.)

The x86-64 System V ABI uses almost the same calling convention for functions as it does for system calls.  This is not a coincidence: it means the implementation for a libc wrapper function like mmap can be:

```<code>mmap:
    mov  r10, rcx       ; syscall destroys rcx and r11; 4th arg passed in r10 for syscalls
    mov  eax, __NR_mmap
    syscall

    cmp  rax, -4096
    ja  .set_errno_and_stuff
    ret
</code>```

This is a tiny advantage, but there's really no reason not to do this.  It also saves a few instructions inside the kernel setting up the arg-passing registers before dispatching to the C implementation of the system call in the kernel.  (See this answer for a look at some kernel side of system call handling.  Mostly about the int 0x80 handler, but I think I mentioned the 64-bit syscall handler and that it dispatches to a table of functions directly from asm.)

The syscall instruction itself destroys RCX and R11 (to save user-space RIP and RFLAGS without needing microcode to set up the kernel stack) so the conventions can't be identical unless the user-space convention avoided RCX and R11.  But RCX is a handy register whose low half can be used without a REX prefix so that probably would have been worse than leaving it as a call-clobbered pure scratch like R11.  Also, the user-space convention uses R10 as a "static chain" pointer for languages with first-class nested functions (not C/C++).

Having the first 4 args able to avoid a REX prefix is probably best for overall code-size, and using RBX or RBP instead of RCX would be weird.  Having a couple call-preserved registers that don't need a REX prefix (EBX/EBP) is good.

See What are the calling conventions for UNIX & Linux system calls on i386 and x86-64 for the function-call and system-call conventions.

The i386 system call convention is the clunky and inconvenient one: ebx is call-preserved, so almost every syscall wrapper needs to save/restore ebx, except for calls with no args like getpid.  (And for that you don't even need to enter the kernel, just call into the vDSO: see The Definitive Guide to Linux System Calls (on x86) for more about vDSO and tons of other stuff.)

But the i386 function-calling convention passes all args on the stack, so glibc wrapper functions still need to mov every arg anyway.

Also note that the "natural" order of x86 registers is EAX, ECX, EDX, EBX, according to their numeric codes in machine code, and also the order that pusha / popa use.  See Why are first four x86 GPRs named in such unintuitive order?.

Body:
There is that one question that troubles me.

So ... Why in x86_32 the parameters are passed in registers that I feel are in alphabetically (eax, ecx, edx, esi) and ranked order (esi, edi, ebp)

+---------+------+------+------+------+------+------+
| syscall | arg0 | arg1 | arg2 | arg3 | arg4 | arg5 |
+---------+------+------+------+------+------+------+
|   %eax  | %ebx | %ecx | %edx | %esi | %edi | %ebp |
+---------+------+------+------+------+------+------+

section .text
    global _start
_start:
    mov eax, 1     ; x86_64 opcode for sys_exit
    mov ebx, 0     ; first argument
    int 0x80

While in x86_64 syscall's parameters are passed in registers that look a little bit randomly arranged:

+---------+------+------+------+------+------+------+
| syscall | arg0 | arg1 | arg2 | arg3 | arg4 | arg5 |
+---------+------+------+------+------+------+------+
|   %rax  | %rdi | %rsi | %rdx | %r10 | %r8  | %r9  |
+---------+------+------+------+------+------+------+

section .text
    global _start
_start:
    mov eax, 1     ; x86_64 opcode for sys_exit
    mov edi, 0     ; first argument
    syscall

Did they do that for a specific reason? Am I not seeing something here?

Body:
The x86-64 System V ABI was designed to minimize instruction-count (and to some degree code-size) in SPECint as compiled by the version of gcc that was current before the first AMD64 CPUs were sold.  See this answer for some history and list-archive links.

Since 5 minutes before I thought all registers were the same but they were used differently because of a convention. Now all things changed for me

x86-64 is not fully orthogonal.  Some instructions implicitly use specific registers.  e.g. push implicitly uses rsp as the stack pointer, shl edx, cl is only usable with a shift count in cl (until BMI2 shlx).

More rarely used: widening mul rdi does rdx:rax = rax*rdi.  The rep-string instructions implicitly use RDI, RSI, and RCX, although they're often not worth using.

It turns out that choosing the arg-passing registers so that functions that passed their args to memcpy could inline it as rep movs was useful in the metric Jan Hubicka was using, thus rdi and rsi were chosen as the first two args.  But that leaving rcx unused until the 4th arg was better, because cl is needed for variable-count shift.  (And most functions don't happen to use their 3rd arg as a shift count.)  (Probably older GCC versions inlined memcpy or memset as rep movs more aggressively; it's usually not worth it vs. SIMD for small arrays these days.)

The x86-64 System V ABI uses almost the same calling convention for functions as it does for system calls.  This is not a coincidence: it means the implementation for a libc wrapper function like mmap can be:

mmap:
    mov  r10, rcx       ; syscall destroys rcx and r11; 4th arg passed in r10 for syscalls
    mov  eax, __NR_mmap
    syscall

    cmp  rax, -4096
    ja  .set_errno_and_stuff
    ret

This is a tiny advantage, but there's really no reason not to do this.  It also saves a few instructions inside the kernel setting up the arg-passing registers before dispatching to the C implementation of the system call in the kernel.  (See this answer for a look at some kernel side of system call handling.  Mostly about the int 0x80 handler, but I think I mentioned the 64-bit syscall handler and that it dispatches to a table of functions directly from asm.)

The syscall instruction itself destroys RCX and R11 (to save user-space RIP and RFLAGS without needing microcode to set up the kernel stack) so the conventions can't be identical unless the user-space convention avoided RCX and R11.  But RCX is a handy register whose low half can be used without a REX prefix so that probably would have been worse than leaving it as a call-clobbered pure scratch like R11.  Also, the user-space convention uses R10 as a "static chain" pointer for languages with first-class nested functions (not C/C++).

Having the first 4 args able to avoid a REX prefix is probably best for overall code-size, and using RBX or RBP instead of RCX would be weird.  Having a couple call-preserved registers that don't need a REX prefix (EBX/EBP) is good.

See What are the calling conventions for UNIX & Linux system calls on i386 and x86-64 for the function-call and system-call conventions.

The i386 system call convention is the clunky and inconvenient one: ebx is call-preserved, so almost every syscall wrapper needs to save/restore ebx, except for calls with no args like getpid.  (And for that you don't even need to enter the kernel, just call into the vDSO: see The Definitive Guide to Linux System Calls (on x86) for more about vDSO and tons of other stuff.)

But the i386 function-calling convention passes all args on the stack, so glibc wrapper functions still need to mov every arg anyway.

Also note that the "natural" order of x86 registers is EAX, ECX, EDX, EBX, according to their numeric codes in machine code, and also the order that pusha / popa use.  See Why are first four x86 GPRs named in such unintuitive order?.


问:
Issue in replacing the values from excel sheet into soap request using groovy script
The values which I try to pass from the excel sheet to the particular field in the soap request are not working in the test case level. I am able to read the excel sheet and also the execution is happening as expected but the values are not replaced in the soap request from the excel sheet.
I have pasted the code below which I am trying to implement for data driven using groovy script.

```<code>import com.eviware.soapui.support.XmlHolder
import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
log.info("Testing Started")
def reqOperationName = "getInsuranceDetails_1_FTC_005";
def inputDataFileName = "D:/SOAP UI Pro/MPI.xls"
def inputDataSheetName = "MPI"
Workbook workbook = Workbook.getWorkbook(new File(inputDataFileName));
WritableWorkbook copy = Workbook.createWorkbook(new File(inputDataFileName),workbook);
WritableSheet sheet1 = copy.getSheet(inputDataSheetName);
log.info("Testing1 Started")
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
String xmlResponse = '${' + reqOperationName + '#Request' +'}'
def reqholder = groovyUtils.getXmlHolder(context.expand(xmlResponse))
try{
    rowcount = sheet1.getRows();
colcount = sheet1.getColumns();
for(Row in 1..rowcount-1){

    String reqTagName = sheet1.getCell(0,0).getContents()
        log.info reqTagName
        def TagCount = reqholder["count(//*:"+reqTagName+")"]
        if(TagCount!=0){
            String reqTagValue = sheet1.getCell(0,Row).getContents()
            reqholder.setNodeValue("//*:"+reqTagName, reqTagValue)
            reqholder.updateProperty()
        }

    //test the request
    testRunner.runTestStepByName(reqOperationName)
log.info("Testing3 Started")
def resholder = groovyUtils.getXmlHolder(reqOperationName+"#Response")
resTagValue1= resholder.getNodeValues("//*:productID")
resTagValue2= resholder.getNodeValues("//*:accountNumber")
resTagValue3= resholder.getNodeValues("//*:insuranceCategory")
resTagValue4= resholder.getNodeValues("//*:imei")
resTagValue5= resholder.getNodeValues("//*:handsetMake")
resTagValue6= resholder.getNodeValues("//*:handsetModel")
resTagValue7= resholder.getNodeValues("//*:insurancePolicyName")
resTagValue8= resholder.getNodeValues("//*:insuranceStartTimestamp")
//Write Response into excel sheet
Label resValue1= new Label(4,Row,resTagValue1);
sheet1.addCell(resValue1);
Label resValue2= new Label(5,Row,resTagValue2);
sheet1.addCell(resValue2);
Label resValue3= new Label(6,Row,resTagValue3);
sheet1.addCell(resValue3);
Label resValue4= new Label(7,Row,resTagValue4);
sheet1.addCell(resValue4);
Label resValue5= new Label(8,Row,resTagValue5);
sheet1.addCell(resValue5);
Label resValue6= new Label(9,Row,resTagValue6);
sheet1.addCell(resValue6);
Label resValue7= new Label(10,Row,resTagValue7);
sheet1.addCell(resValue7);
Label resValue8= new Label(11,Row,resTagValue8);
sheet1.addCell(resValue8);
    }
}catch (Exception e) {log.info(e)}
finally{
    copy.write();
    copy.close();
    workbook.close();
}
log.info("Testing Over")
</code>```

While I try to execute the above code there are no any errors in the error log. The only thing I am getting in the log output is Wed Dec 06 15:04:00 IST 2017:INFO:groovy.lang.GroovyRuntimeException: Could not find matching constructor for: jxl.write.Label(java.lang.Integer, java.lang.Integer, [Ljava.lang.String;)

Any help on the above issue would be very grateful..

Thank you in advance.

New Edit of the code....

```<code>import com.eviware.soapui.support.XmlHolder
import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
log.info("Testing Started")
def reqOperationName = "getInsuranceDetails_1_FTC_005";
def inputDataFileName = "D:/SOAP UI Pro/MPI.xls"
def inputDataSheetName = "MPI"
Workbook workbook = Workbook.getWorkbook(new File(inputDataFileName));
WritableWorkbook copy = Workbook.createWorkbook(new File(inputDataFileName),workbook);
WritableSheet sheet1 = copy.getSheet(inputDataSheetName);
log.info("Testing1 Started")
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
String xmlResponse = '${' + reqOperationName + '#Request' +'}'
def reqholder = groovyUtils.getXmlHolder(context.expand(xmlResponse))
try{
    rowcount = sheet1.getRows();
colcount = sheet1.getColumns();
for(Row in 1..rowcount-1){

    String reqTagName = sheet1.getCell(0,0).getContents()
        log.info reqTagName
        def TagCount = reqholder["count(//*:"+reqTagName+")"]
        if(TagCount!=0){
            String reqTagValue = sheet1.getCell(0,Row).getContents()
            reqholder.setNodeValue("//*:"+reqTagName, reqTagValue)
            reqholder.updateProperty()
        }

    //test the request
    testRunner.runTestStepByName(reqOperationName)
log.info("Testing3 Started")
def resholder = groovyUtils.getXmlHolder(reqOperationName+"#Response")
resTagValue1= resholder.getNodeValue("//*:productID")
resTagValue2= resholder.getNodeValue("//*:accountNumber")
resTagValue3= resholder.getNodeValue("//*:insuranceCategory")
resTagValue4= resholder.getNodeValue("//*:imei")
resTagValue5= resholder.getNodeValue("//*:handsetMake")
resTagValue6= resholder.getNodeValue("//*:handsetModel")
resTagValue7= resholder.getNodeValue("//*:insurancePolicyName")
resTagValue8= resholder.getNodeValue("//*:insuranceStartTimestamp")
//Write Response into excel sheet
Label resValue1= new Label(2,Row,resTagValue1);
sheet1.addCell(resValue1);
Label resValue2= new Label(3,Row,resTagValue2);
sheet1.addCell(resValue2);
Label resValue3= new Label(4,Row,resTagValue3);
sheet1.addCell(resValue3);
Label resValue4= new Label(5,Row,resTagValue4);
sheet1.addCell(resValue4);
Label resValue5= new Label(6,Row,resTagValue5);
sheet1.addCell(resValue5);
Label resValue6= new Label(7,Row,resTagValue6);
sheet1.addCell(resValue6);
Label resValue7= new Label(8,Row,resTagValue7);
sheet1.addCell(resValue7);
Label resValue8= new Label(9,Row,resTagValue8);
sheet1.addCell(resValue8);
    }
}catch (Exception e) {log.info(e)}
finally{
    copy.write();
    copy.close();
    workbook.close();
}
log.info("Testing Over")
</code>```

答:
Try the below code. It will fix your issue :</p>

```<code>import com.eviware.soapui.support.XmlHolder
import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
log.info("Testing Started")
def reqOperationName = "some service"
def inputDataFileName = "D:/sample/temp8.xls"
def inputDataSheetName = "Sheet1"
Workbook workbook = Workbook.getWorkbook(new File(inputDataFileName));
WritableWorkbook copy = Workbook.createWorkbook(new File(inputDataFileName),workbook);
WritableSheet sheet1 = copy.getSheet(inputDataSheetName);
log.info("Testing1 Started")
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
String xmlResponse = reqOperationName+"#Request"
def reqholder = groovyUtils.getXmlHolder(xmlResponse)
try{
    rowcount = sheet1.getRows();
    colcount = sheet1.getColumns();

for(Row in 1..rowcount-1){
       String reqTagName = sheet1.getCell(0,0).getContents()
        def TagCount = reqholder["count(//*:"+reqTagName+")"]
        if(TagCount!=0){
        String reqTagValue = sheet1.getCell(0,Row).getContents()

            if(reqTagValue!=null && !reqTagValue.isEmpty() && reqTagValue!="")
                {

                    reqholder = groovyUtils.getXmlHolder(xmlResponse)
                    reqholder.setNodeValue("//*:"+reqTagName, reqTagValue)
                 reqholder.updateProperty()
                testRunner.runTestStepByName(reqOperationName)

                def resholder = groovyUtils.getXmlHolder(reqOperationName+"#Response")

                resTagValue1= resholder.getNodeValue("//*:email")

                //Write Response into excel sheet
                Label resValue1= new Label(2,Row,resTagValue1);
                sheet1.addCell(resValue1);
                }
            }

    }
}catch (Exception e) {log.info(e)}
finally{
    copy.write();
    copy.close();
    workbook.close();
}
log.info("Testing Over")
</code>```

Body:
The values which I try to pass from the excel sheet to the particular field in the soap request are not working in the test case level. I am able to read the excel sheet and also the execution is happening as expected but the values are not replaced in the soap request from the excel sheet.
I have pasted the code below which I am trying to implement for data driven using groovy script.

import com.eviware.soapui.support.XmlHolder
import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
log.info("Testing Started")
def reqOperationName = "getInsuranceDetails_1_FTC_005";
def inputDataFileName = "D:/SOAP UI Pro/MPI.xls"
def inputDataSheetName = "MPI"
Workbook workbook = Workbook.getWorkbook(new File(inputDataFileName));
WritableWorkbook copy = Workbook.createWorkbook(new File(inputDataFileName),workbook);
WritableSheet sheet1 = copy.getSheet(inputDataSheetName);
log.info("Testing1 Started")
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
String xmlResponse = '${' + reqOperationName + '#Request' +'}'
def reqholder = groovyUtils.getXmlHolder(context.expand(xmlResponse))
try{
    rowcount = sheet1.getRows();
colcount = sheet1.getColumns();
for(Row in 1..rowcount-1){

    String reqTagName = sheet1.getCell(0,0).getContents()
        log.info reqTagName
        def TagCount = reqholder["count(//*:"+reqTagName+")"]
        if(TagCount!=0){
            String reqTagValue = sheet1.getCell(0,Row).getContents()
            reqholder.setNodeValue("//*:"+reqTagName, reqTagValue)
            reqholder.updateProperty()
        }

    //test the request
    testRunner.runTestStepByName(reqOperationName)
log.info("Testing3 Started")
def resholder = groovyUtils.getXmlHolder(reqOperationName+"#Response")
resTagValue1= resholder.getNodeValues("//*:productID")
resTagValue2= resholder.getNodeValues("//*:accountNumber")
resTagValue3= resholder.getNodeValues("//*:insuranceCategory")
resTagValue4= resholder.getNodeValues("//*:imei")
resTagValue5= resholder.getNodeValues("//*:handsetMake")
resTagValue6= resholder.getNodeValues("//*:handsetModel")
resTagValue7= resholder.getNodeValues("//*:insurancePolicyName")
resTagValue8= resholder.getNodeValues("//*:insuranceStartTimestamp")
//Write Response into excel sheet
Label resValue1= new Label(4,Row,resTagValue1);
sheet1.addCell(resValue1);
Label resValue2= new Label(5,Row,resTagValue2);
sheet1.addCell(resValue2);
Label resValue3= new Label(6,Row,resTagValue3);
sheet1.addCell(resValue3);
Label resValue4= new Label(7,Row,resTagValue4);
sheet1.addCell(resValue4);
Label resValue5= new Label(8,Row,resTagValue5);
sheet1.addCell(resValue5);
Label resValue6= new Label(9,Row,resTagValue6);
sheet1.addCell(resValue6);
Label resValue7= new Label(10,Row,resTagValue7);
sheet1.addCell(resValue7);
Label resValue8= new Label(11,Row,resTagValue8);
sheet1.addCell(resValue8);
    }
}catch (Exception e) {log.info(e)}
finally{
    copy.write();
    copy.close();
    workbook.close();
}
log.info("Testing Over")

While I try to execute the above code there are no any errors in the error log. The only thing I am getting in the log output is Wed Dec 06 15:04:00 IST 2017:INFO:groovy.lang.GroovyRuntimeException: Could not find matching constructor for: jxl.write.Label(java.lang.Integer, java.lang.Integer, [Ljava.lang.String;)

Any help on the above issue would be very grateful..

Thank you in advance.

New Edit of the code....

import com.eviware.soapui.support.XmlHolder
import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
log.info("Testing Started")
def reqOperationName = "getInsuranceDetails_1_FTC_005";
def inputDataFileName = "D:/SOAP UI Pro/MPI.xls"
def inputDataSheetName = "MPI"
Workbook workbook = Workbook.getWorkbook(new File(inputDataFileName));
WritableWorkbook copy = Workbook.createWorkbook(new File(inputDataFileName),workbook);
WritableSheet sheet1 = copy.getSheet(inputDataSheetName);
log.info("Testing1 Started")
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
String xmlResponse = '${' + reqOperationName + '#Request' +'}'
def reqholder = groovyUtils.getXmlHolder(context.expand(xmlResponse))
try{
    rowcount = sheet1.getRows();
colcount = sheet1.getColumns();
for(Row in 1..rowcount-1){

    String reqTagName = sheet1.getCell(0,0).getContents()
        log.info reqTagName
        def TagCount = reqholder["count(//*:"+reqTagName+")"]
        if(TagCount!=0){
            String reqTagValue = sheet1.getCell(0,Row).getContents()
            reqholder.setNodeValue("//*:"+reqTagName, reqTagValue)
            reqholder.updateProperty()
        }

    //test the request
    testRunner.runTestStepByName(reqOperationName)
log.info("Testing3 Started")
def resholder = groovyUtils.getXmlHolder(reqOperationName+"#Response")
resTagValue1= resholder.getNodeValue("//*:productID")
resTagValue2= resholder.getNodeValue("//*:accountNumber")
resTagValue3= resholder.getNodeValue("//*:insuranceCategory")
resTagValue4= resholder.getNodeValue("//*:imei")
resTagValue5= resholder.getNodeValue("//*:handsetMake")
resTagValue6= resholder.getNodeValue("//*:handsetModel")
resTagValue7= resholder.getNodeValue("//*:insurancePolicyName")
resTagValue8= resholder.getNodeValue("//*:insuranceStartTimestamp")
//Write Response into excel sheet
Label resValue1= new Label(2,Row,resTagValue1);
sheet1.addCell(resValue1);
Label resValue2= new Label(3,Row,resTagValue2);
sheet1.addCell(resValue2);
Label resValue3= new Label(4,Row,resTagValue3);
sheet1.addCell(resValue3);
Label resValue4= new Label(5,Row,resTagValue4);
sheet1.addCell(resValue4);
Label resValue5= new Label(6,Row,resTagValue5);
sheet1.addCell(resValue5);
Label resValue6= new Label(7,Row,resTagValue6);
sheet1.addCell(resValue6);
Label resValue7= new Label(8,Row,resTagValue7);
sheet1.addCell(resValue7);
Label resValue8= new Label(9,Row,resTagValue8);
sheet1.addCell(resValue8);
    }
}catch (Exception e) {log.info(e)}
finally{
    copy.write();
    copy.close();
    workbook.close();
}
log.info("Testing Over")

Body:
Try the below code. It will fix your issue :

import com.eviware.soapui.support.XmlHolder
import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
log.info("Testing Started")
def reqOperationName = "some service"
def inputDataFileName = "D:/sample/temp8.xls"
def inputDataSheetName = "Sheet1"
Workbook workbook = Workbook.getWorkbook(new File(inputDataFileName));
WritableWorkbook copy = Workbook.createWorkbook(new File(inputDataFileName),workbook);
WritableSheet sheet1 = copy.getSheet(inputDataSheetName);
log.info("Testing1 Started")
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
String xmlResponse = reqOperationName+"#Request"
def reqholder = groovyUtils.getXmlHolder(xmlResponse)
try{
    rowcount = sheet1.getRows();
    colcount = sheet1.getColumns();

for(Row in 1..rowcount-1){
       String reqTagName = sheet1.getCell(0,0).getContents()
        def TagCount = reqholder["count(//*:"+reqTagName+")"]
        if(TagCount!=0){
        String reqTagValue = sheet1.getCell(0,Row).getContents()

            if(reqTagValue!=null && !reqTagValue.isEmpty() && reqTagValue!="")
                {

                    reqholder = groovyUtils.getXmlHolder(xmlResponse)
                    reqholder.setNodeValue("//*:"+reqTagName, reqTagValue)
                 reqholder.updateProperty()
                testRunner.runTestStepByName(reqOperationName)

                def resholder = groovyUtils.getXmlHolder(reqOperationName+"#Response")

                resTagValue1= resholder.getNodeValue("//*:email")

                //Write Response into excel sheet
                Label resValue1= new Label(2,Row,resTagValue1);
                sheet1.addCell(resValue1);
                }
            }

    }
}catch (Exception e) {log.info(e)}
finally{
    copy.write();
    copy.close();
    workbook.close();
}
log.info("Testing Over")


问:
How to implement Google Analytics event tracking inside a React VR project?
This is loosely written to give a basic idea of what I'm trying achieve.

    < VrButton onClick={props.userClick}>< /VrButton>

```<code>userClick={() => this.triggerTracking}

triggerTracking() {
    ga('send', 'event', 'myEventCategory', 'myEventAction', 'myEventLabel');
}
</code>```

I expect the code to trigger Google Analytics event tracking in the GA system when the user clicks on a button, but I get an error message - "ga is not a function".

I have GA set up in my index.html file, with the proper ID, and pulling in the latest analytics.js API.

答:
Try using the window scope as:

```<code>window.ga('send', 'event', 'myEventCategory', 'myEventAction', 'myEventLabel');
</code>```

I'm not familiar with React at all,  but perhaps React causes some abstraction between the window and the react scope, making your ga() function unavailable.

Body:
This is loosely written to give a basic idea of what I'm trying achieve.

    < VrButton onClick={props.userClick}>< /VrButton>

userClick={() => this.triggerTracking}

triggerTracking() {
    ga('send', 'event', 'myEventCategory', 'myEventAction', 'myEventLabel');
}

I expect the code to trigger Google Analytics event tracking in the GA system when the user clicks on a button, but I get an error message - "ga is not a function".

I have GA set up in my index.html file, with the proper ID, and pulling in the latest analytics.js API.

Body:
Try using the window scope as:

window.ga('send', 'event', 'myEventCategory', 'myEventAction', 'myEventLabel');

I'm not familiar with React at all,  but perhaps React causes some abstraction between the window and the react scope, making your ga() function unavailable.


问:
How can i Pass the arguments in the button selector method in iPhone?
Now i want to pass the arguments in the button selector method, so how can i pass that arguments in the button selector method?

```<code>    //Button creation

    -(void) viewDidLoad
    {
         UIButton *imageOverlayBtn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];

     imageOverlayBtn.frame = CGRectMake(xOrigin, yOrigin, theSize.width, theSize.height);

            //Pass this string into selector method
     NSString *passString = [feedArray objectForKey:@"URLString"];

     [imageOverlayBtn addTarget:self action:@selector(overlayBtnAction:) forControlEvents:UIControlEventTouchUpInside];

       }

    // Button Action
    -(void) overlayBtnAction : (NSString *) getString
    {
          NSLog(@"The get string is %@", getString)
    }
</code>```

So how can i pass the string to the selector method?. Please Help me out.

Thanks.

答: If you need a string to persist between methods like this, I'd suggest putting it in your header file. That way, you can set it when you need to and access it from anywhere in the implementation. I don't think passing an argument to a UI action is good design practice. </p>

Body:
Now i want to pass the arguments in the button selector method, so how can i pass that arguments in the button selector method?

    //Button creation

    -(void) viewDidLoad
    {
         UIButton *imageOverlayBtn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];

     imageOverlayBtn.frame = CGRectMake(xOrigin, yOrigin, theSize.width, theSize.height);

            //Pass this string into selector method
     NSString *passString = [feedArray objectForKey:@"URLString"];

     [imageOverlayBtn addTarget:self action:@selector(overlayBtnAction:) forControlEvents:UIControlEventTouchUpInside];

       }

    // Button Action
    -(void) overlayBtnAction : (NSString *) getString
    {
          NSLog(@"The get string is %@", getString)
    }

So how can i pass the string to the selector method?. Please Help me out.

Thanks.


问:
In the for-loop, when I use 'append' to add a new element to the list, the one that has added before also change
I want to get transpose of matrix B without using Numpy. When I use 'append' to add a new element to the list, the one that has added before also change. How can I fix it?

```<code>from decimal import *

B = [[1,2,3,5],
     [2,3,3,5],
     [1,2,5,1]]

def shape(M):
    r = len(M)
    c = len(M[0])
    return r,c

def matxRound(M, decPts=4):
    for p in M:
        for index in range(len(M[0])):
            p[index] = round(p[index], decPts)

def transpose(M):
    c_trans, r_trans = shape(M)
    new_row = [0]*c_trans
    trans_M = []
    for i in range(r_trans):
        for j in range(c_trans):
            new_row[j] = M[j][i]
        print 'new_row',new_row
        print 'trans_M before append',trans_M
        trans_M.append(new_row)
        print 'trans_M after append',trans_M
    return trans_M

print transpose(B)
</code>```

The output is here:

```<code>new_row [1, 2, 1]
trans_M before append []
trans_M after append [[1, 2, 1]]
new_row [2, 3, 2]
trans_M before append [[2, 3, 2]]
trans_M after append [[2, 3, 2], [2, 3, 2]]
new_row [3, 3, 5]
trans_M before append [[3, 3, 5], [3, 3, 5]]
trans_M after append [[3, 3, 5], [3, 3, 5], [3, 3, 5]]
new_row [5, 5, 1]
trans_M before append [[5, 5, 1], [5, 5, 1], [5, 5, 1]]
trans_M after append [[5, 5, 1], [5, 5, 1], [5, 5, 1], [5, 5, 1]]
[[5, 5, 1], [5, 5, 1], [5, 5, 1], [5, 5, 1]]
</code>```

答:
I will complete @glibdud comment's answer :

What you are doing now is creating a list that fits your needs for your Transpose.
You are creating your new matrix.

You are, then, appending your transposed value into your new matrix... without creating a new Transpose list.
What happens then is that you modify the last list you just appended, and try to append it again.

So in the end, you added the 4 same lists to your new matrix. As the 4 lists point to the same address in memory as they are the same object, your new matrix have 4 identical rows.

Body:
I want to get transpose of matrix B without using Numpy. When I use 'append' to add a new element to the list, the one that has added before also change. How can I fix it?

from decimal import *

B = [[1,2,3,5],
     [2,3,3,5],
     [1,2,5,1]]

def shape(M):
    r = len(M)
    c = len(M[0])
    return r,c

def matxRound(M, decPts=4):
    for p in M:
        for index in range(len(M[0])):
            p[index] = round(p[index], decPts)

def transpose(M):
    c_trans, r_trans = shape(M)
    new_row = [0]*c_trans
    trans_M = []
    for i in range(r_trans):
        for j in range(c_trans):
            new_row[j] = M[j][i]
        print 'new_row',new_row
        print 'trans_M before append',trans_M
        trans_M.append(new_row)
        print 'trans_M after append',trans_M
    return trans_M

print transpose(B)

The output is here:

new_row [1, 2, 1]
trans_M before append []
trans_M after append [[1, 2, 1]]
new_row [2, 3, 2]
trans_M before append [[2, 3, 2]]
trans_M after append [[2, 3, 2], [2, 3, 2]]
new_row [3, 3, 5]
trans_M before append [[3, 3, 5], [3, 3, 5]]
trans_M after append [[3, 3, 5], [3, 3, 5], [3, 3, 5]]
new_row [5, 5, 1]
trans_M before append [[5, 5, 1], [5, 5, 1], [5, 5, 1]]
trans_M after append [[5, 5, 1], [5, 5, 1], [5, 5, 1], [5, 5, 1]]
[[5, 5, 1], [5, 5, 1], [5, 5, 1], [5, 5, 1]]


问:
Why am I getting a NullReferenceException in System.Data.Entity.dll (Entity Framework)?
I have a List<State> of State entity objects, and each State object has collections of other objects, such as Licenses, Taxes, Bonds, etc

There's also a collection for ExpiredObjects, which is a list of any object which is expired and needs to be renewed. For some reason, this property is giving me a NullReferenceException when I try and access it for one specific state (Nevada), but I can't for the life of me figure out what is actually null since I don't see any null values anywhere.

Here's my code that throws the exception. It loops through all the states, and adds all the ExpiredObjects to a view-specific collection which gets displayed. My test code is still included

```<code>    private List<ExpiredObject> LoadAllExpiredObjects()
    {
        var list = new List<ExpiredObject>();
        foreach (var state in States)
        {
            // This tells me the state is not null, and neither is state.ExpiredObjects
            Debug.WriteLine(string.Format("{0}|{1}|{2}",
                state.Name, state == null, state.ExpiredObjects == null));

            try
            {
                var x = state.ExpiredObjects;
                Debug.WriteLine(x == null);

                // Exception occurs on the "for" line on the Nevada state only
                // Contents in for loop do not execute
                foreach (var item in x)
                {
                    Debug.WriteLine(string.Format("{0}", item));
                    list.Add(item);
                }

                // This used to be the only line of code before I started testing
                // It fails on Nevada
                //list.AddRange(state.ExpiredObjects);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
            }
        }
        return list;
    }
</code>```

The stack trace of the error is this:

```<code>A first chance exception of type 'System.NullReferenceException' occurred in System.Data.Entity.dll
Object reference not set to an instance of an object.
   at System.Data.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)
   at System.Data.EntityKey.GetHashCode()
   at System.Collections.Generic.GenericEqualityComparer`1.GetHashCode(T obj)
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at System.Data.Objects.ObjectStateManager.TryGetEntityEntry(EntityKey key, EntityEntry& entry)
   at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
   at lambda_method(Closure , Shaper )
   at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
   at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
   at System.Data.Objects.DataClasses.RelatedEnd.Merge[TEntity](IEnumerable`1 collection, MergeOption mergeOption, Boolean setIsLoaded)
   at System.Data.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)
   at System.Data.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)
   at System.Data.Objects.DataClasses.RelatedEnd.Load()
   at System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad()
   at System.Data.Objects.DataClasses.EntityCollection`1.GetEnumerator()
   at MyNamespace.StatesViewModel.LoadAllExpiredObjects() in C:\Users\me\Desktop\MySolution\StatesViewModel.cs:line 217
</code>```

I also get the exact same error when I select Nevada and it tries to bind a DataGrid to the ExpiredObjects collection (if I comment out that binding, the code works fine)

Does anyone know what could be causing this error?

答:
I got the same problem when accidently loading a Module multiple times in a modular Architecture.

Additional, the Module(s) where using 2 copies of the same DbContext, trying to connect one Entity from one Context to another Entity of the other Context.

This masked the InvalidOperationException (cannot use an Entity in multiple Trackers), which occurs normally without the module stuff.

Took me 3 hours to solve, maybe it helps people with the same problem

Body:
I have a List<State> of State entity objects, and each State object has collections of other objects, such as Licenses, Taxes, Bonds, etc

There's also a collection for ExpiredObjects, which is a list of any object which is expired and needs to be renewed. For some reason, this property is giving me a NullReferenceException when I try and access it for one specific state (Nevada), but I can't for the life of me figure out what is actually null since I don't see any null values anywhere.

Here's my code that throws the exception. It loops through all the states, and adds all the ExpiredObjects to a view-specific collection which gets displayed. My test code is still included

    private List<ExpiredObject> LoadAllExpiredObjects()
    {
        var list = new List<ExpiredObject>();
        foreach (var state in States)
        {
            // This tells me the state is not null, and neither is state.ExpiredObjects
            Debug.WriteLine(string.Format("{0}|{1}|{2}",
                state.Name, state == null, state.ExpiredObjects == null));

            try
            {
                var x = state.ExpiredObjects;
                Debug.WriteLine(x == null);

                // Exception occurs on the "for" line on the Nevada state only
                // Contents in for loop do not execute
                foreach (var item in x)
                {
                    Debug.WriteLine(string.Format("{0}", item));
                    list.Add(item);
                }

                // This used to be the only line of code before I started testing
                // It fails on Nevada
                //list.AddRange(state.ExpiredObjects);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
            }
        }
        return list;
    }

The stack trace of the error is this:

A first chance exception of type 'System.NullReferenceException' occurred in System.Data.Entity.dll
Object reference not set to an instance of an object.
   at System.Data.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)
   at System.Data.EntityKey.GetHashCode()
   at System.Collections.Generic.GenericEqualityComparer`1.GetHashCode(T obj)
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at System.Data.Objects.ObjectStateManager.TryGetEntityEntry(EntityKey key, EntityEntry& entry)
   at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
   at lambda_method(Closure , Shaper )
   at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
   at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
   at System.Data.Objects.DataClasses.RelatedEnd.Merge[TEntity](IEnumerable`1 collection, MergeOption mergeOption, Boolean setIsLoaded)
   at System.Data.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)
   at System.Data.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)
   at System.Data.Objects.DataClasses.RelatedEnd.Load()
   at System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad()
   at System.Data.Objects.DataClasses.EntityCollection`1.GetEnumerator()
   at MyNamespace.StatesViewModel.LoadAllExpiredObjects() in C:\Users\me\Desktop\MySolution\StatesViewModel.cs:line 217

I also get the exact same error when I select Nevada and it tries to bind a DataGrid to the ExpiredObjects collection (if I comment out that binding, the code works fine)

Does anyone know what could be causing this error?


问:
Range.Value not working for assigning cell contents to variable in VBA
I am writing my first script with VBA and I am having a hard time assigning the value entered into a cell to a String variable, I used Message Boxes to test where the issue is and it showed me I'm in the right workbook and the right sheet but then shows a blank for the value in "A1" even though I have a text value there and made sure I saved the workbook, what I have is below:

```<code>Sub copyworksheet()

Dim sourceWorkbook As String
Dim destinationWorkbook As String

Dim folderName As String

destinationWorkbook = ActiveWorkbook.Name
Sheets(1).Activate

MsgBox Range("A1").Value        ' Shows blank when debugging
folderName = Range("A1").Value
MsgBox "Here is " & folderName  ' Shows "Here is " when debugging

End Sub
</code>```

** As an additional note, the A1 cell contains 02Nov, and I have tried changing the format of this cell and it hasn't fixed the issue, currently the cell format is Text

答:
I think this should do the trick:</p>

```<code>Sub copyworksheet()

Dim sourceWorkbook As String
Dim destinationWorkbook As String
Dim folderName As String

destinationWorkbook = ActiveWorkbook.Name

MsgBox Sheets(1).Range("A1").Value      'reference the Sheet absolutely when using Range
folderName = Sheets(1).Range("A1").Value
MsgBox "Here is " & folderName

End Sub
</code>```

Body:
I am writing my first script with VBA and I am having a hard time assigning the value entered into a cell to a String variable, I used Message Boxes to test where the issue is and it showed me I'm in the right workbook and the right sheet but then shows a blank for the value in "A1" even though I have a text value there and made sure I saved the workbook, what I have is below:

Sub copyworksheet()

Dim sourceWorkbook As String
Dim destinationWorkbook As String

Dim folderName As String

destinationWorkbook = ActiveWorkbook.Name
Sheets(1).Activate

MsgBox Range("A1").Value        ' Shows blank when debugging
folderName = Range("A1").Value
MsgBox "Here is " & folderName  ' Shows "Here is " when debugging

End Sub

** As an additional note, the A1 cell contains 02Nov, and I have tried changing the format of this cell and it hasn't fixed the issue, currently the cell format is Text

Body:
I think this should do the trick:

Sub copyworksheet()

Dim sourceWorkbook As String
Dim destinationWorkbook As String
Dim folderName As String

destinationWorkbook = ActiveWorkbook.Name

MsgBox Sheets(1).Range("A1").Value      'reference the Sheet absolutely when using Range
folderName = Sheets(1).Range("A1").Value
MsgBox "Here is " & folderName

End Sub


问:
Laravel Extended Validation custom message
I wanted to create this extended validation.

```<code>Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters) {
   // I guess I should be setting the error message for this here.(Its dynamic)
   // We can return true or false here depending upon our need.
}
</code>```

I would use this rule like this

'my_field' => 'required|my_custom_validation_rule',

I want to use some dynamic message for the error of "my_custom_validation_rule"

I was unable to find something from the documentation about it. Is there anyway to do it ?

答:
You can also define the message for your custom validation rule under validation translations file.

/resources/lang/en/validation.php

```<code>....
'unique'                    => 'The :attribute has already been taken.',
'uploaded'                  => 'The :attribute failed to upload.',
'url'                       => 'The :attribute format is invalid.',
//place your translation here
'my_custom_validation_rule' => 'The :attribute value fails custom validation.'
</code>```

Body:
I wanted to create this extended validation.

Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters) {
   // I guess I should be setting the error message for this here.(Its dynamic)
   // We can return true or false here depending upon our need.
}

I would use this rule like this

'my_field' => 'required|my_custom_validation_rule',

I want to use some dynamic message for the error of "my_custom_validation_rule"

I was unable to find something from the documentation about it. Is there anyway to do it ?

Body:
You can also define the message for your custom validation rule under validation translations file.

/resources/lang/en/validation.php

....
'unique'                    => 'The :attribute has already been taken.',
'uploaded'                  => 'The :attribute failed to upload.',
'url'                       => 'The :attribute format is invalid.',
//place your translation here
'my_custom_validation_rule' => 'The :attribute value fails custom validation.'


问:
Merge k sorted arrays - comparing two solutions
If I have K sorted arrays of N elements each, e.g.

```<code>[0, 1, 2]
[1, 6, 8]
[10, 11, 12]
</code>```

I know that I can use a heap to merge them by cycling all of the lists and their elements and inserting them into the heap, then getting back the minimum each time in O(KN * log(KN)).

I checked on the internet and another popular solution seems to be using a min heap of only K elements and inserting all the first items of the K lists into the heap, then get the minimum out and advance the pointer to the list that owned that minimum element.

Aside from a more efficient memory requirement (O(K) in the second case), is the second method more efficient time-wise?

Optional bonus points: is there an even better algorithm than the ones above?

答: The second version should have a runtime of O(KN* log(K)) since you perform a heapify (log (K)) operation for each element (N*K). So yes it is faster. I cannot think of a more efficient way to solve this problem.</p>

Body:
If I have K sorted arrays of N elements each, e.g.

[0, 1, 2]
[1, 6, 8]
[10, 11, 12]

I know that I can use a heap to merge them by cycling all of the lists and their elements and inserting them into the heap, then getting back the minimum each time in O(KN * log(KN)).

I checked on the internet and another popular solution seems to be using a min heap of only K elements and inserting all the first items of the K lists into the heap, then get the minimum out and advance the pointer to the list that owned that minimum element.

Aside from a more efficient memory requirement (O(K) in the second case), is the second method more efficient time-wise?

Optional bonus points: is there an even better algorithm than the ones above?