问:
Doing multiple pull requests on github
When I open a pull request on GitHub, all commits since my last request and all new ones are automatically added to this request. I can't seem to control which commits are added and which are not.

I did the following:

Made a fork of repository

Made a branch called patch and bugs

git checkout patch

Made a file change

git commit -m "Made a commit"

git push origin patch

Made the pull request on GitHub from patch

git checkout bugs

Made a file change

git commit -m "Fixed a Bug"

git push origin bugs

looked at pull request and both commits are present.. I didn't want that. What am I doing wrong? I figured both commits on different branches. I am confused.

答:
Summary

You need to be careful about branch starting points, and the resulting commit graphs.

Description

In Git, commits can be, and very often are, on more than one branch at a time.  If you are coming from some other version control systems, this can be quite startling.  For instance, in Mercurial—which is otherwise very similar to Git in many ways—every commit is on exactly one branch.  In Git, however, each commit is on zero or more branches simultaneously.

The implications of this reach rather far, but the most immediate one for you is that when you make pull requests on GitHub, GitHub's Git manipulations do things you did not expect.  (GitHub—which I have used rather a bit more lately—seems to attempt to hide many of Git's intricacies from users.  This has its advantages, since Git's complexity can be intimidating.  But it has disadvantages, such as leading you down this particular path.)

I will try to avoid going into too much detail here (difficult for me :-) ).  The key to understanding all of this lies in visualizing the commit graph and knowing what, at a sort of fundamental level, a pull request is.

The commit graph

The graph, which is formally a Directed Acyclic Graph or DAG, is formed by the commits you and others make.  Each commit generally has one parent commit.  These parents form a backwards chain.  If we start with a completely empty repository (no commits at all) and make a first commit, that commit has no parent, because there's no earlier commit:

```<code>A
</code>```

(I'm giving the commits one-letter names here instead of Git's incomprehensible hash IDs).  When we make the second commit, it has the first commit as its parent.  We say that the new commit B "points to" existing commit A:

```<code>A <-B
</code>```

This continues on for as many commits as we make: each new one points to some earlier one.  For simple linear chains this is all pretty straightforward, and all we have to do here is add the fact that Git needs a name it can use to find the last commit.  The name we all start out with is master:

```<code>A <-B <-C   <-- master
</code>```

All of Git's arrows are always backwards.  The ones coming from branch names move around—in fact, master, or whatever branch we are on, gets updated automatically as we add each new commit—so I think it's wise to keep drawing them; but the arrows that tell us that commit C points to B, and B points to A, are fixed forever.  It's easier to draw these without the arrows, so that's what I do.

Now let's make a new branch name, with something that has lots of commits:

```<code>...--F--G--H   <-- master, patch
</code>```

What we have now is two branch names, both pointing to the same commit!  Commit H is on both branches.  So are commits G and F and all the earlier ones.  Now it becomes important to know which branch we're actually on, so let's add (HEAD) to one of these:

```<code>...--F--G--H   <-- master, patch (HEAD)
</code>```

Aha, we're on branch HEAD.  Let's add a new commit I now:

```<code>...--F--G--H   <-- master
            \
             I   <-- patch (HEAD)
</code>```

What Git does is the same as always: it makes the new commit with one parent, so that I points to H, and then it moves the current branch—i.e., patch, as indicated by HEAD—so that it points to the new commit.

The master branch does not change at all: it still contains commits A through H inclusive.  The patch branch now contains commits A through I inclusive.

Let's make another new branch now, such as bugs.  But where will the name bugs point?  We have two pretty good options: we can point the name at either commit H, where master points now, or we can point it at commit I, where patch points now.

Whichever one we choose, we can now make a new commit J.  But J's parent will be determined by which commit bugs points to once we create bugs!  So it's pretty important which one we choose.

When you made your first commit, you chose I, and got this kind of picture:

```<code>...--F--G--H   <-- master
            \
             I   <-- patch
              \
               J   <-- bugs (HEAD)
</code>```

If you choose H as the starting point, however, you'll get this other picture:

```<code>             J   <-- bugs (HEAD)
            /
...--F--G--H   <-- master
            \
             I   <-- patch
</code>```

Pull requests

A pull request is always, necessarily, done with respect to some existing starting-point.  If you use the old-school, pure-Git command, git request-pull, you supply the starting point.  What GitHub does with their clicky buttons is automate the starting point selection for you.  But there is a catch: the starting point must be a commit that both you and your upstream repository already share.  (Your upstream, in this particular context, is the repository you forked.  The word upstream is a bit ambiguous here: like much of Git's terminology, the word has been overloaded to mean many different things.)

In short, the upstream commit is always going to be whatever their master points to now, or at least, pointed-to earlier (their own master may have moved forward since you forked things).  That's going to wind up being commit H in our drawings above.

If your graph topology resembles the first one—commit J points back to I which points back to H—then a pull request from that point will include both commits.  It does not matter that I is on several branches in your repository; what matters is that commit H is the latest one that you and the upstream repository are both using.  (Again, each of these one-letter names stands in for an actual raw Git hash ID, such as commit 1f931caf22b7... or whatever.)

To get just the one J commit to be in your pull request, you need your graph topology to resemble the second one, where H is J's parent.  The GitHub interface seems—to me at least, though I still have relatively little experience with it—to be very good at hiding the graph topology from you, and thus very bad at letting you view the actual topology and hence see what will really happen with a pull request.

When you use command-line Git, you can view (visualize) the topology with the help of "A DOG", all decorate oneline graph:

```<code>git log --all --decorate --oneline --graph
</code>```

Various GUIs will also do this for you, e.g., gitk --all.  This draws the graph vertically, rather than horizontally as I do in these StackOverflow postings, but the idea should be clear enough at this point.

Title: Doing multiple pull requests on github

Body:
Summary

You need to be careful about branch starting points, and the resulting commit graphs.

Description

In Git, commits can be, and very often are, on more than one branch at a time.  If you are coming from some other version control systems, this can be quite startling.  For instance, in Mercurial—which is otherwise very similar to Git in many ways—every commit is on exactly one branch.  In Git, however, each commit is on zero or more branches simultaneously.

The implications of this reach rather far, but the most immediate one for you is that when you make pull requests on GitHub, GitHub's Git manipulations do things you did not expect.  (GitHub—which I have used rather a bit more lately—seems to attempt to hide many of Git's intricacies from users.  This has its advantages, since Git's complexity can be intimidating.  But it has disadvantages, such as leading you down this particular path.)

I will try to avoid going into too much detail here (difficult for me :-) ).  The key to understanding all of this lies in visualizing the commit graph and knowing what, at a sort of fundamental level, a pull request is.

The commit graph

The graph, which is formally a Directed Acyclic Graph or DAG, is formed by the commits you and others make.  Each commit generally has one parent commit.  These parents form a backwards chain.  If we start with a completely empty repository (no commits at all) and make a first commit, that commit has no parent, because there's no earlier commit:

A

(I'm giving the commits one-letter names here instead of Git's incomprehensible hash IDs).  When we make the second commit, it has the first commit as its parent.  We say that the new commit B "points to" existing commit A:

A <-B

This continues on for as many commits as we make: each new one points to some earlier one.  For simple linear chains this is all pretty straightforward, and all we have to do here is add the fact that Git needs a name it can use to find the last commit.  The name we all start out with is master:

A <-B <-C   <-- master

All of Git's arrows are always backwards.  The ones coming from branch names move around—in fact, master, or whatever branch we are on, gets updated automatically as we add each new commit—so I think it's wise to keep drawing them; but the arrows that tell us that commit C points to B, and B points to A, are fixed forever.  It's easier to draw these without the arrows, so that's what I do.

Now let's make a new branch name, with something that has lots of commits:

...--F--G--H   <-- master, patch

What we have now is two branch names, both pointing to the same commit!  Commit H is on both branches.  So are commits G and F and all the earlier ones.  Now it becomes important to know which branch we're actually on, so let's add (HEAD) to one of these:

...--F--G--H   <-- master, patch (HEAD)

Aha, we're on branch HEAD.  Let's add a new commit I now:

...--F--G--H   <-- master
            \
             I   <-- patch (HEAD)

What Git does is the same as always: it makes the new commit with one parent, so that I points to H, and then it moves the current branch—i.e., patch, as indicated by HEAD—so that it points to the new commit.

The master branch does not change at all: it still contains commits A through H inclusive.  The patch branch now contains commits A through I inclusive.

Let's make another new branch now, such as bugs.  But where will the name bugs point?  We have two pretty good options: we can point the name at either commit H, where master points now, or we can point it at commit I, where patch points now.

Whichever one we choose, we can now make a new commit J.  But J's parent will be determined by which commit bugs points to once we create bugs!  So it's pretty important which one we choose.

When you made your first commit, you chose I, and got this kind of picture:

...--F--G--H   <-- master
            \
             I   <-- patch
              \
               J   <-- bugs (HEAD)

If you choose H as the starting point, however, you'll get this other picture:

             J   <-- bugs (HEAD)
            /
...--F--G--H   <-- master
            \
             I   <-- patch

Pull requests

