问:
Is there any way I could use Alternate for Lead() and Lag() Functions in SQL Server 2008?
I've table where I need to calculate difference between row to one underneath it and get the resultant to xml. it's daily task so i need it is kind of recursive task.

Structure for my current table is as below :

```<code>CREATE TABLE #Temp
(

    , CurrentDateTime        DateTime
    , ID                     INT
    , ThisYearToDateTotal    INT
    , ThisYearToDateCBT      INT
    , ThisYearToDateManual   INT
    , ThisYearToDateScanned  INT
    , InProcess              INT
    , InputRequired          INT
)`
</code>```

So far I've written the code as below :

```<code>SELECT
  Today_CurrentDateTime
, Today_Total
, Today_CBT
, Today_Manual
, Today_Scanned
, Today_InProcess
, Today_InputRequired
, Yesterday_Total
, Yesterday_CBT
, Yesterday_Manual
, Yesterday_Scanned
, Yesterday_InProcess
, Yesterday_InputRequired
, (TD.Today_Total         - YD.Yesterday_Total)          AS Diff_in_Total
, (TD.Today_CBT           - YD.Yesterday_CBT)            AS Diff_in_CBT
, (TD.Today_Manual        - YD.Yesterday_Manual)         AS Diff_in_Manual
, (TD.Today_Scanned       - YD.Yesterday_Scanned)        AS Diff_in_Scanned
, (TD.Today_InProcess     - YD.Yesterday_InProcess)      AS Diff_in_InProcess
, (TD.Today_InputRequired - YD.Yesterday_InputRequired)  AS Diff_in_InputRequired
 FROM #YesterdayData AS YD
INNER JOIN #TodayData AS TD ON TD.Today_ID = YD.Yesterday_ID
</code>```

and getting the output as below :

Now I've a restriction here that I can't create another permanent table and that's why I can't calculate difference for a each day for throughout a week.

Any Help ?

答:
If the dates are input in order of the identity field ID then you can inner join with the same #temp table ON previous ID.</p>

```<code>CREATE TABLE #Temp
(    CurrentDateTime        DateTime
    , ID                     INT
    , ThisYearToDateTotal    INT
    , ThisYearToDateCBT      INT
    , ThisYearToDateManual   INT
    , ThisYearToDateScanned  INT
    , InProcess              INT
    , InputRequired          INT
)

INSERT INTO #Temp VALUES
 ('2017-11-14 07:50:25.230', 1, 400000, 50000, 20000, 30000, 1000, 700)
,('2017-11-15 07:50:25.230', 2, 460000, 53000, 26000, 38000, 2000, 1400)
,('2017-11-16 07:53:01.943', 3, 469692, 53904, 26755, 389033, 2026, 1489)
,('2017-11-17 07:53:01.943', 4, 469692, 53904, 26755, 389033, 2026, 1489)

DELETE FROM #Temp WHERE ID = 3

SELECT T.CurrentDateTime
     , TPrev.ThisYearToDateTotal - T.ThisYearToDateTotal [Total Diff]
     , TPrev.ThisYearToDateCBT - T.ThisYearToDateCBT [ThisYearToDateCBT Diff]
     , TPrev.ThisYearToDateManual - T.ThisYearToDateManual [ThisYearToDateManual Diff]
     , TPrev.ThisYearToDateScanned - T.ThisYearToDateScanned [ThisYearToDateScanned Diff]
     , TPrev.InProcess - T.InProcess [InProcess Diff]
     , TPrev.InputRequired - T.InputRequired [InputRequired Diff]
  FROM #Temp AS T LEFT JOIN #Temp AS TPrev ON TPrev.ID = (SELECT MAX(T2.ID)
                                                             FROM #Temp T2
                                                            WHERE T2.ID > T.ID)
ORDER BY T.ID

--DROP TABLE #Temp
</code>```

Body:
I've table where I need to calculate difference between row to one underneath it and get the resultant to xml. it's daily task so i need it is kind of recursive task.

Structure for my current table is as below :

CREATE TABLE #Temp
(

    , CurrentDateTime        DateTime
    , ID                     INT
    , ThisYearToDateTotal    INT
    , ThisYearToDateCBT      INT
    , ThisYearToDateManual   INT
    , ThisYearToDateScanned  INT
    , InProcess              INT
    , InputRequired          INT
)`

So far I've written the code as below :

SELECT
  Today_CurrentDateTime
, Today_Total
, Today_CBT
, Today_Manual
, Today_Scanned
, Today_InProcess
, Today_InputRequired
, Yesterday_Total
, Yesterday_CBT
, Yesterday_Manual
, Yesterday_Scanned
, Yesterday_InProcess
, Yesterday_InputRequired
, (TD.Today_Total         - YD.Yesterday_Total)          AS Diff_in_Total
, (TD.Today_CBT           - YD.Yesterday_CBT)            AS Diff_in_CBT
, (TD.Today_Manual        - YD.Yesterday_Manual)         AS Diff_in_Manual
, (TD.Today_Scanned       - YD.Yesterday_Scanned)        AS Diff_in_Scanned
, (TD.Today_InProcess     - YD.Yesterday_InProcess)      AS Diff_in_InProcess
, (TD.Today_InputRequired - YD.Yesterday_InputRequired)  AS Diff_in_InputRequired
 FROM #YesterdayData AS YD
INNER JOIN #TodayData AS TD ON TD.Today_ID = YD.Yesterday_ID

and getting the output as below :

Now I've a restriction here that I can't create another permanent table and that's why I can't calculate difference for a each day for throughout a week.

Any Help ?

Body:
If the dates are input in order of the identity field ID then you can inner join with the same #temp table ON previous ID.

CREATE TABLE #Temp
(    CurrentDateTime        DateTime
    , ID                     INT
    , ThisYearToDateTotal    INT
    , ThisYearToDateCBT      INT
    , ThisYearToDateManual   INT
    , ThisYearToDateScanned  INT
    , InProcess              INT
    , InputRequired          INT
)

INSERT INTO #Temp VALUES
 ('2017-11-14 07:50:25.230', 1, 400000, 50000, 20000, 30000, 1000, 700)
,('2017-11-15 07:50:25.230', 2, 460000, 53000, 26000, 38000, 2000, 1400)
,('2017-11-16 07:53:01.943', 3, 469692, 53904, 26755, 389033, 2026, 1489)
,('2017-11-17 07:53:01.943', 4, 469692, 53904, 26755, 389033, 2026, 1489)

DELETE FROM #Temp WHERE ID = 3

SELECT T.CurrentDateTime
     , TPrev.ThisYearToDateTotal - T.ThisYearToDateTotal [Total Diff]
     , TPrev.ThisYearToDateCBT - T.ThisYearToDateCBT [ThisYearToDateCBT Diff]
     , TPrev.ThisYearToDateManual - T.ThisYearToDateManual [ThisYearToDateManual Diff]
     , TPrev.ThisYearToDateScanned - T.ThisYearToDateScanned [ThisYearToDateScanned Diff]
     , TPrev.InProcess - T.InProcess [InProcess Diff]
     , TPrev.InputRequired - T.InputRequired [InputRequired Diff]
  FROM #Temp AS T LEFT JOIN #Temp AS TPrev ON TPrev.ID = (SELECT MAX(T2.ID)
                                                             FROM #Temp T2
                                                            WHERE T2.ID > T.ID)
ORDER BY T.ID

--DROP TABLE #Temp


来源: stackexchange

问:
Transferring repo from bitbucket to github failing
I am trying to import a repository into github from my bitbucket account it seems to be failing and shows following message,

```<code>"Your old project requires credentials for read-only access
We will only temporarly store them for importing."
</code>```

Path used for importing looked something like: https://blahb@bitbucket.org/blal/blahblahblah.git

What credentials should I put in and where should I put the credentials? I am trying the "Import Repository" feature of github given on their website:

答:
Use your Bitbucket credentials.

Note: if you have enabled two-factor authentication on Bitbucket. Go to Bitbucket settings and create app password. Use that generated password when you are authentication on GitHub instead of your normal Bitbucket password.

It also work for private repositories.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to import a repository into github from my bitbucket account it seems to be failing and shows following message,

"Your old project requires credentials for read-only access
We will only temporarly store them for importing."

Path used for importing looked something like: https://blahb@bitbucket.org/blal/blahblahblah.git

What credentials should I put in and where should I put the credentials? I am trying the "Import Repository" feature of github given on their website:


问:
Apache as proxy with "catch-all"
I want to have Apache proxy to different servers and also have a "catch everything else that doesn't fit" to a server.

I want the following cases where ProxyPass is configured in the proxy's Apache conf file:

ProxyPass / - The "catch-all" where everything else that doesn't fit will go here

ProxyPass /sub1 - going to /sub1 takes me to sub1.domain.com...

ProxyPass /sub2 - going to /sub2 takes me to sub2.domain.com...

I tried the following:

```<code><Location /sub1>
  ProxyPass http://sub1.domain.com/
</Location>

<Location /sub2>
  ProxyPass http://sub2.domain.com/
</Location>

<Location />
  ProxyPass http://sub1.domain.com/
</Location>
</code>```

This doesn't seem to work as everything defaults to <Location />.

I tried using LocationMatch and wasn't successful in getting sub1 or sub2 to return content. Referred from here: https://serverfault.com/questions/591591/apache-locationmatch-regex-behaviour-does-not-seem-correct

With the above LocationMatch, the headers were working but no content was returned. Going to /A or /B resulted to "Not found".

Does anyone know how I can get this working for Apache or is it even possible?

答: Try proxypassmatch instead of location directive.</p>

Title: Apache as proxy with "catch-all"

Body:
I want to have Apache proxy to different servers and also have a "catch everything else that doesn't fit" to a server.

I want the following cases where ProxyPass is configured in the proxy's Apache conf file:

ProxyPass / - The "catch-all" where everything else that doesn't fit will go here

ProxyPass /sub1 - going to /sub1 takes me to sub1.domain.com...

ProxyPass /sub2 - going to /sub2 takes me to sub2.domain.com...

I tried the following:

<Location /sub1>
  ProxyPass http://sub1.domain.com/
</Location>

<Location /sub2>
  ProxyPass http://sub2.domain.com/
</Location>

<Location />
  ProxyPass http://sub1.domain.com/
</Location>

This doesn't seem to work as everything defaults to <Location />.

I tried using LocationMatch and wasn't successful in getting sub1 or sub2 to return content. Referred from here: https://serverfault.com/questions/591591/apache-locationmatch-regex-behaviour-does-not-seem-correct

With the above LocationMatch, the headers were working but no content was returned. Going to /A or /B resulted to "Not found".

Does anyone know how I can get this working for Apache or is it even possible?


问:
Render CSS Classes w/ No Styles Using Webpack Extract Plugin
We use the Extract Text plugin with Webpack 3 and it works great but we recently hired a QA automation engineer who works in Selenium.

We are discussing ways to make selecting elements with Selenium easier but on the front end side. That would involve us writing CSS that we don't use in order to get a class to render on a component. The opposite of what the plugin does essentially.

Is there any way to accomplish this with the plugin? Also open to suggestions if you've worked in Selenium. Maybe even a hack.

Example:

```<code>{ vehicleOptions.map((option, index) => {
  let [label, value] = option
  if (label && value) {
    return (
      <li
        className={ [styles.option, styles[label]].join(' ') }
        key={ `${ label }_${ index }` }>
        <img
          className={ styles.icon }
          src={ `/images/icon-${ label }@2x.png` }
          />
        <p className={ styles.value }>
          { typeof value === 'number'
            ? formatDistance(value, ',', 'mi')
            : value
          }
        </p>
      </li>
    )
  } else {
    return null
  }
</code>```

In this line className={ [styles.option, styles[label]].join(' ') }, the label for only one of the mapped items applies it's label as a class because it has corresponding CSS. The others do not otherwise based on how Extract Text works.

This is where it becomes difficult for the QA engineer to query the HTML for a particular element.

I had a thought of being able to run testing mode but rendering things differently for tests sort of defeats the purpose of testing against real world code that will go to prod.

答:
Similar experience doing this, one thing we ended up doing was adding data-id="foo", then using xpath selectors in our selenium tests.

Then in selenuim you can do things like:
'//*[@data-id="foo"]'

or test in chrome with
$x('//*[@data-id="foo"]')

Body:
We use the Extract Text plugin with Webpack 3 and it works great but we recently hired a QA automation engineer who works in Selenium.

We are discussing ways to make selecting elements with Selenium easier but on the front end side. That would involve us writing CSS that we don't use in order to get a class to render on a component. The opposite of what the plugin does essentially.

Is there any way to accomplish this with the plugin? Also open to suggestions if you've worked in Selenium. Maybe even a hack.

Example:

{ vehicleOptions.map((option, index) => {
  let [label, value] = option
  if (label && value) {
    return (
      <li
        className={ [styles.option, styles[label]].join(' ') }
        key={ `${ label }_${ index }` }>
        <img
          className={ styles.icon }
          src={ `/images/icon-${ label }@2x.png` }
          />

          { typeof value === 'number'
            ? formatDistance(value, ',', 'mi')
            : value
          }

    )
  } else {
    return null
  }

In this line className={ [styles.option, styles[label]].join(' ') }, the label for only one of the mapped items applies it's label as a class because it has corresponding CSS. The others do not otherwise based on how Extract Text works.

This is where it becomes difficult for the QA engineer to query the HTML for a particular element.

I had a thought of being able to run testing mode but rendering things differently for tests sort of defeats the purpose of testing against real world code that will go to prod.


问:
Including a header file in a .S to get some struct size
I am trying to compile a mixed C-code and an assembly-code project, while trying to share information between .S file and some header file, I ran into a problem.

I have created two files, as follows:

asm.S:

```<code>#include "common.h"

.space SOME_STRUCT_SIZE
.word SOME_MAGIC

.globl main
b start

start:
   ; ... code here
</code>```

common.h:

```<code>struct someStruct {
    int data;
};

#define SOME_STRUCT_SIZE sizeof(struct someStruct)
#define SOME_MAGIC 0x12345678
</code>```

When trying to compile the .S file (arm-linux-gnueabi-gcc -o asm asm.S), I get error messages indicating the assembler is trying to assemble the .h file, and obviously fails on the struct definition.

```<code>common.h: Assembler messages:
common.h:2: Error: bad instruction 'int data'
</code>```

Is it possible to force the pre-processor to statically create both defines and insert them in a way that the assembly code can use?

答:
This may seem convoluted but it may also achieve the same goal. You could create a C macro that simply creates #defines for strings and values that may need to propagate to an assembler header. You can create a function that uses these macros to generate the defines. You can then use -S feature of GCC to output the assembly and then use GREP to sift out the defines that were generated dumping them to an include file that can be used by your assembly (.S) file.

File gnuasm.h:

```<code>#define GNUASM_DEFINE_STR(SYMBOL, STR) \
    __asm__  ("#define " SYMBOL " " #STR);

#define GNUASM_DEFINE_VAL(SYMBOL, VALUE) \
    __asm__  ("#define " SYMBOL " %a0" :: "n"(VALUE));
</code>```

The trick in the macro is to use the asm directive to emit the defines. This will cause them to appear in the generated .s file. GNUASM_DEFINE_STR can be used at global scope but for GNUASM_DEFINE_VAL to work you'll need to put it in a dummy function.

Your common.h would remain unchanged:

```<code>struct someStruct {
    int data;
};

#define SOME_STRUCT_SIZE sizeof(struct someStruct)
#define SOME_MAGIC 0x12345678
</code>```

Create a dummy C file (it doesn't need to be linked with your project) that includes common.h and the gnuasm.h macros file with a dummy function. In this case I'll call it common-defs.c:

```<code>#include "gnuasm.h"
#include "common.h"

/* Dummy function used to generate the defines we need */
void common_defines(void)
{
    GNUASM_DEFINE_STR("SOME_STRING", "some string");
    GNUASM_DEFINE_VAL("SOME_STRUCT_SIZE", SOME_STRUCT_SIZE);
    GNUASM_DEFINE_VAL("SOME_MAGIC", SOME_MAGIC);

    return;
}
</code>```

This file is meant to be compiled and for the assembly output to be generated like this:

```<code>gcc common-defs.c -c -S
</code>```

This produces a file common-defs.s. This is the assembly code that represents the C code. All the defines we emitted can then be parsed out with GREP and then output into an include file that our assembly file can include:

```<code>grep "#define" common-defs.s >common.inc
</code>```

Now in our asm.S file you can include this at the top:

```<code>#include "common.inc"
</code>```

The generated common.inc file would appear something like:

```<code>    #define SOME_STRING "some string"
    #define SOME_STRUCT_SIZE 4
    #define SOME_MAGIC 305419896
</code>```

When using struct another useful thing for assembly are the offsets of member variables. Those could be generated like this:

```<code>GNUASM_DEFINE_VAL("SOME_STRUCT_DATA_OFFSET", offsetof(struct someStruct, data));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to compile a mixed C-code and an assembly-code project, while trying to share information between .S file and some header file, I ran into a problem.

I have created two files, as follows:

asm.S:

#include "common.h"

.space SOME_STRUCT_SIZE
.word SOME_MAGIC

.globl main
b start

start:
   ; ... code here

common.h:

struct someStruct {
    int data;
};

#define SOME_STRUCT_SIZE sizeof(struct someStruct)
#define SOME_MAGIC 0x12345678

When trying to compile the .S file (arm-linux-gnueabi-gcc -o asm asm.S), I get error messages indicating the assembler is trying to assemble the .h file, and obviously fails on the struct definition.

common.h: Assembler messages:
common.h:2: Error: bad instruction 'int data'

Is it possible to force the pre-processor to statically create both defines and insert them in a way that the assembly code can use?

Body:
This may seem convoluted but it may also achieve the same goal. You could create a C macro that simply creates #defines for strings and values that may need to propagate to an assembler header. You can create a function that uses these macros to generate the defines. You can then use -S feature of GCC to output the assembly and then use GREP to sift out the defines that were generated dumping them to an include file that can be used by your assembly (.S) file.

File gnuasm.h:

#define GNUASM_DEFINE_STR(SYMBOL, STR) \
    __asm__  ("#define " SYMBOL " " #STR);

#define GNUASM_DEFINE_VAL(SYMBOL, VALUE) \
    __asm__  ("#define " SYMBOL " %a0" :: "n"(VALUE));

The trick in the macro is to use the asm directive to emit the defines. This will cause them to appear in the generated .s file. GNUASM_DEFINE_STR can be used at global scope but for GNUASM_DEFINE_VAL to work you'll need to put it in a dummy function.

Your common.h would remain unchanged:

struct someStruct {
    int data;
};

#define SOME_STRUCT_SIZE sizeof(struct someStruct)
#define SOME_MAGIC 0x12345678

Create a dummy C file (it doesn't need to be linked with your project) that includes common.h and the gnuasm.h macros file with a dummy function. In this case I'll call it common-defs.c:

#include "gnuasm.h"
#include "common.h"

/* Dummy function used to generate the defines we need */
void common_defines(void)
{
    GNUASM_DEFINE_STR("SOME_STRING", "some string");
    GNUASM_DEFINE_VAL("SOME_STRUCT_SIZE", SOME_STRUCT_SIZE);
    GNUASM_DEFINE_VAL("SOME_MAGIC", SOME_MAGIC);

    return;
}

This file is meant to be compiled and for the assembly output to be generated like this:

gcc common-defs.c -c -S

This produces a file common-defs.s. This is the assembly code that represents the C code. All the defines we emitted can then be parsed out with GREP and then output into an include file that our assembly file can include:

grep "#define" common-defs.s >common.inc

Now in our asm.S file you can include this at the top:

#include "common.inc"

The generated common.inc file would appear something like:

    #define SOME_STRING "some string"
    #define SOME_STRUCT_SIZE 4
    #define SOME_MAGIC 305419896

When using struct another useful thing for assembly are the offsets of member variables. Those could be generated like this:

GNUASM_DEFINE_VAL("SOME_STRUCT_DATA_OFFSET", offsetof(struct someStruct, data));


问:
Facebook: User Like/Become fan of page
In any facebook api (connect, graph, rest, etc) is there a way to prompt the user to become a fan of a page (now known as liking a page).</p>

答: It is not possible through the Facebook APIs. Above iframe solution might work.</p>

ContentLicense: CC BY-SA 2.5

Title: Facebook: User Like/Become fan of page


问:
Rails: Model associations
I have two models, one called User and another called Recruiter.  What I would like to do is to be able to create a scope that searches users and returns the results so recruiters can see them.  But I'm not sure how to go about setting up the association.  I made a through association between users and recruiters and created a new join table called recruiter_users but I'm not sure if this is the correct approach.  </p>

<p>1) What the best way to make the association between the 2 models
2) how exactly would I display the user results in the recruiters view? </p>

```<code>  class RecruiterUser < ApplicationRecord

  # this is a join model between recruiters and users
  belongs_to :recruiter
  belongs_to :user

class User < ApplicationRecord

  # creates association with recruiters model through the join table recruiter_users
  has_many :recruiter_users
  has_many :recruiters, through: :recruiter_users

class Recruiter < ApplicationRecord

  # creates association with users model through the join table recruiter_users
  has_many :recruiter_users
  has_many :users, through: :recruiter_users
</code>```

答:
Again, without having more details about your application, if all you need to do is display the Users associated with a particular Recruiter in a view, it could be as simple as this:

```<code><% @recruiter.users.each do |user| %>
  <%= user.whatever_attribute %>
<% end %>
</code>```

Title: Rails: Model associations

Body:
I have two models, one called User and another called Recruiter.  What I would like to do is to be able to create a scope that searches users and returns the results so recruiters can see them.  But I'm not sure how to go about setting up the association.  I made a through association between users and recruiters and created a new join table called recruiter_users but I'm not sure if this is the correct approach.

1) What the best way to make the association between the 2 models
2) how exactly would I display the user results in the recruiters view?

  class RecruiterUser < ApplicationRecord

  # this is a join model between recruiters and users
  belongs_to :recruiter
  belongs_to :user

class User < ApplicationRecord

  # creates association with recruiters model through the join table recruiter_users
  has_many :recruiter_users
  has_many :recruiters, through: :recruiter_users

class Recruiter < ApplicationRecord

  # creates association with users model through the join table recruiter_users
  has_many :recruiter_users
  has_many :users, through: :recruiter_users

Body:
Again, without having more details about your application, if all you need to do is display the Users associated with a particular Recruiter in a view, it could be as simple as this:

<% @recruiter.users.each do |user| %>
  <%= user.whatever_attribute %>
<% end %>


问:
Getting std::bad_alloc in Release but not in Debug
I just don't know what to do with it...

The functions runs well in debug, but not in release.

I am trying to learn about artificial neural networks and C++ vectors.

Here is the code (in Python 2.7) that I'm writing in C++:

http://neuralnetworksanddeeplearning.com/chap1.html#exercise_852508

(just scroll a little to reach it)

I'm using MinGW 7.2.0 from MSYS2 (C++11).

There are some "teste" prints inside the backpropagation method, that is where the problem is comming from (I guess). I also overloaded operators +, - and * to make things easier.

I know that there are some libs like Armadillo that could make things easier, but I really wanna use this problem to learn better.

And here is the files:

neuralnetwork.h

(I made everything public to make things easier to look at)

```<code>#define MIN_NUMBER_TOLERANCE 1e-8

namespace nn
{
    class neuralnetwork
    {
    //private:
    public:
        //total number of weights. useful to reserve memory
        int numWeights;
        //total number of biases. useful to reserve memory
        int numBiases;
        //total number of layers: 1 for input, n hidden layers and 1 for output
        int numLayers;
        //a vector to store the number of neurons in each layer: 0 index is about the input layer, last index is about the output layer
        std::vector<int> sizes;
        //stores all biases: num of neurons of layer 1 + ... + num of neurons of layer (numLayers - 1) (input layer has no bias)
        std::vector<std::vector<double>> biases;
        //stores all weights: (num of neurons of layer 1) x (num of neurons of layer ) + ... + ( num of neurons of layer (numLayers - 1) ) x ( num of neurons of layer (numLayers - 2) ) (input layer has no bias)
        std::vector<std::vector<std::vector<double>>> weights;
        //stores the output of each neuron of each layer
        std::vector<std::vector<double>> layersOutput;

        std::vector<std::vector<std::vector<double>>> derivativeWeights;
        std::vector<std::vector<double>> derivativeBiases;

        std::default_random_engine generator;
        std::normal_distribution<double> distribution;

        double randomNormalNumber(void);

        double costDerivatives(const double&, const double&);

        std::vector<double> costDerivatives(const std::vector<double> &, const std::vector<double> &);

        void backPropagation(const std::vector<double>& neuralNetworkInputs, const std::vector<double>& expectedOutputs, // inputs
                      std::vector<std::vector<std::vector<double>>>& derivativeWeights, std::vector<std::vector<double>>& derivativeBiases); // outputs

        void update_mini_batch( const std::vector<std::pair<std::vector<double>,std::vector<double>>> & mini_batch, double eta);

    //public:

        neuralnetwork(const std::vector<int>& sizes);

        std::vector<double> feedforward(const std::vector<double>&);
    };

    std::vector<double> sigmoid(const std::vector<double> &);
    double sigmoid(double);
    std::vector<double> sigmoid_prime(const std::vector<double> &);
    //double sigmoid_prime(double);

}
</code>```

neuralnetwork.cpp

```<code>#include "neuralnetwork.h"
#include <iostream>
#include <assert.h>
#include <algorithm>

namespace nn
{
    int counter = 0;

    neuralnetwork::neuralnetwork(const std::vector<int> &sizes)
    {
        this->distribution = std::normal_distribution<double>( 0.0 , 1.0 );

        this->numLayers = sizes.size();
        this->sizes = sizes;

        this->numWeights = 0;
        this->numBiases = 0;

        for ( int i = 1 ; i < this->numLayers ; i++ )
        {
            numWeights += this->sizes[ i ] * this->sizes[ i - 1 ];
            numBiases += this->sizes[ i ];
        }

        this->weights.reserve( numWeights );
        this->biases.reserve( numBiases );

        this->derivativeWeights.reserve( numWeights );
        this->derivativeBiases.reserve( numBiases );

        this->layersOutput.reserve( this->sizes[ 0 ] + numBiases );

        std::vector<double> auxVectorWeights;
        std::vector<std::vector<double> > auxMatrixWeights;

        std::vector<double> auxVectorBiases;

#ifdef DEBUG_BUILD
        std::cout << "debugging!\n";
#endif

        //just to accommodate the input layer with null biases and inputs (makes things easier to iterate and reading :D).
        this->layersOutput.push_back( std::vector<double>( this->sizes[ 0 ] ) );
        std::vector<std::vector<double>> matrixNothing( 0 );
        this->weights.push_back( matrixNothing );
        this->biases.push_back( std::vector<double>( 0 ) );

        //since the second layer (index 1) because there is no weights (nor biases) for the neurons of the first layer
        for ( int layer = 1 ; layer < this->numLayers ; layer++ )
        {
            //preallocate memory for the output of each layer.
            layersOutput.push_back( std::vector<double>( this->sizes[ layer ] ) );

            //-----------weights begin--------------
            //auxMatrixWeights will store the weights connections between one layer (number of columns) and its subsequent layer (number of rows)
            //auxMatrixWeights = new std::vector(this->sizes[layer], std::vector<double>( this->sizes[layer - 1] )); // it is not working...

            //size[layer] stores the number of neurons on the layer
            for ( int i = 0 ; i < this->sizes[ layer ] ; i++ )
            {
                //auxVectorWeights will have the size of the amount of wights necessary to connect the neuron i (from this layer) to neuron j (from next layer)
                auxVectorWeights = std::vector<double>( this->sizes[ layer - 1 ] );

                for ( int j = 0 ; j < auxVectorWeights.size() ; j++ )
                {
                    auxVectorWeights[ j ] = this->randomNormalNumber();
                }

                auxMatrixWeights.push_back( auxVectorWeights );
            }

            this->weights.push_back( auxMatrixWeights );

            auxMatrixWeights.clear();

            //-----------weights end----------------

            //-----------biases begin---------------
            auxVectorBiases = std::vector<double>( this->sizes[ layer ] );

            for ( int i = 0 ; i < auxVectorBiases.size() ; i++ )
            {
                auxVectorBiases[ i ] = this->randomNormalNumber();
            }

            this->biases.push_back( auxVectorBiases );
            //-----------biases end-----------------
        }

#ifdef _DEBUG
        for ( int i = 0 ; i < this->weights.size() ; i++ )
        {
            std::cout << "layer " << i << "\n";
            for ( int j = 0 ; j < this->weights[ i ].size() ; j++ )
            {
                std::cout << "neuron" << j << std::endl;
                for ( const auto k : this->weights[ i ][ j ] )
                {
                    std::cout << '\t' << k << ' ';
                }
                std::cout << std::endl;
            }
        }
#endif
    }

    template <class T>
    inline int lastIndex(std::vector<T> vector , int tail)
    {
        return (vector.size() - tail);
    }

    double neuralnetwork::randomNormalNumber(void)
    {
        return this->distribution( this->generator );
    }

    double sigmoid(double z)
    {
        return 1.0 / ( 1.0 + exp( -z ) );
    }

    std::vector<double> sigmoid(const std::vector<double> & z)
    {
        int max = z.size();
        std::vector<double> output;
        output.reserve(max);

        for(int i=0;i<max;i++)
        {
            output.push_back(0);
            output[i] = 1.0 / ( 1.0 + exp( -z[i] ) );
        }

        return output;
    }

    /*double sigmoid_prime(double z)
    {
        return sigmoid( z ) * ( 1 - sigmoid( z ) );
    }*/

    std::vector<double> sigmoid_prime(const std::vector<double>& z)
    {
        int max = z.size();
        std::vector<double> output;
        output.reserve(max);

        for(int i=0;i<max;i++)
        {
            output.push_back(sigmoid( z[i] ) * ( 1 - sigmoid( z[i] ) ) );
        }

        return output;
    }

    //scalar times vector
    std::vector<double> operator* (double a , const std::vector<double> & b)
    {
        int size = b.size();

        std::vector<double> result(size);

        for ( int i = 0 ; i < size ; i++ )
        {
            result[i] = a * b[ i ];
        }

        return result;
    }

    // inner product
    std::vector<double> operator* (const std::vector<double> & a , const std::vector<double> & b)
    {

#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size(); // or b.size(). they should have the same size.

        std::vector<double> result;
        result.reserve(size); // or b.size(). they should have the same size.

        for ( int i = 0 ; i < size ; i++ )
        {
            result.push_back( a[ i ] * b[ i ] );
        }

        return result;
    }

    //matrix times columns vector
    std::vector<double> operator* (const std::vector<std::vector<double>> & a , const std::vector<double> & b)
    {
#ifdef _DEBUG
        assert(a[0].size() == b.size());

        for(int i = 0 ; i < ( lastIndex( a , 1 )) ; i++)
        {
            assert(a[i].size() == a[i+1].size());
        }
#endif

        int lines = a.size();
        int columns = a[0].size();

        std::vector<double> result;
        result.reserve(lines);

        int j = 0;

        for ( int i = 0 ; i < lines ; i++ )
        {
            result.push_back(0);
            for(j = 0 ; j < columns ; j++)
            {
                result[i] += a[ i ][ j ] * b[ j ];
            }
        }

        return result;
    }

    //scalar times matrix (calls scalar times vector)
    std::vector<std::vector<double>> operator* (double a , const std::vector<std::vector<double>> & b)
    {
#ifdef _DEBUG
        for(int i = 0 ; i < b.size()-1 ; i++)
        {
            assert(b[i].size() == b[i+1].size());
        }
#endif

        int lines = b.size();
        int columns = b[0].size();

        std::vector<std::vector<double>> result;

        int j = 0;

        for ( int i = 0 ; i < lines ; i++ )
        {
            result.push_back(a * b[ j ]);
        }

        return result;
    }

    std::vector<double> operator+(const std::vector<double>& a, const std::vector<double>& b)
    {
        assert(a.size() == b.size());

        int size = a.size();

        std::vector<double> result;
        result.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(0);
            result[i] = a[i] + b[i];
        }

        return result;
    }

    //sum of matrices
    std::vector<std::vector<double>> operator+(const std::vector<std::vector<double>>& a, const std::vector<std::vector<double>>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

#ifdef _DEBUG
        for(int i = 0 ; i < size ; i++)
        {
            assert(a[i].size() == b[i].size());
        }
#endif

        std::vector<std::vector<double>> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(a[i] + b[i]);
        }

        return result;
    }

    //subtraction of vectors
    std::vector<double> operator-(const std::vector<double>& a, const std::vector<double>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

        std::vector<double> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result[i] = a[i] - b[i];
        }

        return result;
    }

    //subtraction of matrices (calls subtraction of vectors)
    std::vector<std::vector<double>> operator-(const std::vector<std::vector<double>>& a, const std::vector<std::vector<double>>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

#ifdef _DEBUG
        for(int i = 0 ; i < size ; i++)
        {
            assert(a[i].size() == b[i].size());
        }
#endif

        std::vector<std::vector<double>> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(a[i] - b[i]);
        }

        return result;
    }

    //elementwise division
    std::vector<double> operator/(const std::vector<double>& a, const std::vector<double>& b)
    {
        assert(a.size() == b.size());

        int size = a.size();

        std::vector<double> result;
        result.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            if(b[i] < MIN_NUMBER_TOLERANCE)
            {
                throw std::runtime_error("Can't divide by zero!");
            }
            result[i] = a[i] / b[i];
        }

        return result;
    }

    double neuralnetwork::costDerivatives(const double &networkOutput , const double &expectedOutput)
    {
        return expectedOutput - networkOutput;
    }

    std::vector<double> neuralnetwork::costDerivatives(const std::vector<double> &networkOutput , const std::vector<double> &expectedOutput)
    {
        assert(expectedOutput.size() == networkOutput.size());
        int size = networkOutput.size();
        std::vector<double> output;
        output.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            output.push_back(networkOutput[i] - expectedOutput[i]);
        }

        return output;
    }

    void neuralnetwork::backPropagation(const std::vector<double> &neuralNetworkInputs , const std::vector<double> &expectedOutputs, // inputs
                                        std::vector<std::vector<std::vector<double>>>& derivativeWeights , std::vector<std::vector<double>>& derivativeBiases) // outputs
    {

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        derivativeWeights.reserve( sizes.size() - 1 );
        derivativeBiases.reserve( sizes.size() - 1 );

        //to store one activation layer
        std::vector<double> activation = neuralNetworkInputs;
        //to store each one of the activation layers
        std::vector<std::vector<double>> activations;

        activations.reserve(sizes.size()); // numBiases is the same as the number of neurons (except 1st layer)
        activations.push_back(activation);
        int maxLayerSize = 0;

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        for ( int i = 1 ; i < numBiases ; i++ )
        {
            maxLayerSize = std::max(sizes[i], maxLayerSize);
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        // to store one weighted sum
        std::vector<double> z;
        z.reserve(maxLayerSize);
        // to store each one of the weighted sums
        std::vector<std::vector<double>> zs;
        zs.reserve(sizes.size());

        // layer and neuron counter
        int layer, neuron;

        for ( layer = 1 ; layer < numLayers ; layer++ )
        {
            z = (weights[layer] * activation) + biases[layer];
            zs.push_back(z);
            activation = sigmoid(z);
            activations.push_back(activation);
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        std::vector<double> delta = costDerivatives(activations[ lastIndex( activations , 1 )] , expectedOutputs) * sigmoid_prime(z);
        delta.reserve(maxLayerSize);

        derivativeBiases.push_back(delta);

        int j;

        std::vector<std::vector<double>> dummyMatrix;
        dummyMatrix.reserve(maxLayerSize);

        for (neuron = 0; neuron < sizes[ lastIndex( sizes , 1 )]; neuron++)
        {
            dummyMatrix.push_back(std::vector<double>(activations[ lastIndex( activations , 2 )].size()));
            for (j = 0; j < activations[ lastIndex( activations , 2 )].size(); j++)
            {
                dummyMatrix[neuron][j] = delta[neuron] * activations[ lastIndex( activations , 2 )][j];
            }
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        derivativeWeights.push_back(dummyMatrix);
        dummyMatrix.clear();

        std::vector<double> sp;
        sp.reserve(maxLayerSize);

        std::vector<double> dummyVector;
        dummyVector.reserve(maxLayerSize);

        double dummyDouble = 0;

        for(layer = 2 ; layer < numLayers ; layer++)
        {
            z = zs[ lastIndex( zs , layer )];
            sp = sigmoid_prime(z);

            for(j = 0 ; j < sizes[ lastIndex( weights , layer )] ; j++)
            {
                for (neuron = 0; neuron < sizes[ lastIndex( sizes , layer - 1 )]; neuron++)
                {
                    dummyDouble += weights[ lastIndex( weights , layer - 1 )][neuron][j] * delta[neuron];
                }
                dummyVector.push_back(dummyDouble * sp[j]);
                dummyDouble = 0;
            }
            delta = dummyVector;
            dummyVector.clear();

            derivativeBiases.push_back(delta);

            for (neuron = 0; neuron < sizes[ lastIndex( sizes , layer )]; neuron++)
            {
                dummyMatrix.push_back(std::vector<double>(sizes[ lastIndex( sizes , layer + 1 )]));
                for (j = 0; j < sizes[ lastIndex( sizes , layer + 1 )]; j++)
                {
                    dummyMatrix[neuron][j] = activations[ lastIndex( activations , layer + 1 )][j] * delta[neuron];
                }
            }
            derivativeWeights.push_back(dummyMatrix);
            dummyMatrix.clear();
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        //both derivativeWeights and derivativeBiases are reversed. so let's reverse it.
        std::reverse(derivativeWeights.begin(),derivativeWeights.end());
        std::reverse(derivativeBiases.begin(),derivativeBiases.end());

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

    }
}
</code>```

main.cpp

```<code>#include <stdio.h>
#include <opencv2/opencv.hpp>
#include "neuralnetwork.h"
#include <string>

void printAll(const std::vector<double> & v, const std::string & name)
{
    int size = v.size();

    std::cout << "\t" <<  name << ":\t";

    for(int i = 0 ; i < size ; i++)
    {
        std::cout << v[i] << "\t";
    }

    std::cout << std::endl;
}

template<class T>
void printAll(const std::vector<T> & v, const std::string & name)
{
    int size = v.size();

    std::cout << name << ":" << std::endl;

    for(int i = 0 ; i < size ; i++)
    {
        printAll(v[i], "\t" + ("[" + std::to_string(i)) + "]");
    }
}

int main(int argc, char** argv )
{

    nn::neuralnetwork n({2,4,3});

    n.weights = {{},{{1,2},{3,4},{5,6},{7,8}} , {{9,8,7,6},{5,4,3,2},{1,2,3,4}}};
    n.biases = {{},{1, 4, 6, 8} , {9, 2, 4}};

    printAll(n.weights,"weights");
    printAll(n.biases,"biases");

    std::vector<std::vector<std::vector<double>>> derivativeWeights;
    std::vector<std::vector<double>> derivativeBiases;
    n.backPropagation({1,2},{1,2,3},derivativeWeights,derivativeBiases);

    printAll(n.derivativeWeights,"derivativeWeights");
    printAll(n.derivativeBiases,"derivativeBiases");

    system("PAUSE");

    return 0;
}
</code>```

答:
It looks like your problem is that you are only reserving memory for the vectors in the constructor, not allocating it.

The reserve method does not resize the vector, it is a performance optimization in cases where you know you will resize the vector in the future, but an optimizing compiler is free to ignore it.

This isn't causing a problem for 'weights' and 'biases' in this particular code becuase you are initializing them with vectors of the proper size, which does set them to the correct size. The problems are with derivativeWeights and derivativeBiases, where you reserve memory for the vectors, but they are never actually resized. This makes this memory potentially invalid if you try to dereference it. You could use resize instead of reserve, or push back the elements one by one, which will also resize the vector.

Another comment is that you don't have to use this-> for every member of the class, the 'this->' is assumed for members of the class if you don't use it.

Body:
I just don't know what to do with it...

The functions runs well in debug, but not in release.

I am trying to learn about artificial neural networks and C++ vectors.

Here is the code (in Python 2.7) that I'm writing in C++:

http://neuralnetworksanddeeplearning.com/chap1.html#exercise_852508

(just scroll a little to reach it)

I'm using MinGW 7.2.0 from MSYS2 (C++11).

There are some "teste" prints inside the backpropagation method, that is where the problem is comming from (I guess). I also overloaded operators +, - and * to make things easier.

I know that there are some libs like Armadillo that could make things easier, but I really wanna use this problem to learn better.

And here is the files:

neuralnetwork.h

(I made everything public to make things easier to look at)

#define MIN_NUMBER_TOLERANCE 1e-8

namespace nn
{
    class neuralnetwork
    {
    //private:
    public:
        //total number of weights. useful to reserve memory
        int numWeights;
        //total number of biases. useful to reserve memory
        int numBiases;
        //total number of layers: 1 for input, n hidden layers and 1 for output
        int numLayers;
        //a vector to store the number of neurons in each layer: 0 index is about the input layer, last index is about the output layer
        std::vector<int> sizes;
        //stores all biases: num of neurons of layer 1 + ... + num of neurons of layer (numLayers - 1) (input layer has no bias)
        std::vector<std::vector<double>> biases;
        //stores all weights: (num of neurons of layer 1) x (num of neurons of layer ) + ... + ( num of neurons of layer (numLayers - 1) ) x ( num of neurons of layer (numLayers - 2) ) (input layer has no bias)
        std::vector<std::vector<std::vector<double>>> weights;
        //stores the output of each neuron of each layer
        std::vector<std::vector<double>> layersOutput;

        std::vector<std::vector<std::vector<double>>> derivativeWeights;
        std::vector<std::vector<double>> derivativeBiases;

        std::default_random_engine generator;
        std::normal_distribution<double> distribution;

        double randomNormalNumber(void);

        double costDerivatives(const double&, const double&);

        std::vector<double> costDerivatives(const std::vector<double> &, const std::vector<double> &);

        void backPropagation(const std::vector<double>& neuralNetworkInputs, const std::vector<double>& expectedOutputs, // inputs
                      std::vector<std::vector<std::vector<double>>>& derivativeWeights, std::vector<std::vector<double>>& derivativeBiases); // outputs

        void update_mini_batch( const std::vector<std::pair<std::vector<double>,std::vector<double>>> & mini_batch, double eta);

    //public:

        neuralnetwork(const std::vector<int>& sizes);

        std::vector<double> feedforward(const std::vector<double>&);
    };

    std::vector<double> sigmoid(const std::vector<double> &);
    double sigmoid(double);
    std::vector<double> sigmoid_prime(const std::vector<double> &);
    //double sigmoid_prime(double);

}

neuralnetwork.cpp

#include "neuralnetwork.h"
#include <iostream>
#include <assert.h>
#include <algorithm>

namespace nn
{
    int counter = 0;

    neuralnetwork::neuralnetwork(const std::vector<int> &sizes)
    {
        this->distribution = std::normal_distribution<double>( 0.0 , 1.0 );

        this->numLayers = sizes.size();
        this->sizes = sizes;

        this->numWeights = 0;
        this->numBiases = 0;

        for ( int i = 1 ; i < this->numLayers ; i++ )
        {
            numWeights += this->sizes[ i ] * this->sizes[ i - 1 ];
            numBiases += this->sizes[ i ];
        }

        this->weights.reserve( numWeights );
        this->biases.reserve( numBiases );

        this->derivativeWeights.reserve( numWeights );
        this->derivativeBiases.reserve( numBiases );

        this->layersOutput.reserve( this->sizes[ 0 ] + numBiases );

        std::vector<double> auxVectorWeights;
        std::vector<std::vector<double> > auxMatrixWeights;

        std::vector<double> auxVectorBiases;

#ifdef DEBUG_BUILD
        std::cout << "debugging!\n";
#endif

        //just to accommodate the input layer with null biases and inputs (makes things easier to iterate and reading :D).
        this->layersOutput.push_back( std::vector<double>( this->sizes[ 0 ] ) );
        std::vector<std::vector<double>> matrixNothing( 0 );
        this->weights.push_back( matrixNothing );
        this->biases.push_back( std::vector<double>( 0 ) );

        //since the second layer (index 1) because there is no weights (nor biases) for the neurons of the first layer
        for ( int layer = 1 ; layer < this->numLayers ; layer++ )
        {
            //preallocate memory for the output of each layer.
            layersOutput.push_back( std::vector<double>( this->sizes[ layer ] ) );

            //-----------weights begin--------------
            //auxMatrixWeights will store the weights connections between one layer (number of columns) and its subsequent layer (number of rows)
            //auxMatrixWeights = new std::vector(this->sizes[layer], std::vector<double>( this->sizes[layer - 1] )); // it is not working...

            //size[layer] stores the number of neurons on the layer
            for ( int i = 0 ; i < this->sizes[ layer ] ; i++ )
            {
                //auxVectorWeights will have the size of the amount of wights necessary to connect the neuron i (from this layer) to neuron j (from next layer)
                auxVectorWeights = std::vector<double>( this->sizes[ layer - 1 ] );

                for ( int j = 0 ; j < auxVectorWeights.size() ; j++ )
                {
                    auxVectorWeights[ j ] = this->randomNormalNumber();
                }

                auxMatrixWeights.push_back( auxVectorWeights );
            }

            this->weights.push_back( auxMatrixWeights );

            auxMatrixWeights.clear();

            //-----------weights end----------------

            //-----------biases begin---------------
            auxVectorBiases = std::vector<double>( this->sizes[ layer ] );

            for ( int i = 0 ; i < auxVectorBiases.size() ; i++ )
            {
                auxVectorBiases[ i ] = this->randomNormalNumber();
            }

            this->biases.push_back( auxVectorBiases );
            //-----------biases end-----------------
        }

#ifdef _DEBUG
        for ( int i = 0 ; i < this->weights.size() ; i++ )
        {
            std::cout << "layer " << i << "\n";
            for ( int j = 0 ; j < this->weights[ i ].size() ; j++ )
            {
                std::cout << "neuron" << j << std::endl;
                for ( const auto k : this->weights[ i ][ j ] )
                {
                    std::cout << '\t' << k << ' ';
                }
                std::cout << std::endl;
            }
        }
#endif
    }

    template <class T>
    inline int lastIndex(std::vector<T> vector , int tail)
    {
        return (vector.size() - tail);
    }

    double neuralnetwork::randomNormalNumber(void)
    {
        return this->distribution( this->generator );
    }

    double sigmoid(double z)
    {
        return 1.0 / ( 1.0 + exp( -z ) );
    }

    std::vector<double> sigmoid(const std::vector<double> & z)
    {
        int max = z.size();
        std::vector<double> output;
        output.reserve(max);

        for(int i=0;i<max;i++)
        {
            output.push_back(0);
            output[i] = 1.0 / ( 1.0 + exp( -z[i] ) );
        }

        return output;
    }

    /*double sigmoid_prime(double z)
    {
        return sigmoid( z ) * ( 1 - sigmoid( z ) );
    }*/

    std::vector<double> sigmoid_prime(const std::vector<double>& z)
    {
        int max = z.size();
        std::vector<double> output;
        output.reserve(max);

        for(int i=0;i<max;i++)
        {
            output.push_back(sigmoid( z[i] ) * ( 1 - sigmoid( z[i] ) ) );
        }

        return output;
    }

    //scalar times vector
    std::vector<double> operator* (double a , const std::vector<double> & b)
    {
        int size = b.size();

        std::vector<double> result(size);

        for ( int i = 0 ; i < size ; i++ )
        {
            result[i] = a * b[ i ];
        }

        return result;
    }

    // inner product
    std::vector<double> operator* (const std::vector<double> & a , const std::vector<double> & b)
    {

#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size(); // or b.size(). they should have the same size.

        std::vector<double> result;
        result.reserve(size); // or b.size(). they should have the same size.

        for ( int i = 0 ; i < size ; i++ )
        {
            result.push_back( a[ i ] * b[ i ] );
        }

        return result;
    }

    //matrix times columns vector
    std::vector<double> operator* (const std::vector<std::vector<double>> & a , const std::vector<double> & b)
    {
#ifdef _DEBUG
        assert(a[0].size() == b.size());

        for(int i = 0 ; i < ( lastIndex( a , 1 )) ; i++)
        {
            assert(a[i].size() == a[i+1].size());
        }
#endif

        int lines = a.size();
        int columns = a[0].size();

        std::vector<double> result;
        result.reserve(lines);

        int j = 0;

        for ( int i = 0 ; i < lines ; i++ )
        {
            result.push_back(0);
            for(j = 0 ; j < columns ; j++)
            {
                result[i] += a[ i ][ j ] * b[ j ];
            }
        }

        return result;
    }

    //scalar times matrix (calls scalar times vector)
    std::vector<std::vector<double>> operator* (double a , const std::vector<std::vector<double>> & b)
    {
#ifdef _DEBUG
        for(int i = 0 ; i < b.size()-1 ; i++)
        {
            assert(b[i].size() == b[i+1].size());
        }
#endif

        int lines = b.size();
        int columns = b[0].size();

        std::vector<std::vector<double>> result;

        int j = 0;

        for ( int i = 0 ; i < lines ; i++ )
        {
            result.push_back(a * b[ j ]);
        }

        return result;
    }

    std::vector<double> operator+(const std::vector<double>& a, const std::vector<double>& b)
    {
        assert(a.size() == b.size());

        int size = a.size();

        std::vector<double> result;
        result.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(0);
            result[i] = a[i] + b[i];
        }

        return result;
    }

    //sum of matrices
    std::vector<std::vector<double>> operator+(const std::vector<std::vector<double>>& a, const std::vector<std::vector<double>>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

#ifdef _DEBUG
        for(int i = 0 ; i < size ; i++)
        {
            assert(a[i].size() == b[i].size());
        }
#endif

        std::vector<std::vector<double>> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(a[i] + b[i]);
        }

        return result;
    }

    //subtraction of vectors
    std::vector<double> operator-(const std::vector<double>& a, const std::vector<double>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

        std::vector<double> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result[i] = a[i] - b[i];
        }

        return result;
    }

    //subtraction of matrices (calls subtraction of vectors)
    std::vector<std::vector<double>> operator-(const std::vector<std::vector<double>>& a, const std::vector<std::vector<double>>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

#ifdef _DEBUG
        for(int i = 0 ; i < size ; i++)
        {
            assert(a[i].size() == b[i].size());
        }
#endif

        std::vector<std::vector<double>> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(a[i] - b[i]);
        }

        return result;
    }

    //elementwise division
    std::vector<double> operator/(const std::vector<double>& a, const std::vector<double>& b)
    {
        assert(a.size() == b.size());

        int size = a.size();

        std::vector<double> result;
        result.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            if(b[i] < MIN_NUMBER_TOLERANCE)
            {
                throw std::runtime_error("Can't divide by zero!");
            }
            result[i] = a[i] / b[i];
        }

        return result;
    }

    double neuralnetwork::costDerivatives(const double &networkOutput , const double &expectedOutput)
    {
        return expectedOutput - networkOutput;
    }

    std::vector<double> neuralnetwork::costDerivatives(const std::vector<double> &networkOutput , const std::vector<double> &expectedOutput)
    {
        assert(expectedOutput.size() == networkOutput.size());
        int size = networkOutput.size();
        std::vector<double> output;
        output.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            output.push_back(networkOutput[i] - expectedOutput[i]);
        }

        return output;
    }

    void neuralnetwork::backPropagation(const std::vector<double> &neuralNetworkInputs , const std::vector<double> &expectedOutputs, // inputs
                                        std::vector<std::vector<std::vector<double>>>& derivativeWeights , std::vector<std::vector<double>>& derivativeBiases) // outputs
    {

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        derivativeWeights.reserve( sizes.size() - 1 );
        derivativeBiases.reserve( sizes.size() - 1 );

        //to store one activation layer
        std::vector<double> activation = neuralNetworkInputs;
        //to store each one of the activation layers
        std::vector<std::vector<double>> activations;

        activations.reserve(sizes.size()); // numBiases is the same as the number of neurons (except 1st layer)
        activations.push_back(activation);
        int maxLayerSize = 0;

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        for ( int i = 1 ; i < numBiases ; i++ )
        {
            maxLayerSize = std::max(sizes[i], maxLayerSize);
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        // to store one weighted sum
        std::vector<double> z;
        z.reserve(maxLayerSize);
        // to store each one of the weighted sums
        std::vector<std::vector<double>> zs;
        zs.reserve(sizes.size());

        // layer and neuron counter
        int layer, neuron;

        for ( layer = 1 ; layer < numLayers ; layer++ )
        {
            z = (weights[layer] * activation) + biases[layer];
            zs.push_back(z);
            activation = sigmoid(z);
            activations.push_back(activation);
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        std::vector<double> delta = costDerivatives(activations[ lastIndex( activations , 1 )] , expectedOutputs) * sigmoid_prime(z);
        delta.reserve(maxLayerSize);

        derivativeBiases.push_back(delta);

        int j;

        std::vector<std::vector<double>> dummyMatrix;
        dummyMatrix.reserve(maxLayerSize);

        for (neuron = 0; neuron < sizes[ lastIndex( sizes , 1 )]; neuron++)
        {
            dummyMatrix.push_back(std::vector<double>(activations[ lastIndex( activations , 2 )].size()));
            for (j = 0; j < activations[ lastIndex( activations , 2 )].size(); j++)
            {
                dummyMatrix[neuron][j] = delta[neuron] * activations[ lastIndex( activations , 2 )][j];
            }
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        derivativeWeights.push_back(dummyMatrix);
        dummyMatrix.clear();

        std::vector<double> sp;
        sp.reserve(maxLayerSize);

        std::vector<double> dummyVector;
        dummyVector.reserve(maxLayerSize);

        double dummyDouble = 0;

        for(layer = 2 ; layer < numLayers ; layer++)
        {
            z = zs[ lastIndex( zs , layer )];
            sp = sigmoid_prime(z);

            for(j = 0 ; j < sizes[ lastIndex( weights , layer )] ; j++)
            {
                for (neuron = 0; neuron < sizes[ lastIndex( sizes , layer - 1 )]; neuron++)
                {
                    dummyDouble += weights[ lastIndex( weights , layer - 1 )][neuron][j] * delta[neuron];
                }
                dummyVector.push_back(dummyDouble * sp[j]);
                dummyDouble = 0;
            }
            delta = dummyVector;
            dummyVector.clear();

            derivativeBiases.push_back(delta);

            for (neuron = 0; neuron < sizes[ lastIndex( sizes , layer )]; neuron++)
            {
                dummyMatrix.push_back(std::vector<double>(sizes[ lastIndex( sizes , layer + 1 )]));
                for (j = 0; j < sizes[ lastIndex( sizes , layer + 1 )]; j++)
                {
                    dummyMatrix[neuron][j] = activations[ lastIndex( activations , layer + 1 )][j] * delta[neuron];
                }
            }
            derivativeWeights.push_back(dummyMatrix);
            dummyMatrix.clear();
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        //both derivativeWeights and derivativeBiases are reversed. so let's reverse it.
        std::reverse(derivativeWeights.begin(),derivativeWeights.end());
        std::reverse(derivativeBiases.begin(),derivativeBiases.end());

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

    }
}

main.cpp

#include <stdio.h>
#include <opencv2/opencv.hpp>
#include "neuralnetwork.h"
#include <string>

void printAll(const std::vector<double> & v, const std::string & name)
{
    int size = v.size();

    std::cout << "\t" <<  name << ":\t";

    for(int i = 0 ; i < size ; i++)
    {
        std::cout << v[i] << "\t";
    }

    std::cout << std::endl;
}

template<class T>
void printAll(const std::vector<T> & v, const std::string & name)
{
    int size = v.size();

    std::cout << name << ":" << std::endl;

    for(int i = 0 ; i < size ; i++)
    {
        printAll(v[i], "\t" + ("[" + std::to_string(i)) + "]");
    }
}

int main(int argc, char** argv )
{

    nn::neuralnetwork n({2,4,3});

    n.weights = {{},{{1,2},{3,4},{5,6},{7,8}} , {{9,8,7,6},{5,4,3,2},{1,2,3,4}}};
    n.biases = {{},{1, 4, 6, 8} , {9, 2, 4}};

    printAll(n.weights,"weights");
    printAll(n.biases,"biases");

    std::vector<std::vector<std::vector<double>>> derivativeWeights;
    std::vector<std::vector<double>> derivativeBiases;
    n.backPropagation({1,2},{1,2,3},derivativeWeights,derivativeBiases);

    printAll(n.derivativeWeights,"derivativeWeights");
    printAll(n.derivativeBiases,"derivativeBiases");

    system("PAUSE");

    return 0;
}


问:
R ggplot2 histogram bin allocation
My problem is that when I construct histograms with ggplot2 of certain bin width greater than the resolution of the data, bins sometimes contain uneven numbers of increments from the underlying data. This results in large peaks in the histogram which five a false impression of how peaky the data are. Is there a built-in way to prevent this? Maybe allocate increments between bins?

```<code>require(ggplot2)
require(ggplot2movies)
m <- ggplot(movies, aes(x = rating))
#Original resolution
plot(m + geom_histogram(binwidth = 0.1) + scale_y_sqrt())
#Downsampled
plot(m + geom_histogram(binwidth = 0.25) + scale_y_sqrt())
</code>```

答:
I don't know, if there is a built-in way or not, geom_histogram() has a default of 30 bins, which you can override.
One possible soltution can be, if you count the number of different x values and use that in the number of bins (or a fraction of them):

```<code>plot(m + geom_histogram(bins = nlevels(as.factor(movies$rating))))
</code>```

Title: R ggplot2 histogram bin allocation

Body:
My problem is that when I construct histograms with ggplot2 of certain bin width greater than the resolution of the data, bins sometimes contain uneven numbers of increments from the underlying data. This results in large peaks in the histogram which five a false impression of how peaky the data are. Is there a built-in way to prevent this? Maybe allocate increments between bins?

require(ggplot2)
require(ggplot2movies)
m <- ggplot(movies, aes(x = rating))
#Original resolution
plot(m + geom_histogram(binwidth = 0.1) + scale_y_sqrt())
#Downsampled
plot(m + geom_histogram(binwidth = 0.25) + scale_y_sqrt())

Body:
I don't know, if there is a built-in way or not, geom_histogram() has a default of 30 bins, which you can override.
One possible soltution can be, if you count the number of different x values and use that in the number of bins (or a fraction of them):

plot(m + geom_histogram(bins = nlevels(as.factor(movies$rating))))


问:
My implementation of k-means gives different results
I tried implementing Lloyd's algorithm and it seemed good until I ran it multiple times. Sometimes it gives the results I want, sometimes it gives strange centres.
I tried to change the condition so it stops when it has converged, but it doesn't help. Sorry for not translating comments to English, I hope it's clear enough.

The only randomness I have in the code is in the situation where my cluster empties so I replace it with a random point. I have no other idea what to do when this happens.

I can't see the problem. Can you give me an idea what might be the problem from the result figures?

This is my code:
(A is a matrix whose rows are my points)

```<code>% initialization of centroids; further-first method
n=size(A,1);
dim=size(A,2);
centri=zeros(k,dim); %matrix of centroids
for i=1:n
    centri(1,:)=centri(1,:)+A(i,:);
end
centri(1,:)=centri(1,:)/n;
for j=2:k %u svakom koraku postavljamo za centar onu tocku koja je najdalje od centra 1,..j-1
    maks=zeros(1,n);
    %maks(i) je najveca udaljenost te tocke do centra =max d(x(i),c), c centri
    for i=1:n
        dist=zeros(1,j-1);
        for l=1:j-1
            dist(l)=norm(A(i,:)-centri(l,:));
        end
        if(size(dist,2)==1) maks(i)=dist;
        else
            maks(i)=max(dist);
        end
        %maks(i)=0;
        %for l=1:j-1
          %  if(maks(i)<dist(l)) maks(i)=dist(l);
           % end
        %end
    end
    [maksi, ind]=max(maks);
    centri(j,:)=A(ind(1),:);
end

indeksi=zeros(1,n);
for i=1:n
    indeksi(i)=randi(k,1);
end
% u centrima je postavljena pocetna inicijalizacija
br_iter=0;
tic

while br_iter<=1000
    br_iter=br_iter+1;

    for i=1:n
        dist=zeros(1,k); % udaljenosti od tocke x do centra j
        for j=1:k
            dist(j)=norm(A(i,:)-centri(j,:));
        end
        [mini, ind]=min(dist); % ind je vektor za koji se poprima minimalna vrijednost
        indeksi(i)=ind(1); % uzmemo prvi po redu
    end
    % sad radimo nove centroide koji su aritmetička sredina svih vektora koji mu pripadaju
    for j=1:k
        centri(j,:)=zeros(1,dim);
        brojac=0;
        for i=1:n
            if indeksi(i)==j
                centri(j,:)=centri(j,:)+A(i,:);
                brojac=brojac+1;
            end
        end
        if brojac
            centri(j,:)=centri(j,:)/brojac;
        else
            ind=randi(n, 1);
            centri(j,:)=A(ind,:);
        end
    end
end
toc
for i=1:n
    plot(A(i,1), A(i,2), '.b');
   if(i==1) hold on;
   end
end

for i=1:k
    plot(centri(i,1), centri(i,2), '+r');
end
hold off
</code>```

答:
Starting with centers all zero is not a recommended approach.
After the first iteration, all but one of these centers will be empty. So randomness does have an effect on your result.

The results you show are typical for k-means. It does not guarantee to fond the optimum, but it can get stuck in a "local optimum".

So I don't think there is an error in your code. Just the starting condition is not chosen very wisely & you are mistaken to expect k-means to always give good results.

Body:
I tried implementing Lloyd's algorithm and it seemed good until I ran it multiple times. Sometimes it gives the results I want, sometimes it gives strange centres.
I tried to change the condition so it stops when it has converged, but it doesn't help. Sorry for not translating comments to English, I hope it's clear enough.

The only randomness I have in the code is in the situation where my cluster empties so I replace it with a random point. I have no other idea what to do when this happens.

I can't see the problem. Can you give me an idea what might be the problem from the result figures?

This is my code:
(A is a matrix whose rows are my points)

% initialization of centroids; further-first method
n=size(A,1);
dim=size(A,2);
centri=zeros(k,dim); %matrix of centroids
for i=1:n
    centri(1,:)=centri(1,:)+A(i,:);
end
centri(1,:)=centri(1,:)/n;
for j=2:k %u svakom koraku postavljamo za centar onu tocku koja je najdalje od centra 1,..j-1
    maks=zeros(1,n);
    %maks(i) je najveca udaljenost te tocke do centra =max d(x(i),c), c centri
    for i=1:n
        dist=zeros(1,j-1);
        for l=1:j-1
            dist(l)=norm(A(i,:)-centri(l,:));
        end
        if(size(dist,2)==1) maks(i)=dist;
        else
            maks(i)=max(dist);
        end
        %maks(i)=0;
        %for l=1:j-1
          %  if(maks(i)<dist(l)) maks(i)=dist(l);
           % end
        %end
    end
    [maksi, ind]=max(maks);
    centri(j,:)=A(ind(1),:);
end

indeksi=zeros(1,n);
for i=1:n
    indeksi(i)=randi(k,1);
end
% u centrima je postavljena pocetna inicijalizacija
br_iter=0;
tic

while br_iter<=1000
    br_iter=br_iter+1;

    for i=1:n
        dist=zeros(1,k); % udaljenosti od tocke x do centra j
        for j=1:k
            dist(j)=norm(A(i,:)-centri(j,:));
        end
        [mini, ind]=min(dist); % ind je vektor za koji se poprima minimalna vrijednost
        indeksi(i)=ind(1); % uzmemo prvi po redu
    end
    % sad radimo nove centroide koji su aritmetička sredina svih vektora koji mu pripadaju
    for j=1:k
        centri(j,:)=zeros(1,dim);
        brojac=0;
        for i=1:n
            if indeksi(i)==j
                centri(j,:)=centri(j,:)+A(i,:);
                brojac=brojac+1;
            end
        end
        if brojac
            centri(j,:)=centri(j,:)/brojac;
        else
            ind=randi(n, 1);
            centri(j,:)=A(ind,:);
        end
    end
end
toc
for i=1:n
    plot(A(i,1), A(i,2), '.b');
   if(i==1) hold on;
   end
end

for i=1:k
    plot(centri(i,1), centri(i,2), '+r');
end
hold off


问:
Matplotlib 3D Plot does not work as expected
as a Python and Stackoverflow Newbie, please excuse my dumb question. I've been working on this quite some time without making progress. I'm trying to set up a 3D Plot with X Y Z vectors for the respective axes.

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
import pandas, io
data = np.array([[0 ,0 ,1918],
                [1000 ,0 ,2001],
                [2000 ,0 ,2031],
                [3000 ,0 ,2048],
                [0 ,1000 ,2001],
                [1000 ,1000 ,2084],
                [2000 ,1000 ,2114],
                [3000 ,1000 ,2131],
                [0 ,2000 ,2031],
                [1000 ,2000 ,2114],
                [2000 ,2000 ,2144],
                [3000 ,2000 ,2161],
                [0 ,3000 ,2048],
                [1000 ,3000 ,2131],
                [2000 ,3000 ,2161],
                [3000 ,3000 ,2178]])
df = pandas.DataFrame(data,columns=["X","Y","Z"])
print(df)
x, y = np.meshgrid(df['X'],df['Y'])
plt.clf()
fig = plt.figure()
ax = fig.gca(projection='3d')
myplot = ax.plot_surface(X=x,Y=y,Z=df['Z'])
plt.show(myplot)
</code>```

The sample data has 16 data points. I understand that I have to transform the X and Y vectors into a 4x4 grid which defines each Z value in the space. This is what I try to achieve with np.meshgrid. The result should be a uniform area that with a constant slope from (0,0) towards (3000,3000). However, this is not what I see:

Resulting Graph

I'd be grateful for everybody pushing me in the right direction.

答:
Your code looks alright, although the use of pandas is redundant. It looks like that data you're using is simply not what you're after, i.e. constant slope.

Here is my code

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
import io

data = np.array([[0 ,0 ,1918],
                [1000 ,0 ,2001],
                [2000 ,0 ,2031],
                [3000 ,0 ,2048],
                [0 ,1000 ,2001],
                [1000 ,1000 ,2084],
                [2000 ,1000 ,2114],
                [3000 ,1000 ,2131],
                [0 ,2000 ,2031],
                [1000 ,2000 ,2114],
                [2000 ,2000 ,2144],
                [3000 ,2000 ,2161],
                [0 ,3000 ,2048],
                [1000 ,3000 ,2131],
                [2000 ,3000 ,2161],
                [3000 ,3000 ,2178]])

X, Y = np.meshgrid(data[:, 0], data[:, 1])

Z = X + Y

plt.clf()
fig = plt.figure()
ax = fig.gca(projection='3d')
myplot = ax.plot_surface(X,Y,Z)
plt.show(myplot)
</code>```

Which produces a surface of a plane.

Note that there is a a major difference: In your case, the Z is a 1D vector, whereas I have used X + Y which is a matrix.

The data you are using is basically a point cloud, so if you want to generate a surface from it you'll have to be a lot more specific about how to generate it.

Body:
as a Python and Stackoverflow Newbie, please excuse my dumb question. I've been working on this quite some time without making progress. I'm trying to set up a 3D Plot with X Y Z vectors for the respective axes.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
import pandas, io
data = np.array([[0 ,0 ,1918],
                [1000 ,0 ,2001],
                [2000 ,0 ,2031],
                [3000 ,0 ,2048],
                [0 ,1000 ,2001],
                [1000 ,1000 ,2084],
                [2000 ,1000 ,2114],
                [3000 ,1000 ,2131],
                [0 ,2000 ,2031],
                [1000 ,2000 ,2114],
                [2000 ,2000 ,2144],
                [3000 ,2000 ,2161],
                [0 ,3000 ,2048],
                [1000 ,3000 ,2131],
                [2000 ,3000 ,2161],
                [3000 ,3000 ,2178]])
df = pandas.DataFrame(data,columns=["X","Y","Z"])
print(df)
x, y = np.meshgrid(df['X'],df['Y'])
plt.clf()
fig = plt.figure()
ax = fig.gca(projection='3d')
myplot = ax.plot_surface(X=x,Y=y,Z=df['Z'])
plt.show(myplot)

The sample data has 16 data points. I understand that I have to transform the X and Y vectors into a 4x4 grid which defines each Z value in the space. This is what I try to achieve with np.meshgrid. The result should be a uniform area that with a constant slope from (0,0) towards (3000,3000). However, this is not what I see:

Resulting Graph

I'd be grateful for everybody pushing me in the right direction.

Body:
Your code looks alright, although the use of pandas is redundant. It looks like that data you're using is simply not what you're after, i.e. constant slope.

Here is my code

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
import io

data = np.array([[0 ,0 ,1918],
                [1000 ,0 ,2001],
                [2000 ,0 ,2031],
                [3000 ,0 ,2048],
                [0 ,1000 ,2001],
                [1000 ,1000 ,2084],
                [2000 ,1000 ,2114],
                [3000 ,1000 ,2131],
                [0 ,2000 ,2031],
                [1000 ,2000 ,2114],
                [2000 ,2000 ,2144],
                [3000 ,2000 ,2161],
                [0 ,3000 ,2048],
                [1000 ,3000 ,2131],
                [2000 ,3000 ,2161],
                [3000 ,3000 ,2178]])

X, Y = np.meshgrid(data[:, 0], data[:, 1])

Z = X + Y

plt.clf()
fig = plt.figure()
ax = fig.gca(projection='3d')
myplot = ax.plot_surface(X,Y,Z)
plt.show(myplot)

Which produces a surface of a plane.

Note that there is a a major difference: In your case, the Z is a 1D vector, whereas I have used X + Y which is a matrix.

The data you are using is basically a point cloud, so if you want to generate a surface from it you'll have to be a lot more specific about how to generate it.


问:
FCM notification reply to server
There is a push notification service that sends a message from a web server to an app device. The app has onMessageReceived() method implemented. However, not all the messages are being delivered and I have read somewhere that the delivery_receipt_request field, when set to true then (FCM), replies to the server mentioning the message being either delivered or not. I want to know that how can I catch that reply from the app if the message is delivered to my sender's side code.

答:
Option 1: Via XMPP

You need to run an XMPP client on your backend. This client should connect to FCM with your project parameters. You will then be able to process message delivery stanzas sent to you by FCM. Here are the baby steps:

Follow the steps in https://www.npmjs.com/package/node-xcs to setup the XMPP client, exporting environmental variables with your FCM project parameters.

You can send messages through there.

Listen for message delivery stanzas:

    client.on('stanza', function(stanza) {
        //HERE IS WHERE YOU PROCESS THE STANZA
        console.log('Please process me. I AM, the stanza: ', stanza.toString())
    })```
</div>
</div>
</p>

<p>The stanza you will get for message delivery will look like this:</p>

```<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "category":"com.example.yourapp", // to know which app sent it
      "data":
      {
         “message_status":"MESSAGE_SENT_TO_DEVICE",
         “original_message_id”:”m-1366082849205”
         “device_registration_id”: “REGISTRATION_ID”
      },
      "message_id":"dr2:m-1366082849205",
      "message_type":"receipt",
      "from":"gcm.googleapis.com"
  }
  </gcm>
</message>
```

Currently only CCS (XMPP) supports upstream messaging. Knock yourself out.

Option 2: Via HTTP

Now, if you decide to use the FCM HTTP protocol instead to send the messages, then you will have to interpret the response that you get back when you make the HTTP call. You can tell whether the message was delivered or not by looking at the HTTP response header and the error in the body of the response. The structure of the response is described here: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream

Again, knock yourself out.

Title: FCM notification reply to server

Body:
Option 1: Via XMPP

You need to run an XMPP client on your backend. This client should connect to FCM with your project parameters. You will then be able to process message delivery stanzas sent to you by FCM. Here are the baby steps:

Follow the steps in https://www.npmjs.com/package/node-xcs to setup the XMPP client, exporting environmental variables with your FCM project parameters.

You can send messages through there.

Listen for message delivery stanzas:

    client.on('stanza', function(stanza) {
        //HERE IS WHERE YOU PROCESS THE STANZA
        console.log('Please process me. I AM, the stanza: ', stanza.toString())
    })

The stanza you will get for message delivery will look like this:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "category":"com.example.yourapp", // to know which app sent it
      "data":
      {
         “message_status":"MESSAGE_SENT_TO_DEVICE",
         “original_message_id”:”m-1366082849205”
         “device_registration_id”: “REGISTRATION_ID”
      },
      "message_id":"dr2:m-1366082849205",
      "message_type":"receipt",
      "from":"gcm.googleapis.com"
  }
  </gcm>
</message>

Currently only CCS (XMPP) supports upstream messaging. Knock yourself out.

Option 2: Via HTTP

Now, if you decide to use the FCM HTTP protocol instead to send the messages, then you will have to interpret the response that you get back when you make the HTTP call. You can tell whether the message was delivered or not by looking at the HTTP response header and the error in the body of the response. The structure of the response is described here: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream

Again, knock yourself out.


问:
Cannot get my own JS file to work with Wordpress (4.9).
I am in a bit of a pickle, lol.

Here is my function:

```<code>  function start_group_escapes_4_less() {

    wp_enqueue_style( 'style', get_stylesheet_uri() . '/style.css');
    wp_enqueue_script( 'ge4l', get_stylesheet_uri() . '/js/ge4l.js', array('jquery'), null, true);

  }

  add_action( 'wp_enqueue_scripts', 'start_group_escapes_4_less' );
</code>```

Everywhere I checked, the syntax is right. Or is it?
Help :(

答:
Check the value of return => <?php echo get_stylesheet_uri(); ?>

Use get_template_directory() ?!

Body:
I am in a bit of a pickle, lol.

Here is my function:

  function start_group_escapes_4_less() {

    wp_enqueue_style( 'style', get_stylesheet_uri() . '/style.css');
    wp_enqueue_script( 'ge4l', get_stylesheet_uri() . '/js/ge4l.js', array('jquery'), null, true);

  }

  add_action( 'wp_enqueue_scripts', 'start_group_escapes_4_less' );

Everywhere I checked, the syntax is right. Or is it?
Help :(


问:
Send can only be implemented for a struct/enum type, not a trait
I have having difficulty implementing Send for a trait. Full code in the playground.

I have a Storage trait :

```<code>pub trait Storage {
    fn get_value(&self, key: &str) -> Result<Vec<u8>, Error>;
    fn put_value(&mut self, key: &str, value: &[u8]) -> Result<(), Error>;
    fn key_exists(&self, key: &str) -> bool;
    fn delete_key(&mut self, key: &str) -> Result<(), Error>;
}
</code>```

It is part of the Consistency struct:

```<code>pub struct Consistency<'a> {
    storage: &'a mut Storage,
}
</code>```

I have implemented a MemoryStorage struct:

```<code>#[derive(Debug)]
struct MemoryStorage {
    data: HashMap<String, Vec<u8>>,
}

impl Storage for MemoryStorage {
    fn get_value(&self, key: &str) -> Result<Vec<u8>, Error> {
        self.data.get(key).map_or(
            Err(Error::new(ErrorKind::NotFound, "Key does not exists")),
            |v| Ok(v.clone()),
        )
    }

    fn put_value(&mut self, key: &str, value: &[u8]) -> Result<(), Error> {
        self.data.insert(key.to_string(), Vec::from(value));
        Ok(())
    }

    fn key_exists(&self, key: &str) -> bool {
        self.data.contains_key(key)
    }

    fn delete_key(&mut self, key: &str) -> Result<(), Error> {
        self.data.remove(key).map_or(
            Err(Error::new(ErrorKind::NotFound, "Key does not exists")),
            |v| Ok(()),
        )
    }
}
</code>```

I wrote a test:

```<code>#[test]
fn multiple_threads_bombing_storage() {
    const parallels: usize = 10;
    let mut storage = MemoryStorage {
        data: HashMap::new(),
    };
    let mut consistency = Consistency::new(&mut storage);

    // create all keys.
    let mut keys = Vec::<String>::new();
    for k in 1..parallels {
        keys.push(k.to_string());
    }

    let zero = "0".as_bytes();
    // put default values in files.
    for key in keys.clone() {
        consistency.put_value(&key, zero).unwrap();
    }

    // test write threads
    let write_thread = |to_write: Vec<u8>, keys: &mut Vec<String>| {
        let mut rng = rand::thread_rng();
        rng.shuffle(keys);

        for key in keys {
            let mut val = consistency.get_value(key).unwrap();
            val.append(to_write.clone().as_mut());
            consistency.put_value(key, &val).unwrap();
        }
    };

    // start parallels threads..
    for t in 1..parallels {
        let handle = thread::spawn(move || {
            write_thread(t.to_string().into_bytes(), &mut keys);
        });
    }

    // wait for all threads..

    // check if all parallels keys have all numbers in any order.
}
</code>```

This gives me an error:

error[E0277]: the trait bound `fileapi::Storage: std::marker::Send` is not satisfied
   --> src/consistency.rs:158:26
    |
158 |             let handle = thread::spawn(move || {
    |                          ^^^^^^^^^^^^^ `fileapi::Storage` cannot be sent between threads safely
    |
    = help: the trait `std::marker::Send` is not implemented for `fileapi::Storage`
    = note: required because of the requirements on the impl of `std::marker::Send` for `&mut fileapi::Storage`
    = note: required because it appears within the type `consistency::Consistency<'_>`
    = note: required because of the requirements on the impl of `std::marker::Send` for `&mut consistency::Consistency<'_>`
    = note: required because it appears within the type `[closure@src/consistency.rs:145:28: 154:10 consistency:&mut consistency::Consistency<'_>]`
    = note: required because it appears within the type `[closure@src/consistency.rs:158:40: 160:14 write_thread:[closure@src/consistency.rs:145:28: 154:10 consistency:&mut consistency::Consistency<'_>], t:usize, keys:std::vec::Vec<std::string::String>]`
    = note: required by `std::thread::spawn`
```

<p>Adding <code>unsafe impl Send for Storage {}</code> gives me a contradictory error that <code>Send</code> can't be implemented for a trait:</p>

<pre class="lang-none prettyprint-override"><code>cross-crate traits with a default impl, like `std::marker::Send`, can only be implemented for a struct/enum type, not `fileapi::Storage + 'static`
</code>```

I don't understand how to solve this problem.

答:
You have a reference to something implementing a trait (a trait object), but your trait isn't guaranteed to be able to be sent between threads.

You need to ensure that it is. You can require all implementors of your trait are Send:

```<code>pub trait Storage: Send {
    // ...
}
</code>```

Or that this specific trait object implements Send:

```<code>pub struct Consistency<'a> {
    storage: &'a mut (Storage + Send),
}
</code>```

Your code has many other issues, so it still doesn't compile. Among them:

You attempt to pass a stack-allocated variable to a thread.

You try to share a mutable reference among multiple threads.

You many need to go back and re-read The Rust Programming Language, especially the chapter on concurrency.

See also:

Can I have a static borrowed reference to a trait object?

How can I pass a reference to a stack variable to a thread?

Share mutable object between threads

Body:
I have having difficulty implementing Send for a trait. Full code in the playground.

I have a Storage trait :

pub trait Storage {
    fn get_value(&self, key: &str) -> Result<Vec<u8>, Error>;
    fn put_value(&mut self, key: &str, value: &[u8]) -> Result<(), Error>;
    fn key_exists(&self, key: &str) -> bool;
    fn delete_key(&mut self, key: &str) -> Result<(), Error>;
}

It is part of the Consistency struct:

pub struct Consistency<'a> {
    storage: &'a mut Storage,
}

I have implemented a MemoryStorage struct:

#[derive(Debug)]
struct MemoryStorage {
    data: HashMap<String, Vec<u8>>,
}

impl Storage for MemoryStorage {
    fn get_value(&self, key: &str) -> Result<Vec<u8>, Error> {
        self.data.get(key).map_or(
            Err(Error::new(ErrorKind::NotFound, "Key does not exists")),
            |v| Ok(v.clone()),
        )
    }

    fn put_value(&mut self, key: &str, value: &[u8]) -> Result<(), Error> {
        self.data.insert(key.to_string(), Vec::from(value));
        Ok(())
    }

    fn key_exists(&self, key: &str) -> bool {
        self.data.contains_key(key)
    }

    fn delete_key(&mut self, key: &str) -> Result<(), Error> {
        self.data.remove(key).map_or(
            Err(Error::new(ErrorKind::NotFound, "Key does not exists")),
            |v| Ok(()),
        )
    }
}

I wrote a test:

#[test]
fn multiple_threads_bombing_storage() {
    const parallels: usize = 10;
    let mut storage = MemoryStorage {
        data: HashMap::new(),
    };
    let mut consistency = Consistency::new(&mut storage);

    // create all keys.
    let mut keys = Vec::<String>::new();
    for k in 1..parallels {
        keys.push(k.to_string());
    }

    let zero = "0".as_bytes();
    // put default values in files.
    for key in keys.clone() {
        consistency.put_value(&key, zero).unwrap();
    }

    // test write threads
    let write_thread = |to_write: Vec<u8>, keys: &mut Vec<String>| {
        let mut rng = rand::thread_rng();
        rng.shuffle(keys);

        for key in keys {
            let mut val = consistency.get_value(key).unwrap();
            val.append(to_write.clone().as_mut());
            consistency.put_value(key, &val).unwrap();
        }
    };

    // start parallels threads..
    for t in 1..parallels {
        let handle = thread::spawn(move || {
            write_thread(t.to_string().into_bytes(), &mut keys);
        });
    }

    // wait for all threads..

    // check if all parallels keys have all numbers in any order.
}

This gives me an error:

error[E0277]: the trait bound `fileapi::Storage: std::marker::Send` is not satisfied
   --> src/consistency.rs:158:26
    |
158 |             let handle = thread::spawn(move || {
    |                          ^^^^^^^^^^^^^ `fileapi::Storage` cannot be sent between threads safely
    |
    = help: the trait `std::marker::Send` is not implemented for `fileapi::Storage`
    = note: required because of the requirements on the impl of `std::marker::Send` for `&mut fileapi::Storage`
    = note: required because it appears within the type `consistency::Consistency<'_>`
    = note: required because of the requirements on the impl of `std::marker::Send` for `&mut consistency::Consistency<'_>`
    = note: required because it appears within the type `[closure@src/consistency.rs:145:28: 154:10 consistency:&mut consistency::Consistency<'_>]`
    = note: required because it appears within the type `[closure@src/consistency.rs:158:40: 160:14 write_thread:[closure@src/consistency.rs:145:28: 154:10 consistency:&mut consistency::Consistency<'_>], t:usize, keys:std::vec::Vec<std::string::String>]`
    = note: required by `std::thread::spawn`

Adding unsafe impl Send for Storage {} gives me a contradictory error that Send can't be implemented for a trait:

cross-crate traits with a default impl, like `std::marker::Send`, can only be implemented for a struct/enum type, not `fileapi::Storage + 'static`

I don't understand how to solve this problem.

Body:
You have a reference to something implementing a trait (a trait object), but your trait isn't guaranteed to be able to be sent between threads.

You need to ensure that it is. You can require all implementors of your trait are Send:

pub trait Storage: Send {
    // ...
}

Or that this specific trait object implements Send:

pub struct Consistency<'a> {
    storage: &'a mut (Storage + Send),
}

Your code has many other issues, so it still doesn't compile. Among them:

You attempt to pass a stack-allocated variable to a thread.

You try to share a mutable reference among multiple threads.

You many need to go back and re-read The Rust Programming Language, especially the chapter on concurrency.

See also:

Can I have a static borrowed reference to a trait object?

How can I pass a reference to a stack variable to a thread?

Share mutable object between threads


问:
Superagent error handling React Javascript
I am working on this API React App. I am using Superagent to get the API request. But I have trouble handling the error when there is no response. I get this Uncaught (in promise) Error: Unsuccessful HTTP response. I have tried to put all the code inside a try-catch, but that would not do the job still get the error.
This is my code:

```<code>handleClick() {
var searchWord = this.refs.search.value;
var url = "https://restcountries.eu/rest/v2/name/" + searchWord + "?fullText=true";
Request.get(url).then((response) => {
  var res = JSON.parse(response.text);
  this.setState({
    name:res[0].name,
    flag:res[0].flag,
    capital:res[0].capital,
  });
});
}
</code>```

I want to handle the error, to print out to the user that there was nothing found or something like that.

答:
I think this should do it.

```<code>Request.get(url)
  .then((response) => {
    var res = JSON.parse(response.text);
    this.setState({
    name:res[0].name,
    flag:res[0].flag,
    capital:res[0].capital,
  })
.catch((err) => {console.log(err)});
</code>```

Basically you append a catch() after the then() method.

Body:
I am working on this API React App. I am using Superagent to get the API request. But I have trouble handling the error when there is no response. I get this Uncaught (in promise) Error: Unsuccessful HTTP response. I have tried to put all the code inside a try-catch, but that would not do the job still get the error.
This is my code:

handleClick() {
var searchWord = this.refs.search.value;
var url = "https://restcountries.eu/rest/v2/name/" + searchWord + "?fullText=true";
Request.get(url).then((response) => {
  var res = JSON.parse(response.text);
  this.setState({
    name:res[0].name,
    flag:res[0].flag,
    capital:res[0].capital,
  });
});
}

I want to handle the error, to print out to the user that there was nothing found or something like that.

Body:
I think this should do it.

Request.get(url)
  .then((response) => {
    var res = JSON.parse(response.text);
    this.setState({
    name:res[0].name,
    flag:res[0].flag,
    capital:res[0].capital,
  })
.catch((err) => {console.log(err)});

Basically you append a catch() after the then() method.


问:
write the result into input field
I have problem with my javascript. I'm not able to display the results in the input field. Please can anyone help me?? And if it possible it will be better to calculate the result without clicking on the button!! Thanks.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span style="font-size:20px;">Your bid:</span> <input type="number"    name="bid" class="form-control" style="max-width:250px; margin-top:10px;"> <br>
        <input type="button" onClick="cal();">
        <span style="font-size:20px;" >Our Fee (10%):</span><input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;"><br>
        <span style="font-size:20px;">You'll paid:</span> <input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;"></code>```

答:
getElementsByName gives you an array of elements.

Use zeroeth element for value:

```<code><script>
    function cal(){

        var bid = document.getElementsByName("bid")[0].value;
        var result1= bid * 0.1;
        var result2= bid - result1;
        document.getElementsByName("fee")[0].value = result1;
        document.getElementsByName("get")[0].value = result2;

    }
</script>
</code>```

Edit - without clicking you can update your inputs when you add to your input this:

```<code>onkeyup="cal()"
</code>```

Title: write the result into input field

Body:
I have problem with my javascript. I'm not able to display the results in the input field. Please can anyone help me?? And if it possible it will be better to calculate the result without clicking on the button!! Thanks.

Your bid: <input type="number"    name="bid" class="form-control" style="max-width:250px; margin-top:10px;">

        <input type="button" onClick="cal();">
        Our Fee (10%):<input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">

        You'll paid: <input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

Body:
getElementsByName gives you an array of elements.

Use zeroeth element for value:

<script>
    function cal(){

        var bid = document.getElementsByName("bid")[0].value;
        var result1= bid * 0.1;
        var result2= bid - result1;
        document.getElementsByName("fee")[0].value = result1;
        document.getElementsByName("get")[0].value = result2;

    }
</script>

Edit - without clicking you can update your inputs when you add to your input this:

onkeyup="cal()"


问:
Dealing with bugs that only appear right after boot
I dealt with a bug today that only appeared when I ran my program right after booting my computer.  The cold start exposed a race condition which triggered the bug.  I managed to fix it, but it took a long time because I had to reboot my machine several times to figure out what was going on.  Can anybody suggest better ways of debugging problems like this in the future?  Can I somehow quickly put the computer into a "just booted" state?

Running Python 2.6 on Windows XP.

答: Run it inside a virtual machine.</p>

Body: Run it inside a virtual machine.