问:
RabbitMQ Docker container not working on AWS EC2 instance
I have a RabbitMQ docker container running that is used by PHP AMQ Library with Docker compose.

When running locally on my laptop everything works fine and RabbitMQ can accept requests.

However when deploying to a t2.medium instance for testing, the RabbitMQ container keeps restarting and crashing every 40-50 seconds.

To make matters worse I cannot find the erl_crash.dump file in the EC2 instance.

```<code>   Crash dump is being written to: erl_crash.dump...
              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:05 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

=INFO REPORT==== 5-Dec-2017::13:49:05 ===
node           : rabbit@bbee863f0066
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : o9UBS7q82y5P84WzdKnCaw==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@bbee863f0066
erl_child_setup closed

Crash dump is being written to: erl_crash.dump...erl_child_setup closed

              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:13 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

=INFO REPORT==== 5-Dec-2017::13:49:13 ===
node           : rabbit@bbee863f0066
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : o9UBS7q82y5P84WzdKnCaw==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@bbee863f0066

=ERROR REPORT==== 5-Dec-2017::13:49:15 ===
Loading of /usr/lib/erlang/lib/stdlib-3.2/ebin/dets_v9.beam failed: badfile
WARNING: module dets_v9 not found, so not scanned for boot steps.

=ERROR REPORT==== 5-Dec-2017::13:49:15 ===
beam/beam_load.c(1179): Error loading module dets_v9:
  form size 113612 greater than size 82440 of binary

erl_child_setup closed

Crash dump is being written to: erl_crash.dump...erl_child_setup closed

Crash dump is being written to: erl_crash.dump...
              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:05 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

=INFO REPORT==== 5-Dec-2017::13:49:05 ===
node           : rabbit@bbee863f0066
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : o9UBS7q82y5P84WzdKnCaw==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@bbee863f0066
erl_child_setup closed

Crash dump is being written to: erl_crash.dump...erl_child_setup closed

              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:13 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

=INFO REPORT==== 5-Dec-2017::13:49:13 ===
node           : rabbit@bbee863f0066
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : o9UBS7q82y5P84WzdKnCaw==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@bbee863f0066

=ERROR REPORT==== 5-Dec-2017::13:49:15 ===
Loading of /usr/lib/erlang/lib/stdlib-3.2/ebin/dets_v9.beam failed: badfile
WARNING: module dets_v9 not found, so not scanned for boot steps.

=ERROR REPORT==== 5-Dec-2017::13:49:15 ===
beam/beam_load.c(1179): Error loading module dets_v9:
  form size 113612 greater than size 82440 of binary

erl_child_setup closed

Crash dump is being written to: erl_crash.dump...erl_child_setup closed

              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:22 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

=INFO REPORT==== 5-Dec-2017::13:49:22 ===
node           : rabbit@bbee863f0066
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : o9UBS7q82y5P84WzdKnCaw==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@bbee863f0066
erl_child_setup closed

Crash dump is being written to: erl_crash.dump...erl_child_setup closed

              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:32 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/
</code>```

This is my docker compose file for Rabbit:

```<code>rabbit:
    mem_limit: 80000000
    build: 'support/rabbitmq'
    environment:
        - RABBITMQ_DEFAULT_USER=${RABBITMQ_USER}
        - RABBITMQ_DEFAULT_PASS=${RABBITMQ_PASSWORD}
        - RABBITMQ_VM_MEMORY_HIGH_WATERMARK=800MB
    ports:
        - "15672:15672"
        - "5672:5672"
    restart: unless-stopped
</code>```

Any ideas why its not working, or how I can get this dump file?

答:
The issue was due to docker-compose mem-limit being incorrectly set

```<code>    mem_limit: 80000000
</code>```

This setting is 80mb, which is not enough for RabbitMQ to initialise properly.

Removing this and letting docker_compose manage container memory was the solution.

Body:
I have a RabbitMQ docker container running that is used by PHP AMQ Library with Docker compose.

When running locally on my laptop everything works fine and RabbitMQ can accept requests.

However when deploying to a t2.medium instance for testing, the RabbitMQ container keeps restarting and crashing every 40-50 seconds.

To make matters worse I cannot find the erl_crash.dump file in the EC2 instance.

   Crash dump is being written to: erl_crash.dump...
              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:05 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

=INFO REPORT==== 5-Dec-2017::13:49:05 ===
node           : rabbit@bbee863f0066
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : o9UBS7q82y5P84WzdKnCaw==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@bbee863f0066
erl_child_setup closed

Crash dump is being written to: erl_crash.dump...erl_child_setup closed

              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:13 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

=INFO REPORT==== 5-Dec-2017::13:49:13 ===
node           : rabbit@bbee863f0066
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : o9UBS7q82y5P84WzdKnCaw==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@bbee863f0066

=ERROR REPORT==== 5-Dec-2017::13:49:15 ===
Loading of /usr/lib/erlang/lib/stdlib-3.2/ebin/dets_v9.beam failed: badfile
WARNING: module dets_v9 not found, so not scanned for boot steps.

=ERROR REPORT==== 5-Dec-2017::13:49:15 ===
beam/beam_load.c(1179): Error loading module dets_v9:
  form size 113612 greater than size 82440 of binary

erl_child_setup closed

Crash dump is being written to: erl_crash.dump...erl_child_setup closed

Crash dump is being written to: erl_crash.dump...
              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:05 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

=INFO REPORT==== 5-Dec-2017::13:49:05 ===
node           : rabbit@bbee863f0066
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : o9UBS7q82y5P84WzdKnCaw==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@bbee863f0066
erl_child_setup closed

Crash dump is being written to: erl_crash.dump...erl_child_setup closed

              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:13 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

=INFO REPORT==== 5-Dec-2017::13:49:13 ===
node           : rabbit@bbee863f0066
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : o9UBS7q82y5P84WzdKnCaw==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@bbee863f0066

=ERROR REPORT==== 5-Dec-2017::13:49:15 ===
Loading of /usr/lib/erlang/lib/stdlib-3.2/ebin/dets_v9.beam failed: badfile
WARNING: module dets_v9 not found, so not scanned for boot steps.

=ERROR REPORT==== 5-Dec-2017::13:49:15 ===
beam/beam_load.c(1179): Error loading module dets_v9:
  form size 113612 greater than size 82440 of binary

erl_child_setup closed

Crash dump is being written to: erl_crash.dump...erl_child_setup closed

              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:22 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

=INFO REPORT==== 5-Dec-2017::13:49:22 ===
node           : rabbit@bbee863f0066
home dir       : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config
cookie hash    : o9UBS7q82y5P84WzdKnCaw==
log            : tty
sasl log       : tty
database dir   : /var/lib/rabbitmq/mnesia/rabbit@bbee863f0066
erl_child_setup closed

Crash dump is being written to: erl_crash.dump...erl_child_setup closed

              RabbitMQ 3.6.14. Copyright (C) 2007-2017 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: tty
  ######  ##        tty
  ##########
              Starting broker...

=INFO REPORT==== 5-Dec-2017::13:49:32 ===
Starting RabbitMQ 3.6.14 on Erlang 19.2.1
Copyright (C) 2007-2017 Pivotal Software, Inc.
Licensed under the MPL.  See http://www.rabbitmq.com/

This is my docker compose file for Rabbit:

rabbit:
    mem_limit: 80000000
    build: 'support/rabbitmq'
    environment:
        - RABBITMQ_DEFAULT_USER=${RABBITMQ_USER}
        - RABBITMQ_DEFAULT_PASS=${RABBITMQ_PASSWORD}
        - RABBITMQ_VM_MEMORY_HIGH_WATERMARK=800MB
    ports:
        - "15672:15672"
        - "5672:5672"
    restart: unless-stopped

Any ideas why its not working, or how I can get this dump file?

Body:
The issue was due to docker-compose mem-limit being incorrectly set

    mem_limit: 80000000

This setting is 80mb, which is not enough for RabbitMQ to initialise properly.

Removing this and letting docker_compose manage container memory was the solution.


来源: stackexchange

问:
Quotation Marks Causing Error on Page
I really hope someone can help me.  I've been banging my head against the wall with this one :(.

I have the following code that is driving me nuts

In my PHP file I have entered the following code to display a series of A-Z Links:

```<code><div>
 <ul id="AZList">
     <li><a id="LetterLink1" href="javascript:showonlyone('LetterList1');">#</a></li>
  <?php

   $lettercounter=1;
   for ($i=65; $i<=90; $i++){

      $lettercounter=$lettercounter+1;
      $LetterLinkLbL="ListLetter".$lettercounter;
?>

          <li><a id="LetterLink<?php echo $lettercounter ?>" href="javascript:showonlyone('<?php echo $LetterLinkLbL ?>');"><?php echo chr($i) ?></a></li>

  <?php } ?>
    </ul>

</div>
</code>```

But when I view the source file it displays as

```<code>  <li><a id="LetterLink1"  href="javascript:showonlyone("LetterList1');">#</a></li>

      <li><a id="LetterLink2"  href="javascript:showonlyone("ListLetter2');">A</a></li>

      <li><a id="LetterLink3"  href="javascript:showonlyone("ListLetter3');">B</a></li>
</code>```

Which is causing an error on the page

The first one should read:

```<code> <li><a id="LetterLink1"  href="javascript:showonlyone('LetterList1');">#</a></li>
</code>```

Does anyone know how I can get the quotes to display correctly?

I've just uploaded the file from my laptop to the Remote server and it is working as it should without me making any changes to the file.

I did confirm that I was working on and viewing the same file, by writing an echo statement to the page.

Why would it be showing like this on my localhost?  Does anyone have an idea what he issue could be?

Thank you for all your comments by the way

答:
There is discrepancy between what you have in your code and the ouput should give you :

Your code :

```<code>href="javascript:showonlyone('<?php echo $LetterLinkLbL ?>');"
</code>```

is bound to render :

```<code>href="javascript:showonlyone('ListLetter3');"
</code>```

but you state it renders (with a double quotation mark at the start and a single one at the end) :

```<code>href="javascript:showonlyone("ListLetter3');"
</code>```

The php code you give should not create an error at all as it is correct.
Are you sure you did not give us the output from another trial ?

The rule to insert a quotation inside a PHP/javascript string using that same quotation to enclose it is simply to add a \ before it :

```<code>$Value = "Hello Johnny \"PHP\" Boy !!";
</code>```