A pull request is always, necessarily, done with respect to some existing starting-point.  If you use the old-school, pure-Git command, git request-pull, you supply the starting point.  What GitHub does with their clicky buttons is automate the starting point selection for you.  But there is a catch: the starting point must be a commit that both you and your upstream repository already share.  (Your upstream, in this particular context, is the repository you forked.  The word upstream is a bit ambiguous here: like much of Git's terminology, the word has been overloaded to mean many different things.)

In short, the upstream commit is always going to be whatever their master points to now, or at least, pointed-to earlier (their own master may have moved forward since you forked things).  That's going to wind up being commit H in our drawings above.

If your graph topology resembles the first one—commit J points back to I which points back to H—then a pull request from that point will include both commits.  It does not matter that I is on several branches in your repository; what matters is that commit H is the latest one that you and the upstream repository are both using.  (Again, each of these one-letter names stands in for an actual raw Git hash ID, such as commit 1f931caf22b7... or whatever.)

To get just the one J commit to be in your pull request, you need your graph topology to resemble the second one, where H is J's parent.  The GitHub interface seems—to me at least, though I still have relatively little experience with it—to be very good at hiding the graph topology from you, and thus very bad at letting you view the actual topology and hence see what will really happen with a pull request.

When you use command-line Git, you can view (visualize) the topology with the help of "A DOG", all decorate oneline graph:

git log --all --decorate --oneline --graph

Various GUIs will also do this for you, e.g., gitk --all.  This draws the graph vertically, rather than horizontally as I do in these StackOverflow postings, but the idea should be clear enough at this point.


来源: stackexchange

问:
Bind class based on knockout foreach index
I need to make the first item in a tab group, active. I am attempting to use the index for the foreach, and set the class based on that.

```<code>    <ul class="nav nav-tabs" data-bind="foreach: TemplateGroups">
        <li data-bind="css: {active: $index==0}"><a data-toggle="tab" href="#tb1"><span data-bind="text: Description"></span></a></li>
    </ul>
</code>```

However, the item isn't becoming active. What am I missing?

答:
From Binding context

$index is an observable and is updated whenever the index of the item changes

And an observable is a function.

Then, you are comparing a function with a number, and always is false.

You should use active: $index() == 0 or $index() === 0.

Example: Codepen

ContentLicense: CC BY-SA 3.0

Body:
I need to make the first item in a tab group, active. I am attempting to use the index for the foreach, and set the class based on that.

However, the item isn't becoming active. What am I missing?


问:
Is there a graph algorithm to find shortest path between nodes, incorporating nodes to avoid?
Let's say I have a graph with nodes that represent locations. Starting at some node N, I want to reach another node M via the shortest path possible. The catch is that there some nodes I want to avoid, staying some distance from them (say at least D nodes away).

Is there a graph algorithm that can solve the shortest path problem with the node avoidance requirement? Would a weighted graph (with infinite length edges emanating from the to-be-avoided nodes) be a solution here?

答: Temporarily eliminate the nodes you must avoid and those near them or change the weights of the appropriate edges to infinity. Then use any standard path-finding algorithm. </p>


问:
Understanding React Native Perf Monitor
What is JSC in the Perf Monitor and what does it represent? Also, what are the two levels of Views in Perf Monitor?</p>

答:
The JSC column represents the size of the JavaScriptCore managed heap -- how your app is allocating JS objects.

The two levels of the Views column is for Views that are on-screen, versus views that are off-screen or merged. You want to try to get those numbers to be as close as possible to avoid unnecessary layout calculation and processing.

Title: Understanding React Native Perf Monitor


问:
hide laravel application from wappalyzer extension
I am trying to hide laravel application from wappalyzer extension, already i changed my session name and clear cache but still wappalyzer can detect laravel application.</p>

答:
In the config/session.php, try changing:

'cookie' => 'laravel_session',

To something like:

'cookie' => 'app_name_session',


问:
Container doesn't grow with (kwicks plugin) content
I'm having an issue on the bottom of http://xweasel.chris-cole.de/v3/index.php with a container that doesn't fully grow in height with its content.

The cause seems to be a list, formatted by a plugin named kwicks.

It seems as if the list is floating and the floating is not cleared, or as if list is positioned absolute, but it's relative.

```<code><div class="full-wrapper">
  <div class="inner-wrapper" style="background: #0f0;">

    <section>
      <div class="message numbers">
        <h2>xWeasel in numbers</h2>
      </div>

      <ul class='kwicks kwicks-horizontal kwicks-processed'>
        <li>
        </li>...
      </ul>
    </section>

  </div>
</div>
</code>```

.inner-wrapper grows with .message.numbers but not with .kwicks.

```<code>.kwicks{
  display:block;
  list-style-type:none;
  list-style:none;
  position:relative;
  margin:0;
  padding:0
}
.kwicks>*{
  display:block;
  overflow:hidden;
  padding:0;
  margin:0
}
.kwicks.kwicks-processed>*{
  margin:0;
  position:absolute
}
.kwicks-horizontal>*{
  float:left
}
.kwicks-horizontal>:first-child{
  margin-left:0
}
.kwicks-vertical>:first-child{
  margin-top:0
}
</code>```

答:
This is the ul element which doesn't "grow" with its content.

Try to set a height on it... Like 100px.

;)

Body:
I'm having an issue on the bottom of http://xweasel.chris-cole.de/v3/index.php with a container that doesn't fully grow in height with its content.

The cause seems to be a list, formatted by a plugin named kwicks.

It seems as if the list is floating and the floating is not cleared, or as if list is positioned absolute, but it's relative.

xWeasel in numbers

...

.inner-wrapper grows with .message.numbers but not with .kwicks.

.kwicks{
  display:block;
  list-style-type:none;
  list-style:none;
  position:relative;
  margin:0;
  padding:0
}
.kwicks>*{
  display:block;
  overflow:hidden;
  padding:0;
  margin:0
}
.kwicks.kwicks-processed>*{
  margin:0;
  position:absolute
}
.kwicks-horizontal>*{
  float:left
}
.kwicks-horizontal>:first-child{
  margin-left:0
}
.kwicks-vertical>:first-child{
  margin-top:0
}


问:
PHP accented characters in POST submit
I have a HTML form on submit.php, the page is encoded as UTF-8 (using a meta tag), when the form is submitted to process.php (via POST), some of the variables are stored in the session, and the page uses Header: Location to go back to submit.php, which then uses the session variables to redisplay some of the entered information.

If I enter an accented character, for example é (&eacute), when the page returns to submit.php, it does not render the character correctly, I get an ã (&atilde) and an © (&copy) instead.

Where should I be looking to solve this problem? I'm assuming it's server side, as the rendered page is always UTF-8 (the browser confirms the page is UTF-8 before and after submitting)

Solution:

The string was being passed through htmlentities() at one point, which it turns out has a default character encoding of ISO-8859-1 The answer was to simply specify 'UTF-8' in the function call.

答:
```<code>$_SESSION['thestring'] = $_POST['thestring']
</code>```

Cannot reasonably be the problem source. Here PHP is just copying the two bytes verbatim. No charset conversion is going to occour here. Hence any conversion likely happened before or thereafter.

To make sure $_POST isn't the cultprit, check that your <form> contains the accept-charset="UTF-8". That's often overlooked. Second, for testing purposes output the $_POST["thestring"] right on receival. If the problem arises here, you'll need Firebug and xdebug..

It's very unlikely that the session store or PHP modify the string contents in $_SESSION. That's why I would presume the bug to be in the output page after all. Make a separate test page, and print $_SESSION["thestring"] there. Don't overlook the header("Content-Type: text/html; charset=utf-8"); for it.

Title: PHP accented characters in POST submit

Body:
$_SESSION['thestring'] = $_POST['thestring']

Cannot reasonably be the problem source. Here PHP is just copying the two bytes verbatim. No charset conversion is going to occour here. Hence any conversion likely happened before or thereafter.

To make sure $_POST isn't the cultprit, check that your <form> contains the accept-charset="UTF-8". That's often overlooked. Second, for testing purposes output the $_POST["thestring"] right on receival. If the problem arises here, you'll need Firebug and xdebug..

It's very unlikely that the session store or PHP modify the string contents in $_SESSION. That's why I would presume the bug to be in the output page after all. Make a separate test page, and print $_SESSION["thestring"] there. Don't overlook the header("Content-Type: text/html; charset=utf-8"); for it.

ContentLicense: CC BY-SA 2.5


问:
Sending reliable HTTP request with Arduino Wifi Client
When a sensor on my Arduino MKR1000 is triggered, I send an email:

```<code>//....
WiFiClient client;
char server[] = "www.myserver.com";
//....

void setup() {
//... Connect to wifi ....
}

void loop() {
    // when sensor triggered =>
    if (client.connect(server, 80)) {
        Serial.println("Sending email");
        client.print("GET /WaterOff/sendGridCall.php");
        client.print("?valve=");
        client.print(valve);
        client.print("&position=");
        client.print(position);
        client.println(" HTTP/1.1");
        client.print("Host: ");
        client.println(server);
        client.println("User-Agent: Arduino");
        client.println("Connection: close");
        client.println();
    }

    delay(6000);
}
</code>```

However, it only works the first couple of times ("Sending email" is printed) and after that it does not execute the request ("Sending email" is not printed). Am I supposed to take some additional steps to make it reliable.

答:
You never close the connection. But blocking to wait for email confirmation can take forever. You should consider a small state machine for your network connection to work.

```<code>void loop()
{
    // when sensor triggered =>
    if (client.connect(server, 80)) {      // You connect to client, but it's already
                                           // connected the second time around
        // send ...
        // client() should wait for response, and client.disconnect()
    }

    // ...
    delay(6000);      // tip: avoid blocking the main loop, this blocks your ability to
                      // read your sensor while sending emails.
}
</code>```

A state machine for your app could look like this:

```<code>enum EmailState {
    emIdle, emSendMail, emCheckMailSent, emEmailOK, emEmailError,
};

EmailState email_state;
unsigned long long mail_timer;      // can be shared between states.

// small state handlers that do a bit at a time,
// check for an event, wait on some delay (use millis())
// avoid blocking the instruction flow as much as possible.

static void on_emIdle()
{
  // read sensor, check timer?
  email_state = (triggered) ? emSendMail : emIdle;
}

static void on_sendMail()
{
    if (client.connect())
    {
        // ... prints
        email_state = emCheckMailSent;
        return;
    }
    email_state = emEmailError;
}

static void on_emCheckMailSent()
{
   // receive HTTP response...  can have a long timeout without blocking.
   email_state = emCheckMailSent;
     // or emEmailOK or emEmailError or retry emSendMail
}

static void on_emEmailOK()
{
   if (/*client is connected?*/)
       client.disconnect();

   if (!mail_timer)
       mail_timer = millis();

   if (millis() - mail_timer < 6000)  // stay in this state for 6 seconds...
   {
       email_state = emEmailOK;
       return;
    }

    mail_timer = 0;        // always reset the timer so it can be used by other states
    email_state = emIdle;
}

static void on_emEmailError()
{
   if (/*client is connected?*/)
       client.disconnect();
   // keep a log ?
   email_state = emIdle; // or another timer
}

//...
void loop()
{
   // update readings, manage other things...
   // ...
   switch(email_state)
   {
   default:
   case emIdle:           on_emIdle();          break;
   case emSendMail:       on_emSendMail();      break;
   case emCheckMailSent:  on_emCheckMailSent(); break;
   case emEmailOK:        on_emEmailOK();       break;
   case emEmailError:     on_emEmailError();    break;
   }
}
</code>```

Body:
When a sensor on my Arduino MKR1000 is triggered, I send an email:

//....
WiFiClient client;
char server[] = "www.myserver.com";
//....

void setup() {
//... Connect to wifi ....
}

void loop() {
    // when sensor triggered =>
    if (client.connect(server, 80)) {
        Serial.println("Sending email");
        client.print("GET /WaterOff/sendGridCall.php");
        client.print("?valve=");
        client.print(valve);
        client.print("&position=");
        client.print(position);
        client.println(" HTTP/1.1");
        client.print("Host: ");
        client.println(server);
        client.println("User-Agent: Arduino");
        client.println("Connection: close");
        client.println();
    }

    delay(6000);
}

However, it only works the first couple of times ("Sending email" is printed) and after that it does not execute the request ("Sending email" is not printed). Am I supposed to take some additional steps to make it reliable.

Body:
You never close the connection. But blocking to wait for email confirmation can take forever. You should consider a small state machine for your network connection to work.

