问:
I am getting wrong value from input for link (not form)
I am trying to get input from user and invoke Servlet with that parameter but I can not get changed value. I am getting initial value.</p>

```<code><% int quantity = 1; %>
<input type="text" name="quantity" style="width: 20px;left: 52px;" value="<%= quantity %>" class="form"/>
<a href="addToCart.jsp?id=<%= product_id %>&quantity= <%= quantity %>" id="greenBtn">Add to cart</a>
</code>```

答:
```<code> function getlink(product_id) {
        var link = "addToCart.jsp?id="+product_id+"&quantity="+document.getElementById("quantity").value;
        window.location.replace(link);
    }
</code>```

<p>call this function </p>

```<code><a  href="javascript:getlink(<%=product_id%>);" id="greenBtn">Add to cart</a>
</code>```

Body:
I am trying to get input from user and invoke Servlet with that parameter but I can not get changed value. I am getting initial value.

<% int quantity = 1; %>
<input type="text" name="quantity" style="width: 20px;left: 52px;" value="<%= quantity %>" class="form"/>
<a href="addToCart.jsp?id=<%= product_id %>&quantity= <%= quantity %>" id="greenBtn">Add to cart

Body:
 function getlink(product_id) {
        var link = "addToCart.jsp?id="+product_id+"&quantity="+document.getElementById("quantity").value;
        window.location.replace(link);
    }

call this function

<a  href="javascript:getlink(<%=product_id%>);" id="greenBtn">Add to cart</a>


来源: stackexchange

问:
Speeding up IndexedDB search with Multiple Workers
PROBLEM: I am trying to speed up my IndexedDB searches by using multiple web workers and therefore executing multiple read transactions simultaneously, but it's not really working, and my CPU only gets to around 30-35% utilization.  I have a 4-core processor and was hoping that spawning 4 web workers would dramatically reduce the search time.

I am using Firefox 53 with a WebExtension; other browsers are not an option.

DATABASE: I have a data store with about 250,000 records, each with about 30 keys, some of them containing paragraphs of text.

TASK: Perform a string search on a given key to find matching values.  Currently, this takes about 90 seconds to do on a single thread.  Adding an additional worker reduces that time to about 75 seconds.  More workers than that have no noticeable effect.  An acceptable time to me would be under 10 seconds (somewhat comparable to an SQL database).

CURRENT STRATEGY: Spawn a worker for each processor, and create a Promise that resolves when the worker sends a message.  In each worker, open the database, divide the records up evenly, and search for the string.  I do that by starting on the first record if you're the first worker, second record for the second, etc.  Then advance by the number of workers.  So the first worker checks records 1, 5, 9, etc. Second worker checks 2, 6, 10, etc.  Of course, I could also have the first worker check 1-50, second worker check 51-100, etc. (but obviously thousands each).

Using getAll() on a single thread took almost double the time and 4GB of memory.  Splitting that into 4 ranges significantly reduces the time down to a total of about 40 seconds after merging the results (the 40 seconds varies wildly every time I run the script).

Any ideas on how I can make this work, or other suggestions for significantly speeding up the search?

background.js:

```<code>var key = whatever, val = something
var proc = navigator.hardwareConcurrency;  // Number of processors
var wPromise = [];  // Array of promises (one for each worker)
var workers = [];

/* Create a worker for each processor */
for (var pos = 0; pos < proc; pos++) {
    workers[pos] = new Worker("js/dbQuery.js");
    wPromise.push(
        new Promise( resolve => workers[pos].onmessage = resolve )
    );
    workers[pos].postMessage({key:key, val:val, pos:pos, proc:proc});
}

return Promise.all(wPromise);  // Do something once all the workers have finished
</code>```

dbQuery.js:

```<code>onmessage = e => {
    var data = e.data;
    var req = indexedDB.open("Blah", 1);
    req.onsuccess = e => {
        var keyArr = [];
        var db = e.currentTarget.result;
        db.transaction("Blah").objectStore("Blah").index(data.key).openKeyCursor().onsuccess = e => {
            var cursor = e.target.result;
            if (cursor) {
                if (data.pos) {
                    cursor.advance(data.pos); // Start searching at a position based on which web worker
                    data.pos = false;
                }
                else {
                    if (cursor.key.includes(data.val)) {
                        keyArr.push(cursor.primaryKey);  // Store key if value is a match
                    }
                    cursor.advance(data.proc); // Advance position based on number of processors
                }
            }
            else {
                db.close();
                postMessage(keyArr);
                close();
            }
        }
    }
}
</code>```

答:
Any ideas on how I can make this work, or other suggestions for
  significantly speeding up the search?

You can substitute using Promise.race() for Promise.all() to return a resolved Promise once a match is found, instead of waiting for all of the Promises passed to Promise.all() to be resolved.

ContentLicense: CC BY-SA 3.0

Body:
PROBLEM: I am trying to speed up my IndexedDB searches by using multiple web workers and therefore executing multiple read transactions simultaneously, but it's not really working, and my CPU only gets to around 30-35% utilization.  I have a 4-core processor and was hoping that spawning 4 web workers would dramatically reduce the search time.

I am using Firefox 53 with a WebExtension; other browsers are not an option.

DATABASE: I have a data store with about 250,000 records, each with about 30 keys, some of them containing paragraphs of text.

TASK: Perform a string search on a given key to find matching values.  Currently, this takes about 90 seconds to do on a single thread.  Adding an additional worker reduces that time to about 75 seconds.  More workers than that have no noticeable effect.  An acceptable time to me would be under 10 seconds (somewhat comparable to an SQL database).

CURRENT STRATEGY: Spawn a worker for each processor, and create a Promise that resolves when the worker sends a message.  In each worker, open the database, divide the records up evenly, and search for the string.  I do that by starting on the first record if you're the first worker, second record for the second, etc.  Then advance by the number of workers.  So the first worker checks records 1, 5, 9, etc. Second worker checks 2, 6, 10, etc.  Of course, I could also have the first worker check 1-50, second worker check 51-100, etc. (but obviously thousands each).

Using getAll() on a single thread took almost double the time and 4GB of memory.  Splitting that into 4 ranges significantly reduces the time down to a total of about 40 seconds after merging the results (the 40 seconds varies wildly every time I run the script).

Any ideas on how I can make this work, or other suggestions for significantly speeding up the search?

background.js:

var key = whatever, val = something
var proc = navigator.hardwareConcurrency;  // Number of processors
var wPromise = [];  // Array of promises (one for each worker)
var workers = [];

/* Create a worker for each processor */
for (var pos = 0; pos < proc; pos++) {
    workers[pos] = new Worker("js/dbQuery.js");
    wPromise.push(
        new Promise( resolve => workers[pos].onmessage = resolve )
    );
    workers[pos].postMessage({key:key, val:val, pos:pos, proc:proc});
}

return Promise.all(wPromise);  // Do something once all the workers have finished

dbQuery.js:

onmessage = e => {
    var data = e.data;
    var req = indexedDB.open("Blah", 1);
    req.onsuccess = e => {
        var keyArr = [];
        var db = e.currentTarget.result;
        db.transaction("Blah").objectStore("Blah").index(data.key).openKeyCursor().onsuccess = e => {
            var cursor = e.target.result;
            if (cursor) {
                if (data.pos) {
                    cursor.advance(data.pos); // Start searching at a position based on which web worker
                    data.pos = false;
                }
                else {
                    if (cursor.key.includes(data.val)) {
                        keyArr.push(cursor.primaryKey);  // Store key if value is a match
                    }
                    cursor.advance(data.proc); // Advance position based on number of processors
                }
            }
            else {
                db.close();
                postMessage(keyArr);
                close();
            }
        }
    }
}


问:
Hyperparameter optimization for Pytorch model
What is the best way to perform hyperparameter optimization for a Pytorch model? Implement e.g. Random Search myself? Use Skicit Learn? Or is there anything else I am not aware of?</p>