or

```<code>$Value = 'Hello Johnny \'PHP\' boy !';
</code>```

ContentLicense: CC BY-SA 2.5

Title: Quotation Marks Causing Error on Page

Body:
I really hope someone can help me.  I've been banging my head against the wall with this one :(.

I have the following code that is driving me nuts

In my PHP file I have entered the following code to display a series of A-Z Links:

#

  <?php

   $lettercounter=1;
   for ($i=65; $i<=90; $i++){

      $lettercounter=$lettercounter+1;
      $LetterLinkLbL="ListLetter".$lettercounter;
?>

<a id="LetterLink<?php echo $lettercounter ?>" href="javascript:showonlyone('<?php echo $LetterLinkLbL ?>');"><?php echo chr($i) ?>

  <?php } ?>

But when I view the source file it displays as

#

A

B

Which is causing an error on the page

The first one should read:

#

Does anyone know how I can get the quotes to display correctly?

I've just uploaded the file from my laptop to the Remote server and it is working as it should without me making any changes to the file.

I did confirm that I was working on and viewing the same file, by writing an echo statement to the page.

Why would it be showing like this on my localhost?  Does anyone have an idea what he issue could be?

Thank you for all your comments by the way

Body:
There is discrepancy between what you have in your code and the ouput should give you :

Your code :

href="javascript:showonlyone('<?php echo $LetterLinkLbL ?>');"

is bound to render :

href="javascript:showonlyone('ListLetter3');"

but you state it renders (with a double quotation mark at the start and a single one at the end) :

href="javascript:showonlyone("ListLetter3');"

The php code you give should not create an error at all as it is correct.
Are you sure you did not give us the output from another trial ?

The rule to insert a quotation inside a PHP/javascript string using that same quotation to enclose it is simply to add a \ before it :

$Value = "Hello Johnny \"PHP\" Boy !!";

or

$Value = 'Hello Johnny \'PHP\' boy !';


问:
How does event handlers with arrow functions achieve context binding
I know about the general theory of this binding (function call site what matters, implicit, explicit binding, etc...) and the methods to solving the problem of this binding in React so it always points to what I want this to be (binding in constructor, arrow functions, etc), but I am struggling to get the inner mechanisms.

Take a look at these two pieces of code:

```<code>class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={(e) => this.goToStore(e)}>test</button>
  }
}
</code>```

vs.

```<code>class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={this.goToStore}>test</button>
  }
}
</code>```

What I know is that:

in both versions we end up successfully in the goToStore method, because the this inside the render() method is automatically bound (by React) to the component instance

the first one succeeds because of that,

the second one fails, because class methods in es6 are not bound to the component instance, thus resolving this in the method to undefined

In theory in the first version as far as I understand, the following occurs:

the button click handler is an anonymous arrow function, so whenever I reference this inside of it, it picks up this from the environment (in this case from render())

then it calls the goToStore method, that is a regular function.

because the call seems to fit the rules of implicit binding (object.function()) object will be the context object and in such function calls it will be used as this

so, inside the goToStore method the lexically picked up this (used as a context object) will resolve to the component instance correctly

I feel 3. and 4. is not the case here, because then it would apply to the 2. case:

```<code><button onClick={this.goToStore}>test</button>
</code>```

Also with this the context object.

What is happening exactly in this particular case, step-by-step?

答:
In case 1, as you said, the context is picked up from the environment.
For case 2, you have to remember that the class syntax in ES6 is just syntactic sugar over the more cumbersome prototype syntax on which JavaScript relies upon to implement OOP.

Basically, in the second example, all you are doing is something like this:

```<code>function demo() {
   // this is the constructor
}
demo.prototype.goToStore = function() {
  // handler
};
demo.prototype.render = function() {
  return React.createElement('button', onClick: this.goToStore);
}
</code>```

As you can see, the onClick property is just receiving a reference to the function. Whenever that function is called, no this will be binded, and it will be run in the context of the window object.

In older libraries, prior to the existence of modern transpilers, we used to do something like this ALL OVER THE PLACE:

```<code>function demo() {
   // this is the constructor
   this.goToStore = this.goToStore.bind(this);
   // same for every other handler
}
demo.prototype.goToStore = function() {
   // handling code.
};
demo.prototype.render = function() {
  // this goToStore reference has the proper this binded.
  return React.createElement('button', onClick: this.goToStore);
}
</code>```

Nowadays, this last example I put is automatically handled by all modern transpilers. Babel basically does the autobinding in the constructor when you use the fat arrow method syntax in any class:

```<code>class demo extends Anything {
  constructor() {
  }
  bindedMethod = () => {
    // my context will always be the instance!
  }
}
</code>```

With subtle differences, all transpilers will move the definition of the bindedMethod to the constructor, where the this will be bound to the current instance running the constructor.

ContentLicense: CC BY-SA 3.0

Body:
I know about the general theory of this binding (function call site what matters, implicit, explicit binding, etc...) and the methods to solving the problem of this binding in React so it always points to what I want this to be (binding in constructor, arrow functions, etc), but I am struggling to get the inner mechanisms.

Take a look at these two pieces of code:

class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={(e) => this.goToStore(e)}>test</button>
  }
}

vs.

class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={this.goToStore}>test</button>
  }
}

What I know is that:

in both versions we end up successfully in the goToStore method, because the this inside the render() method is automatically bound (by React) to the component instance

the first one succeeds because of that,

the second one fails, because class methods in es6 are not bound to the component instance, thus resolving this in the method to undefined

In theory in the first version as far as I understand, the following occurs:

the button click handler is an anonymous arrow function, so whenever I reference this inside of it, it picks up this from the environment (in this case from render())

then it calls the goToStore method, that is a regular function.

because the call seems to fit the rules of implicit binding (object.function()) object will be the context object and in such function calls it will be used as this

so, inside the goToStore method the lexically picked up this (used as a context object) will resolve to the component instance correctly

I feel 3. and 4. is not the case here, because then it would apply to the 2. case:

<button onClick={this.goToStore}>test</button>

Also with this the context object.

What is happening exactly in this particular case, step-by-step?

Body:
In case 1, as you said, the context is picked up from the environment.
For case 2, you have to remember that the class syntax in ES6 is just syntactic sugar over the more cumbersome prototype syntax on which JavaScript relies upon to implement OOP.

Basically, in the second example, all you are doing is something like this:

function demo() {
   // this is the constructor
}
demo.prototype.goToStore = function() {
  // handler
};
demo.prototype.render = function() {
  return React.createElement('button', onClick: this.goToStore);
}

As you can see, the onClick property is just receiving a reference to the function. Whenever that function is called, no this will be binded, and it will be run in the context of the window object.

In older libraries, prior to the existence of modern transpilers, we used to do something like this ALL OVER THE PLACE:

function demo() {
   // this is the constructor
   this.goToStore = this.goToStore.bind(this);
   // same for every other handler
}
demo.prototype.goToStore = function() {
   // handling code.
};
demo.prototype.render = function() {
  // this goToStore reference has the proper this binded.
  return React.createElement('button', onClick: this.goToStore);
}

Nowadays, this last example I put is automatically handled by all modern transpilers. Babel basically does the autobinding in the constructor when you use the fat arrow method syntax in any class:

class demo extends Anything {
  constructor() {
  }
  bindedMethod = () => {
    // my context will always be the instance!
  }
}

With subtle differences, all transpilers will move the definition of the bindedMethod to the constructor, where the this will be bound to the current instance running the constructor.


问:
How can I create a column that cumulatively adds the sum of two previous rows based on conditions?
I tried asking this question before but was it was poorly stated. This is a new attempt cause I haven't solved it yet.

I have a dataset with winners, losers, date, winner_points and loser_points.

For each row, I want two new columns, one for the winner and one for the loser that shows how many points they have scored so far (as both winners and losers).

Example data:

```<code>winner <- c(1,2,3,1,2,3,1,2,3)
loser <-  c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)
</code>```

I want the output to be:

```<code>winner_points_sum <- c(0, 0, 1, 3, 1, 3, 5, 3, 5)
loser_points_sum <- c(0, 2, 2, 1, 4, 5, 4, 7, 4)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points, winner_points_sum, loser_points_sum)
</code>```

How I've solved it thus far is to do a for loop such as:

```<code>library(dplyr)
test_data$winner_points_sum_loop <- 0
test_data$loser_points_sum_loop <- 0

for(i in row.names(test_data)) {
  test_data[i,]$winner_points_sum_loop <-
    (
    test_data %>%
      dplyr::filter(winner == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(winner_points, na.rm = TRUE))
  +
    test_data %>%
      dplyr::filter(loser == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(loser_points, na.rm = TRUE))
    )
}

test_data$winner_points_sum_loop <- unlist(test_data$winner_points_sum_loop)
</code>```

Any suggestions how to tackle this problem? The queries take quite some time when the row numbers add up. I've tried elaborating with the AVE function, I can do it for one column to sum a players point as winner but can't figure out how to add their points as loser.

答:
```<code>winner <- c(1,2,3,1,2,3,1,2,3)
loser <-  c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)

library(dplyr)
library(tidyr)

test_data %>%
  unite(winner, winner, winner_points) %>%                    # unite winner columns
  unite(loser, loser, loser_points) %>%                       # unite loser columns
  gather(type, pl_pts, winner, loser, -date) %>%              # reshape
  separate(pl_pts, c("player","points"), convert = T) %>%     # separate columns
  arrange(date) %>%                                           # order dates (in case it's not)
  group_by(player) %>%                                        # for each player
  mutate(sum_points = cumsum(points) - points) %>%            # get points up to that date
  ungroup() %>%                                               # forget the grouping
  unite(pl_pts_sumpts, player, points, sum_points) %>%        # unite columns
  spread(type, pl_pts_sumpts) %>%                             # reshape
  separate(loser, c("loser", "loser_points", "loser_points_sum"), convert = T) %>%                # separate columns and give appropriate names
  separate(winner, c("winner", "winner_points", "winner_points_sum"), convert = T) %>%
  select(winner, loser, date, winner_points, loser_points, winner_points_sum, loser_points_sum)   # select the order you prefer

# # A tibble: 9 x 7
#   winner loser       date winner_points loser_points winner_points_sum loser_points_sum
# *  <int> <int>     <date>         <int>        <int>             <int>            <int>
# 1      1     3 2017-10-01             2            1                 0                0
# 2      2     1 2017-10-02             1            0                 0                2
# 3      3     1 2017-10-03             2            1                 1                2
# 4      1     2 2017-10-04             1            0                 3                1
# 5      2     1 2017-10-05             2            1                 1                4
# 6      3     1 2017-10-06             1            0                 3                5
# 7      1     3 2017-10-07             2            1                 5                4
# 8      2     1 2017-10-08             1            0                 3                7
# 9      3     2 2017-10-09             2            1                 5                4
</code>```