void loop()
{
    // when sensor triggered =>
    if (client.connect(server, 80)) {      // You connect to client, but it's already
                                           // connected the second time around
        // send ...
        // client() should wait for response, and client.disconnect()
    }

    // ...
    delay(6000);      // tip: avoid blocking the main loop, this blocks your ability to
                      // read your sensor while sending emails.
}

A state machine for your app could look like this:

enum EmailState {
    emIdle, emSendMail, emCheckMailSent, emEmailOK, emEmailError,
};

EmailState email_state;
unsigned long long mail_timer;      // can be shared between states.

// small state handlers that do a bit at a time,
// check for an event, wait on some delay (use millis())
// avoid blocking the instruction flow as much as possible.

static void on_emIdle()
{
  // read sensor, check timer?
  email_state = (triggered) ? emSendMail : emIdle;
}

static void on_sendMail()
{
    if (client.connect())
    {
        // ... prints
        email_state = emCheckMailSent;
        return;
    }
    email_state = emEmailError;
}

static void on_emCheckMailSent()
{
   // receive HTTP response...  can have a long timeout without blocking.
   email_state = emCheckMailSent;
     // or emEmailOK or emEmailError or retry emSendMail
}

static void on_emEmailOK()
{
   if (/*client is connected?*/)
       client.disconnect();

   if (!mail_timer)
       mail_timer = millis();

   if (millis() - mail_timer < 6000)  // stay in this state for 6 seconds...
   {
       email_state = emEmailOK;
       return;
    }

    mail_timer = 0;        // always reset the timer so it can be used by other states
    email_state = emIdle;
}

static void on_emEmailError()
{
   if (/*client is connected?*/)
       client.disconnect();
   // keep a log ?
   email_state = emIdle; // or another timer
}

//...
void loop()
{
   // update readings, manage other things...
   // ...
   switch(email_state)
   {
   default:
   case emIdle:           on_emIdle();          break;
   case emSendMail:       on_emSendMail();      break;
   case emCheckMailSent:  on_emCheckMailSent(); break;
   case emEmailOK:        on_emEmailOK();       break;
   case emEmailError:     on_emEmailError();    break;
   }
}


问:
Lua - Most resource efficient way to compare a variable to a fixed list of values
So I have a variable, let's call it 'ID'. I need to check this value relative to a fixed amount of values. The ID, of course, can only match one of the values so there isn't an issue with stopping on the first matching value as none of the others would match. There is also a chance that the variable does not match any of the given values, too. My question is then, what is the most resource efficient way to do this? I can think of two easy ways of tackling the problem. Since I know the values at the time of programming I can setup a conditional with 'or' that just checks each value, like so:

```<code>if (ID == "1" or ID == "16" or ID == "58") then
    --do something--
end
</code>```

The problem with this is that it's quite verbose and tedious to write. The other option involves a foreach loop where I define a table beforehand.

```<code>values = {"1", "16", "58"}
for _, value in ipairs(values) do
    if(ID == value) then
        return true
    end
end
</code>```

The upside to this is it's reusable which is good since I'll need to do this exact check with a different set of values at least 10 times, the downside is I suspect it takes more resources.

Any help would be greatly appreciated.

答:
Tables can be used as sets:

```<code>interesting = {
   ["1"] = true, ["16"] = true, ["58"] = true
}

if interesting[ID] then
   -- ...
end
</code>```

While it eats more memory (80 bytes per empty table plus 32 bytes (IIRC, on x86_64) per entry (while rounding the number of entries up to the next power of two) vs. 16 bytes per comparison plus storage for the value that you compare) the chain of comparisons happens in C and is therefore faster than a chain of comparisons as a sequence of Lua instructions (at least once things get larger).

For small numbers of values, this doesn't really matter.  (If you are CPU-bound and this is very important in your case, measure in the context of your program and see what performs better.  Don't put too much weight on micro-benchmarks with this – cache behavior in particular might produce funny effects here.)

For large numbers of comparisons, this is the right approach.  It's also more flexible than if-then-else chains.  (You can change things at runtime without reloading code.)

Also note that the value you use to anchor an element in the set doesn't really matter, so a relatively common idiom (especially for input handling) is putting the action as a function into the table:

```<code>keybindings = {
   left = function()  Player:move_left( )  end,
   right = function()  Player:move_right( )  end,
   up = function()  Player:jump( )  end,
   -- ...
}

function onKey( k )
   local action = keybindings[k]
   if action then  action( )  end
end
</code>```

While this certainly is slower than a direct comparison and inline code, speed is essentially irrelevant here (generally happens much less often than ~100x per second) and flexibility is of high value.

Body:
So I have a variable, let's call it 'ID'. I need to check this value relative to a fixed amount of values. The ID, of course, can only match one of the values so there isn't an issue with stopping on the first matching value as none of the others would match. There is also a chance that the variable does not match any of the given values, too. My question is then, what is the most resource efficient way to do this? I can think of two easy ways of tackling the problem. Since I know the values at the time of programming I can setup a conditional with 'or' that just checks each value, like so:

if (ID == "1" or ID == "16" or ID == "58") then
    --do something--
end

The problem with this is that it's quite verbose and tedious to write. The other option involves a foreach loop where I define a table beforehand.

values = {"1", "16", "58"}
for _, value in ipairs(values) do
    if(ID == value) then
        return true
    end
end

The upside to this is it's reusable which is good since I'll need to do this exact check with a different set of values at least 10 times, the downside is I suspect it takes more resources.

Any help would be greatly appreciated.

Body:
Tables can be used as sets:

interesting = {
   ["1"] = true, ["16"] = true, ["58"] = true
}

if interesting[ID] then
   -- ...
end

While it eats more memory (80 bytes per empty table plus 32 bytes (IIRC, on x86_64) per entry (while rounding the number of entries up to the next power of two) vs. 16 bytes per comparison plus storage for the value that you compare) the chain of comparisons happens in C and is therefore faster than a chain of comparisons as a sequence of Lua instructions (at least once things get larger).

For small numbers of values, this doesn't really matter.  (If you are CPU-bound and this is very important in your case, measure in the context of your program and see what performs better.  Don't put too much weight on micro-benchmarks with this – cache behavior in particular might produce funny effects here.)

For large numbers of comparisons, this is the right approach.  It's also more flexible than if-then-else chains.  (You can change things at runtime without reloading code.)

Also note that the value you use to anchor an element in the set doesn't really matter, so a relatively common idiom (especially for input handling) is putting the action as a function into the table:

keybindings = {
   left = function()  Player:move_left( )  end,
   right = function()  Player:move_right( )  end,
   up = function()  Player:jump( )  end,
   -- ...
}

function onKey( k )
   local action = keybindings[k]
   if action then  action( )  end
end

While this certainly is slower than a direct comparison and inline code, speed is essentially irrelevant here (generally happens much less often than ~100x per second) and flexibility is of high value.


问:
antlr4 grammar with negative option
In antlr4 I want to define a string but exclude from it the combination := permitting the respective single characters. What is syntax to define the grammar</p>

```<code>EQUAL : '=';
NUMBER: DIGIT+;
DIGIT   :   ('0'..'9');
LITERALEQUAL: ((CHAR | NUMBER | EQUAL | OTHERS) ' '?)+;
fragment CHAR   :[a-z]| [A-Z];
fragment OTHERS:  '.' | '/' | ':' | '-' | '#' | '?' | '&' | '_' | '[' | ']' | '^' | ';' | '"' | '=';
</code>```

答:
As  long as you don't make a lexer rule or implicit token like:

```<code>stmt : value ':=' something ;  <-- implicit token
</code>```

or

```<code>BADEquals : ':=' ; <-- explicit lexer definition
</code>```

your eventual grammar won't allow it if your goal is to a allow : and = but exclude the combination := .

Title: antlr4 grammar with negative option

Body:
In antlr4 I want to define a string but exclude from it the combination := permitting the respective single characters. What is syntax to define the grammar

EQUAL : '=';
NUMBER: DIGIT+;
DIGIT   :   ('0'..'9');
LITERALEQUAL: ((CHAR | NUMBER | EQUAL | OTHERS) ' '?)+;
fragment CHAR   :[a-z]| [A-Z];
fragment OTHERS:  '.' | '/' | ':' | '-' | '#' | '?' | '&' | '_' | '[' | ']' | '^' | ';' | '"' | '=';

Body:
As  long as you don't make a lexer rule or implicit token like:

stmt : value ':=' something ;  <-- implicit token

or

BADEquals : ':=' ; <-- explicit lexer definition

your eventual grammar won't allow it if your goal is to a allow : and = but exclude the combination := .


问:
Combining CGBitmapInfo and CGImageAlphaInfo in Swift
I'm rewriting Apple's UIImageEffects sample code from Objective-C to Swift and I have a question regarding the following line:

```<code>vImage_CGImageFormat format = {
    .bitsPerComponent = 8,
    .bitsPerPixel = 32,
    .colorSpace = NULL,
    .bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little,
    .version = 0,
    .decode = NULL,
    .renderingIntent = kCGRenderingIntentDefault
};
</code>```

Here is my version in Swift:

```<code>let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue)
let format = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil, bitmapInfo: bitmapInfo, version: 0, decode: nil, renderingIntent: .RenderingIntentDefault)
</code>```

Is this the simplest way to create bitmapInfo in Swift?

答:
It’s not pretty right now no matter what you do, but I think the cleanest style (as of Swift 4) is to use something like:

```<code>let bitmapInfo: CGBitmapInfo = [
      .byteOrder32Little,
      .floatComponents,
      CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)]
</code>```

(Or use something similar inline.) This at least preserves the essential optionset-iness of the info.

Body:
I'm rewriting Apple's UIImageEffects sample code from Objective-C to Swift and I have a question regarding the following line:

vImage_CGImageFormat format = {
    .bitsPerComponent = 8,
    .bitsPerPixel = 32,
    .colorSpace = NULL,
    .bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little,
    .version = 0,
    .decode = NULL,
    .renderingIntent = kCGRenderingIntentDefault
};

Here is my version in Swift:

let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue)
let format = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil, bitmapInfo: bitmapInfo, version: 0, decode: nil, renderingIntent: .RenderingIntentDefault)

Is this the simplest way to create bitmapInfo in Swift?

Body:
It’s not pretty right now no matter what you do, but I think the cleanest style (as of Swift 4) is to use something like:

let bitmapInfo: CGBitmapInfo = [
      .byteOrder32Little,
      .floatComponents,
      CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)]

(Or use something similar inline.) This at least preserves the essential optionset-iness of the info.

ContentLicense: CC BY-SA 4.0


问:
how to create batch file in system folder using a batch file
I was wondering how I would be able to create a batch file in the startup folder using a batch file. I can get the file to create in common places on my disk(desktop, documents) but I can not get it to create in the startup folder. Can I give the child batch file admin permissions in order to be copied or created to the startup folder?</p>

答:
Give a try for this code :