答: You can use Bayesian optimization (full disclosure, I've contributed to this package) or Hyperband.  Both of these methods attempt to automate the hyperparameter tuning stage.  Hyperband is supposedly the state of the art in this space.  Hyperband is the only parameter-free method that I've heard of other than random search.  You can also look into using reinforcement learning to learn the optimal hyperparameters if you prefer.</p>


问:
Convert a c hex value into a char*
How to convert a hex value in c into an equivalent char* value. For example if the hex value is 1df2 the char* should also contain 1df2.

I am using the VinC compiler and the VinL linker for the VNC2 USB Chip from FTDI. It has these following header files; stdlib, stdio and string. These are however subsets of the main c libraries and don't have the obvious answers such as snprintf or sprintf.

The docs say the following types are valid,

There are certain definitions for variable and function types which are used  throughout the kernel and drivers. They are available to applications in the vos.h header file.

Null pointer and logic definitions:

```<code>#define NULL                0
#define TRUE                1
#define FALSE               0
</code>```

Variable type definitions:

```<code>#define uint8               unsigned char
#define int8                char
#define int16               short
#define uint16              unsigned short
#define uint32              unsigned int
#define pvoid               unsigned char *
</code>```

Function type definitions:

```<code>typedef uint8 (*PF)(uint8);
typedef void (*PF_OPEN)(void *);
typedef void (*PF_CLOSE)(void *);
typedef uint8 (*PF_IOCTL)(pvoid);
typedef uint8 (*PF_IO)(uint8 *, unsigned short, unsigned short *);
typedef void (*PF_INT)(void);
</code>```

Any suggestions?

答:
Try sprintf:

```<code>int to_hex(char *output,unsigned n)
{
    return sprintf(output, "%.4x", n);
}
</code>```

it's less safe than caf's answer but should work if you have stdio. You must therefore make sure that the output buffer is big enough to hold the resulting string.

Title: Convert a c hex value into a char*

Body:
How to convert a hex value in c into an equivalent char* value. For example if the hex value is 1df2 the char* should also contain 1df2.

I am using the VinC compiler and the VinL linker for the VNC2 USB Chip from FTDI. It has these following header files; stdlib, stdio and string. These are however subsets of the main c libraries and don't have the obvious answers such as snprintf or sprintf.

The docs say the following types are valid,

There are certain definitions for variable and function types which are used  throughout the kernel and drivers. They are available to applications in the vos.h header file.

Null pointer and logic definitions:

#define NULL                0
#define TRUE                1
#define FALSE               0

Variable type definitions:

#define uint8               unsigned char
#define int8                char
#define int16               short
#define uint16              unsigned short
#define uint32              unsigned int
#define pvoid               unsigned char *

Function type definitions:

typedef uint8 (*PF)(uint8);
typedef void (*PF_OPEN)(void *);
typedef void (*PF_CLOSE)(void *);
typedef uint8 (*PF_IOCTL)(pvoid);
typedef uint8 (*PF_IO)(uint8 *, unsigned short, unsigned short *);
typedef void (*PF_INT)(void);

Any suggestions?

Body:
Try sprintf:

int to_hex(char *output,unsigned n)
{
    return sprintf(output, "%.4x", n);
}

it's less safe than caf's answer but should work if you have stdio. You must therefore make sure that the output buffer is big enough to hold the resulting string.

ContentLicense: CC BY-SA 2.5


问:
How to post List<Model> using partial view in asp.net mvc?
Main question: Is it possible to post a list of model using partial view in asp.net mvc?

Example: Lets assume a class as Student having 2 properties(RollNo(int) and Name(string))

```<code>public class Student
{
     public int RollNo { get; set; }
     public string Name { get; set; }
}
</code>```

Controller having post method where I want list of students from partial view

```<code>[HttpPost]
public ActionResult PostListOfStudents(List<Student> lstStudents)
{
    //some logic
}
</code>```

答:
Yes sure you can.

Here is partial view model:

```<code>@model List<Student>
</code>```

You only have to iterate over your list model like below:

```<code>@Html.BeginForm("action", "controller", FormMethod.Post)
{
    if (Model != null)
    {
       for (var i = 0; i < Model.Count; i++)
       {
           @Html.TextBoxFor(m => Model[i].Name)
           @Html.TextBoxFor(m => Model[i].RollNo)
       }
       <input type="submit" value="Post Data" />
    }
}
</code>```

You can pass the list of Students in partial view as below:

```<code>@Html.Partial("_partialview", listOfStudents);
</code>```

Then at your post action you will get the list of student. Just be sure to use proper  input extension methods in your case.

Body:
Main question: Is it possible to post a list of model using partial view in asp.net mvc?

Example: Lets assume a class as Student having 2 properties(RollNo(int) and Name(string))

public class Student
{
     public int RollNo { get; set; }
     public string Name { get; set; }
}

Controller having post method where I want list of students from partial view

[HttpPost]
public ActionResult PostListOfStudents(List<Student> lstStudents)
{
    //some logic
}

Body:
Yes sure you can.

Here is partial view model:

@model List<Student>

You only have to iterate over your list model like below:

@Html.BeginForm("action", "controller", FormMethod.Post)
{
    if (Model != null)
    {
       for (var i = 0; i < Model.Count; i++)
       {
           @Html.TextBoxFor(m => Model[i].Name)
           @Html.TextBoxFor(m => Model[i].RollNo)
       }
       <input type="submit" value="Post Data" />
    }
}

You can pass the list of Students in partial view as below:

@Html.Partial("_partialview", listOfStudents);

Then at your post action you will get the list of student. Just be sure to use proper  input extension methods in your case.


问:
CSS: Profile Picture Align
I have a problem aligning the profile picture in a chat. The profile picture should always be right beside the username like demonstrated in the picture below.

How can I fix this? Been sitting hours trying to fix this, I know there are some smart people out there that can solve this in no time.

Im not the best at css. Code below:

```<code>jsfiddle.net/cefes3au/2/
</code>```

答:
Solution: align-items: center; Should be align-items: flex-start:

REF:

The align-items property is a sub-property of the Flexible Box Layout module.

REF: https://css-tricks.com/almanac/properties/a/align-items/

          Fürher CSGOArena.com

This is my first message.

          Fürher CSGOArena.com

This is my second message.

          Fürher CSGOArena.com

READ: The profile picture to the left should be right beside the username at the top and not vertically centered to the div. It should look like the other messages above.

```

Title: CSS: Profile Picture Align

Body:
I have a problem aligning the profile picture in a chat. The profile picture should always be right beside the username like demonstrated in the picture below.

How can I fix this? Been sitting hours trying to fix this, I know there are some smart people out there that can solve this in no time.

Im not the best at css. Code below:

jsfiddle.net/cefes3au/2/

Body:
Solution: align-items: center; Should be align-items: flex-start:

REF:

The align-items property is a sub-property of the Flexible Box Layout module.

REF: https://css-tricks.com/almanac/properties/a/align-items/

<div id="chat" class="row chat" style="height: 50%; margin-bottom: 0px; overflow-y: scroll; overflow-x: hidden;">

     <!--IGNORE: CORRECT MESSAGES -->

      <div class="col s12 chat-content" style="height: auto; display: flex; align-items: flex-start; margin-top: 10px; margin-bottom: 10px;">
        <div class="chat-profile" style="display: inline;">
          <img class='responsive-img' style='border-radius: 5px; margin-right: 5px; line-height: 55px;' src='http://poedat.org/wp-content/uploads/2015/12/Evrim-Kuzu_avatar_1449332710-32x32.jpg'>
        </div>
        <div class="chat-message" style="display: inline; color: #CDCDC8;">
          <span>Fürher CSGOArena.com</span>
          <p style="margin: 0; color: grey;">This is my first message.</p>
        </div>
      </div>
      <div class="col s12 chat-content" style="height: auto; display: flex; align-items: flex-start; margin-top: 10px; margin-bottom: 10px;">
        <div class="chat-profile" style="display: inline;">
          <img class='responsive-img' style='border-radius: 5px; margin-right: 5px; line-height: 55px;' src='http://poedat.org/wp-content/uploads/2015/12/Evrim-Kuzu_avatar_1449332710-32x32.jpg'>
        </div>
        <div class="chat-message" style="display: inline; color: #CDCDC8;">
          <span>Fürher CSGOArena.com</span>
          <p style="margin: 0; color: grey;">This is my second message.</p>
        </div>
      </div>

 <!-- END HERE -->

 <!--PROBLEM STARTS HERE-->

      <div class="col s12 chat-content" style="height: auto; display: flex; align-items: flex-start; margin-top: 10px; margin-bottom: 10px;">
        <div class="chat-profile" style="display: inline;">
          <img class='responsive-img' style='border-radius: 5px; margin-right: 5px; line-height: 55px;'         src='http://poedat.org/wp-content/uploads/2015/12/Evrim-Kuzu_avatar_1449332710-32x32.jpg'>
        </div>
        <div class="chat-message" style="display: inline; color: #CDCDC8;">
          <span>Fürher CSGOArena.com</span>
          <p style="margin: 0; color: grey; max-width: 225px; word-wrap: break-word;">READ: The profile picture to the left should be right beside the username at the top and not vertically centered to the div. It should look like the other messages above.</p>
        </div>
      </div>
<!--PROBLEM END HERE-->

    </div>


问:
removeChild(); not removing all items from list
When I run the following code, half of the items are removed from the list.. I am trying to remove all items from the list.</p>

```<code>  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");
      console.log(ul.children.length);

      //Moves through the unordered list and removes each list item.
      for(let i = 0; i < ul.children.length; i++) {
        ul.removeChild(ul.children[i]);
      }
  });
</code>```

答:
You could do so, the code would be even more compact

jquery solution

```<code>  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");

      $(ul).empty();

  });
</code>```

This function removes all the children of the father object

```<code> .empty();
</code>```

html standard solution

```<code>  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");

      ul.innerHTML ="";

  });