Body:
I tried asking this question before but was it was poorly stated. This is a new attempt cause I haven't solved it yet.

I have a dataset with winners, losers, date, winner_points and loser_points.

For each row, I want two new columns, one for the winner and one for the loser that shows how many points they have scored so far (as both winners and losers).

Example data:

winner <- c(1,2,3,1,2,3,1,2,3)
loser <-  c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)

I want the output to be:

winner_points_sum <- c(0, 0, 1, 3, 1, 3, 5, 3, 5)
loser_points_sum <- c(0, 2, 2, 1, 4, 5, 4, 7, 4)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points, winner_points_sum, loser_points_sum)

How I've solved it thus far is to do a for loop such as:

library(dplyr)
test_data$winner_points_sum_loop <- 0
test_data$loser_points_sum_loop <- 0

for(i in row.names(test_data)) {
  test_data[i,]$winner_points_sum_loop <-
    (
    test_data %>%
      dplyr::filter(winner == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(winner_points, na.rm = TRUE))
  +
    test_data %>%
      dplyr::filter(loser == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(loser_points, na.rm = TRUE))
    )
}

test_data$winner_points_sum_loop <- unlist(test_data$winner_points_sum_loop)

Any suggestions how to tackle this problem? The queries take quite some time when the row numbers add up. I've tried elaborating with the AVE function, I can do it for one column to sum a players point as winner but can't figure out how to add their points as loser.


问:
can prolog programs using library(real) be made relational?
in such a program using library(real):

```<code>:- use_module( library(real) ).
:- use_module( library(lists) ).
:- use_module( library(apply_macros) ).
:- use_module( library(readutil) ).

my_sum(L, S):-
    i <- L,
    <- i,
    S <- sum(i).
</code>```

is there a way to modify the program to be able to run it backwards?
Currently, this works:

```<code>?- my_sum([1,2,3],X).
X = 6.
</code>```

But this results in an exception:

```<code>?- my_sum(L,2).
ERROR: Arguments are not sufficiently instantiated
ERROR: In:
ERROR:   [13] _6776=..[_6782|_6784]
ERROR:   [12] real:r_call(_6814,[rvar(i),...|_6832]) at /home/raoul/lib/swipl/pack/real/prolog/real.pl:1101
ERROR:    [8] my_sum(_6862++[...|_6870],2) at /home/raoul/Bureau/prolog_relational_stats/relational_R.pl:16
ERROR:    [7] <user>
ERROR:
ERROR: Note: some frames are missing due to last-call optimization.
ERROR: Re-run your program in debug mode (:- debug.) to get more detail.
</code>```

答:
From p. 4 of the manual:

The <-/1 predicate sends an R expression, represented as a ground Prolog
  term, to R, without getting any results back to Prolog. The <-/2 operator
  facilitates bi-directional communication. If the left-hand side is a free
  variable, the library assumes that we are passing data from R to Prolog.
  If the left-hand side is bound, Real assumes that we are passing data or
  function calls to R.

So your code fails if L is uninstantiated.

You can handle the cases like this:

```<code>my_sum(L,S) :-
  ( ground(L), var(S) ->
    i <- L, <- i, S <- sum(i)
  ; var(L), ground(S) ->
    % your code here
  ; % error?
    ).
</code>```

Then my_sum/2 can be used in either direction.

Body:
in such a program using library(real):

:- use_module( library(real) ).
:- use_module( library(lists) ).
:- use_module( library(apply_macros) ).
:- use_module( library(readutil) ).

my_sum(L, S):-
    i <- L,
    <- i,
    S <- sum(i).

is there a way to modify the program to be able to run it backwards?
Currently, this works:

?- my_sum([1,2,3],X).
X = 6.

But this results in an exception:

?- my_sum(L,2).
ERROR: Arguments are not sufficiently instantiated
ERROR: In:
ERROR:   [13] _6776=..[_6782|_6784]
ERROR:   [12] real:r_call(_6814,[rvar(i),...|_6832]) at /home/raoul/lib/swipl/pack/real/prolog/real.pl:1101
ERROR:    [8] my_sum(_6862++[...|_6870],2) at /home/raoul/Bureau/prolog_relational_stats/relational_R.pl:16
ERROR:    [7] <user>
ERROR:
ERROR: Note: some frames are missing due to last-call optimization.
ERROR: Re-run your program in debug mode (:- debug.) to get more detail.

Body:
From p. 4 of the manual:

The <-/1 predicate sends an R expression, represented as a ground Prolog
  term, to R, without getting any results back to Prolog. The <-/2 operator
  facilitates bi-directional communication. If the left-hand side is a free
  variable, the library assumes that we are passing data from R to Prolog.
  If the left-hand side is bound, Real assumes that we are passing data or
  function calls to R.

So your code fails if L is uninstantiated.

You can handle the cases like this:

my_sum(L,S) :-
  ( ground(L), var(S) ->
    i <- L, <- i, S <- sum(i)
  ; var(L), ground(S) ->
    % your code here
  ; % error?
    ).

Then my_sum/2 can be used in either direction.


问:
Accessing component of the ActivatedRoute in the canActivate Guard
As far as I know the call signature of canActivate looks like this:

```<code>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

}
</code>```

I have a service that expects the name of a component and returns the necessary user role to access this component, so that I can check in the canActivate function of my guard, whether the active user has the corresponding role or not.
My problem is, that I don't know  how to access the component. After some googling I found solutions like this:

```<code>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  const nameOfComponent = route.routeConfig.component.name;
  return doSomeRoleCheck(nameOfComponent);
}
</code>```

But in my case I just get an error: "Cannot read proprty 'name' of undefined". How can I access the component of the active Route or especially the name as a string?

Edit

I found out, that I do check this guard on a parent route. When I check it in the child route it works. How can I access the child component from parent can ActivatedRouteSnapshot

答:
Something like this would probably work in your case:</p>

```<code>export abstract class RoleCheck {
  myRoles: string[];
}

@Component({ ... })
export class YourComponent extends RoleCheck {
  public myRoles = ['User', 'Admin'];
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  if (!route.routeConfig.component instanceof RoleCheck) {
    //Throw
  }
  return doSomeRoleCheck(route.routeConfig.component.myRoles)
}
</code>```

Body:
As far as I know the call signature of canActivate looks like this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

}

I have a service that expects the name of a component and returns the necessary user role to access this component, so that I can check in the canActivate function of my guard, whether the active user has the corresponding role or not.
My problem is, that I don't know  how to access the component. After some googling I found solutions like this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  const nameOfComponent = route.routeConfig.component.name;
  return doSomeRoleCheck(nameOfComponent);
}

But in my case I just get an error: "Cannot read proprty 'name' of undefined". How can I access the component of the active Route or especially the name as a string?

Edit

I found out, that I do check this guard on a parent route. When I check it in the child route it works. How can I access the child component from parent can ActivatedRouteSnapshot

Body:
Something like this would probably work in your case:

export abstract class RoleCheck {
  myRoles: string[];
}

@Component({ ... })
export class YourComponent extends RoleCheck {
  public myRoles = ['User', 'Admin'];
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  if (!route.routeConfig.component instanceof RoleCheck) {
    //Throw
  }
  return doSomeRoleCheck(route.routeConfig.component.myRoles)
}


问:
Temporary store a value using `java-stream`
I was wondering if there is a way of temporary storing/carrying a value within a java-stream?

```<code>List<Department> departments = (ArrayList<Department>) departmentRepository.findAll();

departments.parallelStream()
        .filter(e -> e.getUnderstuffCount(date) > 0)
        .forEach(e -> {
            holidaysPlaningProblemManager.addProblem(e, date, e.getUnderstuffCount(date));
        });
</code>```

the multiple calls for e.getUnderstuffCount(date) seams "dirty" and I was wondering if there is a way to avoid it by carrying the result of a single call?

EDIT:

Please consider this as a java-stream question. There are a lot of ways to solve this, for example a @Transient field in the Department @Entity can store the value and a simple getter can return it.

But i'm interested if this can be done using the java-stream

答:
As I mentioned in my comment, there is a popular suggestion for questions like this to map a stream element to a pair containing the element itself and whichever intermediate value you need. First, let's find a simpler example (that also compiles for me):

```<code>Stream.of("Hello", "World", "!")
      .filter(s -> s.length() > 1)
      .forEach(s -> System.out.println(s + ": " + s.length()));
// Hello: 5
// World: 5
</code>```

If we now take either a simple array or an AbstractMap.SimpleEntry as a pair object, we can add one mapping step:

```<code>Stream.of("Hello", "World", "!")
      .map(s -> new Object[] {s, s.length()})
      .filter(a -> ((int) a[1]) > 1)
      .forEach(a -> System.out.println(a[0] + ": " + a[1]));

Stream.of("Hello", "World", "!")
      .map(s -> new AbstractMap.SimpleEntry<>(s, s.length()))
      .filter(e -> e.getValue() > 1)
      .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
</code>```

The array variant is a bit shorter to write, but not type-safe. I'd use the second posibility. Or maybe you could add an actual Pair<L, R> class to your project with short method names and a nice factory method (Pair.of(s, s.length())). Whichever way you choose, it is better than collecting into a map with a collector (stream.collect(toMap()).entrySet().stream().filter(e).forEach(e)), as you do not materialize the whole map into memory.

The other possibility I mentioned is to pull the check into the forEach. Given your (possibily simplified) example, I'd say this is the most easy to read way, but is of course not as "stream-y" or "lambda-y".

```<code>Stream.of("Hello", "World", "!").forEach(s -> {
    int length = s.length();
    if (length > 1)
    {
        System.out.println(s + ": " + length);
    }
});
</code>```

In this simple example, you don't even need to have a stream. Just call Collection.forEach().

In the end you have to see whether using streams here is even worth it. You use parallel stream, but does it actually speed things up (e.g. is your holidaysPlaningProblemManager thread-safe or does it just synchronize all threads again, making the parallel stream pointless)? If not, you could just refactor to a normal for loop or Collection.forEach.