@echo off
Set "Startup_Folder=%AppData%\Microsoft\Windows\Start Menu\Programs\Startup"
(
    echo @echo off
    echo echo Hello this is a test
    echo pause
) >"%Startup_Folder%\test.bat"
pause
```


问:
GetAsyncKeyState randomly works in release version
I want to capture key presses (e.g., ctrl+WinKey or only comma). I use WH_KEYBOARD_LL hook and GetAsyncKeyState in C#. It all works fine if I run it under debugger (i.e., debugger attached no breakpoints set). However, if I run it without debugger it rarely works. The hot keys code isn't invoked - the very same code that works if under debugger.

I've noticed that if I add logging code then it works also without debugger.
It also usually works on a slower PC.

How can I resolve the problem ?

The following is code excerpt from the hook handler

```<code>private bool HotKeyHandler(WPARAM wParam, LPARAM lParam, WH_KEYBOARD_LL.KBDLLHOOKSTRUCT KeyInfo) {

if ((WH_KEYBOARD_LL.GetAsyncKeyState(Keys.LWin) < 0 || WH_KEYBOARD_LL.GetAsyncKeyState(Keys.RWin) < 0)) {
    if ((int)wParam == WH_KEYBOARD_LL.WM_KEYDOWN) {
            if (WH_KEYBOARD_LL.GetAsyncKeyState(Keys.ControlKey) < 0) {
                switch (KeyInfo.VkCode) {
                    case WH_KEYBOARD_LL.VK_OEM_COMMA:
                        // Some action - this doesn't work randomly ...
                    return true;
...
                }
            }

        }
    }
return false;
}

WH_KEYBOARD_LL.Initialize(HotKeyHandler);

        public static void Initialize(Func<WPARAM, LPARAM, KBDLLHOOKSTRUCT, bool> Handler) {
            HandlerI = Handler;
            KeyboardHookProcedureHandle = NativeCalls.Hooks.SetWindowsHookEx(NativeCalls.Hooks.HookType.WH_KEYBOARD_LL, KeyboardLLHandler, IntPtr.Zero, 0);
        }

        private static NativeCalls.Hooks.Procedure KeyboardLLHandler = KeyboardProcedure;

        private static LRESULT KeyboardProcedure(int MustProcessMessage, WPARAM wParam, LPARAM lParam) {
            if (MustProcessMessage != HC_ACTION) { return NativeCalls.Hooks.CallNextHookEx(KeyboardHookProcedureHandle, MustProcessMessage, wParam, lParam); }

            var KeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(KBDLLHOOKSTRUCT));
            return HandlerI(wParam, lParam, KeyInfo) ? (IntPtr)1 : NativeCalls.Hooks.CallNextHookEx(KeyboardHookProcedureHandle, MustProcessMessage, wParam, lParam);
        }

        [DllImport("user32.dll")]
        public static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);

        [StructLayout(LayoutKind.Sequential)]
        public struct KBDLLHOOKSTRUCT {
            public DWORD VkCode;
            public DWORD ScanCode;
            public DWORD Flags;
            public DWORD Time;
            public ULONG_PTR DwExtraInfo;
        }

        public const int HC_ACTION = 0;
        public const int WM_KEYDOWN = 0x0100;
        public const int WM_KEYUP = 0x0101;
        public const int WM_SYSKEYUP = 0x0105;
        public const int VK_OEM_COMMA = 0xBC;
        public const int VK_OEM_PERIOD = 0xBE;
        public const int VK_TAB = 0x09;
        public const int VK_ESCAPE = 0x18;

        public const int VK_1 = 0x31;
        public const int VK_2 = 0x32;
        public const int VK_3 = 0x33;
        public const int VK_4 = 0x34;
        public const int VK_5 = 0x35;
        public const int VK_6 = 0x36;
        public const int VK_7 = 0x37;
        public const int VK_8 = 0x38;
        public const int VK_9 = 0x39;

        public const int VK_N = 0x4E;
        public const int VK_W = 0x57; // Virtual-Key Codes - https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
        public const int VK_Z = 0x5A;

/*
using DWORD = System.UInt32;
using HHOOK = System.IntPtr;
using LPARAM = System.IntPtr;
using LRESULT = System.IntPtr;
using ULONG_PTR = System.UIntPtr;
using WPARAM = System.UIntPtr;
*/
</code>```

答: GetAsyncKeyState retrieves the state right at the moment you call it, not the state synchronized with other keys you care about. You already have a hook, track the Ctrl & Win key state yourself in the hook.

Body:
I want to capture key presses (e.g., ctrl+WinKey or only comma). I use WH_KEYBOARD_LL hook and GetAsyncKeyState in C#. It all works fine if I run it under debugger (i.e., debugger attached no breakpoints set). However, if I run it without debugger it rarely works. The hot keys code isn't invoked - the very same code that works if under debugger.

I've noticed that if I add logging code then it works also without debugger.
It also usually works on a slower PC.

How can I resolve the problem ?

The following is code excerpt from the hook handler

private bool HotKeyHandler(WPARAM wParam, LPARAM lParam, WH_KEYBOARD_LL.KBDLLHOOKSTRUCT KeyInfo) {

if ((WH_KEYBOARD_LL.GetAsyncKeyState(Keys.LWin) < 0 || WH_KEYBOARD_LL.GetAsyncKeyState(Keys.RWin) < 0)) {
    if ((int)wParam == WH_KEYBOARD_LL.WM_KEYDOWN) {
            if (WH_KEYBOARD_LL.GetAsyncKeyState(Keys.ControlKey) < 0) {
                switch (KeyInfo.VkCode) {
                    case WH_KEYBOARD_LL.VK_OEM_COMMA:
                        // Some action - this doesn't work randomly ...
                    return true;
...
                }
            }

        }
    }
return false;
}

WH_KEYBOARD_LL.Initialize(HotKeyHandler);

        public static void Initialize(Func<WPARAM, LPARAM, KBDLLHOOKSTRUCT, bool> Handler) {
            HandlerI = Handler;
            KeyboardHookProcedureHandle = NativeCalls.Hooks.SetWindowsHookEx(NativeCalls.Hooks.HookType.WH_KEYBOARD_LL, KeyboardLLHandler, IntPtr.Zero, 0);
        }

        private static NativeCalls.Hooks.Procedure KeyboardLLHandler = KeyboardProcedure;

        private static LRESULT KeyboardProcedure(int MustProcessMessage, WPARAM wParam, LPARAM lParam) {
            if (MustProcessMessage != HC_ACTION) { return NativeCalls.Hooks.CallNextHookEx(KeyboardHookProcedureHandle, MustProcessMessage, wParam, lParam); }

            var KeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(KBDLLHOOKSTRUCT));
            return HandlerI(wParam, lParam, KeyInfo) ? (IntPtr)1 : NativeCalls.Hooks.CallNextHookEx(KeyboardHookProcedureHandle, MustProcessMessage, wParam, lParam);
        }

        [DllImport("user32.dll")]
        public static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);

        [StructLayout(LayoutKind.Sequential)]
        public struct KBDLLHOOKSTRUCT {
            public DWORD VkCode;
            public DWORD ScanCode;
            public DWORD Flags;
            public DWORD Time;
            public ULONG_PTR DwExtraInfo;
        }

        public const int HC_ACTION = 0;
        public const int WM_KEYDOWN = 0x0100;
        public const int WM_KEYUP = 0x0101;
        public const int WM_SYSKEYUP = 0x0105;
        public const int VK_OEM_COMMA = 0xBC;
        public const int VK_OEM_PERIOD = 0xBE;
        public const int VK_TAB = 0x09;
        public const int VK_ESCAPE = 0x18;

        public const int VK_1 = 0x31;
        public const int VK_2 = 0x32;
        public const int VK_3 = 0x33;
        public const int VK_4 = 0x34;
        public const int VK_5 = 0x35;
        public const int VK_6 = 0x36;
        public const int VK_7 = 0x37;
        public const int VK_8 = 0x38;
        public const int VK_9 = 0x39;

        public const int VK_N = 0x4E;
        public const int VK_W = 0x57; // Virtual-Key Codes - https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
        public const int VK_Z = 0x5A;

/*
using DWORD = System.UInt32;
using HHOOK = System.IntPtr;
using LPARAM = System.IntPtr;
using LRESULT = System.IntPtr;
using ULONG_PTR = System.UIntPtr;
using WPARAM = System.UIntPtr;
*/


问:
Javah error while using it in JNI
Command:

```<code>javah -jni JavaHowTo
</code>```

Result:

```<code>error: cannot access JavaHowTo
class file for JavaHowTo not found

javadoc: error - Class JavaHowTo not found.
Error: No classes were specified on the command line.  Try -help.
</code>```

I have set the class path correctly, but still i am getting this javah error.

Any solution for this will be much helpful.

答:
I had this problem when I add to -classpath my source directory. I thought classes are in *.java files ;)

Javah is working on byte code so you have to add directory with your binaries to classpath

I made some eclipse task:

"Location"

```<code>${env_var:JAVA_HOME}\bin\javah.exe
</code>```

"Arguments"

```<code>-verbose
-force
-classpath ;${project_loc}\bin
-d ${project_loc}\jni
${java_type_name}
</code>```

Select file and Run

Title: Javah error while using it in JNI

Body:
Command:

javah -jni JavaHowTo

Result:

error: cannot access JavaHowTo
class file for JavaHowTo not found

javadoc: error - Class JavaHowTo not found.
Error: No classes were specified on the command line.  Try -help.

I have set the class path correctly, but still i am getting this javah error.

Any solution for this will be much helpful.

Body:
I had this problem when I add to -classpath my source directory. I thought classes are in *.java files ;)

Javah is working on byte code so you have to add directory with your binaries to classpath

I made some eclipse task:

"Location"

${env_var:JAVA_HOME}\bin\javah.exe

"Arguments"

-verbose
-force
-classpath ;${project_loc}\bin
-d ${project_loc}\jni
${java_type_name}

Select file and Run


问:
Delete tag with specific content in php?
This is my function to delete some tags:

```<code>private function removeTag($el, $tag) {
        $el = preg_replace("#\<".$tag."(.*)/".$tag.">#iUs", "", $el);
        return $el;
    }