</code>```

This variable represents the html content of the parent object

```<code>.innerHTML =""
</code>```

Body:
When I run the following code, half of the items are removed from the list.. I am trying to remove all items from the list.

  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");
      console.log(ul.children.length);

      //Moves through the unordered list and removes each list item.
      for(let i = 0; i < ul.children.length; i++) {
        ul.removeChild(ul.children[i]);
      }
  });

Body:
You could do so, the code would be even more compact

jquery solution

  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");

      $(ul).empty();

  });

This function removes all the children of the father object

 .empty();

html standard solution

  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");

      ul.innerHTML ="";

  });

This variable represents the html content of the parent object

.innerHTML =""


问:
How do I get the last 50 rows for this table using Cassandra CQL?
This is the query I used to create the table:

```<code>CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (msguuid));
</code>```

I want to get the last 50 rows sorted by timestamp in descending order.

If I try something like: SELECT * FROM test.comments WHERE page = 'test' AND timestamp < 1496468332, I get this error:

```<code>Error from server: code=2200 [Invalid query] message="Cannot execute this query as it might involve data filtering and thus may have unpredictable performance. If you want to execute this query despite the performance unpredictability, use ALLOW FILTERING"
</code>```

I'd prefer not to use allow filtering, I want the query to be as quick as possible.

I've looked at another stackoverflow question here Cassandra cql: how to select the LAST n rows from a table and tried the solution:

```<code>CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (msguuid)) WITH CLUSTERING ORDER BY (msguuid DESC);
</code>```

But then I get this error: InvalidRequest: Error from server: code=2200 [Invalid query] message="Only clustering key columns can be defined in CLUSTERING ORDER directive"

I'm new to Cassandra, so forgive me if this has an obvious answer. I just can't seem to get it to work.

I would highly appreciate if anyone could help me.

答:
In cassandra world try to model your table based on the queries it needs to satisfy. If the query always goes by where clause "page" and msguuid is only there for uniqueness redesign the table to something like as follows

```<code>CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (page, msguuid), WITH CLUSTERING ORDER BY (msguuid DESC));
</code>```

Now the table is naturally order by msguuid and there isn't any requirement to have additional overhead of Materialized View.

Body:
This is the query I used to create the table:

CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (msguuid));

I want to get the last 50 rows sorted by timestamp in descending order.

If I try something like: SELECT * FROM test.comments WHERE page = 'test' AND timestamp < 1496468332, I get this error:

Error from server: code=2200 [Invalid query] message="Cannot execute this query as it might involve data filtering and thus may have unpredictable performance. If you want to execute this query despite the performance unpredictability, use ALLOW FILTERING"

I'd prefer not to use allow filtering, I want the query to be as quick as possible.

I've looked at another stackoverflow question here Cassandra cql: how to select the LAST n rows from a table and tried the solution:

CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (msguuid)) WITH CLUSTERING ORDER BY (msguuid DESC);

But then I get this error: InvalidRequest: Error from server: code=2200 [Invalid query] message="Only clustering key columns can be defined in CLUSTERING ORDER directive"

I'm new to Cassandra, so forgive me if this has an obvious answer. I just can't seem to get it to work.

I would highly appreciate if anyone could help me.

Body:
In cassandra world try to model your table based on the queries it needs to satisfy. If the query always goes by where clause "page" and msguuid is only there for uniqueness redesign the table to something like as follows

CREATE TABLE test.comments (msguuid timeuuid, page text, userid text, username text, msg text, timestamp int, PRIMARY KEY (page, msguuid), WITH CLUSTERING ORDER BY (msguuid DESC));

Now the table is naturally order by msguuid and there isn't any requirement to have additional overhead of Materialized View.


问:
How to Pass Parameters to a client executable in a link
If I have a link in my page of the form:

```<code><A HREF="/executable.exe?param=1">Run</A>
</code>```

Are the parameters after the "?" passed to the executable after the browser has downloaded the executable, and the user has chosen to run the executable?

I have examined argv, and the environment, but doesn't seem to be there.

Is there any other place where the browser might be passing the parameters to the executable?

答:
Link it to .cmd or a bat file which has the command to execute executable.exe with parameters.

So, your link should lookl ike

```<code><a href ="/someth.cmd> Run me </a>
</code>```

and the .cmd file should contain

```<code>executable.exe param1 param2
</code>```

Hope it helps.

Body:
If I have a link in my page of the form:

Run

Are the parameters after the "?" passed to the executable after the browser has downloaded the executable, and the user has chosen to run the executable?

I have examined argv, and the environment, but doesn't seem to be there.

Is there any other place where the browser might be passing the parameters to the executable?

Body:
Link it to .cmd or a bat file which has the command to execute executable.exe with parameters.

So, your link should lookl ike

<a href ="/someth.cmd> Run me </a>

and the .cmd file should contain

executable.exe param1 param2

Hope it helps.


问:
Make bold text inside element (jQuery)
I'm trying to make text (fat) bold. Curretly I managed to do this whit code below:

```<code>Movie <b>fat</b> was been added
</code>```

But this bold tags won't work. Now the question is how to enable html for only (fat), to be bold like this: Movie fat was been added

My code so far:

```<code>var boldy = (Movie[0].title)
var fat = boldy.bold()

$("div.container div:first").text("Movie " + (fat) + " was been added")
</code>```

I also tried whit this:

```<code>$("div.container div:first").html("Hello <b>"+(boldy)+"</b>")
</code>```

答:
```<code>var html = $("div.container div:first").html;
$("div.container div:first").html(html.replace(/fat/gi, '<strong>$& </strong>'));
</code>```

Title: Make bold text inside element (jQuery)

Body:
I'm trying to make text (fat) bold. Curretly I managed to do this whit code below:

Movie fat was been added

But this bold tags won't work. Now the question is how to enable html for only (fat), to be bold like this: Movie fat was been added

My code so far:

var boldy = (Movie[0].title)
var fat = boldy.bold()

$("div.container div:first").text("Movie " + (fat) + " was been added")

I also tried whit this:

$("div.container div:first").html("Hello "+(boldy)+"")


问:
Numpy minimum like np.outer()
Maybe I'm just being lazy here, but let's say that I have two arrays, of length n and m, and I'd like a pairwise minimum of all of the elements of the two arrays compared against each other. For example:

```<code>a = [1,5,3]
b = [2,4]
cross_min(a,b)
= [[1,1],[2,4],[2,3]]
</code>```

This is similar to the behavior of np.outer(), except that instead of multiplying the two arrays, it computes the minimum of the two elements.

Is there an operation in numpy that does a similar thing?

I know that I can just run np.minimum() along b and stack the results together. I'm wondering if this is a well-known operation that I just don't know the name of.

答:
You might turn one of the array into a 2d array, and then make use of the broadcasting rule and np.minimum:

```<code>import numpy as np
a = np.array([1,5,3])
b = np.array([2,4])