Body:
I was wondering if there is a way of temporary storing/carrying a value within a java-stream?

List<Department> departments = (ArrayList<Department>) departmentRepository.findAll();

departments.parallelStream()
        .filter(e -> e.getUnderstuffCount(date) > 0)
        .forEach(e -> {
            holidaysPlaningProblemManager.addProblem(e, date, e.getUnderstuffCount(date));
        });

the multiple calls for e.getUnderstuffCount(date) seams "dirty" and I was wondering if there is a way to avoid it by carrying the result of a single call?

EDIT:

Please consider this as a java-stream question. There are a lot of ways to solve this, for example a @Transient field in the Department @Entity can store the value and a simple getter can return it.

But i'm interested if this can be done using the java-stream

Body:
As I mentioned in my comment, there is a popular suggestion for questions like this to map a stream element to a pair containing the element itself and whichever intermediate value you need. First, let's find a simpler example (that also compiles for me):

Stream.of("Hello", "World", "!")
      .filter(s -> s.length() > 1)
      .forEach(s -> System.out.println(s + ": " + s.length()));
// Hello: 5
// World: 5

If we now take either a simple array or an AbstractMap.SimpleEntry as a pair object, we can add one mapping step:

Stream.of("Hello", "World", "!")
      .map(s -> new Object[] {s, s.length()})
      .filter(a -> ((int) a[1]) > 1)
      .forEach(a -> System.out.println(a[0] + ": " + a[1]));

Stream.of("Hello", "World", "!")
      .map(s -> new AbstractMap.SimpleEntry<>(s, s.length()))
      .filter(e -> e.getValue() > 1)
      .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));

The array variant is a bit shorter to write, but not type-safe. I'd use the second posibility. Or maybe you could add an actual Pair<L, R> class to your project with short method names and a nice factory method (Pair.of(s, s.length())). Whichever way you choose, it is better than collecting into a map with a collector (stream.collect(toMap()).entrySet().stream().filter(e).forEach(e)), as you do not materialize the whole map into memory.

The other possibility I mentioned is to pull the check into the forEach. Given your (possibily simplified) example, I'd say this is the most easy to read way, but is of course not as "stream-y" or "lambda-y".

Stream.of("Hello", "World", "!").forEach(s -> {
    int length = s.length();
    if (length > 1)
    {
        System.out.println(s + ": " + length);
    }
});

In this simple example, you don't even need to have a stream. Just call Collection.forEach().

In the end you have to see whether using streams here is even worth it. You use parallel stream, but does it actually speed things up (e.g. is your holidaysPlaningProblemManager thread-safe or does it just synchronize all threads again, making the parallel stream pointless)? If not, you could just refactor to a normal for loop or Collection.forEach.


问:
How to split a string and get only segament after the question mark
how do you split a string and get the sentence only after the question mark. For example say you have the line : hello?myNameIs...

 how could you only get what's after the question mark

 many thanks

答:
If all your use cases will be similar to the simple example you've stated, you could use a simple split.

The code:

```<code>String delim = "\\?";
String s = "hello?myNameIs";
String token[] = s.split(delim);
System.out.println(token[1]);
</code>```

Gives the output:

```<code>myNameIs
</code>```

Of course, you can tinker with it to solve your specific problems.

Body:
If all your use cases will be similar to the simple example you've stated, you could use a simple split.

The code:

String delim = "\\?";
String s = "hello?myNameIs";
String token[] = s.split(delim);
System.out.println(token[1]);

Gives the output:

myNameIs

Of course, you can tinker with it to solve your specific problems.


问:
Draw SpatialPolygons with multiple subpolygons and holes using ggplot2
I would like to draw SpatialPolygons from library sp with holes in ggplot2.
Thanks to others questions on stackoverflow, I know that this is allowed while dealing with clockwise written polygons:

http://stackoverflow.com/questions/12047643/geom-polygon-with-multiple-hole/12051278#12051278

Indeed, when transforming a SpatialPolygons using broom::tidy (replacing ggplot2::fortify), holes polygons are saved in clockwise direction to be drawn as holes.

In ggplot2, the way polygons with holes are drawn force to draw them once using fill, and another time using colour, otherwise you may see lines crossing polygons.
When dealing with multiple subpolygons, some with holes, this is more tricky, the order of points features as defined by broom::tidy may not allow for filling polygons (see image below).

Do any of you have a solution to get rid of this filling problem behaviour ?

Here is a reproducible example:

```<code>library(sp)
library(ggplot2)

# Create two polygons: second would be a hole inside the first
xy = cbind(
  x = c(13.4, 13.4, 13.6, 13.6, 13.4),
  y = c(48.9, 49, 49, 48.9, 48.9)
    )
hole.xy <- cbind(
  x = c(13.5, 13.5, 13.45, 13.45, 13.5),
  y = c(48.98, 48.92, 48.92, 48.98, 48.98)
  )

# Transform as SpatialPolygons with holes
xy.sp <- SpatialPolygons(list(
  Polygons(list(Polygon(xy),
                Polygon(hole.xy, hole = TRUE)), "1"),
  Polygons(list(Polygon(xy + 0.2),
                Polygon(xy + 0.35),
                Polygon(hole.xy + 0.2, hole = TRUE)), "2")
  ))

# Transform SpatialObject to be used by ggplot2
xy.sp.l <- broom::tidy(xy.sp)

ggplot(xy.sp.l) +
  geom_polygon(aes(x = long, y = lat, group = id, fill = id))
</code>```

(source: statnmap.com)

答:
This post is a good question and already received great answers. I also believe people should learn how to work with sf objects as it is the next generation of the spatial data type in R. But I want to share that in this case geom_spatial from the ggspatial package could be an option to plot the SpatialPolygons.

```<code>library(sp)
library(ggplot2)
library(ggspatial)

ggplot() +
  geom_spatial(xy.sp, aes(fill = id))
# Ignoring argument 'mapping' in geom_spatial.SpatialPolygons
# Autodetect projection: assuming lat/lon (epsg 4326)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to draw SpatialPolygons from library sp with holes in ggplot2.
Thanks to others questions on stackoverflow, I know that this is allowed while dealing with clockwise written polygons:

http://stackoverflow.com/questions/12047643/geom-polygon-with-multiple-hole/12051278#12051278

Indeed, when transforming a SpatialPolygons using broom::tidy (replacing ggplot2::fortify), holes polygons are saved in clockwise direction to be drawn as holes.

In ggplot2, the way polygons with holes are drawn force to draw them once using fill, and another time using colour, otherwise you may see lines crossing polygons.
When dealing with multiple subpolygons, some with holes, this is more tricky, the order of points features as defined by broom::tidy may not allow for filling polygons (see image below).

Do any of you have a solution to get rid of this filling problem behaviour ?

Here is a reproducible example:

library(sp)
library(ggplot2)

# Create two polygons: second would be a hole inside the first
xy = cbind(
  x = c(13.4, 13.4, 13.6, 13.6, 13.4),
  y = c(48.9, 49, 49, 48.9, 48.9)
    )
hole.xy <- cbind(
  x = c(13.5, 13.5, 13.45, 13.45, 13.5),
  y = c(48.98, 48.92, 48.92, 48.98, 48.98)
  )

# Transform as SpatialPolygons with holes
xy.sp <- SpatialPolygons(list(
  Polygons(list(Polygon(xy),
                Polygon(hole.xy, hole = TRUE)), "1"),
  Polygons(list(Polygon(xy + 0.2),
                Polygon(xy + 0.35),
                Polygon(hole.xy + 0.2, hole = TRUE)), "2")
  ))

# Transform SpatialObject to be used by ggplot2
xy.sp.l <- broom::tidy(xy.sp)

ggplot(xy.sp.l) +
  geom_polygon(aes(x = long, y = lat, group = id, fill = id))

(source: statnmap.com)

Body:
This post is a good question and already received great answers. I also believe people should learn how to work with sf objects as it is the next generation of the spatial data type in R. But I want to share that in this case geom_spatial from the ggspatial package could be an option to plot the SpatialPolygons.

library(sp)
library(ggplot2)
library(ggspatial)

ggplot() +
  geom_spatial(xy.sp, aes(fill = id))
# Ignoring argument 'mapping' in geom_spatial.SpatialPolygons
# Autodetect projection: assuming lat/lon (epsg 4326)


问:
PHPIniDir broken under windows 7?
I had a server running on a Windows XP machine using Apache2 with PHP and MySQL. I've recently upgraded to Windows 7 and have been having trouble getting it to work. Apache works fine and PHP works, but I can't seem to get it to work with a php.ini file.

When I set PHPIniDir to a directory with a php.ini file, the Apache service does NOT start.

When I set PHPIniDir to a directory with NO php.ini file, the Apache service does start.

When I leave out PHPIniDir, the Apache service does not start.

Has anyone found a fix for this problem? Thanks!

EDIT :

PHPIniDir "C:\Windows"                   #works (no php.ini file)

PHPIniDir "C:\Program Files (x86)\php\"  #does not work (contains php.ini file)

I enable at most one at any given time.

答:
As an alternative to the @ar2r answer of deleting the last backslash, you can write the path using (forward) slashes and it would work even with an slash at the end. For some reason using a backslash at the end of a path doesn't works in recent versions of Windows:

```<code># works, no slash or forward slash at the end
PHPIniDir "C:\Program Files\PHP7"
PHPIniDir "C:/Program Files/PHP7/"
PHPIniDir "C:\Program Files\PHP7/" # mixing slashes and backslashes