</code>```

How can I extend this function to delete or replace tag with empty string if tag contains word: "ignore"

答:
Use preg_match to search for ignored within the content of the tag.

```<code>function removeTag($el, $tag) {
    return (preg_match('/^(.*)+>ignored<(.*)+>$/', $el) === false)
        ? preg_replace("#\<$tag(.*)/$tag>#iUs", "", $el) : $el
}
</code>```

If you want to set the ignored phrase as a param, you can do something like this:

```<code>function removeTag($el, $tag, $ignored = false) {
    if (!$ignored) return $el;
    else return (preg_match("/^(.*)+>$ignored<(.*)+>$/", $el) === false)
        ? preg_replace("#\<$tag(.*)/$tag>#iUs", "", $el) : $el
}
</code>```

Body:
This is my function to delete some tags:

private function removeTag($el, $tag) {
        $el = preg_replace("#\<".$tag."(.*)/".$tag.">#iUs", "", $el);
        return $el;
    }

How can I extend this function to delete or replace tag with empty string if tag contains word: "ignore"

Body:
Use preg_match to search for ignored within the content of the tag.

function removeTag($el, $tag) {
    return (preg_match('/^(.*)+>ignored<(.*)+>$/', $el) === false)
        ? preg_replace("#\<$tag(.*)/$tag>#iUs", "", $el) : $el
}

If you want to set the ignored phrase as a param, you can do something like this:

function removeTag($el, $tag, $ignored = false) {
    if (!$ignored) return $el;
    else return (preg_match("/^(.*)+>$ignored<(.*)+>$/", $el) === false)
        ? preg_replace("#\<$tag(.*)/$tag>#iUs", "", $el) : $el
}


问:
Lambda including if...elif...else
I want to apply a lambda function to a DataFrame column using if...elif...else within the lambda function.

The df and the code are something like:

```<code>df=pd.DataFrame({"one":[1,2,3,4,5],"two":[6,7,8,9,10]})

df["one"].apply(lambda x: x*10 if x<2 elif x<4 x**2 else x+10)
</code>```

Obviously, this doesn't work. Is there a way to apply if....elif....else to a lambda?
How can I get the same result with List Comprehension?

答:
I do not recommend the use of apply here: it should be avoided if there are better alternatives.

For example, if you are performing the following operation on a Series:

```<code>if cond1:
    exp1
elif cond2:
    exp2
else:
    exp3
</code>```

This is usually a good use case for np.where or np.select.

numpy.where

The if else chain above can be written using

```<code>np.where(cond1, exp1, np.where(cond2, exp2, ...))
</code>```

np.where allows nesting. With one level of nesting, your problem can be solved with,

```<code>df['three'] = (
    np.where(
        df['one'] < 2,
        df['one'] * 10,
        np.where(df['one'] < 4, df['one'] ** 2, df['one'] + 10))
df

   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15
</code>```

numpy.select

Allows for flexible syntax and is easily extensible. It follows the form,

```<code>np.select([cond1, cond2, ...], [exp1, exp2, ...])
</code>```

Or, in this case,

```<code>np.select([cond1, cond2], [exp1, exp2], default=exp3)
</code>```

```<code>df['three'] = (
    np.select(
        condlist=[df['one'] < 2, df['one'] < 4],
        choicelist=[df['one'] * 10, df['one'] ** 2],
        default=df['one'] + 10))
df

   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15
</code>```

and/or (similar to the if/else)

Similar to if-else, requires the lambda:

```<code>df['three'] = df["one"].apply(
    lambda x: (x < 2 and x * 10) or (x < 4 and x ** 2) or x + 10)

df
   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15
</code>```

List Comprehension

Loopy solution that is still faster than apply.

```<code>df['three'] = [x*10 if x<2 else (x**2 if x<4 else x+10) for x in df['one']]
# df['three'] = [
#    (x < 2 and x * 10) or (x < 4 and x ** 2) or x + 10) for x in df['one']
# ]
df
   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15
</code>```

Title: Lambda including if...elif...else

Body:
I want to apply a lambda function to a DataFrame column using if...elif...else within the lambda function.

The df and the code are something like:

df=pd.DataFrame({"one":[1,2,3,4,5],"two":[6,7,8,9,10]})

df["one"].apply(lambda x: x*10 if x<2 elif x<4 x**2 else x+10)

Obviously, this doesn't work. Is there a way to apply if....elif....else to a lambda?
How can I get the same result with List Comprehension?

Body:
I do not recommend the use of apply here: it should be avoided if there are better alternatives.

For example, if you are performing the following operation on a Series:

if cond1:
    exp1
elif cond2:
    exp2
else:
    exp3

This is usually a good use case for np.where or np.select.

numpy.where

The if else chain above can be written using

np.where(cond1, exp1, np.where(cond2, exp2, ...))

np.where allows nesting. With one level of nesting, your problem can be solved with,

df['three'] = (
    np.where(
        df['one'] < 2,
        df['one'] * 10,
        np.where(df['one'] < 4, df['one'] ** 2, df['one'] + 10))
df

   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15

numpy.select

Allows for flexible syntax and is easily extensible. It follows the form,

np.select([cond1, cond2, ...], [exp1, exp2, ...])

Or, in this case,

np.select([cond1, cond2], [exp1, exp2], default=exp3)

df['three'] = (
    np.select(
        condlist=[df['one'] < 2, df['one'] < 4],
        choicelist=[df['one'] * 10, df['one'] ** 2],
        default=df['one'] + 10))
df

   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15

and/or (similar to the if/else)

Similar to if-else, requires the lambda:

df['three'] = df["one"].apply(
    lambda x: (x < 2 and x * 10) or (x < 4 and x ** 2) or x + 10)

df
   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15

List Comprehension

Loopy solution that is still faster than apply.

df['three'] = [x*10 if x<2 else (x**2 if x<4 else x+10) for x in df['one']]
# df['three'] = [
#    (x < 2 and x * 10) or (x < 4 and x ** 2) or x + 10) for x in df['one']
# ]
df
   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15


问:
How to validate data on datagridview to prevent duplicate
for example i have "NID" as textbox and datagrid with @NID field.

i want save NID with Value "N001" to @NID on datagrid.

how to prevent duplicate when i save NID with value "N001" to datagrid.

I trying like this but error

private sub save()
dim dgv as datagridview1
if dgv.CurrentRow.Cells(0).value = NID.text then
msgbox("Data duplicate")
else
dgv.rows.insert(.NewRowIndex, NID.text)
end if
end sub

help me

thanks

答:
In your code, you are only checking the current row of the DataGridView. You need to check all the rows.</p>

```<code>'For loops are inclusive, meaning that both indexes will be reached.
'dgv.Rows is a zero indexed collection so "dgv.Rows(dgv.RowCount)" would give an error
For i = 0 To dgv.RowCount - 1

    If dgv.Rows(i).Cells(0).Value = NID.Text
        MsgBox("Duplicate data")
        Exit Sub 'So no insert occurs
    End If

Next
'code to insert row
</code>```

Body:
In your code, you are only checking the current row of the DataGridView. You need to check all the rows.

'For loops are inclusive, meaning that both indexes will be reached.
'dgv.Rows is a zero indexed collection so "dgv.Rows(dgv.RowCount)" would give an error
For i = 0 To dgv.RowCount - 1

    If dgv.Rows(i).Cells(0).Value = NID.Text
        MsgBox("Duplicate data")
        Exit Sub 'So no insert occurs
    End If

Next
'code to insert row


问:
String to Double in Java
I have in my Java app double numbers. I need to convert String to Double, but string representation of number is

, - separates decimal part of number (
  example    1,5  eq 6/4 )

. - separates groups of three digits (
  example  1.000.000  eq 1000000 )

.
How to achieve this conversion String to Double ?

答: DecimalFormat is your friend.

Title: String to Double in Java

Body: DecimalFormat is your friend.


问:
Accept newline in bash script
I have the following script that continuously accepts input from the user until he/she enters some form of y* or Y*.

```<code>while true; do
read -p "Are you ready? " yn
case $yn in
    [Yy]* ) break;;
    [Nn]* ) ;;
    * ) echo "Please answer yes or no.";;
esac
done
</code>```

However, I would like to break out of the while loop when the user simply presses enter. I tried using \n, \r, and \r\n but these don't seem to be the right patterns.

I am using Cygwin if that makes a difference (though I would also like to know the answer for a Linux distribution like Ubuntu).

答:
Because read strips the newline, you'll have to match an empty string, "":

```<code>#!/bin/bash
while true; do
    read -p "Are you ready? " yn
    case "$yn" in
        [Yy]*|"") break;;
        [Nn]*) ;;
        *) echo "Please answer yes or no.";;
    esac
done
</code>```

Depending on your application logic, you can (obviously) make that a separate case branch, like: "") break;;.

Title: Accept newline in bash script

Body:
I have the following script that continuously accepts input from the user until he/she enters some form of y* or Y*.

while true; do
read -p "Are you ready? " yn
case $yn in
    [Yy]* ) break;;
    [Nn]* ) ;;
    * ) echo "Please answer yes or no.";;
esac
done

However, I would like to break out of the while loop when the user simply presses enter. I tried using \n, \r, and \r\n but these don't seem to be the right patterns.

I am using Cygwin if that makes a difference (though I would also like to know the answer for a Linux distribution like Ubuntu).

Body:
Because read strips the newline, you'll have to match an empty string, "":

#!/bin/bash
while true; do
    read -p "Are you ready? " yn
    case "$yn" in
        [Yy]*|"") break;;
        [Nn]*) ;;
        *) echo "Please answer yes or no.";;
    esac
done

Depending on your application logic, you can (obviously) make that a separate case branch, like: "") break;;.


问:
How is `getattr` related to `object.__getattribute__` and to `object.__getattr__`?
From https://docs.python.org/3.6/library/functions.html#getattr

```<code>getattr(object, name[, default])
</code>```

Return the value of the named attribute of object. name must be a
  string. If the string is the name of one of the object’s attributes,
  the result is the value of that attribute. For example, getattr(x,
  'foobar') is equivalent to x.foobar. If the named attribute does
  not exist, default is returned if provided, otherwise
  AttributeError is raised.

How is getattr related to object.__getattribute__ and to object.__getattr__?

Does getattr call object.__getattribute__ or object.__getattr__? I would guess the former?

答:
getattr(foo, 'bar')(which is basically foo.bar) calls __getattribute__ and from there __getattr__ can be called(if it exists) when:

AttributeError is raised by __getattribute__

__getattribute__ calls it explicitly

From docs:

If the class also defines __getattr__(), the latter will not be called
  unless __getattribute__() either calls it explicitly or raises an
  AttributeError.

Defining __getattr__ can be useful if you don't want to throw attribute errors on random attribute access. Mock library is great example of that.

```<code>>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.foo.bar.spam
<Mock name='mock.foo.bar.spam' id='4367274280'>
</code>```

If you don't want to define __getattr__ all the time nor want to handle AttributeError all the time then you could either use the 3 argument form of getattr() to return default value if attribute wasn't found or use hasattr to check for its existence.

```<code>>> getattr([], 'foo')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-60-f1834c32d3ce> in <module>()
----> 1 getattr([], 'foo')

AttributeError: 'list' object has no attribute 'foo'
>>> getattr([], 'foo', 'default')
'default'
</code>```

Demo:

```<code>class A:
    def __getattr__(self, attr):
        print('Inside A.__getattr__')
        return 'eggs'