np.minimum(a[:,None], b)
#array([[1, 1],
#       [2, 4],
#       [2, 3]])
</code>```

Title: Numpy minimum like np.outer()

Body:
Maybe I'm just being lazy here, but let's say that I have two arrays, of length n and m, and I'd like a pairwise minimum of all of the elements of the two arrays compared against each other. For example:

a = [1,5,3]
b = [2,4]
cross_min(a,b)
= [[1,1],[2,4],[2,3]]

This is similar to the behavior of np.outer(), except that instead of multiplying the two arrays, it computes the minimum of the two elements.

Is there an operation in numpy that does a similar thing?

I know that I can just run np.minimum() along b and stack the results together. I'm wondering if this is a well-known operation that I just don't know the name of.

Body:
You might turn one of the array into a 2d array, and then make use of the broadcasting rule and np.minimum:

import numpy as np
a = np.array([1,5,3])
b = np.array([2,4])

np.minimum(a[:,None], b)
#array([[1, 1],
#       [2, 4],
#       [2, 3]])


问:
How can I inject an already existing object into the object graph in Dagger 2?
I'm writing a web application with a framework that calls the run() method of my Application class and passes in an object of type Environment.

Other objects I'm writing depend on this Environment class, as they need to call its register() and metrics() methods.

The problem is that I create the object graph in the main() function of my application, like this:

```<code>public class MainApplication extends Application<MainConfiguration> {

private final ConnectionPool sharedPool;

public static void main(String[] args) throws Exception {
MainApplication mainApplication = DaggerMainApplicationComponent.create()
    .createApplication();

mainApplication.run(args);
}

@Inject public MainApplication(ConnectionPool connectionPool) {
super();
sharedPool = connectionPool;
}

@Override
public void run(MainConfiguration configuration, Environment environment) throws Exception {
    // Here is where I have access to the environment variable
}
</code>```

So, by the time MainApplication is constructed by Dagger, the environment variable is not ready. It is only when run() is called that it is available.

Is there a way to inject this variable into the object graph at that point?

答:
This kind of question has already had some traction here but to answer your specific case and to elaborate on EpicPandaForce's comment you can easily escape a small dependency cycle by creating a holder class:

```<code>class EnvironmentHolder {

    private Environment environment;

    @Nullable
    Environment get() {
        return environment;
    }

    void set(Environment environment) {
        this.environment = environment;
    }
}
</code>```

And making the former dependencies of Environment dependencies of EnvironmentHolder instead:

```<code>class DependsOnEnvironment {

    private final EnvironmentHolder environmentHolder;

    @Inject
    DependsOnEnvironment(EnvironmentHolder environmentHolder) {
        this.environmentHolder = environmentHolder;
    }

    public void doSomethingWithMetrics() {
        Environment environment = environmentHolder.get();
        if (environment == null) {
            throw new IllegalStateException("Environment object should be available at the injection time of this class");
        }

        Metrics metrics = environment.metrics();
        //etc.
    }
}
</code>```

If you find yourself using this often it may be a sign that you need a custom scope instead.

Body:
I'm writing a web application with a framework that calls the run() method of my Application class and passes in an object of type Environment.

Other objects I'm writing depend on this Environment class, as they need to call its register() and metrics() methods.

The problem is that I create the object graph in the main() function of my application, like this:

public class MainApplication extends Application<MainConfiguration> {

private final ConnectionPool sharedPool;

public static void main(String[] args) throws Exception {
MainApplication mainApplication = DaggerMainApplicationComponent.create()
    .createApplication();

mainApplication.run(args);
}

@Inject public MainApplication(ConnectionPool connectionPool) {
super();
sharedPool = connectionPool;
}

@Override
public void run(MainConfiguration configuration, Environment environment) throws Exception {
    // Here is where I have access to the environment variable
}

So, by the time MainApplication is constructed by Dagger, the environment variable is not ready. It is only when run() is called that it is available.

Is there a way to inject this variable into the object graph at that point?

Body:
This kind of question has already had some traction here but to answer your specific case and to elaborate on EpicPandaForce's comment you can easily escape a small dependency cycle by creating a holder class:

class EnvironmentHolder {

    private Environment environment;

    @Nullable
    Environment get() {
        return environment;
    }

    void set(Environment environment) {
        this.environment = environment;
    }
}

And making the former dependencies of Environment dependencies of EnvironmentHolder instead:

class DependsOnEnvironment {

    private final EnvironmentHolder environmentHolder;

    @Inject
    DependsOnEnvironment(EnvironmentHolder environmentHolder) {
        this.environmentHolder = environmentHolder;
    }

    public void doSomethingWithMetrics() {
        Environment environment = environmentHolder.get();
        if (environment == null) {
            throw new IllegalStateException("Environment object should be available at the injection time of this class");
        }

        Metrics metrics = environment.metrics();
        //etc.
    }
}

If you find yourself using this often it may be a sign that you need a custom scope instead.


问:
PHP nested if syntax error
I have a weird syntax issue relating to nested if statements.

This code errors:

```<code>if(true):
    if(true){
        var_dump(true);
    }
else:
    var_dump(false);
endif;
</code>```

This code does not error (note the added ;):

```<code>if(true):
    if(true){
        var_dump(true);
    };
else:
    var_dump(false);
endif;
</code>```

What gives?

答:
I know this is an old question, but I found a valid answer to it. I changed the OP's code:

```<code>if(true):
   if(true){
       var_dump(true);
   }
else:
   var_dump(false);
endif;
</code>```

to the following:

```<code>if (true) :
    {
        if (true) {
            var_dump ( true );
        } else {
            var_dump ( false );
        }
    }
endif;
</code>```

which successfully ran and printed true.

The only change I made was that I wrapped the nested if in a block.

Simplified code:

```<code>if (true) :
    {
        if (true)
            var_dump ( true );
        else
            var_dump ( false );
    }
endif;
</code>```

Note that I am using PHP 7.0.0.

Title: PHP nested if syntax error

Body:
I have a weird syntax issue relating to nested if statements.

This code errors:

if(true):
    if(true){
        var_dump(true);
    }
else:
    var_dump(false);
endif;

This code does not error (note the added ;):

if(true):
    if(true){
        var_dump(true);
    };
else:
    var_dump(false);
endif;

What gives?

Body:
I know this is an old question, but I found a valid answer to it. I changed the OP's code:

if(true):
   if(true){
       var_dump(true);
   }
else:
   var_dump(false);
endif;

to the following:

if (true) :
    {
        if (true) {
            var_dump ( true );
        } else {
            var_dump ( false );
        }
    }
endif;

which successfully ran and printed true.

The only change I made was that I wrapped the nested if in a block.

Simplified code:

if (true) :
    {
        if (true)
            var_dump ( true );
        else
            var_dump ( false );
    }
endif;

Note that I am using PHP 7.0.0.


问:
Eloquent orderBy except one row
I basically just want to order my results by name except for 1 row - which I want to keep at the bottom of the results.

I have the following database table:

```<code>INSERT INTO `teams` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'Anaheim Ducks', NULL, NULL),
(2, 'Arizona Coyotes', NULL, NULL),
(3, 'Atlanta Flames', NULL, NULL),
(4, 'Atlanta Thrashers', NULL, NULL),
(5, 'Boston Bruins', NULL, NULL),
(6, 'Buffalo Sabres', NULL, NULL),
(7, 'Calgary Flames', NULL, NULL),
(8, 'California Golden Seals', NULL, NULL),
(9, 'Carolina Hurricanes', NULL, NULL),
(10, 'Chicago Blackhawks', NULL, NULL),
(11, 'Cleveland Barons', NULL, NULL),
(12, 'Colorado Avalanche', NULL, NULL),
(13, 'Colorado Rockies', NULL, NULL),
(14, 'Columbus Blue Jackets', NULL, NULL),
(49, 'Other', NULL, NULL);
</code>```

Now, I want to use Eloquent to order these all by name, EXCEPT I want Other to be at the bottom.

I am unsure how to do this using orderBy(). How do I do this?

答:
You can write your own comparator for sorting and implement any logic you want.

For example:

```<code>Teams::all()->sort(function($a, $b) {
    if ($a->name === 'Other') return 1; // $a has lower priority, so move $a down
    if ($b->name === 'Other') return -1; // $b has lower priority, so move $b down
    return ($a->id > $b->id) ? 1 : -1; // default sort logic, you can compare any other fields
});
</code>```

Title: Eloquent orderBy except one row

Body:
I basically just want to order my results by name except for 1 row - which I want to keep at the bottom of the results.

I have the following database table:

INSERT INTO `teams` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'Anaheim Ducks', NULL, NULL),
(2, 'Arizona Coyotes', NULL, NULL),
(3, 'Atlanta Flames', NULL, NULL),
(4, 'Atlanta Thrashers', NULL, NULL),
(5, 'Boston Bruins', NULL, NULL),
(6, 'Buffalo Sabres', NULL, NULL),
(7, 'Calgary Flames', NULL, NULL),
(8, 'California Golden Seals', NULL, NULL),
(9, 'Carolina Hurricanes', NULL, NULL),
(10, 'Chicago Blackhawks', NULL, NULL),
(11, 'Cleveland Barons', NULL, NULL),
(12, 'Colorado Avalanche', NULL, NULL),
(13, 'Colorado Rockies', NULL, NULL),
(14, 'Columbus Blue Jackets', NULL, NULL),
(49, 'Other', NULL, NULL);

Now, I want to use Eloquent to order these all by name, EXCEPT I want Other to be at the bottom.

I am unsure how to do this using orderBy(). How do I do this?

Body:
You can write your own comparator for sorting and implement any logic you want.

For example:

Teams::all()->sort(function($a, $b) {
    if ($a->name === 'Other') return 1; // $a has lower priority, so move $a down
    if ($b->name === 'Other') return -1; // $b has lower priority, so move $b down
    return ($a->id > $b->id) ? 1 : -1; // default sort logic, you can compare any other fields
});


问:
How I can parse html source in website where it check javascript enable?
Before Questioning, Sorry for my English.

While I constructing Java Source to parse web and extract attribute tag from html source, I found some websites where they embeded ads in their WebPage and they make client redirect to warning page when We disabled JAVASCRIPT option.
I think This Because when We disabled the javascript option, Some ads working on Javascript is not appear.

```<code><html><title>You are being redirected...</title>
<noscript>Javascript is required. Please enable javascript before you are allowed to see this page.</noscript>
<script>vars={},u,c,U,r,i,l=0,a,e=eval,w=String.fromCharCode,sucuri_cloudproxy_js='',S='az0nNXZYOCcuc3Vic3RyKDMsIDEpICsiNSIgKyAiNXN1Y3VyIi5jaGFyQXQoMCkrJ1lhJy5zbGljZSgxLDIpKydhWzQnLmNoYXJBdCgyKSsiNHN1Ii5zbGljZSgwLDEpICsgJzQnICsgICJmc2VjIi5zdWJzdHIoMCwxKSArICI2Ii5zbGljZSgwLDEpICsgJ2EnICsgICdhWjgnLmNoYXJBdCgyKSsnMycgKyAgICcnICsnJysiYiIgKyAiNHN1Ii5zbGljZSgwLDEpICsgIiIgKyIzc3UiLnNsaWNlKDAsMSkgKyAiIiArJ3RANycuY2hhckF0KDIpKyJmIi5zbGljZSgwLDEpICsgImNzdWN1ciIuY2hhckF0KDApKyd0NGQnLmNoYXJBdCgyKSsnOScgKyAgJ2InICsgICI3IiArICdsPzYnLmNoYXJBdCgyKSsnMzInLnNsaWNlKDEsMikrJ1RsWmEnLnN1YnN0cigzLCAxKSArJ0E5Jy5zbGljZSgxLDIpKyJibiIuY2hhckF0KDApICsgIiIgKyI5c3VjdXIiLmNoYXJBdCgwKSsgJycgKyJhc3VjdXIiLmNoYXJBdCgwKSsiY3ciLmNoYXJBdCgwKSArICczYk82Jy5zdWJzdHIoMywgMSkgKyIiICsiZWkiLmNoYXJBdCgwKSArICcnO2RvY3VtZW50LmNvb2tpZT0ncycrJ3UnKydjJysnJysndXN1Y3VyJy5jaGFyQXQoMCkrICdyJysnJysnc3VjdWknLmNoYXJBdCg0KSsgJ3NfJy5jaGFyQXQoMSkrJ2NzJy5jaGFyQXQoMCkrJ3N1Y3VybCcuY2hhckF0KDUpICsgJ28nKyd1JysnZCcrJycrJ3BzdWN1cicuY2hhckF0KDApKyAncnN1Y3VyaScuY2hhckF0KDApICsgJ29zdScuY2hhckF0KDApICsnc3VjdXgnLmNoYXJBdCg0KSsgJ3lzdScuY2hhckF0KDApICsnXycrJycrJ3VzdWN1cmknLmNoYXJBdCgwKSArICd1JysnJysnaXMnLmNoYXJBdCgwKSsnZCcrJ19zdWN1cmknLmNoYXJBdCgwKSArICdzdWInLmNoYXJBdCgyKSsnNXMnLmNoYXJBdCgwKSsnc3VjdTcnLmNoYXJBdCg0KSsgJ3NkJy5jaGFyQXQoMSkrJzYnLmNoYXJBdCgwKSsnc3VjdXI5Jy5jaGFyQXQoNSkgKyAnNicrJycrJ3N1MScuY2hhckF0KDIpKycxJysnJysiPSIgKyBrOyBsb2NhdGlvbi5yZWxvYWQoKTs=';L=S.length;U=0;r='';var A='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';for(u=0;u<64;u++){s[A.charAt(u)]=u;}for(i=0;i<L;i++){c=s[S.charAt(i)];U=(U<<6)+c;l+=6;while(l>=8){((a=(U>>>(l-=8))&0xff)||(i<(L-2)))&&(r+=w(a));}}e(r);</script></html>
</code>```

If someone know How I can enable javascript on android java or prevent redirecting, Help!

答:
It's a protection against ddos, web crawling and other such things…

Unless they provide you the real host u are unable to get the desired output…

When u try to web crawl a specific link, if they are using these, it means they are not showing their page directly, rather they are showing a dummy html (which you are getting as output) and that script is later redirecting to the real page blocking you… ☺

Body:
Before Questioning, Sorry for my English.

While I constructing Java Source to parse web and extract attribute tag from html source, I found some websites where they embeded ads in their WebPage and they make client redirect to warning page when We disabled JAVASCRIPT option.
I think This Because when We disabled the javascript option, Some ads working on Javascript is not appear.

<title>You are being redirected...</title>
Javascript is required. Please enable javascript before you are allowed to see this page.

If someone know How I can enable javascript on android java or prevent redirecting, Help!


问:
Where does finite-state machine code belong in µC?
I asked this question on EE forum. You guys on StackOverflow know more about coding than we do on EE so maybe you can give more detail information about this :)

When I learned about micrcontrollers, teachers taught me to always end the code with  while(1); with no code inside that loop.

This was to be sure that the software get "stuck" to keep interruption working. When I asked them if it was possible to put some code in this infinite loop, they told me it was a bad idea. Knowing that, I now try my best to keep this loop empty.

I now need to implement a finite state machine in a microcontroller. At first view, it seems that that code belong in this loop. That makes coding easier.

Is that a good idea? What are the pros and cons?

This is what I plan to do :

```<code>void main(void)
{
    // init phase

 while(1)
 {
    switch(current_State)
    {
    case 1:
        if(...)
        {
            current_State = 2;
        }
        else(...)
        {
            current_State = 3;
        }
        else
            current_State = 4;
        break;

    case 2:
        if(...)
        {
            current_State = 3;
        }
        else(...)
        {
            current_State = 1;
        }
        else
            current_State = 5;
        break;
   }
}
</code>```

Instead of:

```<code> void main(void)
    {
        // init phase

     while(1);
    }
</code>```

And manage the FSM with interrupt

答:
It is like saying return all functions in one place, or other habits.  There is one type of design where you might want to do this, one that is purely interrupt/event based.  There are products, that go completely the other way, polled and not even driven. And anything in between.

What matters is doing your system engineering, thats it, end of story.  Interrupts add complication and risk, they have a higher price than not using them.  Automatically making any design interrupt driven is automatically a bad decision, simply means there was no effort put into the design, the requirements the risks, etc.

Ideally you want most of your code in the main loop, you want your interrupts lean and mean in order to keep the latency down for other time critical tasks.  Not all MCUs have a complicated interrupt priority system that would allow you to burn a lot of time or have all of your application in handlers.  Inputs into your system engineering, may help choose the mcu, but here again you are adding risk.

You have to ask yourself what are the tasks your mcu has to do, what if any latency is there for each task from when an event happens until they have to start responding and until they have to finish, per event/task what if any portion of it can be deferred.  Can any be interrupted while doing the task, can there be a gap in time.  All the questions you would do for a hardware design, or cpld or fpga design.  except you have real parallelism there.

What you are likely to end up with in real world solutions are some portion in interrupt handlers and some portion in the main (infinite) loop.  The main loop polling breadcrumbs left by the interrupts and/or directly polling status registers to know what to do during the loop.  If/when you get to where you need to be real time you can still use the main super loop, your real time response comes from the possible paths through the loop and the worst case time for any of those paths.

Most of the time you are not going to need to do this much work.  Maybe some interrupts, maybe some polling, and a main loop doing some percentage of the work.

As you should know from the EE world if a teacher/other says there is one and only one way to do something and everything else is by definition wrong...Time to find a new teacher and or pretend to drink the kool-aid, pass the class and move on with your life.  Also note that the classroom experience is not real world.  There are so many things that can go wrong with MCU development, that you are really in a controlled sandbox with ideally only a few variables you can play with so that you dont have spend years to try to get through a few month class.  Some percentage of the rules they state in class are to get you through the class and/or to get the teacher through the class, easier to grade papers if you tell folks a function cant be bigger than X or no gotos or whatever.  First thing you should do when the class is over or add to your lifetime bucket list, is to question all of these rules.  Research and try on your own, fall into the traps and dig out.

Body:
I asked this question on EE forum. You guys on StackOverflow know more about coding than we do on EE so maybe you can give more detail information about this :)

When I learned about micrcontrollers, teachers taught me to always end the code with  while(1); with no code inside that loop.

This was to be sure that the software get "stuck" to keep interruption working. When I asked them if it was possible to put some code in this infinite loop, they told me it was a bad idea. Knowing that, I now try my best to keep this loop empty.

I now need to implement a finite state machine in a microcontroller. At first view, it seems that that code belong in this loop. That makes coding easier.

Is that a good idea? What are the pros and cons?

This is what I plan to do :

void main(void)
{
    // init phase

 while(1)
 {
    switch(current_State)
    {
    case 1:
        if(...)
        {
            current_State = 2;
        }
        else(...)
        {
            current_State = 3;
        }
        else
            current_State = 4;
        break;

    case 2:
        if(...)
        {
            current_State = 3;
        }
        else(...)
        {
            current_State = 1;
        }
        else
            current_State = 5;
        break;
   }
}

Instead of:

 void main(void)
    {
        // init phase

     while(1);
    }

And manage the FSM with interrupt


问:
How to load scores in Unity?
I have a simple game published in Google Play. When player wins the game his score should be incremented in leaderboard. My problem is that when player wins the game, app stops. I think that problem is in PlayGamesPlatform.Instance.LoadScores because when I removed this part, no one had a problem. Also, I want to notice that not every player has such problem in game. This problem happens just to those, who haven't ever won the game (they have no score in leaderboard). So,  PlayGamesPlatform.Instance.LoadScores works only to those who already have some score in leaderboard.

My script:

```<code>PlayGamesPlatform.Instance.LoadScores(GPGSIds.leaderboard_rating, GooglePlayGames.BasicApi.LeaderboardStart.PlayerCentered, 1, GooglePlayGames.BasicApi.LeaderboardCollection.Public, GooglePlayGames.BasicApi.LeaderboardTimeSpan.AllTime, (GooglePlayGames.BasicApi.LeaderboardScoreData data) =>
{
    long score;
    if (long.TryParse(data.PlayerScore.formattedValue, out score))
        Social.ReportScore(score + 50, GPGSIds.leaderboard_rating, (bool success) => { });
    else
        Social.ReportScore(50, GPGSIds.leaderboard_rating, (bool success) => { });
});
</code>```

答:
Try this google sample from github

Using PlayGamesPlatform.LoadScores()

This method uses the PlayGamesPlatform directly. This approach provides additional flexibility and information when accessing the leaderboard data.

```<code> PlayGamesPlatform.Instance.LoadScores(
            GPGSIds.leaderboard_leaders_in_smoketesting,
            LeaderboardStart.PlayerCentered,
            100,
            LeaderboardCollection.Public,
            LeaderboardTimeSpan.AllTime,
            (data) =>
            {
                mStatus = "Leaderboard data valid: " + data.Valid;
                mStatus += "\n approx:" +data.ApproximateCount + " have " + data.Scores.Length;
            });
</code>```

The parameters for LoadScores() are:

leaderboardId start position (top scores or player centered) row count
  leaderboard collection (social or public) time span (daily, weekly,
  all-time) callback accepting a LeaderboardScoreData object. The
  LeaderboardScoreData class is used to return information back to the
  caller when loading scores. The members are:
   1. Id - the leaderboard id 2. Valid - true if the returned data is valid (the call was successful) 3. Status - the ResponseStatus of the
  call 4. ApproximateCount - the approximate number of scores in the
  leaderboard 5. Title - the title of the leaderboard 6. PlayerScore -
  the score of the current player 7. Scores - the list of scores 8.
  PrevPageToken - a token that can be used to call LoadMoreScores() to
  get the previous page of scores. 9. NextPageToken - a token that can
  be used to call LoadMoreScores() to get the next page of scores.

```<code>void GetNextPage(LeaderboardScoreData data)
    {
        PlayGamesPlatform.Instance.LoadMoreScores(data.NextPageToken, 10,
            (results) =>
            {
                mStatus = "Leaderboard data valid: " + data.Valid;
                mStatus += "\n approx:" +data.ApproximateCount + " have " + data.Scores.Length;
            });
    }
</code>```

Additional reference How to get the user score value from Google Play Services Leaderboard.

P.S.:

Try setting the scores of all players to default 0 so players who havent played yet can make calls to loadScores.

Title: How to load scores in Unity?

Body:
I have a simple game published in Google Play. When player wins the game his score should be incremented in leaderboard. My problem is that when player wins the game, app stops. I think that problem is in PlayGamesPlatform.Instance.LoadScores because when I removed this part, no one had a problem. Also, I want to notice that not every player has such problem in game. This problem happens just to those, who haven't ever won the game (they have no score in leaderboard). So,  PlayGamesPlatform.Instance.LoadScores works only to those who already have some score in leaderboard.

My script:

PlayGamesPlatform.Instance.LoadScores(GPGSIds.leaderboard_rating, GooglePlayGames.BasicApi.LeaderboardStart.PlayerCentered, 1, GooglePlayGames.BasicApi.LeaderboardCollection.Public, GooglePlayGames.BasicApi.LeaderboardTimeSpan.AllTime, (GooglePlayGames.BasicApi.LeaderboardScoreData data) =>
{
    long score;
    if (long.TryParse(data.PlayerScore.formattedValue, out score))
        Social.ReportScore(score + 50, GPGSIds.leaderboard_rating, (bool success) => { });
    else
        Social.ReportScore(50, GPGSIds.leaderboard_rating, (bool success) => { });
});

Body:
Try this google sample from github

Using PlayGamesPlatform.LoadScores()

This method uses the PlayGamesPlatform directly. This approach provides additional flexibility and information when accessing the leaderboard data.

 PlayGamesPlatform.Instance.LoadScores(
            GPGSIds.leaderboard_leaders_in_smoketesting,
            LeaderboardStart.PlayerCentered,
            100,
            LeaderboardCollection.Public,
            LeaderboardTimeSpan.AllTime,
            (data) =>
            {
                mStatus = "Leaderboard data valid: " + data.Valid;
                mStatus += "\n approx:" +data.ApproximateCount + " have " + data.Scores.Length;
            });

The parameters for LoadScores() are:

leaderboardId start position (top scores or player centered) row count
  leaderboard collection (social or public) time span (daily, weekly,
  all-time) callback accepting a LeaderboardScoreData object. The
  LeaderboardScoreData class is used to return information back to the
  caller when loading scores. The members are:
   1. Id - the leaderboard id 2. Valid - true if the returned data is valid (the call was successful) 3. Status - the ResponseStatus of the
  call 4. ApproximateCount - the approximate number of scores in the
  leaderboard 5. Title - the title of the leaderboard 6. PlayerScore -
  the score of the current player 7. Scores - the list of scores 8.
  PrevPageToken - a token that can be used to call LoadMoreScores() to
  get the previous page of scores. 9. NextPageToken - a token that can
  be used to call LoadMoreScores() to get the next page of scores.

void GetNextPage(LeaderboardScoreData data)
    {
        PlayGamesPlatform.Instance.LoadMoreScores(data.NextPageToken, 10,
            (results) =>
            {
                mStatus = "Leaderboard data valid: " + data.Valid;
                mStatus += "\n approx:" +data.ApproximateCount + " have " + data.Scores.Length;
            });
    }

Additional reference How to get the user score value from Google Play Services Leaderboard.

P.S.:

Try setting the scores of all players to default 0 so players who havent played yet can make calls to loadScores.


问:
Facebook's Batch Request not picking up a JSON parameter
My goal is to create a number of ads using Facebook's Batch API : https://developers.facebook.com/docs/marketing-api/asyncrequests/v2.9

I am sending a POST request at this URL:

```<code>https://graph.facebook.com/v2.9/act_158365238/ads
</code>```

I am sending 2 parameters as per the documentation:

1- access_token

2- batch

The JSON in the batch parameter looks like :

```<code>{
  "method": "POST",
  "relative_url": "v2.9\/act_158365238\/ads",
  "attached_files": "test1",
  "body": "creative={\"title\":\"Test title 1\",\"body\":\"Test body 1\",\"object_url\":\"https:\/\/apps.facebook.com\/testapp\/\", \"image_file\":\"test1.jpg\"}&targeting={\"countries\":[\"US\"]}&name=test1"
}
</code>```

The Problem

When I send this request with POSTman or my PHP code, it throws the following error

```<code>{
  "error": {
    "message": "(#100) The parameter creative is required",
    "type": "OAuthException",
    "code": 100,
    "fbtrace_id": "Gj2sG7N8l1f"
  }
}
</code>```

However when I send the exact same request via Facebook's Graph API tool, it successfully creates the ads.

答:
I think the message is a red herring -- it's not seeing your body's creative field because the OAuth isn't properly set in your POSTman requests, so it isn't parsing the body or seeing the creative field.

If you don't know how to set OAuth in POSTman, here's a good tutorial:
https://docs.brightcove.com/en/video-cloud/concepts/postman/postman.html

Body:
My goal is to create a number of ads using Facebook's Batch API : https://developers.facebook.com/docs/marketing-api/asyncrequests/v2.9

I am sending a POST request at this URL:

https://graph.facebook.com/v2.9/act_158365238/ads

I am sending 2 parameters as per the documentation:

1- access_token

2- batch

The JSON in the batch parameter looks like :

{
  "method": "POST",
  "relative_url": "v2.9\/act_158365238\/ads",
  "attached_files": "test1",
  "body": "creative={\"title\":\"Test title 1\",\"body\":\"Test body 1\",\"object_url\":\"https:\/\/apps.facebook.com\/testapp\/\", \"image_file\":\"test1.jpg\"}&targeting={\"countries\":[\"US\"]}&name=test1"
}

The Problem

When I send this request with POSTman or my PHP code, it throws the following error

{
  "error": {
    "message": "(#100) The parameter creative is required",
    "type": "OAuthException",
    "code": 100,
    "fbtrace_id": "Gj2sG7N8l1f"
  }
}

However when I send the exact same request via Facebook's Graph API tool, it successfully creates the ads.


问:
GitHub project deployment failed on azure
I want to deploy my .Net project from GitHub repository to the azure server.

In Deployment options I am getting Building failed error.

Here are screen shots of my Deployment details and Logs

1- Deployment Details:

2- Activity Log:

答:
Azure looks in your site/repository/packages folder for all the packages your app uses. By looking through it you will find that visual studio doesn't deploy all of the files from your local packages folder to the azure one. MSBuild needs these files when you push to git and trigger a build. Ftp into your azure site and look for the packages folder. Upload every missing file (dll) from your local folder to the azure one. This worked for me and now I can trigger a build and deployment from bitbucket to azure app service upon a push.

Additionally, if you have other projects in your VS solution and you are using VS to build those projects and then put the dll into your main projects bin folder, that will cause a missing file error also. I create a folder in my packages folder and link the dll to my main folder from there. That way when you perform the fix above, the file needed by your main project is in the packages folder also.

I hope this helps!


问:
PHP loop is not throwing the correct link
for my issue i'll try to be as brief as possible

what am trying to do is reference a page with a specific id in the HTML anchor link with PHP as the below

```<code><body>
<?php  $linkName = "Second Page"; ?>
<?php $id = 5; ?>

<a href="secondPage.php?id=<?php echo $id;?>"><?php echo $linkName?></a><br>
</code>```

and it works fine

now what am trying to do is to make the $id part more dynamic by making looping the number from 1 to 10 and also providing 10 links

the code is

```<code></head>
<body>
    <?php  $linkName = "Second Page"; ?>
    <?php $id = 5; ?>

    <?php
        for ($i=0; $i < 10 ; $i++) {
            echo "<a href='secondPage.php?id=<?php echo $i;?'>Link1</a>";
        };

    ?>
</body>
</code>```

however what i did notice as the below images indicates when i hover on the links i noticed that i refer to a strange link

and when i cliched on it it takes me to the following link with an id that i did not want as below

```<code>http://localhost/PHP_Course/secondPage.php?id=%3C?php%20echo%201;?
</code>```

i tried researching the subject and i tried escaping the quotation but it does not seem to resolve the problem

Any help please ??

答:
You're echoing a string in PHP, and using <?php... inside that string.

Solution:

```<code>echo "<a href='secondPage.php?id=" . $i . "'>Link1</a>";
</code>```

id=$i will also work, because you can include variables directly in double-quoted strings.

Body:
for my issue i'll try to be as brief as possible

what am trying to do is reference a page with a specific id in the HTML anchor link with PHP as the below

<?php  $linkName = "Second Page"; ?>
<?php $id = 5; ?>

<a href="secondPage.php?id=<?php echo $id;?>"><?php echo $linkName?>

and it works fine

now what am trying to do is to make the $id part more dynamic by making looping the number from 1 to 10 and also providing 10 links

the code is

    <?php  $linkName = "Second Page"; ?>
    <?php $id = 5; ?>

    <?php
        for ($i=0; $i < 10 ; $i++) {
            echo "<a href='secondPage.php?id=<?php echo $i;?'>Link1";
        };

    ?>

however what i did notice as the below images indicates when i hover on the links i noticed that i refer to a strange link

and when i cliched on it it takes me to the following link with an id that i did not want as below

http://localhost/PHP_Course/secondPage.php?id=%3C?php%20echo%201;?

i tried researching the subject and i tried escaping the quotation but it does not seem to resolve the problem

Any help please ??

Body:
You're echoing a string in PHP, and using <?php... inside that string.

Solution:

echo "<a href='secondPage.php?id=" . $i . "'>Link1</a>";

id=$i will also work, because you can include variables directly in double-quoted strings.


答:
The reason your code seemingly seems random is due to:

```<code>for(let i = 0; i < ul.children.length; i++) {
    ul.removeChild(ul.children[i]);
}
</code>```

As you are removing elements from the UL, it's children length is getting smaller so ul.children.length is reducing from n, to n-1, to n-2 etc.  However, your i is increasing.  Eventually, i will be larger than ul.children.length even thought there children left over. As i increases, your children in UL is getting smaller, however you are removing from the 0 first.  So it means you will also eventually be attempting to remove elements which doesn't exist, as they are now in [0].

I modified your code to this following:

```<code>document.getElementById('reset').addEventListener('click', (e) => {
  const ul = document.getElementById("myUL");

  while (ul.children[0]) {
    ul.removeChild(ul.children[0])
  }
});
</code>```

Title: removeChild(); not removing all items from list

Body:
When I run the following code, half of the items are removed from the list.. I am trying to remove all items from the list.

  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");
      console.log(ul.children.length);

      //Moves through the unordered list and removes each list item.
      for(let i = 0; i < ul.children.length; i++) {
        ul.removeChild(ul.children[i]);
      }
  });

Body:
The reason your code seemingly seems random is due to:

for(let i = 0; i < ul.children.length; i++) {
    ul.removeChild(ul.children[i]);
}

As you are removing elements from the UL, it's children length is getting smaller so ul.children.length is reducing from n, to n-1, to n-2 etc.  However, your i is increasing.  Eventually, i will be larger than ul.children.length even thought there children left over. As i increases, your children in UL is getting smaller, however you are removing from the 0 first.  So it means you will also eventually be attempting to remove elements which doesn't exist, as they are now in [0].

I modified your code to this following:

document.getElementById('reset').addEventListener('click', (e) => {
  const ul = document.getElementById("myUL");

  while (ul.children[0]) {
    ul.removeChild(ul.children[0])
  }
});


答:
You're echoing the PHP code itself as a string.  You don't need to put PHP code inside of PHP code.  Just concatenate the values you want to echo:

```<code>echo '<a href="secondPage.php?id=' . $i . '">Link1</a>';
</code>```

Title: PHP loop is not throwing the correct link

Body:
You're echoing the PHP code itself as a string.  You don't need to put PHP code inside of PHP code.  Just concatenate the values you want to echo:

echo '<a href="secondPage.php?id=' . $i . '">Link1</a>';


问:
how far can the epoch time go back in time?
I was trying out http://www.epochconverter.com/ and I can do year 100, but when I go to year 99, it seems to break down and report 1999 instead of 0099.  Is this a bug?  How far back is epoch time supposed to be able to represent.

I also tried plugging in MIN_LONG+1 to joda-time which reported -292275055-05-16T16:47:04.192Z so basically year -292275055 which sounds a bit more correct than 1999 and epochconverter.com can't even parse the min long.

What is the minimum value of epoch time allowed?  Can I use min long?

thanks,
Dean

答:
The reason it interprets your input year 99 as the year 1999 is because more likely than not it uses the Javascript function Date.parse() to parse your date, which has this particular anomaly.

You can get the correctly parsed timestamp at another online timestamp parser such as http://www.convertunixdate.com/ - you might need to enter your year as a 4 digit number to make sure it isn't changed.


问:
How to compute the "15% of the time" randomness?
I'm looking for a decent, elegant method of calculating this simple logic.

Right now I can't think of one, it's spinning my head.

I am required to do some action only 15% of the time.

I'm used to "50% of the time" where I just mod the milliseconds of the current time and see if it's odd or even, but I don't think that's elegant.

How would I elegantly calculate "15% of the time"?  Random number generator maybe?

Pseudo-code or any language are welcome.

Hope this is not subjective, since I'm looking for the "smartest" short-hand method of doing that.

Thanks.

答:
Random number generator would give you the best randomness. Generate a random between 0 and 1, test for < 0.15.

Using the time like that isn't true random, as it's influenced by processing time. If a task takes less than 1 millisecond to run, then the next random choice will be the same one.

That said, if you do want to use the millisecond-based method, do milliseconds % 20 < 3.


问:
How to get mod_wsgi-express from pip using Dockerfile
I can't recall how I installed mod_wsgi-express, but I'm almost certain that I used pip.

I've got this line in my requirements.txt file:
mod_wsgi-express==4.5.15

```<code>Collecting mod_wsgi-express==4.5.15 (from -r /usr/src/app/requirements.txt (line 16))
  Could not find a version that satisfies the requirement mod_wsgi-express==4.5.15 (from -r /usr/src/app/requirements.txt (line 16)) (from versions: )
No matching distribution found for mod_wsgi-express==4.5.15 (from -r /usr/src/app/requirements.txt (line 16))
You are using pip version 9.0.0, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

Is the naming different here? Or am I just not seeing that package?

```<code>$ pip list | grep mod
mod-wsgi (4.5.15)
mod-wsgi-httpd (2.4.23.2)
</code>```

答:
In requirements.txt: mod_wsgi==4.5.15

The package information can be found on PyPi at:

https://pypi.python.org/pypi/mod_wsgi

Body:
I can't recall how I installed mod_wsgi-express, but I'm almost certain that I used pip.

I've got this line in my requirements.txt file:
mod_wsgi-express==4.5.15

Collecting mod_wsgi-express==4.5.15 (from -r /usr/src/app/requirements.txt (line 16))
  Could not find a version that satisfies the requirement mod_wsgi-express==4.5.15 (from -r /usr/src/app/requirements.txt (line 16)) (from versions: )
No matching distribution found for mod_wsgi-express==4.5.15 (from -r /usr/src/app/requirements.txt (line 16))
You are using pip version 9.0.0, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

Is the naming different here? Or am I just not seeing that package?

$ pip list | grep mod
mod-wsgi (4.5.15)
mod-wsgi-httpd (2.4.23.2)


答:
because you already started an echo statement so you don't need to add another PHP starting and ending tags. just check my code below and try it.</p>

```<code><?php
           for ($i=0; $i < 10 ; $i++) {
             echo "<a href='secondPage.php?id=".$i."'>Link1</a>";
    } ;

?>
</code>```

Body:
because you already started an echo statement so you don't need to add another PHP starting and ending tags. just check my code below and try it.

<?php
           for ($i=0; $i < 10 ; $i++) {
             echo "<a href='secondPage.php?id=".$i."'>Link1</a>";
    } ;

?>


问:
Firebase database count number of child
I want to get first the number of children (if any). Then I want to add 1 to number of children, so the added children will be +1 from the existing.

So when I add new question, II want to add number 3. But I get it added as number 1 and it updates the existing number.

```<code>    int count = 0;
 public void addQuestion(View view) {
     mDatabase = FirebaseDatabase.getInstance();
     mRef = FirebaseDatabase.getInstance().getReference("Questions");
       count = count + 1;
        String nr = String.valueOf(count);
        GetData getdata = new GetData(qs, A, B, C, correct);
        mRef.child(nr).setValue(getdata);
        Toast.makeText(AdminPanel.this, "Adding question...", Toast.LENGTH_SHORT).show();
                    }
</code>```

答:
You can use the push function and it will generate a unique key, so you don't have to worry about giving then unique numbers.
mRef.push();

you can also get the key that was generated if you need it,
https://firebase.google.com/docs/database/admin/save-data#getting-the-unique-key-generated-by-push

or just retrieve all the children (your questions) when needed.

I suggest you read the documentation, I found there all the information I needed.
https://firebase.google.com/docs/database/

Title: Firebase database count number of child

Body:
I want to get first the number of children (if any). Then I want to add 1 to number of children, so the added children will be +1 from the existing.

So when I add new question, II want to add number 3. But I get it added as number 1 and it updates the existing number.

    int count = 0;
 public void addQuestion(View view) {
     mDatabase = FirebaseDatabase.getInstance();
     mRef = FirebaseDatabase.getInstance().getReference("Questions");
       count = count + 1;
        String nr = String.valueOf(count);
        GetData getdata = new GetData(qs, A, B, C, correct);
        mRef.child(nr).setValue(getdata);
        Toast.makeText(AdminPanel.this, "Adding question...", Toast.LENGTH_SHORT).show();
                    }


问:
Android Google Calendar dtstart dtend
Actually I need to create an event in Google Calendar using my app. Every thing working fine I am not able to create desire start time and end time. Can any body please help me to tell how can I generate dtstart n dtend. i.e. I need to create an event for 20/12/2010. please

thanks

答:
For your example, DTSTART=20101220, DTEND=20101221 since the end is exclusive.

See RFC 2445 for details, but the basic grammar is below:

```<code>date               = date-value

date-value         = date-fullyear date-month date-mday
date-fullyear      = 4DIGIT
date-month         = 2DIGIT        ; 01-12
date-mday          = 2DIGIT        ; 01-28, 01-29, 01-30, 01-31
                                   ; based on month/year
</code>```

Title: Android Google Calendar dtstart dtend

Body:
For your example, DTSTART=20101220, DTEND=20101221 since the end is exclusive.

See RFC 2445 for details, but the basic grammar is below:

date               = date-value

date-value         = date-fullyear date-month date-mday
date-fullyear      = 4DIGIT
date-month         = 2DIGIT        ; 01-12
date-mday          = 2DIGIT        ; 01-28, 01-29, 01-30, 01-31
                                   ; based on month/year


问:
How to use Android Service or ServiceIntent
Can someone help me understand how to use Android Service or IntentService correctly.  The documentation seems to contradict itself here:

```<code>    Caution: A service runs in the same process as the application in which it is
declared and in the main thread of that application by default. If your service
performs intensive or blocking operations while the user interacts with an
activity from the same application, the service slows down activity performance.
To avoid impacting application performance, start a new thread inside the service.
</code>```

and here

```<code>public class HelloIntentService extends IntentService {

  /**
   * A constructor is required, and must call the super IntentService(String)
   * constructor with a name for the worker thread.
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }

  /**
   * The IntentService calls this method from the default worker thread with
   * the intent that started the service. When this method returns, IntentService
   * stops the service, as appropriate.
   */
  @Override
  protected void onHandleIntent(Intent intent) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      try {
          Thread.sleep(5000);
      } catch (InterruptedException e) {
          // Restore interrupt status.
          Thread.currentThread().interrupt();
      }
  }
}
</code>```

Given the whole purpose of the Service or ServiceIntent is to run long running jobs in the background without affecting the UI why then does the example code do exactly what the Caution indicated you should not do - and I am assuming a call to Thread.sleep() will cause the main thread to block.

Am I correct in the following understanding:

The service itself still runs on the main application thread but has no UI component (Activity) and will continue running even if the application is not used by the user, unlike an Activity which will not

Any long running background work must still create a separate thread to avoid blocking the main application thread

AsyncTask is associated with an Activity which presumably will stop running if the application is no longer the active application (i.e. if the user switches to another application) which is why one would use Service or ServiceIntent if the task needs to keep running.

IntentService will run the task on a separate thread to the main thread so there is no need to worry about blocking the main thread with long tasks or when calling Thread.sleep().

Have I misunderstood something with the description of Android Service or ServiceIntents?

答:
Your first comment is from the the documentation about services in general.

There is nothing in Android named ServiceIntent. Your code snippet is an IntentService.

In Java, we have classes and inheritance. Service is the base class from which all services inherit. IntentService extends Service.

If you call startService(), pointing to a class of yours that inherits directly from Service, you need to implement a background thread yourself, as Service will not do that for you.

If, however, you call startService(), pointing to a class of yours that inherits from IntentService, then you will get a background thread created for you automatically by IntentService. This is code added by IntentService, above and beyond what Service provides.

and I am assuming a call to Thread.sleep() will cause the main thread to block.

No, because onHandleIntent() is called on the IntentService-supplied background thread.

The service itself still runs on the main application thread

No. In Java, objects do not run on threads. Methods run on threads.

Any long running background work must still create a separate thread to avoid blocking the main application thread

Any long-running background work needs to be performed on a background thread. Whether that is a thread that you create (e.g., in a direct subclass of Service) or whether it is a thread that is provided to you (e.g., in a direct subclass of IntentService) varies.

AsyncTask is associated with an Activity which presumably will stop running if the application is no longer the active application

The primary role of a service is to tell Android that we are doing background work that should continue for a while, even if the app's UI moves to the background. That is because Android will terminate your process eventually, to free up system RAM for other apps.

Using a service will tend to keep your process around for a little while longer. An AsyncTask, or a bare Thread, does not do this. When the app's UI moves to the background, your process is not terminated immediately, but it may be terminated soon, and so if you want greater assurance that your work will get done, you use a service to manage that work.

Body:
Can someone help me understand how to use Android Service or IntentService correctly.  The documentation seems to contradict itself here:

    Caution: A service runs in the same process as the application in which it is
declared and in the main thread of that application by default. If your service
performs intensive or blocking operations while the user interacts with an
activity from the same application, the service slows down activity performance.
To avoid impacting application performance, start a new thread inside the service.

and here

public class HelloIntentService extends IntentService {

  /**
   * A constructor is required, and must call the super IntentService(String)
   * constructor with a name for the worker thread.
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }

  /**
   * The IntentService calls this method from the default worker thread with
   * the intent that started the service. When this method returns, IntentService
   * stops the service, as appropriate.
   */
  @Override
  protected void onHandleIntent(Intent intent) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      try {
          Thread.sleep(5000);
      } catch (InterruptedException e) {
          // Restore interrupt status.
          Thread.currentThread().interrupt();
      }
  }
}