# doesn't works, backslash at the end
PHPIniDir "C:\Program Files\PHP7\"
</code>```

Note that mixing forward and backslashes works as long as the trailing slash is not a backslash.

This applies also to other directives, I noticed this behavior when configuring the Alias for the icons of the directory index.

Title: PHPIniDir broken under windows 7?

Body:
As an alternative to the @ar2r answer of deleting the last backslash, you can write the path using (forward) slashes and it would work even with an slash at the end. For some reason using a backslash at the end of a path doesn't works in recent versions of Windows:

# works, no slash or forward slash at the end
PHPIniDir "C:\Program Files\PHP7"
PHPIniDir "C:/Program Files/PHP7/"
PHPIniDir "C:\Program Files\PHP7/" # mixing slashes and backslashes

# doesn't works, backslash at the end
PHPIniDir "C:\Program Files\PHP7\"

Note that mixing forward and backslashes works as long as the trailing slash is not a backslash.

This applies also to other directives, I noticed this behavior when configuring the Alias for the icons of the directory index.


问:
Windows updateWarning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

Fatal error: Unknown: Failed opening required 'C:/School/OneDrive - Noorderpoort/PHP/htdocs/Jaar1/Blok1/Les7/oefening16.php' (include_path='C:\xampp\php\PEAR') in Unknown on line 0

After a long windows update I suddenly get this error when I try to open a php file through the localhost.

How can I solve this problem?

答:
I've got the same problem with MAMP for Windows. The problem occurs when you use your OneDrive folder for hosting your files.
It seems the Fall Creators Update introduced it.
I've worked around the problem and moved my files to a non-Onedrive location.
See also: https://social.technet.microsoft.com/Forums/windows/en-US/f445b2f1-01e1-4380-8b8f-28f331b30d41/fall-creators-update-onedrive-interfering-with-wamp-web-server</p>


问:
Some times response not sending when sequelize error occur (Unhandled rejection SequelizeDatabaseError)
when i pass wrong QueryParams value like minus value. occur Unhandled rejection SequelizeDatabaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-8, 4' at line 1 that situation not get response from server

```<code>http://localhost:500/XXX/getXXX?currentPage=-1&numPerPage=4
</code>```

答:
Most likely global error was not handled properly. Try adding it to your routes.</p>

```<code>app.use(function(err, req, res, next) {
  console.error(err);
  res.status(500).send('internal server error');
})
</code>```

Body:
when i pass wrong QueryParams value like minus value. occur Unhandled rejection SequelizeDatabaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-8, 4' at line 1 that situation not get response from server

http://localhost:500/XXX/getXXX?currentPage=-1&numPerPage=4

Body:
Most likely global error was not handled properly. Try adding it to your routes.

app.use(function(err, req, res, next) {
  console.error(err);
  res.status(500).send('internal server error');
})


问:
Downloading Files with Python Urllib, Urllib2
I am trying to download files from a website using urllib as described in this thread: link text

```<code>import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
</code>```

I am able to download the files (mostly pdf) but all I get is corrupted files that cannot open. I suspect it's because the website requires a login.

How can the above function be modified to handle cookies? I already know the names of the form fields that carry the username & password information. When I print the return values of urlretrieve I get messages like:

```<code>a, b = urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
print a, b

>> **cache-control:** no-cache, no-store, must-revalidate, s-maxage=300, proxy-revalida
te

>> **connection:** close
</code>```

I am able to manually download the files if I enter their urls in the browser. Thanks

答: I might be possible that the server you requesting to is looking for certain header messages, such as User-Agent. You may try mimicking a browser behavior by sending additional headers.</p>

Body:
I am trying to download files from a website using urllib as described in this thread: link text

import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")

I am able to download the files (mostly pdf) but all I get is corrupted files that cannot open. I suspect it's because the website requires a login.

How can the above function be modified to handle cookies? I already know the names of the form fields that carry the username & password information. When I print the return values of urlretrieve I get messages like:

a, b = urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
print a, b

>> **cache-control:** no-cache, no-store, must-revalidate, s-maxage=300, proxy-revalida
te

>> **connection:** close

I am able to manually download the files if I enter their urls in the browser. Thanks


问:
Enumerator's loop magic (No break and no endless loop at the same time)
How do loop inside a Enumerator.new knows where to stop?

Now more descriptive example. Here are tow snippets of code both of them return same array: [1,2,4,8]. But in first example break condition in loop exists, when second example stops somehow.

Example #1 with break

```<code>def simple n
  x  = []
  a = 1
  i = 0
  loop do
    x << a
    a *= 2
    i += 1
    break unless i < n # in this case condition for stop used
  end
  x
end
p simple(4)== [1,2,4,8]
</code>```

Example #2 "magical"

```<code>def enumer
  Enumerator.new do |x|
      a = 1
      loop do # How do this loop know where to stop?
       x << a
       a *= 2
      end
  end
end
p enumer.take(4) == [1,2,4,8]
</code>```

答:
Consider the following:

```<code>enum = Enumerator.new do |x|
  x << "hello"
  x << "world"
end

enum.take(1)
 #=> ["hello"]
enum.take(100)
 #=> ["hello", "world"]
</code>```

What's going on here?

Well, the yielded variable x is an instance of Enumerator::Yielder. Whenever you call << or yield on the variable, a value will be appended to the final array of results.

enum.take(n) is saying "try to collect up to n values for this enumerable".

So, looking back at your original example, we had:

```<code>loop do
  x << a
  a *= 2
end
</code>```

Because you called take(4) on the enumerable, the Enumerator::Yielder will know to return immediately, if has collected 4 items.

...On the other hand, if you try running e.g. enumer.to_a then the loop will just go on forever - as it wasn't given any condition to exit early!

From what I've found, the ruby documentation on how this works is a little sparse; but there is this helpful description of the behaviour in the source code:

```<code>/*
 * call-seq:
 *   Enumerator.new(size = nil) { |yielder| ... }
 *   Enumerator.new(obj, method = :each, *args)
 *
 * Creates a new Enumerator object, which can be used as an
 * Enumerable.
 *
 * In the first form, iteration is defined by the given block, in
 * which a "yielder" object, given as block parameter, can be used to
 * yield a value by calling the +yield+ method (aliased as +<<+):
 *
 *   fib = Enumerator.new do |y|
 *     a = b = 1
 *     loop do
 *       y << a
 *       a, b = b, a + b
 *     end
 *   end
 *
 *   p fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
 *
 * The optional parameter can be used to specify how to calculate the size
 * in a lazy fashion (see Enumerator#size). It can either be a value or
 * a callable object.
 *
 * In the second, deprecated, form, a generated Enumerator iterates over the
 * given object using the given method with the given arguments passed.
 *
 * Use of this form is discouraged.  Use Kernel#enum_for or Kernel#to_enum
 * instead.
 *
 *   e = Enumerator.new(ObjectSpace, :each_object)
 *       #-> ObjectSpace.enum_for(:each_object)
 *
 *   e.select { |obj| obj.is_a?(Class) }  #=> array of all classes
 *
 */
</code>```

Body:
How do loop inside a Enumerator.new knows where to stop?

Now more descriptive example. Here are tow snippets of code both of them return same array: [1,2,4,8]. But in first example break condition in loop exists, when second example stops somehow.

Example #1 with break

def simple n
  x  = []
  a = 1
  i = 0
  loop do
    x << a
    a *= 2
    i += 1
    break unless i < n # in this case condition for stop used
  end
  x
end
p simple(4)== [1,2,4,8]

Example #2 "magical"

def enumer
  Enumerator.new do |x|
      a = 1
      loop do # How do this loop know where to stop?
       x << a
       a *= 2
      end
  end
end
p enumer.take(4) == [1,2,4,8]

Body:
Consider the following:

enum = Enumerator.new do |x|
  x << "hello"
  x << "world"
end

enum.take(1)
 #=> ["hello"]
enum.take(100)
 #=> ["hello", "world"]

What's going on here?

Well, the yielded variable x is an instance of Enumerator::Yielder. Whenever you call << or yield on the variable, a value will be appended to the final array of results.

enum.take(n) is saying "try to collect up to n values for this enumerable".

So, looking back at your original example, we had:

loop do
  x << a
  a *= 2
end

Because you called take(4) on the enumerable, the Enumerator::Yielder will know to return immediately, if has collected 4 items.

...On the other hand, if you try running e.g. enumer.to_a then the loop will just go on forever - as it wasn't given any condition to exit early!

From what I've found, the ruby documentation on how this works is a little sparse; but there is this helpful description of the behaviour in the source code:

/*
 * call-seq:
 *   Enumerator.new(size = nil) { |yielder| ... }
 *   Enumerator.new(obj, method = :each, *args)
 *
 * Creates a new Enumerator object, which can be used as an
 * Enumerable.
 *
 * In the first form, iteration is defined by the given block, in
 * which a "yielder" object, given as block parameter, can be used to
 * yield a value by calling the +yield+ method (aliased as +<<+):
 *
 *   fib = Enumerator.new do |y|
 *     a = b = 1
 *     loop do
 *       y << a
 *       a, b = b, a + b
 *     end
 *   end
 *
 *   p fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
 *
 * The optional parameter can be used to specify how to calculate the size
 * in a lazy fashion (see Enumerator#size). It can either be a value or
 * a callable object.
 *
 * In the second, deprecated, form, a generated Enumerator iterates over the
 * given object using the given method with the given arguments passed.
 *
 * Use of this form is discouraged.  Use Kernel#enum_for or Kernel#to_enum
 * instead.
 *
 *   e = Enumerator.new(ObjectSpace, :each_object)
 *       #-> ObjectSpace.enum_for(:each_object)
 *
 *   e.select { |obj| obj.is_a?(Class) }  #=> array of all classes
 *
 */


问:
increment value outside of function for every use in python
I have a function that I want to use multiple times, on every use I want a variable outside of the function to increment. Along the lines of -

```<code>def funtion1(mylists,x):
    row=1
    for elm in mylists:
        ws.write(row,x,elm)
        row+=1
    x += 1

col=0
function1(mylist1,col)
function1(mylist2,col)
function1(mylist3,col)
</code>```

etc

I thought col would increment on every use, but it stays at 0. Should I be returning a value from the function?

答:
Two options, pure functions which don't modify anything outside their scope, Most recommended

as our friend Jacques Gaudin has added: https://stackoverflow.com/a/47680265/7579116

the other one, less fancy, and not recommended but is what you asked for is to declare x as global

```<code>x = 0
def funtion1(mylists,x):
    global x
    row=1
    for elm in whichlist:
        ws.write(row,x,elm)
        row=row+1
    x += 1