print(A().foo)
</code>```

outputs:

```<code>Inside A.__getattr__
eggs
</code>```

Note that the data model documentation points it out as object.__getattr__, but that doesn't mean they exists on builtin object type. Instead they can exist on any object in general. And object in this case is a type as dunder methods are looked up on an object's type.

Body:
From https://docs.python.org/3.6/library/functions.html#getattr

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a
  string. If the string is the name of one of the object’s attributes,
  the result is the value of that attribute. For example, getattr(x,
  'foobar') is equivalent to x.foobar. If the named attribute does
  not exist, default is returned if provided, otherwise
  AttributeError is raised.

How is getattr related to object.__getattribute__ and to object.__getattr__?

Does getattr call object.__getattribute__ or object.__getattr__? I would guess the former?

Body:
getattr(foo, 'bar')(which is basically foo.bar) calls __getattribute__ and from there __getattr__ can be called(if it exists) when:

AttributeError is raised by __getattribute__

__getattribute__ calls it explicitly

From docs:

If the class also defines __getattr__(), the latter will not be called
  unless __getattribute__() either calls it explicitly or raises an
  AttributeError.

Defining __getattr__ can be useful if you don't want to throw attribute errors on random attribute access. Mock library is great example of that.

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.foo.bar.spam
<Mock name='mock.foo.bar.spam' id='4367274280'>

If you don't want to define __getattr__ all the time nor want to handle AttributeError all the time then you could either use the 3 argument form of getattr() to return default value if attribute wasn't found or use hasattr to check for its existence.

>> getattr([], 'foo')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-60-f1834c32d3ce> in <module>()
----> 1 getattr([], 'foo')

AttributeError: 'list' object has no attribute 'foo'
>>> getattr([], 'foo', 'default')
'default'

Demo:

class A:
    def __getattr__(self, attr):
        print('Inside A.__getattr__')
        return 'eggs'

print(A().foo)

outputs:

Inside A.__getattr__
eggs

Note that the data model documentation points it out as object.__getattr__, but that doesn't mean they exists on builtin object type. Instead they can exist on any object in general. And object in this case is a type as dunder methods are looked up on an object's type.


问:
Binary search / bisection for floating point numbers
It is easy to find an integer with binary search even if it can be arbitrarily large: first guess the order of magnitude, then keep dividing the interval.
This answer describes how to find an arbitrary rational number.

Having set the scene, my question is similar: how can we guess a IEEE 754 floating point number?  Assume it is not NaN, but everything else is fair game.  For each guess, your program will be told whether the number in question is higher, equal or lower.  Minimize the number of guesses required in the worst case.

(This is not a homework assignment.  Though, I might make it one, if this turns out to have an interesting answer that's not just "beat the floating point numerical difficulties to death with lots and lots of special case handling.")

Edit: if I were better at searching I could have found the answer---but that only works if you already know that reinterpretation as int works (with certain caveats). So leaving this up. Thanks to Harold for a great answer!

答:
The same approach can be applied to a floating point number. Worse case run time is O(log n).</p>

```<code>public class GuessComparer
{
    private float random;
    public GuessComparer() // generate a random float and keep it private
    {
        Random rnd = new Random();
        var buffer = new byte[4];
        rnd.NextBytes(buffer);
        random = BitConverter.ToSingle(buffer, 0);
    }
    public int CheckGuess(float quess) // answer whether number is high, lower or the same.
    {
        return random.CompareTo(quess);
    }
}
public class FloatFinder
{

    public static int Find(GuessComparer checker)
    {
        float guess = 0;
        int result = checker.CheckGuess(guess);
        int guesscount = 1;
        var high = float.MaxValue;
        var low = float.MinValue;
        while (result != 0)
        {
            if (result > 0) //random is higher than guess
                low = guess;
            else// random is lower than guess

                high = guess;

            guess = (high + low) / 2;
            guesscount++;
            result = checker.CheckGuess(guess);
        }
        Console.WriteLine("Found answer in {0}", guesscount);
        return guesscount;
    }

    public static void Find()
    {
        var checker = new GuessComparer();
        int guesses = Find(checker);
    }
}
</code>```

Body:
The same approach can be applied to a floating point number. Worse case run time is O(log n).

public class GuessComparer
{
    private float random;
    public GuessComparer() // generate a random float and keep it private
    {
        Random rnd = new Random();
        var buffer = new byte[4];
        rnd.NextBytes(buffer);
        random = BitConverter.ToSingle(buffer, 0);
    }
    public int CheckGuess(float quess) // answer whether number is high, lower or the same.
    {
        return random.CompareTo(quess);
    }
}
public class FloatFinder
{

    public static int Find(GuessComparer checker)
    {
        float guess = 0;
        int result = checker.CheckGuess(guess);
        int guesscount = 1;
        var high = float.MaxValue;
        var low = float.MinValue;
        while (result != 0)
        {
            if (result > 0) //random is higher than guess
                low = guess;
            else// random is lower than guess

                high = guess;

            guess = (high + low) / 2;
            guesscount++;
            result = checker.CheckGuess(guess);
        }
        Console.WriteLine("Found answer in {0}", guesscount);
        return guesscount;
    }

    public static void Find()
    {
        var checker = new GuessComparer();
        int guesses = Find(checker);
    }
}


问:
Finding 'first occurrence' using Match Function in R
I am new to 'R' and 'Stackoverflow' so forgive me for the incredibly basic question. I'm trying to find the 'index' of the first female in my dataset.

Code Snapshot

My overall dataset is called 'bike', so first I thought it would be a good idea to assign a new vector of just the genders...

```<code>bike$genders
</code>```

Then I tried using the function:

```<code>match(1, genders)
match(F, genders)
</code>```

Neither of which worked! I know this is and should be relatively simple but I'm just starting out so I really appreciate your help.

答:
Probably the most direct method would be to use
match("F", bike[,"genders"] which will return the index of the first match.

Body:
I am new to 'R' and 'Stackoverflow' so forgive me for the incredibly basic question. I'm trying to find the 'index' of the first female in my dataset.

Code Snapshot

My overall dataset is called 'bike', so first I thought it would be a good idea to assign a new vector of just the genders...

bike$genders

Then I tried using the function:

match(1, genders)
match(F, genders)

Neither of which worked! I know this is and should be relatively simple but I'm just starting out so I really appreciate your help.


问:
Should I add a insert_time column for tracking the sequence [sqlite]
I have a table with an auto-increment primary key column; I want to fetch the items of this table order by the time when the record is inserted. I wonder is it necessary to have a dedicated insert_time column for that purpose?</p>

答: You don't need to add insert_time column. You can order your data with auto-increment column. Last inserted row have max number.</p>


问:
Starting salt-master on Vagrant: [Errno 98]
Trying to run salt-master on Vagrant running Ubuntu,

no edits to /etc/salt/master

I get:

```<code>vagrant@markvagrant:/etc/salt$ sudo salt-master -l all
[DEBUG   ] Reading configuration from /etc/salt/master
[DEBUG   ] Configuration file path: /etc/salt/master
[TRACE   ] Trying pysss.getgrouplist for 'root'
[TRACE   ] Trying generic group list for 'root'
[TRACE   ] Group list for user 'root': []
[INFO    ] Setting up the Salt Master
[WARNING ] Unable to bind socket, error: [Errno 98] Address already in use
The ports are not available to bind
</code>```

My Vagrantfile:

```<code>Vagrant.configure(2) do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.network "private_network", ip: "192.168.2.2"
  config.vm.network "public_network"
  config.vm.hostname = "markvagrant"
  config.vm.synced_folder "./data", "/vagrant_data"
  config.vm.provider "virtualbox" do |vb|
    vb.memory = "1024"
  end
end
</code>```

答:
I'm on Ubuntu 16.04 LTS. I'm running salt-master 2015.8.8 (Beryllium). Neither service salt-master stop or service salt-master restart work for me. The existing salt master process continues to run and holds the port open blocking a new instance from starting. In order to restart the salt master I need to:

```<code>pkill salt-master;
service salt-master start;
</code>```

Body:
Trying to run salt-master on Vagrant running Ubuntu,

no edits to /etc/salt/master

I get:

vagrant@markvagrant:/etc/salt$ sudo salt-master -l all
[DEBUG   ] Reading configuration from /etc/salt/master
[DEBUG   ] Configuration file path: /etc/salt/master
[TRACE   ] Trying pysss.getgrouplist for 'root'
[TRACE   ] Trying generic group list for 'root'
[TRACE   ] Group list for user 'root': []
[INFO    ] Setting up the Salt Master
[WARNING ] Unable to bind socket, error: [Errno 98] Address already in use
The ports are not available to bind

My Vagrantfile:

Vagrant.configure(2) do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.network "private_network", ip: "192.168.2.2"
  config.vm.network "public_network"
  config.vm.hostname = "markvagrant"
  config.vm.synced_folder "./data", "/vagrant_data"
  config.vm.provider "virtualbox" do |vb|
    vb.memory = "1024"
  end
end

Body:
I'm on Ubuntu 16.04 LTS. I'm running salt-master 2015.8.8 (Beryllium). Neither service salt-master stop or service salt-master restart work for me. The existing salt master process continues to run and holds the port open blocking a new instance from starting. In order to restart the salt master I need to:

pkill salt-master;
service salt-master start;


问:
What is the best approach to find and store all pair distances in a weighted tree?
What is the best approach to find and store all pair distances in a weighted tree?

My current approach is to run bfs on every node. But obviously this approach approach suffers from large complexity. Can we improve it further ?

答:
A reasonable way to store them is to use consecutive node numbers starting at 0 so the distances fit neatly in a triangular array d[i,j] where j < i.  A reasonable way to compute them is to augment a single search.  I'll use the shorthand D[i,j] for d[max(i,j), min(i,j)]. This lets me ignore vertex numbering for convenience.

```<code>Let C be a set of completed nodes
Set W be a working set of nodes
Choose any node. Add it to C. Add all its adjacent nodes to W.
while W is not empty
  Remove any node x from W
  Let e be the unique edge (x,y) where y \in C and d(x, y) be its length
  D[x, y] = d(x, y)
  for each node z in C - {y}
    D[x, z] = D[x, y] + D[y, z]
  add x to C
  add all nodes adjacent to x but not in C to W
</code>```

The loop invariant is that for each pair of nodes in C -- call such a pair (p, q) -- we have already computed D[p,q]. The nodes in C always correspond to a subtree and W the nodes adjacent to that subtree.

While this has the same asymptotic complexity as doing n breadth first searches, it's potentially quite a bit faster because it traverses each graph edge only once rather than n times and computes each distance once rather than twice.

A quick Python implementation:

```<code>def distance_matrix(graph):
  adj, dist = graph
  result = [ [0 for j in range(i)] for i in range(len(adj)) ]
  c = set([0])
  w = set([(x, 0) for x in adj[0]])
  while w:
    x, y = pair = w.pop()
    d = result[max(pair)][min(pair)] = dist[pair]
    for z in c:
      if z != y:
        result[max(x,z)][min(x,z)] = d + result[max(y,z)][min(y,z)]
    c.add(x)
    for a in adj[x]:
      if a not in c:
        w.add((a, x))
  return result