Given the whole purpose of the Service or ServiceIntent is to run long running jobs in the background without affecting the UI why then does the example code do exactly what the Caution indicated you should not do - and I am assuming a call to Thread.sleep() will cause the main thread to block.

Am I correct in the following understanding:

The service itself still runs on the main application thread but has no UI component (Activity) and will continue running even if the application is not used by the user, unlike an Activity which will not

Any long running background work must still create a separate thread to avoid blocking the main application thread

AsyncTask is associated with an Activity which presumably will stop running if the application is no longer the active application (i.e. if the user switches to another application) which is why one would use Service or ServiceIntent if the task needs to keep running.

IntentService will run the task on a separate thread to the main thread so there is no need to worry about blocking the main thread with long tasks or when calling Thread.sleep().

Have I misunderstood something with the description of Android Service or ServiceIntents?


问:
GLSL Compiler choosing wrong overloaded function?
I am trying to compute the surface normal for a height map in GLSL.  I basically copied the code from a SO answer here with minor changes to match my vars:

```<code>77:                 float s01 = textureOffset(uTexture, uv, off.xy).x;
78:                 float s21 = textureOffset(uTexture, uv, off.zy).x;
79:                 float s10 = textureOffset(uTexture, uv, off.yx).x;
80:                 float s12 = textureOffset(uTexture, uv, off.yz).x;
81:                 vec3 va = normalize(vec3(size.xy, s21-s01));
82:                 vec3 vb = normalize(vec3(size.yx, s12-s10));
83:                 vec3 vNormal = cross(va,vb);
</code>```