function1(mylist1,col)
function1(mylist2,col)
function1(mylist3,col)
</code>```

Body:
I have a function that I want to use multiple times, on every use I want a variable outside of the function to increment. Along the lines of -

def funtion1(mylists,x):
    row=1
    for elm in mylists:
        ws.write(row,x,elm)
        row+=1
    x += 1

col=0
function1(mylist1,col)
function1(mylist2,col)
function1(mylist3,col)

etc

I thought col would increment on every use, but it stays at 0. Should I be returning a value from the function?

Body:
Two options, pure functions which don't modify anything outside their scope, Most recommended

as our friend Jacques Gaudin has added: https://stackoverflow.com/a/47680265/7579116

the other one, less fancy, and not recommended but is what you asked for is to declare x as global

x = 0
def funtion1(mylists,x):
    global x
    row=1
    for elm in whichlist:
        ws.write(row,x,elm)
        row=row+1
    x += 1

function1(mylist1,col)
function1(mylist2,col)
function1(mylist3,col)


问:
What does requests do with a proxyDict?
I need an explanation on what requests does with a proxyDict, specifically the following:

1. Does it evenly cycle through all of the proxies in the dictionary?

2. What happens if one of them goes down, will requests be able to handle it, or do I have to?

3. What happens if one gets "banned", will it handle it?

4. If I make a get call in a function, will it still cycle through the proxies evenly?

So if I have a dictionary of proxies like so:

```<code>proxyDict = {
    'https' : 'https://IP1:PORT',
    'https' : 'https://IP2:PORT',
    'https' : 'https://IP3:PORT',
    'https' : 'https://IP4:PORT'
}
</code>```

And I have a get request:

```<code>s = requests.Session()
data = {"Username":"user", "Password":"pass"}
s.get(download_url, proxies = proxyDict, verify=False)
</code>```

Which might be in a function, similarly to this (my question #4):

```<code> def foo(download_url, proxyDict, s):
    s.get(download_url, proxies = proxyDict, verify=False)
</code>```

Also is there any way to print which proxy is currently in use?

答:
I think you will find that the keys in your proxyDict are supposed to be protocols (like http or https), and that requests will simply ignore your proxies with keys like http1, etc.

If you enable DEBUG logging, you can see what proxy requests is using.  Consider this initial request without proxies:

```<code>>>> import logging
>>> logging.basicConfig(level='DEBUG')
>>> requests.get('http://google.com')
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): google.com
DEBUG:urllib3.connectionpool:http://google.com:80 "GET / HTTP/1.1" 301 219
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): www.google.com
DEBUG:urllib3.connectionpool:http://www.google.com:80 "GET / HTTP/1.1" 200 4796
<Response [200]>
</code>```

Now, let's set up a proxy dictionary:

```<code>>>> proxyDict={'http': 'http://squid.corp.example.com:3128'}
</code>```

And re-issue the request using that dictionary:

```<code>>>> requests.get('http://google.com', proxies=proxyDict)
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): squid.corp.example.com
DEBUG:urllib3.connectionpool:http://squid.corp.example.com:3128 "GET http://google.com/ HTTP/1.1" 301 219
DEBUG:urllib3.connectionpool:http://squid.corp.example.com:3128 "GET http://www.google.com/ HTTP/1.1" 200 4768
<Response [200]>
</code>```

You can see in the DEBUG messages that it is using the proxy rather than making a direct connection.  Now if we use your proxy dictionary and make the same request...

```<code>>>> proxyDict = {
...     'https1' : 'https://IP1:PORT',
...     'https2' : 'https://IP2:PORT',
...     'https3' : 'https://IP3:PORT',
...     'https4' : 'https://IP4:PORT'
... }
>>> requests.get('http://google.com', proxies=proxyDict)
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): google.com
DEBUG:urllib3.connectionpool:http://google.com:80 "GET / HTTP/1.1" 301 219
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): www.google.com
DEBUG:urllib3.connectionpool:http://www.google.com:80 "GET / HTTP/1.1" 200 4790
<Response [200]>
</code>```

...you can see that it doesn't use any proxies.

Title: What does requests do with a proxyDict?

Body:
I need an explanation on what requests does with a proxyDict, specifically the following:

1. Does it evenly cycle through all of the proxies in the dictionary?

2. What happens if one of them goes down, will requests be able to handle it, or do I have to?

3. What happens if one gets "banned", will it handle it?

4. If I make a get call in a function, will it still cycle through the proxies evenly?

So if I have a dictionary of proxies like so:

proxyDict = {
    'https' : 'https://IP1:PORT',
    'https' : 'https://IP2:PORT',
    'https' : 'https://IP3:PORT',
    'https' : 'https://IP4:PORT'
}

And I have a get request:

s = requests.Session()
data = {"Username":"user", "Password":"pass"}
s.get(download_url, proxies = proxyDict, verify=False)

Which might be in a function, similarly to this (my question #4):

 def foo(download_url, proxyDict, s):
    s.get(download_url, proxies = proxyDict, verify=False)

Also is there any way to print which proxy is currently in use?

Body:
I think you will find that the keys in your proxyDict are supposed to be protocols (like http or https), and that requests will simply ignore your proxies with keys like http1, etc.

If you enable DEBUG logging, you can see what proxy requests is using.  Consider this initial request without proxies:

>>> import logging
>>> logging.basicConfig(level='DEBUG')
>>> requests.get('http://google.com')
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): google.com
DEBUG:urllib3.connectionpool:http://google.com:80 "GET / HTTP/1.1" 301 219
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): www.google.com
DEBUG:urllib3.connectionpool:http://www.google.com:80 "GET / HTTP/1.1" 200 4796
<Response [200]>

Now, let's set up a proxy dictionary:

>>> proxyDict={'http': 'http://squid.corp.example.com:3128'}

And re-issue the request using that dictionary:

>>> requests.get('http://google.com', proxies=proxyDict)
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): squid.corp.example.com
DEBUG:urllib3.connectionpool:http://squid.corp.example.com:3128 "GET http://google.com/ HTTP/1.1" 301 219
DEBUG:urllib3.connectionpool:http://squid.corp.example.com:3128 "GET http://www.google.com/ HTTP/1.1" 200 4768
<Response [200]>

You can see in the DEBUG messages that it is using the proxy rather than making a direct connection.  Now if we use your proxy dictionary and make the same request...

>>> proxyDict = {
...     'https1' : 'https://IP1:PORT',
...     'https2' : 'https://IP2:PORT',
...     'https3' : 'https://IP3:PORT',
...     'https4' : 'https://IP4:PORT'
... }
>>> requests.get('http://google.com', proxies=proxyDict)
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): google.com
DEBUG:urllib3.connectionpool:http://google.com:80 "GET / HTTP/1.1" 301 219
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): www.google.com
DEBUG:urllib3.connectionpool:http://www.google.com:80 "GET / HTTP/1.1" 200 4790
<Response [200]>

...you can see that it doesn't use any proxies.


问:
How can I know when the file download/"Save As" prompt appears?
I have a link on a page

```<code><a class="btn btn-success" href="DownloadCsv">Download CSV</a>
</code>```

When the user clicks on said link, the server responds with the header Content-Disposition: attachment to prompt the user with the "Save File" Dialog.

What I'd like to accomplish is: disable the link while the server is generating its response, and enable it once the server responds.

Is there any event fired for that response from the server? Or is there any other way to accomplish this?

答:
I went through my old questions. I even don't remember what I need it for but I decided to answer on this now because it has not been solved yet after 3.5 years... It can be accomplished this way

Link can be

```<code><a class="btn btn-success" onclick="clickHandler(this); return false;">Download CSV</a>
</code>```

Handler

```<code>    function clickHandler(element) {
        //disable link
        var href = element.href;
        element.href = 'javascript:void(0)';

        //download file
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'DownloadCsv', true);
        xhr.responseType = 'arraybuffer';
        xhr.onload = function(e) {
          if (this.status == 200) {
            var uInt8Array = new Uint8Array(this.response);
            var i = uInt8Array.length;
            var binaryString = new Array(i);
            while (i--) { binaryString[i] = String.fromCharCode(uInt8Array[i]); }
            var data = binaryString.join('');

            //initiate save as dialog
            var base64 = window.btoa(data);
            var a = document.createElement('a');
            a.href = 'data:application/csv;base64,'+ base64;
            a.setAttribute('download', 'data.csv');
            a.click();

            //enable link
            element.href = href;
          }
        };

        xhr.send();
    }
</code>```

Body:
I have a link on a page

Download CSV

When the user clicks on said link, the server responds with the header Content-Disposition: attachment to prompt the user with the "Save File" Dialog.

What I'd like to accomplish is: disable the link while the server is generating its response, and enable it once the server responds.

Is there any event fired for that response from the server? Or is there any other way to accomplish this?

Body:
I went through my old questions. I even don't remember what I need it for but I decided to answer on this now because it has not been solved yet after 3.5 years... It can be accomplished this way

Link can be

<a class="btn btn-success" onclick="clickHandler(this); return false;">Download CSV</a>

Handler

    function clickHandler(element) {
        //disable link
        var href = element.href;
        element.href = 'javascript:void(0)';

        //download file
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'DownloadCsv', true);
        xhr.responseType = 'arraybuffer';
        xhr.onload = function(e) {
          if (this.status == 200) {
            var uInt8Array = new Uint8Array(this.response);
            var i = uInt8Array.length;
            var binaryString = new Array(i);
            while (i--) { binaryString[i] = String.fromCharCode(uInt8Array[i]); }
            var data = binaryString.join('');

            //initiate save as dialog
            var base64 = window.btoa(data);
            var a = document.createElement('a');
            a.href = 'data:application/csv;base64,'+ base64;
            a.setAttribute('download', 'data.csv');
            a.click();

            //enable link
            element.href = href;
          }
        };

        xhr.send();
    }


问:
ckeditor 5 - How do you get the editor data?
I have the following div:

```<code><div name="content" id="editor">
</code>```

I have the following script:

```<code><script>
    $(document).ready(function () {
        // CKEDITORs
        var myeditor = ClassicEditor
            .create(document.querySelector('#editor'))
            .then(editor => {
                console.log(editor);
            })
            .catch(error => {
                console.error(error);
            });
    });

    const data = editor.getData();
    const data = myeditor.getData();

</script>
</code>```

From the documentation, I thought I would be able to do the following:

```<code>const data = editor.getData(); //fails with editor.getData is not a function
</code>```

So added the myeditor var as above and tried this:

```<code>myeditor.getData();// also fails with same error.
</code>```

How do I get data?

答:
Usually the creditor data  is obtained as

```<code>CKEDITOR.instances.editorid.getData();
</code>```

But in CKEditor 5 there's no single global editor instance like old versions so we have to manually create a instance to hold the data globally to get the data when needed.

```<code>let editorinstance;
<script>
    $(document).ready(function () {
    // CKEDITORs
    var myeditor = ClassicEditor.create(document.querySelector('#editor'))
    .then
    (editor => { editorinstance =editor;})
    .catch(error => {
        console.error(error);
        });
});