def to_graph(tree):
  adj = [ set() for i in range(len(tree)) ]
  dist = {}
  for (parent, child_pairs) in tree:
    for (edge_len, child) in child_pairs:
      adj[child].add(parent)
      adj[parent].add(child)
      dist[(parent, child)] = edge_len
      dist[(child, parent)] = edge_len
  return (adj, dist)

def main():
  tree = (
    (0, ((12, 1), (7, 2), (9, 3))),
    (1, ((5, 4), (19, 5))),
    (2, ()),
    (3, ((31, 6),)),
    (4, ((27, 7), (15, 8))),
    (5, ()),
    (6, ((23, 9), (11, 10))),
    (7, ()),
    (8, ()),
    (9, ()),
    (10, ()))
  graph = to_graph(tree)
  print distance_matrix(graph)
</code>```

Output (with pprint):

```<code>[[],
 [12],
 [7, 19],
 [9, 21, 16],
 [17, 5, 24, 26],
 [31, 19, 38, 40, 24],
 [40, 52, 47, 31, 57, 71],
 [44, 32, 51, 53, 27, 51, 84],
 [32, 20, 39, 41, 15, 39, 72, 42],
 [63, 75, 70, 54, 80, 94, 23, 107, 95],
 [51, 63, 58, 42, 68, 82, 11, 95, 83, 34]]
</code>```

Body:
A reasonable way to store them is to use consecutive node numbers starting at 0 so the distances fit neatly in a triangular array d[i,j] where j < i.  A reasonable way to compute them is to augment a single search.  I'll use the shorthand D[i,j] for d[max(i,j), min(i,j)]. This lets me ignore vertex numbering for convenience.

Let C be a set of completed nodes
Set W be a working set of nodes
Choose any node. Add it to C. Add all its adjacent nodes to W.
while W is not empty
  Remove any node x from W
  Let e be the unique edge (x,y) where y \in C and d(x, y) be its length
  D[x, y] = d(x, y)
  for each node z in C - {y}
    D[x, z] = D[x, y] + D[y, z]
  add x to C
  add all nodes adjacent to x but not in C to W

The loop invariant is that for each pair of nodes in C -- call such a pair (p, q) -- we have already computed D[p,q]. The nodes in C always correspond to a subtree and W the nodes adjacent to that subtree.

While this has the same asymptotic complexity as doing n breadth first searches, it's potentially quite a bit faster because it traverses each graph edge only once rather than n times and computes each distance once rather than twice.

A quick Python implementation:

def distance_matrix(graph):
  adj, dist = graph
  result = [ [0 for j in range(i)] for i in range(len(adj)) ]
  c = set([0])
  w = set([(x, 0) for x in adj[0]])
  while w:
    x, y = pair = w.pop()
    d = result[max(pair)][min(pair)] = dist[pair]
    for z in c:
      if z != y:
        result[max(x,z)][min(x,z)] = d + result[max(y,z)][min(y,z)]
    c.add(x)
    for a in adj[x]:
      if a not in c:
        w.add((a, x))
  return result

def to_graph(tree):
  adj = [ set() for i in range(len(tree)) ]
  dist = {}
  for (parent, child_pairs) in tree:
    for (edge_len, child) in child_pairs:
      adj[child].add(parent)
      adj[parent].add(child)
      dist[(parent, child)] = edge_len
      dist[(child, parent)] = edge_len
  return (adj, dist)

def main():
  tree = (
    (0, ((12, 1), (7, 2), (9, 3))),
    (1, ((5, 4), (19, 5))),
    (2, ()),
    (3, ((31, 6),)),
    (4, ((27, 7), (15, 8))),
    (5, ()),
    (6, ((23, 9), (11, 10))),
    (7, ()),
    (8, ()),
    (9, ()),
    (10, ()))
  graph = to_graph(tree)
  print distance_matrix(graph)

Output (with pprint):

[[],
 [12],
 [7, 19],
 [9, 21, 16],
 [17, 5, 24, 26],
 [31, 19, 38, 40, 24],
 [40, 52, 47, 31, 57, 71],
 [44, 32, 51, 53, 27, 51, 84],
 [32, 20, 39, 41, 15, 39, 72, 42],
 [63, 75, 70, 54, 80, 94, 23, 107, 95],
 [51, 63, 58, 42, 68, 82, 11, 95, 83, 34]]


问:
How to set a cookie to hide a notice bar on second page load?
This is what I wan't:

A new user visits my website. A notice bar fixed to the bottom of the viewport is visible.

The user then clicks on a menu item, to go to another page. A cookie is set on 2nd page load, that hides the notice bar for 60 days (must be 100% hidden and not flash on page load duo to javascript being loaded asynchronous).

The user can also click on the "Ok" button to close the notice bar and set the same cookie.

This is my HTML:

```<code><div id="cookie-message">
    <span>Cookie notice here <a href="#">Read more</a> <a href="#" id="cookie-message-close">Ok</a></span>
</div>
</code>```

How can I do this with jQuery?

Thanks!

答:
You can use a API to deal with cookies, makes the things much more easy.

First of all you put display: none; in the div cookie-message.

About the logic of hidden or not the notice, you can put a listener in the first load of the window:

```<code>window.addEventListener('load', function(){...});
</code>```

this way you can get the moment when the window is loaded. If in this moment there is no cookie for notice read, you show the div ($('#cookie-message').show(), and then you set up a cookie. If there is a cookie for that already set, you do nothing.

About the OK click, set up a click listener in the link to hide the notice div ($('#cookie-message').show()).

To help you, I make a simple example example of what I said.

Body:
This is what I wan't:

A new user visits my website. A notice bar fixed to the bottom of the viewport is visible.

The user then clicks on a menu item, to go to another page. A cookie is set on 2nd page load, that hides the notice bar for 60 days (must be 100% hidden and not flash on page load duo to javascript being loaded asynchronous).

The user can also click on the "Ok" button to close the notice bar and set the same cookie.

This is my HTML:

    Cookie notice here Read more Ok

How can I do this with jQuery?

Thanks!

Body:
You can use a API to deal with cookies, makes the things much more easy.

First of all you put display: none; in the div cookie-message.

About the logic of hidden or not the notice, you can put a listener in the first load of the window:

window.addEventListener('load', function(){...});

this way you can get the moment when the window is loaded. If in this moment there is no cookie for notice read, you show the div ($('#cookie-message').show(), and then you set up a cookie. If there is a cookie for that already set, you do nothing.

About the OK click, set up a click listener in the link to hide the notice div ($('#cookie-message').show()).

To help you, I make a simple example example of what I said.


问:
How to avoiding types with same name conflict in Kotlin?
i am very new to kotlin, and i am having some trouble with an application i am building from a book. i have two classes in separate packages named Forecast and i am trying to define some functions in one that package that uses the class of same name inside it. the book said to import the Forecast class as ModelForecast and i did but now i am having a problem tracking down the source of this type mismatch error. it seems my convertForecastListToDomain() method is expecting something the other? please help me find the mistake that i am making. i would not be surprised if it is something very simple, but i still can not find it.

MainActivity.kt:

```<code>package com.example.zacharymcdaniel.weatherkot

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.example.zacharymcdaniel.weatherkot.domain.Forecast
import org.jetbrains.anko.find

class MainActivity : AppCompatActivity() {
private val url: String = "http://openweathermap.org/"

private val items = listOf(
        "Mon 6/23 - Sunny - 31/17",
        "Tue 6/24 - Foggy - 21/8",
        "Wed 6/25 - Cloudy - 22/17",
        "Thur 6/26 - Rainy - 18/11",
        "Fri 6/27 - Foggy - 21/10",
        "Sat 6/28 - TRAPPED IN WEATHER STATION - 23/18",
        "Sun 6/29 - Sunny - 20/7"
)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val forecastList: RecyclerView = find(R.id.forecast_list)
    forecastList.layoutManager = LinearLayoutManager(this)
    forecastList.adapter = ForecastListAdapter(items)

}

}

data class ForecastResult(val city: City, val list: List<Forecast>)

data class City(val id: Long, val name: String, val coord: Coordinates, val country: String, val population: Int)

data class Coordinates(val ion: Float, val lat: Float)

data class Forecast(val dt: Long, val temp: Tempurature, val pressure: Float,
                val humidity: Int, val weather: List<Weather>,
                val speed: Float, val deg: Int, val clouds: Int,
                val rain: Float) //<----this is supposed to be Forecast in second page

data class Tempurature(val day: Float, val min: Float, val max: Float,
                   val night: Float, val eve: Float, val morn: Float)

data class Weather(val id: Long, val main: String, val desciption: String, val icon: String)
</code>```

domain.kt in the domain package:

```<code>package com.example.zacharymcdaniel.weatherkot.domain

import com.example.zacharymcdaniel.weatherkot.Forecast
import com.example.zacharymcdaniel.weatherkot.ForecastResult
import java.text.DateFormat
import java.util.*
import com.example.zacharymcdaniel.weatherkot.domain.Forecast as
ModelForecast

public interface Command<T>{
fun execute(): T
}

data class ForecastList(val city: String, val country: String, val dailyForecast: List<ModelForecast>)

data class Forecast(val date: String, val description: String, val high: Int, val low: Int)