where

```<code>uniform sampler2D   uTexture;
attribute vec2      uv;
const vec2          size = vec2(2.0, 0.0);
const ivec3         off = ivec3(-1, 0, 1);
</code>```

The problem is that the compiler returns the errors:

```<code>THREE.WebGLProgram: shader error:  0 gl.VALIDATE_STATUS false gl.getProgramInfoLog invalid shaders ERROR: 0:77: 'textureOffset' : no matching overloaded function found
ERROR: 0:77: 'x' :  field selection requires structure or vector on left hand side
ERROR: 0:78: 'textureOffset' : no matching overloaded function found
ERROR: 0:78: 'x' :  field selection requires structure or vector on left hand side
ERROR: 0:79: 'textureOffset' : no matching overloaded function found
ERROR: 0:79: 'x' :  field selection requires structure or vector on left hand side
ERROR: 0:80: 'textureOffset' : no matching overloaded function found
ERROR: 0:80: 'x' :  field selection requires structure or vector on left hand side
</code>```

The compiler is apparently choosing the wrong overload of textureOffset, but looking at the spec here, it looks like it should work fine. So... what am I missing?  I'm still researching, but any tips for a GLSL newbie would be appreciated. TIA.

Note: This is on OSX with three.js r85

答:
Looking at the spec for webgl 1.0 shaders are explicitly restricted to the shader glsl spec Es 1.0 which doesn't include textureOffset.