const data = editorinstance.getData();
</script>
</code>```

Body:
I have the following div:

I have the following script:

From the documentation, I thought I would be able to do the following:

const data = editor.getData(); //fails with editor.getData is not a function

So added the myeditor var as above and tried this:

myeditor.getData();// also fails with same error.

How do I get data?

Body:
Usually the creditor data  is obtained as

CKEDITOR.instances.editorid.getData();

But in CKEditor 5 there's no single global editor instance like old versions so we have to manually create a instance to hold the data globally to get the data when needed.

let editorinstance;
<script>
    $(document).ready(function () {
    // CKEDITORs
    var myeditor = ClassicEditor.create(document.querySelector('#editor'))
    .then
    (editor => { editorinstance =editor;})
    .catch(error => {
        console.error(error);
        });
});

const data = editorinstance.getData();
</script>


问:
grep a tab in UNIX
How do I grep tab (\t) in files on the Unix platform?

答:
Another way of inserting the tab literally inside the expression is using the lesser-known $'\t' quotation in Bash:

grep $'foo\tbar'        # matches eg. 'foo<tab>bar'
```
<p>(Note that if you're matching for fixed strings you can use this with <code>-F</code> mode.)</p>
<p>Sometimes using variables can make the notation a bit more readable and manageable:</p>
<pre class="lang-bash prettyprint-override"><code>tab=$'\t'               # `tab=$(printf '\t')` in POSIX
id='[[:digit:]]\+'
name='[[:alpha:]_][[:alnum:]_-]*'
grep "$name$tab$id"     # matches eg. `bob2<tab>323`
</code>```

Title: grep a tab in UNIX

Body:
Another way of inserting the tab literally inside the expression is using the lesser-known $'\t' quotation in Bash:

grep $'foo\tbar'        # matches eg. 'foo<tab>bar'

(Note that if you're matching for fixed strings you can use this with -F mode.)

Sometimes using variables can make the notation a bit more readable and manageable:

tab=$'\t'               # `tab=$(printf '\t')` in POSIX
id='[[:digit:]]\+'
name='[[:alpha:]_][[:alnum:]_-]*'
grep "$name$tab$id"     # matches eg. `bob2<tab>323`


问:
Tic Tac Toe- finding the winner in React
So I'm creating a Tic Tac Toe game in React. right now I'm trying to figure out the logic of player wins in my app component. I already have the possible moves that they can win as well as the array. For testing purposes, I try an if statement for midWin, but it seems to not work. Can some tell me why it is not working? I'm not able to show my code on JS fiddle for some strange reason, but here is my code:

```<code>let data = {
    "box":[
        [ "", "", "" ],
        [ "", "", "" ],
        [ "", "", "" ]
    ],
    "players": ['X','O']
}
class DataStore {
    constructor(data, players) {
        //store that data in the object
        this.data = data;
        this.players = players;
        //empty array for our watchers
        //watchers are objects that want to be informed about when the data changes
        this.registeredWatchers = [];
    }
    //add a new watcher to the list
    register(watcher) {
        this.registeredWatchers.push(watcher);
    }
    setCrop(newDataState, row, col) {
        //update data
        this.data[row][col] = newDataState;
        //inform all watching objects..
        this.registeredWatchers.map((watcher) => {
            watcher.dataUpdated();
        })
    }
    reset() {
        // this.data = data;
    }
}
class Dispatcher {
    constructor() {
        this.registeredHandlers = []; //D:
    }
    register(callback) {
        this.registeredHandlers.push(callback);
    }
    dispatch(action) {
        //call every method in our registered handlers array
        //with this action as an input
        this.registeredHandlers.map((handler) => {
            //call that individual function in the array..
            handler(action);
        })
    }
    reset(val){

    }
}
class BoxComponent extends React.Component {
    render() {
        return (
            <div
                className="box"
                onClick={this.handleClick.bind(this)}>
                <span>{this.props.type}</span>
            </div>);
    }
    handleClick() {
        //try a test dispatch
        if(this.props.type.length > 0) {
            return false;
        } else {
            boxDispatcher.dispatch({ type: "pick", row: this.props.rowNum, col: this.props.colNum});
        }
    }
}
class GridComponent extends React.Component {
    render() {
        return(
            <div>
                <p>Player {this.props.turn} is next.</p>
                {
                    //loop through all the  rows...
                    this.props.box.map((row, rowNum) => {
                        //and write them out to the page..
                        return (<div className="row">
                            {
                                row.map((cropEntry, colNum) => {
                                    return <BoxComponent type={cropEntry}  rowNum={rowNum} colNum={colNum} turn={rowNum}/>
                                })
                            }
                        </div>);
                    })
                }
            </div>
        )
    }
}
class App extends React.Component {
    constructor(props) {
        //make sure this stays a react component
        super(props);
        this.state = {
            turn: boxDataStore.players[0],
            box: boxDataStore.data
        }
        //ensure we're listening to the data store
        boxDataStore.register(this);
    }
    dataUpdated() {
        this.setState(prevState => ({
            box: boxDataStore.data,
            // turn: cropDataStore.players,
            turn: prevState.turn === 'X'
                ? boxDataStore.players[1]
                : boxDataStore.players[0]
        }))
    }

    render() {
        return (
            // renders out the whole data on the board
            <div>
                <h1>Tic Tac Toe </h1>
                <button onClick={this.resetBoard.bind(this)}>Reset Board</button>
                <button onClick={this.checkWinner.bind(this)}>Check Winner</button>
                <GridComponent box={this.state.box} turn={this.state.turn} />
            </div>
        );
    }
    // rests the data back to the orginal state which is  from the let data
    resetBoard() {
        const newBoxData = [
            [ "", "", "" ],
            [ "", "", "" ],
            [ "", "", "" ]
        ]
        boxDataStore.data = newBoxData;
        this.setState({
            box: boxDataStore.data
        })

    }
    // end data that tells the update

    // events that help users find out who the winner or the losers
    checkWinner() {

        //vertical wins
        const topWin = [
            this.state.box["0"]["0"],
            this.state.box["0"]["1"],
            this.state.box["0"]["2"]
        ];

        const midWin = [
            this.state.box["1"]["0"],
            this.state.box["1"]["1"],
            this.state.box["1"]["2"]
        ];

        const bottom = [
            this.state.box["2"]["0"],
            this.state.box["2"]["1"],
            this.state.box["2"]["2"]
        ];
        // vertical wins end.

        //horizontal wins
        const horizMid = [
            this.state.box["0"]["1"],
            this.state.box["1"]["1"],
            this.state.box["2"]["1"]
        ];

        const horizleft = [
            this.state.box["0"]["2"],
            this.state.box["1"]["2"],
            this.state.box["2"]["2"]
        ];

        const horizright = [
            this.state.box["0"]["0"],
            this.state.box["1"]["1"],
            this.state.box["2"]["2"]
        ];
        //horiztanl end

        const diagonalright = [
            this.state.box["0"]["0"],
            this.state.box["1"]["1"],
            this.state.box["2"]["2"]
        ];

        function identical(array) {
            for(let i = 2; i < array.length; i++) {
                if(array[i] === array[i+1]) {
                    return true;

                }
            }
        };

        if(identical(midWin)) {
            alert('midWin')
        }

    }
}
//start of app
var boxDispatcher = new Dispatcher();
var boxDataStore = new DataStore(data.box, data.players);
boxDispatcher.register((action) => {
    if(boxDataStore.registeredWatchers["0"].state.turn == "X") {
        //actually waint to handle it
        boxDataStore.setCrop('X', action.row, action.col);
    } else {
        boxDataStore.setCrop('O', action.row, action.col);
    }
})
ReactDOM.render(<App data={boxDataStore.data} />, document.querySelector("#app"));
export default App;
</code>```

答:
The issue is with identical function. I have corrected the function.

```<code>        function identical(array) {

        // Check if any of the box is blank. if yes then no need to check the win
        if(array.some(function(element){return element===""})){
            return false;
        }

        let winFlag = true;

        for(let i = 0; i < array.length-1; i++) {
            if(array[i] !== array[i+1]) {
                winFlag = false;
            }
        }
        return winFlag;
    }
</code>```

Please check JS fiddle for the details -

https://jsfiddle.net/abhijeet_srivastava/wx2tq713/11/

Body:
So I'm creating a Tic Tac Toe game in React. right now I'm trying to figure out the logic of player wins in my app component. I already have the possible moves that they can win as well as the array. For testing purposes, I try an if statement for midWin, but it seems to not work. Can some tell me why it is not working? I'm not able to show my code on JS fiddle for some strange reason, but here is my code:

let data = {
    "box":[
        [ "", "", "" ],
        [ "", "", "" ],
        [ "", "", "" ]
    ],
    "players": ['X','O']
}
class DataStore {
    constructor(data, players) {
        //store that data in the object
        this.data = data;
        this.players = players;
        //empty array for our watchers
        //watchers are objects that want to be informed about when the data changes
        this.registeredWatchers = [];
    }
    //add a new watcher to the list
    register(watcher) {
        this.registeredWatchers.push(watcher);
    }
    setCrop(newDataState, row, col) {
        //update data
        this.data[row][col] = newDataState;
        //inform all watching objects..
        this.registeredWatchers.map((watcher) => {
            watcher.dataUpdated();
        })
    }
    reset() {
        // this.data = data;
    }
}
class Dispatcher {
    constructor() {
        this.registeredHandlers = []; //D:
    }
    register(callback) {
        this.registeredHandlers.push(callback);
    }
    dispatch(action) {
        //call every method in our registered handlers array
        //with this action as an input
        this.registeredHandlers.map((handler) => {
            //call that individual function in the array..
            handler(action);
        })
    }
    reset(val){

    }
}
class BoxComponent extends React.Component {
    render() {
        return (

                {this.props.type}

);
    }
    handleClick() {
        //try a test dispatch
        if(this.props.type.length > 0) {
            return false;
        } else {
            boxDispatcher.dispatch({ type: "pick", row: this.props.rowNum, col: this.props.colNum});
        }
    }
}
class GridComponent extends React.Component {
    render() {
        return(

Player {this.props.turn} is next.

                {
                    //loop through all the  rows...
                    this.props.box.map((row, rowNum) => {
                        //and write them out to the page..
                        return (

                            {
                                row.map((cropEntry, colNum) => {
                                    return <BoxComponent type={cropEntry}  rowNum={rowNum} colNum={colNum} turn={rowNum}/>
                                })
                            }

);
                    })
                }

        )
    }
}
class App extends React.Component {
    constructor(props) {
        //make sure this stays a react component
        super(props);
        this.state = {
            turn: boxDataStore.players[0],
            box: boxDataStore.data
        }
        //ensure we're listening to the data store
        boxDataStore.register(this);
    }
    dataUpdated() {
        this.setState(prevState => ({
            box: boxDataStore.data,
            // turn: cropDataStore.players,
            turn: prevState.turn === 'X'
                ? boxDataStore.players[1]
                : boxDataStore.players[0]
        }))
    }

    render() {
        return (
            // renders out the whole data on the board

Tic Tac Toe

                <button onClick={this.resetBoard.bind(this)}>Reset Board</button>
                <button onClick={this.checkWinner.bind(this)}>Check Winner</button>
                <GridComponent box={this.state.box} turn={this.state.turn} />

        );
    }
    // rests the data back to the orginal state which is  from the let data
    resetBoard() {
        const newBoxData = [
            [ "", "", "" ],
            [ "", "", "" ],
            [ "", "", "" ]
        ]
        boxDataStore.data = newBoxData;
        this.setState({
            box: boxDataStore.data
        })

    }
    // end data that tells the update

    // events that help users find out who the winner or the losers
    checkWinner() {

        //vertical wins
        const topWin = [
            this.state.box["0"]["0"],
            this.state.box["0"]["1"],
            this.state.box["0"]["2"]
        ];

        const midWin = [
            this.state.box["1"]["0"],
            this.state.box["1"]["1"],
            this.state.box["1"]["2"]
        ];

        const bottom = [
            this.state.box["2"]["0"],
            this.state.box["2"]["1"],
            this.state.box["2"]["2"]
        ];
        // vertical wins end.

        //horizontal wins
        const horizMid = [
            this.state.box["0"]["1"],
            this.state.box["1"]["1"],
            this.state.box["2"]["1"]
        ];

        const horizleft = [
            this.state.box["0"]["2"],
            this.state.box["1"]["2"],
            this.state.box["2"]["2"]
        ];

        const horizright = [
            this.state.box["0"]["0"],
            this.state.box["1"]["1"],
            this.state.box["2"]["2"]
        ];
        //horiztanl end

        const diagonalright = [
            this.state.box["0"]["0"],
            this.state.box["1"]["1"],
            this.state.box["2"]["2"]
        ];

        function identical(array) {
            for(let i = 2; i < array.length; i++) {
                if(array[i] === array[i+1]) {
                    return true;

                }
            }
        };

        if(identical(midWin)) {
            alert('midWin')
        }

    }
}
//start of app
var boxDispatcher = new Dispatcher();
var boxDataStore = new DataStore(data.box, data.players);
boxDispatcher.register((action) => {
    if(boxDataStore.registeredWatchers["0"].state.turn == "X") {
        //actually waint to handle it
        boxDataStore.setCrop('X', action.row, action.col);
    } else {
        boxDataStore.setCrop('O', action.row, action.col);
    }
})
ReactDOM.render(<App data={boxDataStore.data} />, document.querySelector("#app"));
export default App;

Body:
The issue is with identical function. I have corrected the function.

        function identical(array) {

        // Check if any of the box is blank. if yes then no need to check the win
        if(array.some(function(element){return element===""})){
            return false;
        }

        let winFlag = true;

        for(let i = 0; i < array.length-1; i++) {
            if(array[i] !== array[i+1]) {
                winFlag = false;
            }
        }
        return winFlag;
    }

Please check JS fiddle for the details -

https://jsfiddle.net/abhijeet_srivastava/wx2tq713/11/


问:
Compare or align 3D objects
I have two 3D matrices. Each pixel is a gray scale value.

The first 3D matrix is a reference shape. e.g. imagine a 3D model of a mouth.

The second 3D matrix is an approximate subsection of the reference shape. e.g. imagine a tooth. The subsection is approximate as it is from a different mouth. Note the subsection could be slightly oblique.

The challenge is to identify what are the coordinates of the subsection inside the reference matrix. Expanding on the mouth example above, the challenge is to identify what tooth the second 3D matrix most accurately represents.

The output could be a 3D pixel location and an orientation value.

答:
In general, you want to compare your subsection matrix B with every possible subsection matrix of the reference matrix A (so that it has the same size, as a matrix B) and find the most similar piece.

By comparison, I mean the estimation of the difference, e.g. if B_i is some subsection of matrix A, you can calculate:

```<code> d_i=sum(sum(sum((B_i-B).^2)));
</code>```

After that, you need to find the minimum of $d_i$. If you are working with big matrices A(NxNxN) and B(MxMxM), there are (N-M)^3 possible submatrices B_i with the same size as matrix B. The algorithm will be quite expensive.

However, there is an alternative implementation using convolutions. You can take a look at the Particle Image Velocimetry algorithm, that is really similar to your problem.

Title: Compare or align 3D objects

Body:
In general, you want to compare your subsection matrix B with every possible subsection matrix of the reference matrix A (so that it has the same size, as a matrix B) and find the most similar piece.

By comparison, I mean the estimation of the difference, e.g. if B_i is some subsection of matrix A, you can calculate:

 d_i=sum(sum(sum((B_i-B).^2)));

After that, you need to find the minimum of $d_i$. If you are working with big matrices A(NxNxN) and B(MxMxM), there are (N-M)^3 possible submatrices B_i with the same size as matrix B. The algorithm will be quite expensive.

However, there is an alternative implementation using convolutions. You can take a look at the Particle Image Velocimetry algorithm, that is really similar to your problem.


问:
Swift 4: Getting first two digits in float
i am trying to get the first two digits in a float that changes continuously, i tried %.05f,%.5f %.3f, but it didn't work,

the code i used

```<code> let str = NSString(format: "%.01f", Float(totalBytesWritten))
</code>```

the value (float) i created looks something like this 294525.0, but i want to get the first two digits, something like  29

Thanks

答:
If you are trying to convert the number of bytes writen to display to the user as the download percentage completed, you would need first to convert the totalBytesWritten from Int64 to Double as well as the totalBytesExpectedToWrite. Then you divide the written by the expected to write and multiply the result by 100:

```<code>let percentageCompleted = (Double(totalBytesWritten)/Double(totalBytesExpectedToWrite)) * 100
let percentageToDisplay = String(format: "%.0f%%", percentageCompleted)
</code>```

Body:
i am trying to get the first two digits in a float that changes continuously, i tried %.05f,%.5f %.3f, but it didn't work,

the code i used

 let str = NSString(format: "%.01f", Float(totalBytesWritten))

the value (float) i created looks something like this 294525.0, but i want to get the first two digits, something like  29

Thanks

Body:
If you are trying to convert the number of bytes writen to display to the user as the download percentage completed, you would need first to convert the totalBytesWritten from Int64 to Double as well as the totalBytesExpectedToWrite. Then you divide the written by the expected to write and multiply the result by 100:

let percentageCompleted = (Double(totalBytesWritten)/Double(totalBytesExpectedToWrite)) * 100
let percentageToDisplay = String(format: "%.0f%%", percentageCompleted)


问:
How to compare two objects in Java 8
Lets take an example you have two employee object having same values as follows.

```<code>Employee employee1 = new Employee(1001, "Sam", 20000);
Employee employee2 = new Employee(1001, "Sam", 20000);
if(doCompareEmployees(employee1, employee2)){
    System.out.println("Both employee objects are same.");
}else{
    System.out.println("Both employee objects are not same.");
}

//Here is compare method using java 8.

private boolean doCompareEmployees(Employee employee1, Employee employee2) {
int returnValue = Comparator.comparing(Employee::getID)
    .thenComparing(Employee::getName)
    .thenComparing(Employee::getSalary)
    .compare(employee1, employee2);
    if (returnValue != 0){
        return false;
    }
    return true;
}
</code>```

I would like know about, is there any other better approach to compare objects in Java 8 ?

答:
You can check this LambdaEquals utility. However, as a good habit, you should stick to the equals overriding for the best performance. Overriding the "equals" method could be faster than Comparator.comparing.

Below is the same example of override as Hoopje provided, just slightly differs.

In the Employee class override the equals method:

```<code>public class Employee {
.....
.....
@Override
public boolean equals(Object o) {
     if(super.equals(o)) {
         return true;
     }
    if(!(o instanceof Employee)) {
        return false
    }

    Employee otherEmployee = (Employee) o;

    return
        id == otherEmplyee.getId &&
        name == otherEmplyee.getName() &&
        salary == otherEmplyee.getSalary;

}

//Use the equal method
if(emp1.equals(emp2) {
    //do something
}
</code>```

Title: How to compare two objects in Java 8

Body:
Lets take an example you have two employee object having same values as follows.

Employee employee1 = new Employee(1001, "Sam", 20000);
Employee employee2 = new Employee(1001, "Sam", 20000);
if(doCompareEmployees(employee1, employee2)){
    System.out.println("Both employee objects are same.");
}else{
    System.out.println("Both employee objects are not same.");
}

//Here is compare method using java 8.

private boolean doCompareEmployees(Employee employee1, Employee employee2) {
int returnValue = Comparator.comparing(Employee::getID)
    .thenComparing(Employee::getName)
    .thenComparing(Employee::getSalary)
    .compare(employee1, employee2);
    if (returnValue != 0){
        return false;
    }
    return true;
}

I would like know about, is there any other better approach to compare objects in Java 8 ?

Body:
You can check this LambdaEquals utility. However, as a good habit, you should stick to the equals overriding for the best performance. Overriding the "equals" method could be faster than Comparator.comparing.

Below is the same example of override as Hoopje provided, just slightly differs.

In the Employee class override the equals method:

public class Employee {
.....
.....
@Override
public boolean equals(Object o) {
     if(super.equals(o)) {
         return true;
     }
    if(!(o instanceof Employee)) {
        return false
    }

    Employee otherEmployee = (Employee) o;

    return
        id == otherEmplyee.getId &&
        name == otherEmplyee.getName() &&
        salary == otherEmplyee.getSalary;

}

//Use the equal method
if(emp1.equals(emp2) {
    //do something
}