public class ForecastdataMapper{

private fun convertFromDataModel(forecast: ForecastResult): ForecastList {
    return ForecastList(forecast.city.name, forecast.city.country, convertForecastListToDomain(forecast.list)) //<---wrong type found here (forecast.list is indicated)
}

private fun convertForecastListToDomain(list: List<Forecast>): List<ModelForecast>{
    return list.map { convertForecastItemToDomain(it) }
}

private fun convertForecastItemToDomain(forecast: Forecast): ModelForecast{
    return ModelForecast(convertDate(forecast.dt),
            forecast.weather[0].desciption,
            forecast.temp.max.toInt(),
            forecast.temp.min.toInt())
}

private fun convertDate(date: Long): String{
    val df = DateFormat.getDateInstance(DateFormat.MEDIUM,
            Locale.getDefault())
    return df.format(date * 1000)
}
}
</code>```

thanks for the help

答:
you should remove the import statement from the first page, which is use the domain.Forecast in the second page rather your own Forecast.

```<code>import com.example.zacharymcdaniel.weatherkot.domain.Forecast
// ^--- remove it from your source code
</code>```

OR using typealias to rename it, for example:

```<code>typealias DomainForecast = com.example.zacharymcdaniel.weatherkot.domain.Forecast
</code>```

OR using alias import statement to rename it, for example:

```<code>import com.example.zacharymcdaniel.weatherkot.domain.Forecast as DomainForecast
</code>```

Body:
i am very new to kotlin, and i am having some trouble with an application i am building from a book. i have two classes in separate packages named Forecast and i am trying to define some functions in one that package that uses the class of same name inside it. the book said to import the Forecast class as ModelForecast and i did but now i am having a problem tracking down the source of this type mismatch error. it seems my convertForecastListToDomain() method is expecting something the other? please help me find the mistake that i am making. i would not be surprised if it is something very simple, but i still can not find it.

MainActivity.kt:

package com.example.zacharymcdaniel.weatherkot

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.example.zacharymcdaniel.weatherkot.domain.Forecast
import org.jetbrains.anko.find

class MainActivity : AppCompatActivity() {
private val url: String = "http://openweathermap.org/"

private val items = listOf(
        "Mon 6/23 - Sunny - 31/17",
        "Tue 6/24 - Foggy - 21/8",
        "Wed 6/25 - Cloudy - 22/17",
        "Thur 6/26 - Rainy - 18/11",
        "Fri 6/27 - Foggy - 21/10",
        "Sat 6/28 - TRAPPED IN WEATHER STATION - 23/18",
        "Sun 6/29 - Sunny - 20/7"
)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val forecastList: RecyclerView = find(R.id.forecast_list)
    forecastList.layoutManager = LinearLayoutManager(this)
    forecastList.adapter = ForecastListAdapter(items)

}

}

data class ForecastResult(val city: City, val list: List<Forecast>)

data class City(val id: Long, val name: String, val coord: Coordinates, val country: String, val population: Int)

data class Coordinates(val ion: Float, val lat: Float)

data class Forecast(val dt: Long, val temp: Tempurature, val pressure: Float,
                val humidity: Int, val weather: List<Weather>,
                val speed: Float, val deg: Int, val clouds: Int,
                val rain: Float) //<----this is supposed to be Forecast in second page

data class Tempurature(val day: Float, val min: Float, val max: Float,
                   val night: Float, val eve: Float, val morn: Float)

data class Weather(val id: Long, val main: String, val desciption: String, val icon: String)

domain.kt in the domain package:

package com.example.zacharymcdaniel.weatherkot.domain

import com.example.zacharymcdaniel.weatherkot.Forecast
import com.example.zacharymcdaniel.weatherkot.ForecastResult
import java.text.DateFormat
import java.util.*
import com.example.zacharymcdaniel.weatherkot.domain.Forecast as
ModelForecast

public interface Command<T>{
fun execute(): T
}

data class ForecastList(val city: String, val country: String, val dailyForecast: List<ModelForecast>)

data class Forecast(val date: String, val description: String, val high: Int, val low: Int)

public class ForecastdataMapper{

private fun convertFromDataModel(forecast: ForecastResult): ForecastList {
    return ForecastList(forecast.city.name, forecast.city.country, convertForecastListToDomain(forecast.list)) //<---wrong type found here (forecast.list is indicated)
}

private fun convertForecastListToDomain(list: List<Forecast>): List<ModelForecast>{
    return list.map { convertForecastItemToDomain(it) }
}

private fun convertForecastItemToDomain(forecast: Forecast): ModelForecast{
    return ModelForecast(convertDate(forecast.dt),
            forecast.weather[0].desciption,
            forecast.temp.max.toInt(),
            forecast.temp.min.toInt())
}

private fun convertDate(date: Long): String{
    val df = DateFormat.getDateInstance(DateFormat.MEDIUM,
            Locale.getDefault())
    return df.format(date * 1000)
}
}

thanks for the help

Body:
you should remove the import statement from the first page, which is use the domain.Forecast in the second page rather your own Forecast.

import com.example.zacharymcdaniel.weatherkot.domain.Forecast
// ^--- remove it from your source code

OR using typealias to rename it, for example:

typealias DomainForecast = com.example.zacharymcdaniel.weatherkot.domain.Forecast

OR using alias import statement to rename it, for example:

import com.example.zacharymcdaniel.weatherkot.domain.Forecast as DomainForecast


问:
Data structure for huge amount of records with ability to do "GetAllWithPrefix" fast
I need an in-memory data structure to store lots of values (~10M records) of type string with length of up to 100 characters (just in case it helps).

I'm going to run the following operations extensively:

Add

Get

Remove

GetAllWithPrefix(string prefix) - returns a list of all values corresponding to the prefix.

Obviously, any of the above operations need to be done in O(1) or O(logn)

I'm a bit rusty. What would be the best data structure for that? preferably direct me to the right class.

Thank you

答:
What you want is a trie, which is a tree where  each node has a map of character to nodes (branch) and a walk in the trie is a prefix walk, certain nodes also have a flag that implies if it's at the end of a string stored in the trie even though there could be further branches from node (string is prefix of another added string). A normal implementation has complexity: Insertion O(w), lookup is O(w) and prefix search is O(w+n) where w is string length and n is total length of words in the tree with w as prefix.

You can read about one c# implementation here

https://visualstudiomagazine.com/articles/2015/10/20/text-pattern-search-trie-class-net.aspx?m=1

Update
I want to clarify that the time complexities above in your special case is actually O(1) when considering your string length has an upper limit of 100.


问:
Can I use a JQuery Variable to select MYSQL column?
When one of my forms (name= QuestionTypeSelector value=AddingFractions) posts, the following snippet of PHP is part of the code that runs:

```<code>$QuestionTypeSelector = $_POST['QuestionTypeSelector'];
 $db->query(" UPDATE answers SET QuestionType = '$QuestionTypeSelector' WHERE user_id=$id");
</code>```

$_POST['QuestionTypeSelector'] successfully returns AddingFractions and this successfully sets $QuestionTypeSelector = AddingFractions. In turn, this sets a column titled QuestionType equal to AddingFractions.

Instead of this, I want to set a column titled AddingFractionsScore equal to 2. I tried the following code but it doesn't work.

```<code>$QuestionTypeSelector = $_POST['QuestionTypeSelector'];
 $db->query(" UPDATE answers SET '$QuestionTypeSelector+Score' = '2' WHERE user_id=$id");
</code>```

In other words, I'm trying to use the JQuery variable to select the column. Any advice would be much appreciated. Thanks!

答:
Sure</p>

```<code>$col = $_POST['QuestionTypeSelector'] . 'Score';
$db->query("UPDATE answers SET '$col' = '2' WHERE user_id=$id");
</code>```

Body:
When one of my forms (name= QuestionTypeSelector value=AddingFractions) posts, the following snippet of PHP is part of the code that runs:

$QuestionTypeSelector = $_POST['QuestionTypeSelector'];
 $db->query(" UPDATE answers SET QuestionType = '$QuestionTypeSelector' WHERE user_id=$id");

$_POST['QuestionTypeSelector'] successfully returns AddingFractions and this successfully sets $QuestionTypeSelector = AddingFractions. In turn, this sets a column titled QuestionType equal to AddingFractions.

Instead of this, I want to set a column titled AddingFractionsScore equal to 2. I tried the following code but it doesn't work.

$QuestionTypeSelector = $_POST['QuestionTypeSelector'];
 $db->query(" UPDATE answers SET '$QuestionTypeSelector+Score' = '2' WHERE user_id=$id");

In other words, I'm trying to use the JQuery variable to select the column. Any advice would be much appreciated. Thanks!

Body:
Sure

$col = $_POST['QuestionTypeSelector'] . 'Score';
$db->query("UPDATE answers SET '$col' = '2' WHERE user_id=$id");


问:
page reload not triggering document ready
The following td is updated on 1st page load by the javascript to yeild the result below (i.e.it all works).
However when pagination links are called the document ready is not called & thus the date not re written.
Ive tried various things but dont seam to get it working. On page rewriting the attribute is updated server side.
There are no ajax calls, the pagination link is just a simple url reloading the same page but with the query path changed. I understand the reload behaviour is normal - i just cant workaround it.

Any Ideas please to invoke my initialise call on subsequent loads?

```<code><td class="date" data-time="1499543100110"></td>

$(document).ready(function () {
    initialise();
});

function initialise() {
    $(".date").each(function(){
        var millisec = parseInt($(this).attr("data-time"));
        var ts = moment(new Date(millisec)).format("MMMM Do YYYY, h:mm:ss a");
        $(this).text(ts);
    });
}

<a href="?page=6&size=20&criteria=" data-ajax-load="#ajaxload">7</a>
</code>```

output

```<code><td class="date" data-time="1499543100110">July 8th 2017, 8:45:00 pm</td>
</code>```

update

As was suggested below there was more to the issue. The pagination link was being captured & the request was being issued by ajax, bypassing all the normal js hooks. I removed the capture below & every thing works as expected. The network url traffic looked like straight forward page-load but was in fact an ajax call.

```<code>$(document).on('click', 'a[data-ajax-load]', function(event) {
    var _url = $(event.target).attr('href');
    var _target = $(event.target).data('ajax-load');
    $(_target).load(_Url + ' ' + _target,
        function(response, status, xhr) {
            // display errors etc
        }
    );
    return false;
});
</code>```

The answers below are all probably correct, but did not need to explore them - thanks for guidance.

答:
I just found this...

Try using ajaxComplete()... It fires when an ajax request has completed.

```<code>$( document ).ajaxComplete(initialise);
</code>```

;)

Body:
The following td is updated on 1st page load by the javascript to yeild the result below (i.e.it all works).
However when pagination links are called the document ready is not called & thus the date not re written.
Ive tried various things but dont seam to get it working. On page rewriting the attribute is updated server side.
There are no ajax calls, the pagination link is just a simple url reloading the same page but with the query path changed. I understand the reload behaviour is normal - i just cant workaround it.

Any Ideas please to invoke my initialise call on subsequent loads?

$(document).ready(function () {
    initialise();
});

function initialise() {
    $(".date").each(function(){
        var millisec = parseInt($(this).attr("data-time"));
        var ts = moment(new Date(millisec)).format("MMMM Do YYYY, h:mm:ss a");
        $(this).text(ts);
    });
}

7

output

July 8th 2017, 8:45:00 pm

update

As was suggested below there was more to the issue. The pagination link was being captured & the request was being issued by ajax, bypassing all the normal js hooks. I removed the capture below & every thing works as expected. The network url traffic looked like straight forward page-load but was in fact an ajax call.

$(document).on('click', 'a[data-ajax-load]', function(event) {
    var _url = $(event.target).attr('href');
    var _target = $(event.target).data('ajax-load');
    $(_target).load(_Url + ' ' + _target,
        function(response, status, xhr) {
            // display errors etc
        }
    );
    return false;
});

The answers below are all probably correct, but did not need to explore them - thanks for guidance.

Body:
I just found this...

Try using ajaxComplete()... It fires when an ajax request has completed.

$( document ).ajaxComplete(initialise);

;)