WebGL 2.0 can use ES 3.0 shaders which do include textureOffset.

I.e. The restriction you are hitting is mandated by the Webgl 1.0 spec, rather than a browser/three.js/platform fault.

Body:
I am trying to compute the surface normal for a height map in GLSL.  I basically copied the code from a SO answer here with minor changes to match my vars:

77:                 float s01 = textureOffset(uTexture, uv, off.xy).x;
78:                 float s21 = textureOffset(uTexture, uv, off.zy).x;
79:                 float s10 = textureOffset(uTexture, uv, off.yx).x;
80:                 float s12 = textureOffset(uTexture, uv, off.yz).x;
81:                 vec3 va = normalize(vec3(size.xy, s21-s01));
82:                 vec3 vb = normalize(vec3(size.yx, s12-s10));
83:                 vec3 vNormal = cross(va,vb);

where

uniform sampler2D   uTexture;
attribute vec2      uv;
const vec2          size = vec2(2.0, 0.0);
const ivec3         off = ivec3(-1, 0, 1);

The problem is that the compiler returns the errors:

THREE.WebGLProgram: shader error:  0 gl.VALIDATE_STATUS false gl.getProgramInfoLog invalid shaders ERROR: 0:77: 'textureOffset' : no matching overloaded function found
ERROR: 0:77: 'x' :  field selection requires structure or vector on left hand side
ERROR: 0:78: 'textureOffset' : no matching overloaded function found
ERROR: 0:78: 'x' :  field selection requires structure or vector on left hand side
ERROR: 0:79: 'textureOffset' : no matching overloaded function found
ERROR: 0:79: 'x' :  field selection requires structure or vector on left hand side
ERROR: 0:80: 'textureOffset' : no matching overloaded function found
ERROR: 0:80: 'x' :  field selection requires structure or vector on left hand side

The compiler is apparently choosing the wrong overload of textureOffset, but looking at the spec here, it looks like it should work fine. So... what am I missing?  I'm still researching, but any tips for a GLSL newbie would be appreciated. TIA.

Note: This is on OSX with three.js r85


答:
<?php and ?> tags indicate to the PHP preprocessor that anything inside them is code and needs to be parsed, everything outside is just text PHP doesn't touch.

Inside the <?php tag, "<?php" string has no special meaning, so is printed. You do not need to open and close tags all the time, try this:

```<code></head>
<body>
    <?php
        $linkName = "Second Page";
        $id = 5;

        for ($i = 0; $i < 10 ; $i++) {
            echo "<a href='secondPage.php?id=$i;'>Link1</a>";
        };
    ?>
</body>
</code>```

Body:
<?php and ?> tags indicate to the PHP preprocessor that anything inside them is code and needs to be parsed, everything outside is just text PHP doesn't touch.

Inside the <?php tag, "<?php" string has no special meaning, so is printed. You do not need to open and close tags all the time, try this:

</head>
<body>
    <?php
        $linkName = "Second Page";
        $id = 5;

        for ($i = 0; $i < 10 ; $i++) {
            echo "<a href='secondPage.php?id=$i;'>Link1</a>";
        };
    ?>
</body>


问:
Error with on click event in wxpython
I want to collect input from the user in test box. So when I click a button it should give me name of that button in test box
Error: you should omit either rows of column</p>

```<code>   for i in A:

        hbox1=wx.BoxSizer(wx.HORIZONTAL)

        btn = wx.Button(p, -1, i, (10,20))

        btn.myname = I

        gs.Add(btn,0,)

        self.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        self.t1=wx.TextCtrl(p)

        gs.Add(btn,0,)

        self.t1.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        gs.Add(hbox1)

    p.SetSizer(gs)

def OnClick(self, event):  #When the button is clicked

    name = event.GetEventObject().myname
</code>```

答: Use wx.TextCtrl: self.t1=wx.TextCtrl(p)

Title: Error with on click event in wxpython

Body:
I want to collect input from the user in test box. So when I click a button it should give me name of that button in test box
Error: you should omit either rows of column

   for i in A:

        hbox1=wx.BoxSizer(wx.HORIZONTAL)

        btn = wx.Button(p, -1, i, (10,20))

        btn.myname = I

        gs.Add(btn,0,)

        self.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        self.t1=wx.TextCtrl(p)

        gs.Add(btn,0,)

        self.t1.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        gs.Add(hbox1)

    p.SetSizer(gs)

def OnClick(self, event):  #When the button is clicked

    name = event.GetEventObject().myname

Body: Use wx.TextCtrl: self.t1=wx.TextCtrl(p)


问:
What is Cyclomatic Complexity?
A term that I see every now and then is "Cyclomatic Complexity". Here on SO I saw some Questions about "how to calculate the CC of Language X" or "How do I do Y with the minimum amount of CC", but I'm not sure I really understand what it is.

On the NDepend Website, I saw an explanation that basically says "The number of decisions in a method. Each if, for, && etc. adds +1 to the CC "score"). Is that really it? If yes, why is this bad? I can see that one might want to keep the number of if-statements fairly low to keep the code easy to understand, but is this really everything to it?

Or is there some deeper concept to it?

答: Cyclomatic complexity is computed using the control flow graph. The Number of quantitative measure of linearly independent paths through a program's source code is called as Cyclomatic Complexity ( if/ if else / for / while )</p>

Title: What is Cyclomatic Complexity?


答:
You can produce a random number between 0 and 99, and check if it's less than 15:

```<code>if (rnd.Next(100) < 15) ...
</code>```

You can also reduce the numbers, as 15/100 is the same as 3/20:

```<code>if (rnd.Next(20) < 3) ...
</code>```

Title: How to compute the "15% of the time" randomness?

Body:
I'm looking for a decent, elegant method of calculating this simple logic.

Right now I can't think of one, it's spinning my head.

I am required to do some action only 15% of the time.

I'm used to "50% of the time" where I just mod the milliseconds of the current time and see if it's odd or even, but I don't think that's elegant.

How would I elegantly calculate "15% of the time"?  Random number generator maybe?

Pseudo-code or any language are welcome.

Hope this is not subjective, since I'm looking for the "smartest" short-hand method of doing that.

Thanks.

Body:
You can produce a random number between 0 and 99, and check if it's less than 15:

if (rnd.Next(100) < 15) ...

You can also reduce the numbers, as 15/100 is the same as 3/20:

if (rnd.Next(20) < 3) ...


问:
Syntax for accessing nested array elements in PHP double quotes string
I'm attempting to access a nested array element within a double quotes string, like this:

```<code>"$variable[first_index][second_index]";
</code>```

This is throwing an Array to string conversion notice and halting my script.

Is there a correct syntax for accessing the data within a string in this manner, or do I need to set a temp variable to reference the required data, and then use THAT in the string?

答:
Use this syntax:

```<code>$string = "Value is {$variable["first_index"]["second_index"]}";
</code>```

It's called complex extended variable syntax and it's very useful. You can access fields of an object inside string in double quotes, as well as nested array.

Body:
I'm attempting to access a nested array element within a double quotes string, like this:

"$variable[first_index][second_index]";

This is throwing an Array to string conversion notice and halting my script.

Is there a correct syntax for accessing the data within a string in this manner, or do I need to set a temp variable to reference the required data, and then use THAT in the string?

Body:
Use this syntax:

$string = "Value is {$variable["first_index"]["second_index"]}";

It's called complex extended variable syntax and it's very useful. You can access fields of an object inside string in double quotes, as well as nested array.