问:
ComponenWillMount happening after render for some reason in react native
```<code>    componentDidMount() {
    const refi = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    refi.orderByChild("highscore").limitToLast(3).on("value", function(snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function(child) {
            sortedHighscores.push({
                "username" : child.val().username,
                "score" : child.val().highscore
            });
        });

        sortedHighscores.sort(function(a,b) {
            return a.score - b.score;
        });
        this.setState({highscoreArray : sortedHighscores.reverse()});
    });
    console.log("highscore is:", this.state.highscoreArray);
}
</code>```

I am trying to get data from database and put it inside highscoreArray. Then I am trying to put it as a text in render. Some reason it is empty or null. This means that componentWillMount() happens after render()

Can someone explain or make this work? I am so frustrated.

I have changed the code as people have assisted me but still it is giving error:

```<code>undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores.reverse()})')
</code>```

答:
As the others have said, data is read from Firebase asynchronously. And while the data is being read, you call setState() with an empty array. Then when the data comes back, you add it to the array, but you don't call setState() anymore.

The solution is to move the call to setState() into the callback that fires when the data has been read (or changed):

```<code>    refi.orderByChild("highscore").limitToLast(3).on("value", function(snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function(child) {
          sortedHighscores.push({
            "username" : child.val().username,
            "score" : child.val().highscore
          });
        });

        sortedHighscores.sort(function(a,b) {
            return a.score - b.score;
        });
        this.setState({highscoreArray : sortedHighscores.reverse()});
    });
</code>```

You'll note that I listen for a value event, which ensures that I get all 3 scores in one go. I also clear the array before adding the scores, since this value callback will be called whenever the last 3 scores change. So this means that your scores will automatically update in the UI, when you for example change them in the Firebase Database console. Try it. It's fun!

Given the answers from Andrew and Hennek, you might want to put this code in componentDidMount(). But there too, you'll need to call setState() from within the callback.

Body:
    componentDidMount() {
    const refi = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    refi.orderByChild("highscore").limitToLast(3).on("value", function(snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function(child) {
            sortedHighscores.push({
                "username" : child.val().username,
                "score" : child.val().highscore
            });
        });

        sortedHighscores.sort(function(a,b) {
            return a.score - b.score;
        });
        this.setState({highscoreArray : sortedHighscores.reverse()});
    });
    console.log("highscore is:", this.state.highscoreArray);
}

I am trying to get data from database and put it inside highscoreArray. Then I am trying to put it as a text in render. Some reason it is empty or null. This means that componentWillMount() happens after render()

Can someone explain or make this work? I am so frustrated.

I have changed the code as people have assisted me but still it is giving error:

undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores.reverse()})')

Body:
As the others have said, data is read from Firebase asynchronously. And while the data is being read, you call setState() with an empty array. Then when the data comes back, you add it to the array, but you don't call setState() anymore.

The solution is to move the call to setState() into the callback that fires when the data has been read (or changed):

    refi.orderByChild("highscore").limitToLast(3).on("value", function(snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function(child) {
          sortedHighscores.push({
            "username" : child.val().username,
            "score" : child.val().highscore
          });
        });

        sortedHighscores.sort(function(a,b) {
            return a.score - b.score;
        });
        this.setState({highscoreArray : sortedHighscores.reverse()});
    });

You'll note that I listen for a value event, which ensures that I get all 3 scores in one go. I also clear the array before adding the scores, since this value callback will be called whenever the last 3 scores change. So this means that your scores will automatically update in the UI, when you for example change them in the Firebase Database console. Try it. It's fun!

Given the answers from Andrew and Hennek, you might want to put this code in componentDidMount(). But there too, you'll need to call setState() from within the callback.


来源: stackexchange

问:
What unit should I use for HTML?
I like to use em, and tend to stay away from % because it tends to screw up the design easily, and pt, px, cm... Because they aren't that friendly to all devices. Am I right in doing so?</p>

答: It depends. Using em links dimensions to the font size and using % links to the size of the container (and ultimately the screen). In some places one will be better than the other for achieving a consistent effect. I agree it is generally good to avoid absolute units, but px is useful for small dimensions (e.g. border widths, shims).</p>

ContentLicense: CC BY-SA 2.5

Title: What unit should I use for HTML?


问:
NPM in Visual Studio 2015 just won't install anything
I have the latest version of node.js, v6, and the npm.cmd in my VS Web Extensions contains this command, as many google hits have said it must:

```<code>@”C:\Program Files\nodejs\node.exe” “C:\Program files\nodejs\node_modules\npm\bin\npm-cli.js” %*
</code>```

Every time I change package.json in an 'Empty' Core 1 project, I get the following error in the output window:

The filename, directory name, or volume label syntax is incorrect.

====npm command completed with exit code 1====

Any ideas what could be wrong? Bower installed it's files just nicely, and everything else seems to be working fine. The app builds and runs, I just can't get Angular2 installed, or anything under npm.

答:
You can try this method. Surely will work for you. But this method will only
  works if you are going to restore package.json file to run AngularJS2.</p>

```<code>     $ cd project_working_directory
     $ npm init -y # create package.json
     $ npm install  typings --save
     $ npm uninstall typings --save
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the latest version of node.js, v6, and the npm.cmd in my VS Web Extensions contains this command, as many google hits have said it must:

@”C:\Program Files\nodejs\node.exe” “C:\Program files\nodejs\node_modules\npm\bin\npm-cli.js” %*

Every time I change package.json in an 'Empty' Core 1 project, I get the following error in the output window:

The filename, directory name, or volume label syntax is incorrect.

====npm command completed with exit code 1====

Any ideas what could be wrong? Bower installed it's files just nicely, and everything else seems to be working fine. The app builds and runs, I just can't get Angular2 installed, or anything under npm.

Body:
You can try this method. Surely will work for you. But this method will only
  works if you are going to restore package.json file to run AngularJS2.

     $ cd project_working_directory
     $ npm init -y # create package.json
     $ npm install  typings --save
     $ npm uninstall typings --save


问:
Efficient way to do Regexp match with a vector of patterns
I'm trying to match values in a data.table against a vector containing multiple patterns.  The demo code I have is:

```<code>library(data.table)

sites <- c("www.google.com", "plus.google.com", "www.yahoo.com", "www.bbc.co.uk")
patterns <- c("bb", "goog")
x <- data.table(sites)

# Regexp version of the in operator, iterates over a group
`%match_in%` <- function (values, match_list) {
   sapply(values,
       function (x, ml) {
          any(sapply(ml, grepl, x, ignore.case=TRUE, perl=TRUE))
       }
       ,match_list
)}

x[sites %match_in% patterns]
</code>```

Which correctly returns:

```<code>             sites
1:  www.google.com
2: plus.google.com
3:   www.bbc.co.uk
</code>```

However because this contains a nested sapply, it is very slow to run with larger data.tables.

Is there a more efficient way to do this that will work with larger tables?

答:
If you're searching for multiple patterns, why not combine the patterns with an or syntax? As @Marius suggests, this can be created using paste0(patterns, collapse = "|") if you have a lot of patterns to check.

For example,

```<code>all_patterns = paste0(patterns, collapse = "|")

stringr::str_subset(sites, all_patterns)
[1] "www.google.com"  "plus.google.com" "www.bbc.co.uk"
</code>```

To stick with your data.table use-case, perhaps

```<code>x[stringr::str_detect(sites, all_patterns)]
             sites
1:  www.google.com
2: plus.google.com
3:   www.bbc.co.uk
</code>```

Body:
I'm trying to match values in a data.table against a vector containing multiple patterns.  The demo code I have is:

library(data.table)

sites <- c("www.google.com", "plus.google.com", "www.yahoo.com", "www.bbc.co.uk")
patterns <- c("bb", "goog")
x <- data.table(sites)

# Regexp version of the in operator, iterates over a group
`%match_in%` <- function (values, match_list) {
   sapply(values,
       function (x, ml) {
          any(sapply(ml, grepl, x, ignore.case=TRUE, perl=TRUE))
       }
       ,match_list
)}

x[sites %match_in% patterns]

Which correctly returns:

             sites
1:  www.google.com
2: plus.google.com
3:   www.bbc.co.uk

However because this contains a nested sapply, it is very slow to run with larger data.tables.

Is there a more efficient way to do this that will work with larger tables?

Body:
If you're searching for multiple patterns, why not combine the patterns with an or syntax? As @Marius suggests, this can be created using paste0(patterns, collapse = "|") if you have a lot of patterns to check.

For example,

all_patterns = paste0(patterns, collapse = "|")

stringr::str_subset(sites, all_patterns)
[1] "www.google.com"  "plus.google.com" "www.bbc.co.uk"

To stick with your data.table use-case, perhaps

x[stringr::str_detect(sites, all_patterns)]
             sites
1:  www.google.com
2: plus.google.com
3:   www.bbc.co.uk


问:
PDO data types does not enforce the type casting
I have a problem or misunderstanding of PDO data binding especially bindValue() method,
I have searched a lot but I haven't found my answer yet.

here is the example,

```<code>global $connection;

$name = 22;

$stm = $connection->prepare("INSERT INTO users SET `name` = :name");

$stm->bindValue(":name", $name, PDO::PARAM_STR);

if ($stm->execute()) {
    echo 'Done';
}
</code>```

And then, the execution is done, the value is stored in the database as an integer number, not a string and no error appears.

答:
I Don't think so, please at first try that at your browser frst:

```<code>$name = '22';
echo $name;
var_dump($name);
</code>```

as you see eventought he echoOut 22 as an integer but it's type is a string.
PHP handled this in the recent versions, If you tried to add some number to the $name variable it will goes fine, Eventhought the variable is string!

Body:
I have a problem or misunderstanding of PDO data binding especially bindValue() method,
I have searched a lot but I haven't found my answer yet.

here is the example,

global $connection;

$name = 22;

$stm = $connection->prepare("INSERT INTO users SET `name` = :name");

$stm->bindValue(":name", $name, PDO::PARAM_STR);

if ($stm->execute()) {
    echo 'Done';
}

And then, the execution is done, the value is stored in the database as an integer number, not a string and no error appears.

Body:
I Don't think so, please at first try that at your browser frst:

$name = '22';
echo $name;
var_dump($name);

as you see eventought he echoOut 22 as an integer but it's type is a string.
PHP handled this in the recent versions, If you tried to add some number to the $name variable it will goes fine, Eventhought the variable is string!


问:
getsockname returns -1, errno is EBADF?
The program runs up to the getsockname where the return is -1 and errno is 9 (EBADF， bad file descriptor). However, the code instrumented  in Android app goes well.

```<code>void sysLibCSendHookHandler(CPUState* env, int isStart){

if(isStart){
    int fd = env->regs[0];
    int buf = env->regs[1];
    int len = env->regs[2];
    int flags = env->regs[3];
    DECAF_printf("xxxxx send(%d, %p, %d, %d)\n", fd, buf, len, flags);
    extern int errno;
    struct sockaddr_un sock_addr;
    socklen_t sock_addr_len;
    sock_addr_len = sizeof(sock_addr);
    int t = getsockname(fd, (struct sockaddr*)&sock_addr, &sock_addr_len);
     DECAF_printf("fd:%d",fd);}
</code>```

答:
This code results in undefined behavior:

```<code>extern int errno;
</code>```

Per 7.5 Errors <errno.h> of the C Standard (note the bolded part):

The  header  defines  several  macros,  all  relating  to
  the  reporting  of  error conditions.

The macros are

```<code>EDOM
EILSEQ
ERANGE
</code>```

which expand to integer constant expressions with type int, distinct
  positive values, and which are suitable for use in #if preprocessing
  directives; and

```<code>errno
</code>```

which  expands  to  a  modifiable  lvalue that  has  type int and
  thread  local  storage duration, the value of which is set to a
  positive error number by several library functions.  If  a  macro
  definition  is  suppressed  in  order  to  access  an  actual  object,
  or  a  program defines an identifier with the name errno, the
  behavior is undefined.

According to the Google Android source code, errno is a macro defined as

```<code>extern int *__geterrno(void);

#define errno (*__geterrno())
</code>```

That being the case, the value you see in your extern int errno is meaningless.

Title: getsockname returns -1, errno is EBADF?

Body:
The program runs up to the getsockname where the return is -1 and errno is 9 (EBADF， bad file descriptor). However, the code instrumented  in Android app goes well.

void sysLibCSendHookHandler(CPUState* env, int isStart){

if(isStart){
    int fd = env->regs[0];
    int buf = env->regs[1];
    int len = env->regs[2];
    int flags = env->regs[3];
    DECAF_printf("xxxxx send(%d, %p, %d, %d)\n", fd, buf, len, flags);
    extern int errno;
    struct sockaddr_un sock_addr;
    socklen_t sock_addr_len;
    sock_addr_len = sizeof(sock_addr);
    int t = getsockname(fd, (struct sockaddr*)&sock_addr, &sock_addr_len);
     DECAF_printf("fd:%d",fd);}

Body:
This code results in undefined behavior:

extern int errno;

Per 7.5 Errors <errno.h> of the C Standard (note the bolded part):

The  header  defines  several  macros,  all  relating  to
  the  reporting  of  error conditions.

The macros are

EDOM
EILSEQ
ERANGE

which expand to integer constant expressions with type int, distinct
  positive values, and which are suitable for use in #if preprocessing
  directives; and

errno

which  expands  to  a  modifiable  lvalue that  has  type int and
  thread  local  storage duration, the value of which is set to a
  positive error number by several library functions.  If  a  macro
  definition  is  suppressed  in  order  to  access  an  actual  object,
  or  a  program defines an identifier with the name errno, the
  behavior is undefined.

According to the Google Android source code, errno is a macro defined as

extern int *__geterrno(void);

#define errno (*__geterrno())

That being the case, the value you see in your extern int errno is meaningless.


问:
React Native in VS Code: add configuration for iOS Device to launch.json
I have a React Native project open in Visual Studio code, and Im trying to run the project on a physical connected iOS device. I successfully ran the app on the device directly from Xcode, but from Visual Studio Code I'm having issues. I believe I need to add a configuration for the device into launch.json. I have tried different entries in there but non seem to work. What is the proper way to add a configuration for a connected iOS device?</p>

答:
This is what I eventually had and managed to get it to install and launch on the connected device. The value for key name does not seem to uniquely identify a connected device. Its just the name that shows in Device Debug drop down.

```<code>    {
        "name": "My iPad",
        "program": "${workspaceRoot}/.vscode/launchReactNative.js",
        "type": "reactnative",
        "request": "launch",
        "platform": "ios",
        "target": "device",
        "sourceMaps": true,
        "outDir": "${workspaceRoot}/.vscode/.react"
    },
</code>```

Body:
This is what I eventually had and managed to get it to install and launch on the connected device. The value for key name does not seem to uniquely identify a connected device. Its just the name that shows in Device Debug drop down.

    {
        "name": "My iPad",
        "program": "${workspaceRoot}/.vscode/launchReactNative.js",
        "type": "reactnative",
        "request": "launch",
        "platform": "ios",
        "target": "device",
        "sourceMaps": true,
        "outDir": "${workspaceRoot}/.vscode/.react"
    },


问:
How to have a bootstrap class button link to an external site
I m having problem with a button that i created and trying to link to an external website. my code is

```<code><div id="home-btn" class="animated zoomIn">
   <a class="btn btn-lg btn-general btn-white smooth-scroll"
   href="http://www.yumpu.com/fr/embed/view/OPR2Gbw5Ml83hkp4" target="_blank"
   role="button"  title="Magazine Carrefour Floride en ligne">Clicquez ici pour
   lire le Magazine en Ligne</a>
   </div>
</code>```

I tried to place the href else where but same thing will not work.
Thanks!

答:
Adding role of button to the link is what has prevented the default behaviours. Either you remove the role attributes or modify your code to look something light this;

```<code><div id="home-btn" class="animated zoomIn">
    <a href="http://www.yumpu.com/fr/embed/view/OPR2Gbw5Ml83hkp4" target="_blank">
        <button class="btn btn-lg btn-general btn-white smooth-scroll"  type="button" title="Magazine Carrefour Floride en ligne">Clicquez ici pour lire le Magazine en Ligne.   <button>
    </a>
</code>```

Body:
I m having problem with a button that i created and trying to link to an external website. my code is

   Clicquez ici pour
   lire le Magazine en Ligne

I tried to place the href else where but same thing will not work.
Thanks!

Body:
Adding role of button to the link is what has prevented the default behaviours. Either you remove the role attributes or modify your code to look something light this;

<div id="home-btn" class="animated zoomIn">
    <a href="http://www.yumpu.com/fr/embed/view/OPR2Gbw5Ml83hkp4" target="_blank">
        <button class="btn btn-lg btn-general btn-white smooth-scroll"  type="button" title="Magazine Carrefour Floride en ligne">Clicquez ici pour lire le Magazine en Ligne.   <button>
    </a>


问:
SAS macros to print multiple reports
I have a data set that looks like this:

```<code>data have;
    input name $ class $ time score;
cards;
chewbacca wookie  1 97
chewbacca wookie 2 100
chewbacca wookie 3 95
saruman wizard 1 79
saruman wizard 2 85
saruman wizard 3 40
gandalf wizard 1 22
gandalf wizard 2 50
gandalf wizard 3 87
bieber canadian 1 50
bieber canadian 2 45
bieber canadian 3 10
;
run;
</code>```

I'm creating a program that does two things:
1. prints the data for each distinct class
2. creates a scatterplot x=time y=score for each name.

Executing the code below will illustrate my desired output:

```<code>data chewbacca saruman gandalf bieber;
    set have;
    if name='chewbacca' then output chewbacca;
    else if name='saruman' then output saruman;
    else if name='gandalf' then output gandalf;
    else if name='bieber' then output bieber;
run;

title 'Report for wookie';
proc print data=have;
    where class='wookie';
run;
title 'Plot Chewbacca';
proc sgplot data=chewbacca;
    scatter x=time y=score;
run;
title 'Report for wizard';
proc print data=have;
    where class='wizard';
run;
title 'Plot Saruman';
proc sgplot data=saruman;
    scatter x=time y=score;
run;
title 'Plot Gandalf';
proc sgplot data=gandalf;
    scatter x=time y=score;
run;
title 'Report for canadian';
proc print data=have;
    where class='canadian';
run;
title 'Plot Bieber';
proc sgplot data=bieber;
    scatter x=time y=score;
run;
</code>```

Ideally, I'd like to automate this.  I've been trying to set this up, but am missing something.  Here is my attempt:

```<code>proc sql;
    select count(distinct name) into :numname
    from have;
    %let numname=&numname;
    select distinct name into :name1 - :name&numname
    from have;
    select count(distinct class) into :numclass
    from have;
    %let numclass=&numclass;
    select distinct class into :class1 - :class&numclass
    from have;
quit;

%macro printit;
%do i = 1 %to &numclass;
title 'Report for &&class&i';
proc print data=have;
    where class=&&class&i;
run;
/*insert sgplot here*/
%end;
%mend;
%printit;
</code>```

Please help here.  Can't get the syntax sorted....

Thanks.

答:
The print procedure and most ODS procedures support by-group processing, which might be a lot simpler and save a lot of time depending on what you require.

```<code>proc sort data=have; by class;
proc print data=have;
    by class;
run;
</code>```

and

```<code>proc sort data=have; by name;
proc sgplot data=have;
 by name;
 scatter x=time y=score;
run;
</code>```

Title: SAS macros to print multiple reports

Body:
I have a data set that looks like this:

data have;
    input name $ class $ time score;
cards;
chewbacca wookie  1 97
chewbacca wookie 2 100
chewbacca wookie 3 95
saruman wizard 1 79
saruman wizard 2 85
saruman wizard 3 40
gandalf wizard 1 22
gandalf wizard 2 50
gandalf wizard 3 87
bieber canadian 1 50
bieber canadian 2 45
bieber canadian 3 10
;
run;

I'm creating a program that does two things:
1. prints the data for each distinct class
2. creates a scatterplot x=time y=score for each name.

Executing the code below will illustrate my desired output:

data chewbacca saruman gandalf bieber;
    set have;
    if name='chewbacca' then output chewbacca;
    else if name='saruman' then output saruman;
    else if name='gandalf' then output gandalf;
    else if name='bieber' then output bieber;
run;

title 'Report for wookie';
proc print data=have;
    where class='wookie';
run;
title 'Plot Chewbacca';
proc sgplot data=chewbacca;
    scatter x=time y=score;
run;
title 'Report for wizard';
proc print data=have;
    where class='wizard';
run;
title 'Plot Saruman';
proc sgplot data=saruman;
    scatter x=time y=score;
run;
title 'Plot Gandalf';
proc sgplot data=gandalf;
    scatter x=time y=score;
run;
title 'Report for canadian';
proc print data=have;
    where class='canadian';
run;
title 'Plot Bieber';
proc sgplot data=bieber;
    scatter x=time y=score;
run;

Ideally, I'd like to automate this.  I've been trying to set this up, but am missing something.  Here is my attempt:

proc sql;
    select count(distinct name) into :numname
    from have;
    %let numname=&numname;
    select distinct name into :name1 - :name&numname
    from have;
    select count(distinct class) into :numclass
    from have;
    %let numclass=&numclass;
    select distinct class into :class1 - :class&numclass
    from have;
quit;

%macro printit;
%do i = 1 %to &numclass;
title 'Report for &&class&i';
proc print data=have;
    where class=&&class&i;
run;
/*insert sgplot here*/
%end;
%mend;
%printit;

Please help here.  Can't get the syntax sorted....

Thanks.

Body:
The print procedure and most ODS procedures support by-group processing, which might be a lot simpler and save a lot of time depending on what you require.

proc sort data=have; by class;
proc print data=have;
    by class;
run;

and

proc sort data=have; by name;
proc sgplot data=have;
 by name;
 scatter x=time y=score;
run;


问:
Save tensorflow model: variables not found
I'm trying to save and restore a tensorflow model using tf.train.Saver. I think I've done the saving part correctly, but when I try to restore the model I get this error:

```<code>2017-07-03 15:55:14.824767: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key train/beta2_power not found in checkpoint
2017-07-03 15:55:14.824796: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases-outputlayer not found in checkpoint
2017-07-03 15:55:14.825913: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases-outputlayer/Adam not found in checkpoint
2017-07-03 15:55:14.826588: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases-outputlayer/Adam_1 not found in checkpoint
2017-07-03 15:55:14.827369: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key train/beta1_power not found in checkpoint
2017-07-03 15:55:14.828101: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases1 not found in checkpoint
2017-07-03 15:55:14.828973: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases1/Adam not found in checkpoint
2017-07-03 15:55:14.829151: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases1/Adam_1 not found in checkpoint
2017-07-03 15:55:14.830308: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights5/Adam_1 not found in checkpoint
2017-07-03 15:55:14.830590: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases2 not found in checkpoint
2017-07-03 15:55:14.831279: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases2/Adam not found in checkpoint
2017-07-03 15:55:14.832268: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases2/Adam_1 not found in checkpoint
2017-07-03 15:55:14.832558: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights5/Adam not found in checkpoint
2017-07-03 15:55:14.833052: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases3 not found in checkpoint
2017-07-03 15:55:14.834195: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases3/Adam not found in checkpoint
2017-07-03 15:55:14.834228: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases3/Adam_1 not found in checkpoint
2017-07-03 15:55:14.834629: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases4 not found in checkpoint
2017-07-03 15:55:14.835986: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights5 not found in checkpoint
2017-07-03 15:55:14.836128: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases5 not found in checkpoint
2017-07-03 15:55:14.836423: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases4/Adam not found in checkpoint
2017-07-03 15:55:14.837906: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases4/Adam_1 not found in checkpoint
2017-07-03 15:55:14.838055: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights4/Adam_1 not found in checkpoint
2017-07-03 15:55:14.838388: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases5/Adam not found in checkpoint
2017-07-03 15:55:14.839666: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases5/Adam_1 not found in checkpoint
2017-07-03 15:55:14.840299: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights-outputlayer not found in checkpoint
2017-07-03 15:55:14.840774: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights4/Adam not found in checkpoint
2017-07-03 15:55:14.841568: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights-outputlayer/Adam not found in checkpoint
2017-07-03 15:55:14.842312: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights-outputlayer/Adam_1 not found in checkpoint
2017-07-03 15:55:14.842689: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights1 not found in checkpoint
2017-07-03 15:55:14.843789: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights4 not found in checkpoint
2017-07-03 15:55:14.844030: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights1/Adam not found in checkpoint
2017-07-03 15:55:14.844775: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights1/Adam_1 not found in checkpoint
2017-07-03 15:55:14.845580: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights2 not found in checkpoint
2017-07-03 15:55:14.845919: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights3/Adam_1 not found in checkpoint
2017-07-03 15:55:14.846800: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights2/Adam not found in checkpoint
2017-07-03 15:55:14.847101: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights2/Adam_1 not found in checkpoint
2017-07-03 15:55:14.847274: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights3 not found in checkpoint
2017-07-03 15:55:14.847467: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights3/Adam not found in checkpoint
Traceback (most recent call last):
  File "predict2.py", line 6, in <module>
    saver.restore(sess,tf.train.latest_checkpoint('./'))
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1457, in restore
    {self.saver_def.filename_tensor_name: save_path})
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 778, in run
    run_metadata_ptr)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 982, in _run
    feed_dict_string, options, run_metadata)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1032, in _do_run
    target_list, options, run_metadata)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.NotFoundError: Key Biases-outputlayer not found in checkpoint
     [[Node: save/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/RestoreV2/tensor_names, save/RestoreV2/shape_and_slices)]]

Caused by op u'save/RestoreV2', defined at:
  File "predict2.py", line 5, in <module>
    saver = tf.train.import_meta_graph(os.getcwd()+'/models/baseDNN.meta')
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1595, in import_meta_graph
    **kwargs)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/meta_graph.py", line 499, in import_scoped_meta_graph
    producer_op_list=producer_op_list)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/importer.py", line 308, in import_graph_def
    op_def=op_def)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

NotFoundError (see above for traceback): Key Biases-outputlayer not found in checkpoint
     [[Node: save/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/RestoreV2/tensor_names, save/RestoreV2/shape_and_slices)]]
</code>```

I've looked at other StackOverflow questions where they use import_meta_graph, get_graph_by_tensor, and restore to load back the tensorflow model, and I have tried adapting that to my code, but I keep getting these errors where it says that it couldn't find any variables in the checkpoint.

Here is the code to save the model:

```<code>TRAIN_KEEP_PROB = 1.0
TEST_KEEP_PROB = 1.0
learning_rate = 0.0001
ne = 10

train = 100
test = 1
num_nodes = 250
len_puzzle = 80
n_nodes_hl1 = num_nodes # hidden layer 1
n_nodes_hl2 = num_nodes
n_nodes_hl3 = num_nodes
n_nodes_hl4 = num_nodes
n_nodes_hl5 = num_nodes

n_classes = 4
batch_size = 100 # load 100 features at a time

x = tf.placeholder('float',[None,TF_SHAPE],name="x_placeholder")
y = tf.placeholder('float',name='y_placeholder')
keep_prob = tf.placeholder('float',name='keep_prob_placeholder')

def neuralNet(data):
    hl_1 = {'weights':tf.Variable(tf.random_normal([TF_SHAPE, n_nodes_hl1]),name='Weights1'),
            'biases':tf.Variable(tf.random_normal([n_nodes_hl1]),name='Biases1')}

    hl_2 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2]),name='Weights2'),
            'biases':tf.Variable(tf.random_normal([n_nodes_hl2]),name='Biases2')}

    hl_3 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3]),name='Weights3'),
            'biases':tf.Variable(tf.random_normal([n_nodes_hl3]),name='Biases3')}

    hl_4 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_nodes_hl4]),name='Weights4'),
            'biases':tf.Variable(tf.random_normal([n_nodes_hl4]),name='Biases4')}

    hl_5 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl4, n_nodes_hl5]),name='Weights5'),
            'biases':tf.Variable(tf.random_normal([n_nodes_hl5]),name='Biases5')}

    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl5, n_classes]),name='Weights-outputlayer'),
            'biases':tf.Variable(tf.random_normal([n_classes]),name='Biases-outputlayer')}

    l1 = tf.add(tf.matmul(data, hl_1['weights']), hl_1['biases'])
    l1 = tf.nn.sigmoid(l1,name='op1')

    l2 = tf.add(tf.matmul(l1, hl_2['weights']), hl_2['biases'])
    l2 = tf.nn.sigmoid(l2,name='op2')

    l3 = tf.add(tf.matmul(l2, hl_3['weights']), hl_3['biases'])
    l3 = tf.nn.sigmoid(l3,name='op3')

    l4 = tf.add(tf.matmul(l3, hl_4['weights']), hl_4['biases'])
    l4 = tf.nn.sigmoid(l4,name='op4')

    l5 = tf.add(tf.matmul(l4, hl_5['weights']), hl_5['biases'])
    l5 = tf.nn.sigmoid(l5,name='op5')

    dropout = tf.nn.dropout(l5,keep_prob, name='op6')
    ol = tf.add(tf.matmul(dropout, output_layer['weights']), output_layer['biases'], name='op7')

    return ol

def train(x):
    prediction = neuralNet(x)
    #print prediction
    with tf.name_scope('cross_entropy'):
        cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
        tf.summary.scalar('cross_entropy',cost)

    with tf.name_scope('train'):
        optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) # learning rate = 0.001

    with tf.name_scope('accuracy'):
        correct = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct,'float'))
        tf.summary.scalar('accuracy',accuracy)

    # cycles of feed forward and backprop
    num_epochs = ne

    with tf.Session() as sess:
        saver = tf.train.Saver()
        sess.run(tf.global_variables_initializer())
        merged_summary = tf.summary.merge_all()

        for epoch in range(num_epochs):
            epoch_loss = 0
            for i in range(int(real_X_9.shape[0])/batch_size):#mnist.train.num_examples/batch_size)): # X.shape[0]
                randidx = np.random.choice(real_X_9.shape[0], batch_size, replace=False)
                epoch_x,epoch_y = real_X_9[randidx,:],real_y_9[randidx,:] #mnist.train.next_batch(batch_size) # X,y
                j,c = sess.run([optimizer,cost],feed_dict={x:epoch_x,y:epoch_y,keep_prob:TRAIN_KEEP_PROB})
                if i == 0:
                    [ta] = sess.run([accuracy],feed_dict={x:epoch_x,y:epoch_y,keep_prob:TRAIN_KEEP_PROB})
                    print 'Train Accuracy', ta

                epoch_loss += c
            print '\n','Epoch', epoch + 1, 'completed out of', num_epochs, '\nLoss:',epoch_loss
        saver.save(sess, os.getcwd()+'/models/baseDNN')
train(x)
</code>```

Here is my code to try to restore the model (which is the code that produces the error):

```<code>import tensorflow as tf
import os

sess = tf.Session()
saver = tf.train.import_meta_graph(os.getcwd()+'/models/baseDNN.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))

graph = tf.get_default_graph()

x = graph.get_tensor_by_name('x_placeholder:0')
y = graph.get_tensor_by_name('y_placeholder:0')

op1 = graph.get_tensor_by_name('op1:0')
op2 = graph.get_tensor_by_name('op2:0')
op3 = graph.get_tensor_by_name('op3:0')
op4 = graph.get_tensor_by_name('op4:0')
op5 = graph.get_tensor_by_name('op5:0')
op6 = graph.get_tensor_by_name('op6:0')
op7 = graph.get_tensor_by_name('op7:0')
</code>```

Any help would be greatly appreciated. Thanks.

答:
Don't think the correct checkpoint file is loaded.
Check the files saved in your /models/baseDNN directory. It should contain  model.ckpt and model.ckpt.meta (or something similar). Then point to the correct files:

```<code>saver = tf.train.import_meta_graph('/path/baseDNN.meta')
saver.restore(sess,'/path/baseDNN')
</code>```

Body:
I'm trying to save and restore a tensorflow model using tf.train.Saver. I think I've done the saving part correctly, but when I try to restore the model I get this error:

2017-07-03 15:55:14.824767: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key train/beta2_power not found in checkpoint
2017-07-03 15:55:14.824796: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases-outputlayer not found in checkpoint
2017-07-03 15:55:14.825913: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases-outputlayer/Adam not found in checkpoint
2017-07-03 15:55:14.826588: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases-outputlayer/Adam_1 not found in checkpoint
2017-07-03 15:55:14.827369: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key train/beta1_power not found in checkpoint
2017-07-03 15:55:14.828101: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases1 not found in checkpoint
2017-07-03 15:55:14.828973: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases1/Adam not found in checkpoint
2017-07-03 15:55:14.829151: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases1/Adam_1 not found in checkpoint
2017-07-03 15:55:14.830308: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights5/Adam_1 not found in checkpoint
2017-07-03 15:55:14.830590: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases2 not found in checkpoint
2017-07-03 15:55:14.831279: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases2/Adam not found in checkpoint
2017-07-03 15:55:14.832268: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases2/Adam_1 not found in checkpoint
2017-07-03 15:55:14.832558: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights5/Adam not found in checkpoint
2017-07-03 15:55:14.833052: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases3 not found in checkpoint
2017-07-03 15:55:14.834195: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases3/Adam not found in checkpoint
2017-07-03 15:55:14.834228: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases3/Adam_1 not found in checkpoint
2017-07-03 15:55:14.834629: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases4 not found in checkpoint
2017-07-03 15:55:14.835986: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights5 not found in checkpoint
2017-07-03 15:55:14.836128: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases5 not found in checkpoint
2017-07-03 15:55:14.836423: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases4/Adam not found in checkpoint
2017-07-03 15:55:14.837906: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases4/Adam_1 not found in checkpoint
2017-07-03 15:55:14.838055: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights4/Adam_1 not found in checkpoint
2017-07-03 15:55:14.838388: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases5/Adam not found in checkpoint
2017-07-03 15:55:14.839666: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Biases5/Adam_1 not found in checkpoint
2017-07-03 15:55:14.840299: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights-outputlayer not found in checkpoint
2017-07-03 15:55:14.840774: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights4/Adam not found in checkpoint
2017-07-03 15:55:14.841568: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights-outputlayer/Adam not found in checkpoint
2017-07-03 15:55:14.842312: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights-outputlayer/Adam_1 not found in checkpoint
2017-07-03 15:55:14.842689: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights1 not found in checkpoint
2017-07-03 15:55:14.843789: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights4 not found in checkpoint
2017-07-03 15:55:14.844030: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights1/Adam not found in checkpoint
2017-07-03 15:55:14.844775: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights1/Adam_1 not found in checkpoint
2017-07-03 15:55:14.845580: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights2 not found in checkpoint
2017-07-03 15:55:14.845919: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights3/Adam_1 not found in checkpoint
2017-07-03 15:55:14.846800: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights2/Adam not found in checkpoint
2017-07-03 15:55:14.847101: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights2/Adam_1 not found in checkpoint
2017-07-03 15:55:14.847274: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights3 not found in checkpoint
2017-07-03 15:55:14.847467: W tensorflow/core/framework/op_kernel.cc:1152] Not found: Key Weights3/Adam not found in checkpoint
Traceback (most recent call last):
  File "predict2.py", line 6, in <module>
    saver.restore(sess,tf.train.latest_checkpoint('./'))
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1457, in restore
    {self.saver_def.filename_tensor_name: save_path})
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 778, in run
    run_metadata_ptr)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 982, in _run
    feed_dict_string, options, run_metadata)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1032, in _do_run
    target_list, options, run_metadata)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.NotFoundError: Key Biases-outputlayer not found in checkpoint
     [[Node: save/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/RestoreV2/tensor_names, save/RestoreV2/shape_and_slices)]]

Caused by op u'save/RestoreV2', defined at:
  File "predict2.py", line 5, in <module>
    saver = tf.train.import_meta_graph(os.getcwd()+'/models/baseDNN.meta')
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1595, in import_meta_graph
    **kwargs)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/meta_graph.py", line 499, in import_scoped_meta_graph
    producer_op_list=producer_op_list)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/importer.py", line 308, in import_graph_def
    op_def=op_def)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

NotFoundError (see above for traceback): Key Biases-outputlayer not found in checkpoint
     [[Node: save/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/RestoreV2/tensor_names, save/RestoreV2/shape_and_slices)]]

I've looked at other StackOverflow questions where they use import_meta_graph, get_graph_by_tensor, and restore to load back the tensorflow model, and I have tried adapting that to my code, but I keep getting these errors where it says that it couldn't find any variables in the checkpoint.

Here is the code to save the model:

TRAIN_KEEP_PROB = 1.0
TEST_KEEP_PROB = 1.0
learning_rate = 0.0001
ne = 10

train = 100
test = 1
num_nodes = 250
len_puzzle = 80
n_nodes_hl1 = num_nodes # hidden layer 1
n_nodes_hl2 = num_nodes
n_nodes_hl3 = num_nodes
n_nodes_hl4 = num_nodes
n_nodes_hl5 = num_nodes

n_classes = 4
batch_size = 100 # load 100 features at a time

x = tf.placeholder('float',[None,TF_SHAPE],name="x_placeholder")
y = tf.placeholder('float',name='y_placeholder')
keep_prob = tf.placeholder('float',name='keep_prob_placeholder')

def neuralNet(data):
    hl_1 = {'weights':tf.Variable(tf.random_normal([TF_SHAPE, n_nodes_hl1]),name='Weights1'),
            'biases':tf.Variable(tf.random_normal([n_nodes_hl1]),name='Biases1')}

    hl_2 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2]),name='Weights2'),
            'biases':tf.Variable(tf.random_normal([n_nodes_hl2]),name='Biases2')}

    hl_3 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3]),name='Weights3'),
            'biases':tf.Variable(tf.random_normal([n_nodes_hl3]),name='Biases3')}

    hl_4 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_nodes_hl4]),name='Weights4'),
            'biases':tf.Variable(tf.random_normal([n_nodes_hl4]),name='Biases4')}

    hl_5 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl4, n_nodes_hl5]),name='Weights5'),
            'biases':tf.Variable(tf.random_normal([n_nodes_hl5]),name='Biases5')}

    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl5, n_classes]),name='Weights-outputlayer'),
            'biases':tf.Variable(tf.random_normal([n_classes]),name='Biases-outputlayer')}

    l1 = tf.add(tf.matmul(data, hl_1['weights']), hl_1['biases'])
    l1 = tf.nn.sigmoid(l1,name='op1')

    l2 = tf.add(tf.matmul(l1, hl_2['weights']), hl_2['biases'])
    l2 = tf.nn.sigmoid(l2,name='op2')

    l3 = tf.add(tf.matmul(l2, hl_3['weights']), hl_3['biases'])
    l3 = tf.nn.sigmoid(l3,name='op3')

    l4 = tf.add(tf.matmul(l3, hl_4['weights']), hl_4['biases'])
    l4 = tf.nn.sigmoid(l4,name='op4')

    l5 = tf.add(tf.matmul(l4, hl_5['weights']), hl_5['biases'])
    l5 = tf.nn.sigmoid(l5,name='op5')

    dropout = tf.nn.dropout(l5,keep_prob, name='op6')
    ol = tf.add(tf.matmul(dropout, output_layer['weights']), output_layer['biases'], name='op7')

    return ol

def train(x):
    prediction = neuralNet(x)
    #print prediction
    with tf.name_scope('cross_entropy'):
        cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
        tf.summary.scalar('cross_entropy',cost)

    with tf.name_scope('train'):
        optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) # learning rate = 0.001

    with tf.name_scope('accuracy'):
        correct = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct,'float'))
        tf.summary.scalar('accuracy',accuracy)

    # cycles of feed forward and backprop
    num_epochs = ne

    with tf.Session() as sess:
        saver = tf.train.Saver()
        sess.run(tf.global_variables_initializer())
        merged_summary = tf.summary.merge_all()

        for epoch in range(num_epochs):
            epoch_loss = 0
            for i in range(int(real_X_9.shape[0])/batch_size):#mnist.train.num_examples/batch_size)): # X.shape[0]
                randidx = np.random.choice(real_X_9.shape[0], batch_size, replace=False)
                epoch_x,epoch_y = real_X_9[randidx,:],real_y_9[randidx,:] #mnist.train.next_batch(batch_size) # X,y
                j,c = sess.run([optimizer,cost],feed_dict={x:epoch_x,y:epoch_y,keep_prob:TRAIN_KEEP_PROB})
                if i == 0:
                    [ta] = sess.run([accuracy],feed_dict={x:epoch_x,y:epoch_y,keep_prob:TRAIN_KEEP_PROB})
                    print 'Train Accuracy', ta

                epoch_loss += c
            print '\n','Epoch', epoch + 1, 'completed out of', num_epochs, '\nLoss:',epoch_loss
        saver.save(sess, os.getcwd()+'/models/baseDNN')
train(x)

Here is my code to try to restore the model (which is the code that produces the error):

import tensorflow as tf
import os

sess = tf.Session()
saver = tf.train.import_meta_graph(os.getcwd()+'/models/baseDNN.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))

graph = tf.get_default_graph()

x = graph.get_tensor_by_name('x_placeholder:0')
y = graph.get_tensor_by_name('y_placeholder:0')

op1 = graph.get_tensor_by_name('op1:0')
op2 = graph.get_tensor_by_name('op2:0')
op3 = graph.get_tensor_by_name('op3:0')
op4 = graph.get_tensor_by_name('op4:0')
op5 = graph.get_tensor_by_name('op5:0')
op6 = graph.get_tensor_by_name('op6:0')
op7 = graph.get_tensor_by_name('op7:0')

Any help would be greatly appreciated. Thanks.

Body:
Don't think the correct checkpoint file is loaded.
Check the files saved in your /models/baseDNN directory. It should contain  model.ckpt and model.ckpt.meta (or something similar). Then point to the correct files:

saver = tf.train.import_meta_graph('/path/baseDNN.meta')
saver.restore(sess,'/path/baseDNN')


问:
c# Loop not incrementing as expected
Hi I had a loop that was stepping through an array with each index being multiplied by two. However I changed it so that the index is multiplied by 0, then 1, then 2 etc til it hits 10. (This is j in the code below) j is not incrementing as expected and just multiplies by nine. Can anyone help? Tks</p>

```<code>using System;

namespace ArrayandStringPractice
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int[] a = new int[10];

      for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
        {
          {
            a[i] = i * j;
            //Console.WriteLine(a[i]);
          }
        }

      foreach (int i in a)
      {
        Console.WriteLine(i);
      }
    }
  }
}
</code>```

答:
Use a two dimensional array to store all the values:

```<code>int[,] a = new int[10,10];
</code>```

Then replace

```<code>a[i] = i * j;
</code>```

with

```<code>a[i,j] = i * j;
</code>```

and use this to read the values back:

```<code>for (int i = 0; i < 10; i++)
    for (int j = 0; j < 10; j++)
        Console.WriteLine(a[i,j]);
</code>```

Title: c# Loop not incrementing as expected

Body:
Hi I had a loop that was stepping through an array with each index being multiplied by two. However I changed it so that the index is multiplied by 0, then 1, then 2 etc til it hits 10. (This is j in the code below) j is not incrementing as expected and just multiplies by nine. Can anyone help? Tks

using System;

namespace ArrayandStringPractice
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int[] a = new int[10];

      for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
        {
          {
            a[i] = i * j;
            //Console.WriteLine(a[i]);
          }
        }

      foreach (int i in a)
      {
        Console.WriteLine(i);
      }
    }
  }
}

Body:
Use a two dimensional array to store all the values:

int[,] a = new int[10,10];

Then replace

a[i] = i * j;

with

a[i,j] = i * j;

and use this to read the values back:

for (int i = 0; i < 10; i++)
    for (int j = 0; j < 10; j++)
        Console.WriteLine(a[i,j]);


问:
Combinations from different groups in a specific order
I have a list of parameters that each accept a specific range of inputs. I am working on creating a test that creates every possible valid input. Furthermore, each group is optional (can be skipped entirely), so the combination lengths don't necessarily have to be the same length of the list.

Input

```<code>List<string[]> temp = new List<string[]>
{
    // The order of these groups is important
    new string[] { "a", "b", "c" },
    new string[] { "d", "e" },
    new string[] { "f", "g", "h" }
};
</code>```

Constraints

0 or 1 item per group (a string[] above)

Order of the List<T> must be preserved

Valid Combinations

a, e, f

a, d, g

c, e, f

b, g

c, f

Invalid Combinations

a, b, f (a and b are from the same group - not allowed)

a, f, d (wrong order - d must come before f)

So far, I have gone back to my library where I have a Combinations LINQ method.

```<code>public static class IEnumerableExtensions
{
    // Can be used to get all permutations at a certain level
    // Source: http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n#1898744
    public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        return k == 0 ? new[] { new T[0] } :
          elements.SelectMany((e, i) =>
            elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
    }
}
</code>```

In the past I have only used this on single sequence to do things like generate every permutation of URL segments. But I am struggling with its usage on a nested list with the constraints of one per group and in a specific order.

I know I can solve this particular puzzle by doing 3 nested loops and using lists to track which items were already used, but I don't know in advance how many items will be in the List<T>, so that won't work in the general case.

How can I get all of the valid combinations of the above input?

I would prefer LINQ, but will accept any solution that solves this problem.

答:
Here is a Linq expression that enumerates all combinations. You can try it out in online C# repl. The idea is to use accumulator "a" to gather all combinations by going through each item of your temp collection "b" and add elements of "b" (single item combination) as well as add to every accumulated combination so far. Pretty hairy expression though.  </p>

```<code>var combinations = temp.Aggregate(Enumerable.Empty<IEnumerable<string>>(), (a, b) => a
          .Concat(b.Select(i => Enumerable.Repeat(i, 1)))
          .Concat(a.SelectMany(i => b.Select(j => i.Concat(Enumerable.Repeat(j, 1))))));
</code>```

Body:
I have a list of parameters that each accept a specific range of inputs. I am working on creating a test that creates every possible valid input. Furthermore, each group is optional (can be skipped entirely), so the combination lengths don't necessarily have to be the same length of the list.

Input

List<string[]> temp = new List<string[]>
{
    // The order of these groups is important
    new string[] { "a", "b", "c" },
    new string[] { "d", "e" },
    new string[] { "f", "g", "h" }
};

Constraints

0 or 1 item per group (a string[] above)

Order of the List<T> must be preserved

Valid Combinations

a, e, f

a, d, g

c, e, f

b, g

c, f

Invalid Combinations

a, b, f (a and b are from the same group - not allowed)

a, f, d (wrong order - d must come before f)

So far, I have gone back to my library where I have a Combinations LINQ method.

public static class IEnumerableExtensions
{
    // Can be used to get all permutations at a certain level
    // Source: http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n#1898744
    public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        return k == 0 ? new[] { new T[0] } :
          elements.SelectMany((e, i) =>
            elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
    }
}

In the past I have only used this on single sequence to do things like generate every permutation of URL segments. But I am struggling with its usage on a nested list with the constraints of one per group and in a specific order.

I know I can solve this particular puzzle by doing 3 nested loops and using lists to track which items were already used, but I don't know in advance how many items will be in the List<T>, so that won't work in the general case.

How can I get all of the valid combinations of the above input?

I would prefer LINQ, but will accept any solution that solves this problem.

Body:
Here is a Linq expression that enumerates all combinations. You can try it out in online C# repl. The idea is to use accumulator "a" to gather all combinations by going through each item of your temp collection "b" and add elements of "b" (single item combination) as well as add to every accumulated combination so far. Pretty hairy expression though.

var combinations = temp.Aggregate(Enumerable.Empty<IEnumerable<string>>(), (a, b) => a
          .Concat(b.Select(i => Enumerable.Repeat(i, 1)))
          .Concat(a.SelectMany(i => b.Select(j => i.Concat(Enumerable.Repeat(j, 1))))));


问:
OpenTBS/PHP - Merge content into embedded worksheet inside of a PowerPoint template
How do I properly fill an embedded worksheet of a PowerPoint template with data using OpenTBS, where the worksheet is embedded inside of a PowerPoint presentation?

I used sub files but the embedded worksheet retains the input tags and no replaced values.

Excel Template that merges properly as a standalone xls file, but not when embedded in a presentation (PPTX).

```<code>+------------------------------+---------------------------------+
|                              |    [c.key;block=tbs:cell]       |
+------------------------------+---------------------------------+
|       [r.#;block=tbs:row]    |    [cell.val;block=tbs:cell]    |
+------------------------------+---------------------------------+
</code>```

PHP Merge Code

```<code>$template = 'riskwaterfalltemplate.pptm';
$TBS->LoadTemplate($template.'#ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx',  OPENTBS_ALREADY_UTF8);

// -----------------
// Output the result
// -----------------
$nbr_row = 5;
$nbr_col = 5;
// List of column's names
$columns = array();
for ($col=1; $col <= $nbr_col; $col++)
{
    $columns[$col]['key'] = $col;
}

$data = array();
$record = array();

for ($col=1; $col <= $nbr_col; $col++)
{
    $record[$col]['val'] = 1;
}
for ($row=0; $row < $nbr_row; $row++)
{

    $data[$row] = $record;
}

// Expanding columns
$TBS->MergeBlock('c',$columns);

//Expanding Cells
$TBS->MergeBlock('cell', $record);

// Merging rows
$TBS->MergeBlock('r',$data);

$TBS->Show();
</code>```

Debug Output

```<code>* OPENTBS DEBUG MODE: if the star, (*) on the left before the word OPENTBS, is not the very first character of this page, then your
merged Document will be corrupted when you use the OPENTBS_DOWNLOAD option. If there is a PHP error message, then you have to fix it.
If they are blank spaces, line beaks, or other unexpected characters, then you have to check your code in order to avoid them.

------------------------------
INFORMATION
------------------------------
* Debug command: OPENTBS_DEBUG_XML_CURRENT
* OpenTBS version: 1.9.9
* TinyButStrong version: 3.10.1
* PHP version: 5.6.25YES
* Opened document: riskwaterfalltemplate.pptm
* Activated features for document type: openxml/pptx
* Deleted files in the archive: none
* Added files in the archive: none
* Modified files in the archive:
  - ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx

------------------------------
File merged with OpenTBS: ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx
</code>```

答:
If you are merging the embedded XLSX in order to have a chart modified in the PPTX Presentation, this  will not work.

In both Ms Word ans Ms PowerPoint, embedded XLSX attached to chart does not contains the true data of the chart. It is a simple copy that helps the user for editing the data using Ms Excel. The true data are stored in the XML sub-file related to the chart.

If you want to edit the chart, use command OPENTBS_CHART.

If you actually want to merge the embedded XLSX file, your code is not working because the sub-file ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx is not an XML file, it is a binary file. So TBS cannot merge anything in it directly.

The solution is to:

load the PPTX template using $TBS->LoadTemplate('my_presentation.pptx'),

the load the ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx sub-file as the current sub-file using $TBS->PlugIn(OPENTBS_SELECT_FILE, $SubFile)

save the binary of the XLSX sub-file in a temp file using $handle = tmpfile(); fwrite($handle, $TBS->Source);

open a new TBS instance for this temp file using $TBS2->LoadTemplate($handle);

do your data merging in the XLSX with $TBS2,

finalize the XLSX using $TBS2->Show(OPENTBS_STRING);

save the result in the PPTX using $TBS->Source = $TBS2->Source;

finalize the PPTX using $TBS->Show(...);

Body:
How do I properly fill an embedded worksheet of a PowerPoint template with data using OpenTBS, where the worksheet is embedded inside of a PowerPoint presentation?

I used sub files but the embedded worksheet retains the input tags and no replaced values.

Excel Template that merges properly as a standalone xls file, but not when embedded in a presentation (PPTX).

+------------------------------+---------------------------------+
|                              |    [c.key;block=tbs:cell]       |
+------------------------------+---------------------------------+
|       [r.#;block=tbs:row]    |    [cell.val;block=tbs:cell]    |
+------------------------------+---------------------------------+

PHP Merge Code

$template = 'riskwaterfalltemplate.pptm';
$TBS->LoadTemplate($template.'#ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx',  OPENTBS_ALREADY_UTF8);

// -----------------
// Output the result
// -----------------
$nbr_row = 5;
$nbr_col = 5;
// List of column's names
$columns = array();
for ($col=1; $col <= $nbr_col; $col++)
{
    $columns[$col]['key'] = $col;
}

$data = array();
$record = array();

for ($col=1; $col <= $nbr_col; $col++)
{
    $record[$col]['val'] = 1;
}
for ($row=0; $row < $nbr_row; $row++)
{

    $data[$row] = $record;
}

// Expanding columns
$TBS->MergeBlock('c',$columns);

//Expanding Cells
$TBS->MergeBlock('cell', $record);

// Merging rows
$TBS->MergeBlock('r',$data);

$TBS->Show();

Debug Output

* OPENTBS DEBUG MODE: if the star, (*) on the left before the word OPENTBS, is not the very first character of this page, then your
merged Document will be corrupted when you use the OPENTBS_DOWNLOAD option. If there is a PHP error message, then you have to fix it.
If they are blank spaces, line beaks, or other unexpected characters, then you have to check your code in order to avoid them.

------------------------------
INFORMATION
------------------------------
* Debug command: OPENTBS_DEBUG_XML_CURRENT
* OpenTBS version: 1.9.9
* TinyButStrong version: 3.10.1
* PHP version: 5.6.25YES
* Opened document: riskwaterfalltemplate.pptm
* Activated features for document type: openxml/pptx
* Deleted files in the archive: none
* Added files in the archive: none
* Modified files in the archive:
  - ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx

------------------------------
File merged with OpenTBS: ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx


问:
Sort breaking on subsequent render in React JS components
I have an array closedPeriods that looks like this:

```<code>this.state = {
    selectedPortfolio: "",
    selectedPeriod: "",
    closedPeriods= [
        { portfolio: "foo", period: "june 2017", periodStart: "2017-06-01 00:00:00.000" },
        { portfolio: "foo", period: "may 2017", periodStart: "2017-05-01 00:00:00.000" },
        { portfolio: "bar", period: "may 2017", periodStart: "2017-05-01 00:00:00.000" }
    ]
}
</code>```

I have a dropdown that selects the portfolio, then with the portfolio hand, I am rendering the period.

Filter state array by portfolio

```<code>let periodByPortfolio = [];
if(this.state.selectedPortfolio) {
    periodByPortfolio = this.state.closedPeriods
        .filter(item => item.portfolio === this.state.selectedPortfolio);
}
</code>```

Render periods belonging to portfolio:

```<code><label>Closed Periods</label>
<select id="closedPeriods">
    {periodByPortfolio.sort((previous, current) => current.periodStart - previous.periodStart)
        .map(option => {
            return (<option key={option.period} value={option.period}>{option.period}</option>);
    })}
</select>
</code>```

TLDR:  My sorting function works on the first render.  As soon as I change Portfolio, and change back to the selected portfolio, my sorting becomes scrambled.  Why?

EDIT

Sorting issue was caused by one of the functions double-binding to the component.

```<code>// Bind 1
constructor() {
    this.filterOption = this.filterOption.bind(this);
}

// Bind 2
<select id="portfolio" value={this.props.portfolio} onChange={this.filterOption.bind(this, "portfolio")}>
</code>```

Solution in Answer.

答:
The solution is to remove the second bind.  Also, you don't have to feed the function a target.  You can use the event object to handle the name part.

From

```<code><select id="portfolio" value={this.props.portfolio} onChange={this.filterOption.bind(this, "portfolio")}>
</code>```

To

```<code><select id="portfolio" name="selectedPortfolio" value={this.props.portfolio} onChange={this.filterOption}>
</code>```

Body:
I have an array closedPeriods that looks like this:

this.state = {
    selectedPortfolio: "",
    selectedPeriod: "",
    closedPeriods= [
        { portfolio: "foo", period: "june 2017", periodStart: "2017-06-01 00:00:00.000" },
        { portfolio: "foo", period: "may 2017", periodStart: "2017-05-01 00:00:00.000" },
        { portfolio: "bar", period: "may 2017", periodStart: "2017-05-01 00:00:00.000" }
    ]
}

I have a dropdown that selects the portfolio, then with the portfolio hand, I am rendering the period.

Filter state array by portfolio

let periodByPortfolio = [];
if(this.state.selectedPortfolio) {
    periodByPortfolio = this.state.closedPeriods
        .filter(item => item.portfolio === this.state.selectedPortfolio);
}

Render periods belonging to portfolio:

Closed Periods
<select id="closedPeriods">
    {periodByPortfolio.sort((previous, current) => current.periodStart - previous.periodStart)
        .map(option => {
            return (<option key={option.period} value={option.period}>{option.period}</option>);
    })}
</select>

TLDR:  My sorting function works on the first render.  As soon as I change Portfolio, and change back to the selected portfolio, my sorting becomes scrambled.  Why?

EDIT

Sorting issue was caused by one of the functions double-binding to the component.

// Bind 1
constructor() {
    this.filterOption = this.filterOption.bind(this);
}

// Bind 2
<select id="portfolio" value={this.props.portfolio} onChange={this.filterOption.bind(this, "portfolio")}>

Solution in Answer.

Body:
The solution is to remove the second bind.  Also, you don't have to feed the function a target.  You can use the event object to handle the name part.

From

<select id="portfolio" value={this.props.portfolio} onChange={this.filterOption.bind(this, "portfolio")}>

To

<select id="portfolio" name="selectedPortfolio" value={this.props.portfolio} onChange={this.filterOption}>


问:
Need to move code from hosted svn repo to production server
I was going to do an export but since the repo is externally hosted svn it's a https:// address which is not allowed with export command(torotoise svn). How do i move the code? (The production server is another externally hosted address).</p>

答:
May be I do not understand you correctly, but of course you can use the export-command of tortoiseSVN with https://

Have you tried it? What is your exact error message?

Ohterwise you can use the commandline:

```<code>svn export <YOUR_REPO_URL> <PATH(optional)>
</code>```

Body:
May be I do not understand you correctly, but of course you can use the export-command of tortoiseSVN with https://

Have you tried it? What is your exact error message?

Ohterwise you can use the commandline:

svn export <YOUR_REPO_URL> <PATH(optional)>


问:
Why doesn't my IBDesignable allow me to use setImage: on my custom UIButton?
In layoutSubviews I'm calling setImage() and pass it a UIImage but it never shows up in Interface Builder, but it always shows up when I run the program.

答:
Going to give the swift answer for anyone who comes across this problem like I did. </p>

<p>The problem is that paths to images are different in Interface Builder than they are in your app. </p>

```<code> let bundle = Bundle(for: self.classForCoder)
 image = UIImage(named: "your_image.png", in: bundle, compatibleWith: self.traitCollection)!
 self.setImage(image, for: .normal)
</code>```

Body:
Going to give the swift answer for anyone who comes across this problem like I did.

The problem is that paths to images are different in Interface Builder than they are in your app.

 let bundle = Bundle(for: self.classForCoder)
 image = UIImage(named: "your_image.png", in: bundle, compatibleWith: self.traitCollection)!
 self.setImage(image, for: .normal)


问:
Would it be a good practice or just unnecessary to wrap mixpanel or something similar in wrapper?
Hi I'm about to implement mixpanel in a application. I thought that I might wrap it another function or object  so that I could get more control of it and that it would be easier to edit if there would be any changes in the future.

But I'm not sure if that would me true in the end, would it just make me write unnecessary code instead of just using mixpanel library directly.

What's your thougts?
What would be the best practice?

答:
I just did something similar to this for the same reasons. I can't see any harm. If you're making the same call in multiple places within the app, this is a way of keeping it Dry. I'm building a Django app, and placed it inside a simple util file with a method that looks like</p>

```<code>def track(user_id, event_name, circumstances={}):
    mp.track(user_id, event_name, circumstances)
</code>```

Body:
I just did something similar to this for the same reasons. I can't see any harm. If you're making the same call in multiple places within the app, this is a way of keeping it Dry. I'm building a Django app, and placed it inside a simple util file with a method that looks like

def track(user_id, event_name, circumstances={}):
    mp.track(user_id, event_name, circumstances)


问:
getting blank name (display name) from google plus api
I am working on login system where user is logged to website using google plus api . I am hitting "me" endpoint after token verification .But I am facing a problem in some cases where I don't get the displayName/Name object of the user .
scopes used : plus.profile and plus.login
Endpint hit : "me"

```<code>$service=new Google_Service_Plus($client);
    $userinfo=$service->people->get('me');
</code>```

I want to fetch the username of the user .

答:
If you want to bring information about the profile (Names) and Email.

I'd recommed you add the follow scopes separated by two spaces:

```<code>profile  email
</code>```

profile bring the Names (givenName, familyName, etc.) and email bring the email.

Body:
I am working on login system where user is logged to website using google plus api . I am hitting "me" endpoint after token verification .But I am facing a problem in some cases where I don't get the displayName/Name object of the user .
scopes used : plus.profile and plus.login
Endpint hit : "me"

$service=new Google_Service_Plus($client);
    $userinfo=$service->people->get('me');

I want to fetch the username of the user .

Body:
If you want to bring information about the profile (Names) and Email.

I'd recommed you add the follow scopes separated by two spaces:

profile  email

profile bring the Names (givenName, familyName, etc.) and email bring the email.


问:
How to get URL params and make them hidden values
I'm a noob when it comes to this. I'm simply trying to allow a customer to first fill out a form, save their information for the next page, save their information again for the 3rd page, and when the customer is done filling out the 3rd page to POST it to our CRM.

I've read through many different strategies on getting the URL parameters, but I don't understand how to make them hidden input values.

Ex: http://crackerjackpromo.wjserver800.com/ START QUOTE ...

Thanks and happy 4th!

答:
You could also store those values in local storage. By doing that, even if the user refreshes the page while being in step 2, 3 or any other step, the values will still be there and it'll be a much cleaner approach than saving all those values in the URL or in hidden fields (and it'll still be invisible for the user... as long as he doesn't inspect the dev tools, but it's pretty much the same case with hidden fields).

The best part is that it's really easy to use it. You can store a new values like this:

```<code>localStorage.setItem("name", "John");
</code>```

And you can retrieve the values like this:

```<code>localStorage.getItem("name");
</code>```

Just remember that the local storage information is being stored in the web browser, so if your user wants to resume the process in a different web browser, that information will not be there anymore, and he'll need to start all over agian.

Body:
You could also store those values in local storage. By doing that, even if the user refreshes the page while being in step 2, 3 or any other step, the values will still be there and it'll be a much cleaner approach than saving all those values in the URL or in hidden fields (and it'll still be invisible for the user... as long as he doesn't inspect the dev tools, but it's pretty much the same case with hidden fields).

The best part is that it's really easy to use it. You can store a new values like this:

localStorage.setItem("name", "John");

And you can retrieve the values like this:

localStorage.getItem("name");

Just remember that the local storage information is being stored in the web browser, so if your user wants to resume the process in a different web browser, that information will not be there anymore, and he'll need to start all over agian.


问:
How to read props from a React Native touchable event currentTarget?
I have the following React Native code that runs the press() method when a user taps an image. I want to get the itemIndex prop from the event object. I set a break point in the press method and added some expressions to the Watch. From the Watch I determined that the target (event origination) from the event is the Image which is correct. The itemIndex prop is also available. The element being processed is the currentTarget, the Watch sees it's a "RCTView" and I was expecting a TouchableOpacity, so maybe underneath TouchableOpacity is a View? The currentTarget itemIndex prop is undefined, why? How can I get the props from the currentTarget?

I want to do it this way to avoid creating addition methods for each rendered item.

FYI,
ref={(c) => this._input = c} will not work because it's being run in a loop.
onPress={(e) => this.press(e, i)} creates a new function which I'm trying to avoid.

Watch

target._currentElement.props.itemIndex: 2

target._currentElement.type.displayName: "RCTImageView"

currentTarget._currentElement.props.itemIndex: undefined

currentTarget._currentElement.type.displayName: "RCTView"

```<code>press: function(event){
    var currentTarget = ReactNativeComponentTree.getInstanceFromNode(event.currentTarget);
    var target = ReactNativeComponentTree.getInstanceFromNode(event.target);
    var currentTargetIndex = currentTarget._currentElement.props.itemIndex;
    var targetIndex = target._currentElement.props.itemIndex;
    var url = this.state.data.items[currentTargetIndex].url;
    Linking.openURL(url).catch(err => console.error('An error occurred', err));
},

render: function() {
return (
    <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={styles.galleryView}>
        {
            this.state.data.items.map((data, i) =>
                <TouchableOpacity itemIndex={i} key={i} activeOpacity={0.5} onPress={this.press} >
                    <Image itemIndex={i} key={i} source={{uri:data.previewImageUri}} style={styles.galleryImage} />
                </TouchableOpacity>
            )
        }
    </ScrollView>
);
}
</code>```

答:
Binding the needed information to a callback and assigning one to each child avoids recreating the callback on every render of children.

```<code>class Hello extends React.Component{
  state = { names: this.props.names.map((name, i) => {
      return Object.assign({
        onClick: this._onClick.bind(this, i, this.props),
      }, name)
    }),
  };

  _onClick(ind, _props, e) {
    alert('props:' + JSON.stringify(_props));
  }

  render() {
    const { names } = this.state;
    return (
      <div>
        { names.map((name, i) => (
            <div key={i}>Name: <input value={ name.first } onClick={ name.onClick } /></div>
          ))}
      </div>
  )}
}

ReactDOM.render(
  <Hello names={[{first:'aaa'},{first:'bbb'},{first:'ccc'}]}/>,
  document.getElementById('container')
);
</code>```

JS Fiddle

Body:
I have the following React Native code that runs the press() method when a user taps an image. I want to get the itemIndex prop from the event object. I set a break point in the press method and added some expressions to the Watch. From the Watch I determined that the target (event origination) from the event is the Image which is correct. The itemIndex prop is also available. The element being processed is the currentTarget, the Watch sees it's a "RCTView" and I was expecting a TouchableOpacity, so maybe underneath TouchableOpacity is a View? The currentTarget itemIndex prop is undefined, why? How can I get the props from the currentTarget?

I want to do it this way to avoid creating addition methods for each rendered item.

FYI,
ref={(c) => this._input = c} will not work because it's being run in a loop.
onPress={(e) => this.press(e, i)} creates a new function which I'm trying to avoid.

Watch

target._currentElement.props.itemIndex: 2

target._currentElement.type.displayName: "RCTImageView"

currentTarget._currentElement.props.itemIndex: undefined

currentTarget._currentElement.type.displayName: "RCTView"

press: function(event){
    var currentTarget = ReactNativeComponentTree.getInstanceFromNode(event.currentTarget);
    var target = ReactNativeComponentTree.getInstanceFromNode(event.target);
    var currentTargetIndex = currentTarget._currentElement.props.itemIndex;
    var targetIndex = target._currentElement.props.itemIndex;
    var url = this.state.data.items[currentTargetIndex].url;
    Linking.openURL(url).catch(err => console.error('An error occurred', err));
},

render: function() {
return (
    <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={styles.galleryView}>
        {
            this.state.data.items.map((data, i) =>
                <TouchableOpacity itemIndex={i} key={i} activeOpacity={0.5} onPress={this.press} >
                    <Image itemIndex={i} key={i} source={{uri:data.previewImageUri}} style={styles.galleryImage} />
                </TouchableOpacity>
            )
        }
    </ScrollView>
);
}

Body:
Binding the needed information to a callback and assigning one to each child avoids recreating the callback on every render of children.

class Hello extends React.Component{
  state = { names: this.props.names.map((name, i) => {
      return Object.assign({
        onClick: this._onClick.bind(this, i, this.props),
      }, name)
    }),
  };

  _onClick(ind, _props, e) {
    alert('props:' + JSON.stringify(_props));
  }

  render() {
    const { names } = this.state;
    return (
      <div>
        { names.map((name, i) => (
            <div key={i}>Name: <input value={ name.first } onClick={ name.onClick } /></div>
          ))}
      </div>
  )}
}

ReactDOM.render(
  <Hello names={[{first:'aaa'},{first:'bbb'},{first:'ccc'}]}/>,
  document.getElementById('container')
);

JS Fiddle


问:
SEO Meta Tags From Behind Code - C#
I'm new to adding meta tags from behind code, but if SEO Meta Tags were added from behind code,from a database for example, will they work as they were added in the markup from the beginning?

If so, where should I create them? Page_PreRender, Page_Init,..etc.

Thanks in advance.

答:
Server will render your page to client(browser, search engine crawler)

It is better add it to your page's template, your Razor file or aspx file.

if you do want to add it to you page. you could add it to Page_Load, Page_Render or Page_Pre_Render

E.g.

I will add below to my _Layout.cshtml file or similar code to master page template.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    @if (Page.NeedAdditionMeta)
    {
        <meta name="m1" content="xxx" />
        <meta name="m2" content="yyy" />
        <meta name="m2" content="zzz" />
    }
</code>```

Title: SEO Meta Tags From Behind Code - C#

Body:
Server will render your page to client(browser, search engine crawler)

It is better add it to your page's template, your Razor file or aspx file.

if you do want to add it to you page. you could add it to Page_Load, Page_Render or Page_Pre_Render

E.g.

I will add below to my _Layout.cshtml file or similar code to master page template.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    @if (Page.NeedAdditionMeta)
    {
        <meta name="m1" content="xxx" />
        <meta name="m2" content="yyy" />
        <meta name="m2" content="zzz" />
    }


问:
PrimeNG Calendar - can't disable days or dates
I am using Angular 2 and trying to get a PrimeNG calendar datepicker to allow me to disable specific days (holidays) as well as weekends.

Their documentation says I should be able to do both and gives an example which I've tried to implement.  However, no dates ever get disabled!

In my component template:

```<code><p-calendar [(ngModel)]="requestedShipDate" name="requestedShipDate"
                      [disabledDates]="restrictedShipDates" [disabledDays]="[0,6]"></p-calendar>
</code>```

In my component class (with some sample initialization code that I cannot get to work):

```<code>export class OrdersNewComponent implements OnInit {
  requestedShipDate: Date;
  restrictedShipDates: Array<Date>;

  ngOnInit() {
    let today = new Date();
    let invalidDate = new Date();
    invalidDate.setDate(today.getDate() - 1);
    this.restrictedShipDates = [today,invalidDate];
  }
}
</code>```

Is there not a better angular 2 calendar datepicker out there that allows disabling specific dates?  (not just minDate and maxDate)? This is the only one I've found with this feature and it of course doesn't work for me!

And in case it is a issue with some incompatabile packages or something, here are the dependencies from my project.json:

```<code>"dependencies": {
"@angular/common": "2.4.2",
"@angular/compiler": "2.4.2",
"@angular/core": "2.4.2",
"@angular/flex-layout": "2.0.0-beta.3",
"@angular/forms": "2.4.2",
"@angular/http": "2.4.2",
"@angular/material": "2.0.0-beta.2",
"@angular/platform-browser": "2.4.2",
"@angular/platform-browser-dynamic": "2.4.2",
"@angular/router": "3.4.2",
"angular2-select": "1.0.0-alpha.12",
"core-js": "2.4.1",
"hammerjs": "2.0.8",
"jsrsasign": "6.1.1",
"jwt-decode": "2.1.0",
"lodash": "4.16.4",
"material-design-lite": "1.2.1",
"moment": "2.15.1",
"ng2-pagination": "0.5.1",
"ng2-translate": "4.0.0",
"normalize.css": "4.2.0",
"primeng": "1.1.4",
"rxjs": "5.0.3",
"ts-helpers": "1.1.1",
"xmljson": "0.2.0",
"zone.js": "0.7.4"
},
  "devDependencies": {
    "@angular/compiler-cli": "2.4.2",
    "@types/jasmine": "2.5.38",
    "@types/lodash": "4.14.37",
    "@types/node": "6.0.42",
    "angular-cli": "1.0.0-beta.25.5",
    "angular2-perfect-scrollbar": "^2.0.6",
    "codelyzer": "^2.0.0-beta.4",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-remap-istanbul": "0.2.1",
    "protractor": "4.0.13",
    "ts-node": "1.2.1",
    "tslint": "4.3.0",
    "typescript": "2.0.10"
  }
</code>```

答:
You could look into Angular Material instead of PrimeNG.

You could use it's date validation to filter through the dates you don't want to allow. A function return value of true would indicate a valid date.

This would definitely be a lot more work than using PrimeNG, but if their datepicker doesn't do what you want, you gotta compromise.

So for this, you could have something like

```<code>filterUnwantedDates = (date: Date) => {
  return !listOfDates.contains(date) // or something along those lines.
  // look into lodash / underscore to help with this.
}
</code>```

Body:
I am using Angular 2 and trying to get a PrimeNG calendar datepicker to allow me to disable specific days (holidays) as well as weekends.

Their documentation says I should be able to do both and gives an example which I've tried to implement.  However, no dates ever get disabled!

In my component template:

In my component class (with some sample initialization code that I cannot get to work):

export class OrdersNewComponent implements OnInit {
  requestedShipDate: Date;
  restrictedShipDates: Array<Date>;

  ngOnInit() {
    let today = new Date();
    let invalidDate = new Date();
    invalidDate.setDate(today.getDate() - 1);
    this.restrictedShipDates = [today,invalidDate];
  }
}

Is there not a better angular 2 calendar datepicker out there that allows disabling specific dates?  (not just minDate and maxDate)? This is the only one I've found with this feature and it of course doesn't work for me!

And in case it is a issue with some incompatabile packages or something, here are the dependencies from my project.json:

"dependencies": {
"@angular/common": "2.4.2",
"@angular/compiler": "2.4.2",
"@angular/core": "2.4.2",
"@angular/flex-layout": "2.0.0-beta.3",
"@angular/forms": "2.4.2",
"@angular/http": "2.4.2",
"@angular/material": "2.0.0-beta.2",
"@angular/platform-browser": "2.4.2",
"@angular/platform-browser-dynamic": "2.4.2",
"@angular/router": "3.4.2",
"angular2-select": "1.0.0-alpha.12",
"core-js": "2.4.1",
"hammerjs": "2.0.8",
"jsrsasign": "6.1.1",
"jwt-decode": "2.1.0",
"lodash": "4.16.4",
"material-design-lite": "1.2.1",
"moment": "2.15.1",
"ng2-pagination": "0.5.1",
"ng2-translate": "4.0.0",
"normalize.css": "4.2.0",
"primeng": "1.1.4",
"rxjs": "5.0.3",
"ts-helpers": "1.1.1",
"xmljson": "0.2.0",
"zone.js": "0.7.4"
},
  "devDependencies": {
    "@angular/compiler-cli": "2.4.2",
    "@types/jasmine": "2.5.38",
    "@types/lodash": "4.14.37",
    "@types/node": "6.0.42",
    "angular-cli": "1.0.0-beta.25.5",
    "angular2-perfect-scrollbar": "^2.0.6",
    "codelyzer": "^2.0.0-beta.4",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-remap-istanbul": "0.2.1",
    "protractor": "4.0.13",
    "ts-node": "1.2.1",
    "tslint": "4.3.0",
    "typescript": "2.0.10"
  }

Body:
You could look into Angular Material instead of PrimeNG.

You could use it's date validation to filter through the dates you don't want to allow. A function return value of true would indicate a valid date.

This would definitely be a lot more work than using PrimeNG, but if their datepicker doesn't do what you want, you gotta compromise.

So for this, you could have something like

filterUnwantedDates = (date: Date) => {
  return !listOfDates.contains(date) // or something along those lines.
  // look into lodash / underscore to help with this.
}


问:
HighCharts inside of a javascript function
I'm trying to draw a 3d box after a user has selected some data from the server.

When I put the highcharts inside of a js function, it throws some errors.

My code is:

```<code><a href="#" onclick="chart3d();">Chart It</a><br/>

<div id="container" style="height: 400px"></div>
 <script>
 var chart;

function chart3d() {

    // Give the points a 3D feel by adding a radial gradient
    Highcharts.getOptions().colors = $.map(Highcharts.getOptions().colors, function (color) {
        return {
            radialGradient: {
                cx: 0.4,
                cy: 0.3,
                r: 0.5
            },
            stops: [
                [0, color],
                [1, Highcharts.Color(color).brighten(-0.2).get('rgb')]
            ]
        };
    });

    // Set up the chart
    chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            margin: 100,
            type: 'scatter',
            options3d: {
                enabled: true,
                alpha: 10,
                beta: 30,
                depth: 250,
                viewDistance: 5,
                fitToPlot: false,
                frame: {
                    bottom: {
                        size: 1,
                        color: 'rgba(0,0,0,0.02)'
                    },
                    back: {
                        size: 1,
                        color: 'rgba(0,0,0,0.04)'
                    },
                    side: {
                        size: 1,
                        color: 'rgba(0,0,0,0.06)'
                    }
                }
            }
        },
        title: {
            text: 'Draggable box'
        },
        subtitle: {
            text: 'Click and drag the plot area to rotate in space'
        },
        plotOptions: {
            scatter: {
                width: 10,
                height: 10,
                depth: 10
            }
        },
        yAxis: {
            min: 0,
            max: 10,
            title: null
        },
        xAxis: {
            min: 0,
            max: 10,
            gridLineWidth: 1
        },
        zAxis: {
            min: 0,
            max: 10,
            showFirstLabel: false
        },
        legend: {
            enabled: false
        },
        series: [{
            planeProjection: {
                enabled: false,
            },
            lineProjection: {
                enabled: 'hover',
                colorByPoint: true
            },
            name: 'Reading',
            colorByPoint: true,
            data: darray
        }]
    });

    // Add mouse events for rotation
    $(chart.container).on('mousedown.hc touchstart.hc', function (eStart) {
        eStart = chart.pointer.normalize(eStart);

        var posX = eStart.pageX,
            posY = eStart.pageY,
            alpha = chart.options.chart.options3d.alpha,
            beta = chart.options.chart.options3d.beta,
            newAlpha,
            newBeta,
            sensitivity = 5; // lower is more sensitive

        $(document).on({
            'mousemove.hc touchdrag.hc': function (e) {
                // Run beta
                newBeta = beta + (posX - e.pageX) / sensitivity;
                chart.options.chart.options3d.beta = newBeta;

                // Run alpha
                newAlpha = alpha + (e.pageY - posY) / sensitivity;
                chart.options.chart.options3d.alpha = newAlpha;

                chart.redraw(false);
            },
            'mouseup touchend': function () {
                $(document).off('.hc');
            }
        });
    });

}

</script>
</code>```

This loads fine if I do not put it inside of the chart3d function. Is there a way to get this working. The error message I get is:

```<code>highcharts.js:10 Uncaught Error: Highcharts error #13: www.highcharts.com/errors/13
    at Object.a.error (highcharts.js:10)
    at a.Chart.getContainer (highcharts.js:256)
    at a.Chart.firstRender (highcharts.js:271)
    at a.Chart.init (highcharts.js:247)
    at a.Chart.getArgs (highcharts.js:246)
    at new a.Chart (highcharts.js:246)
    at chart3d (graphingCustom.js:26)
    at HTMLAnchorElement.onclick (VM599 :643)
</code>```

答:
As they say:

Highcharts Error #13

Rendering div not found

This error occurs if the chart.renderTo option is misconfigured so that
Highcharts is unable to find the HTML element to render the chart in.

You don't have a div with the id=container at the time you are calling the method.

Body:
I'm trying to draw a 3d box after a user has selected some data from the server.

When I put the highcharts inside of a js function, it throws some errors.

My code is:

Chart It

This loads fine if I do not put it inside of the chart3d function. Is there a way to get this working. The error message I get is:

highcharts.js:10 Uncaught Error: Highcharts error #13: www.highcharts.com/errors/13
    at Object.a.error (highcharts.js:10)
    at a.Chart.getContainer (highcharts.js:256)
    at a.Chart.firstRender (highcharts.js:271)
    at a.Chart.init (highcharts.js:247)
    at a.Chart.getArgs (highcharts.js:246)
    at new a.Chart (highcharts.js:246)
    at chart3d (graphingCustom.js:26)
    at HTMLAnchorElement.onclick (VM599 :643)


问:
Regex Pattern Matching for similar URL
I need to send different Response for different urls. But the Regex that I am using is not working.

The two Regex in question is

```<code>"/v1/users/[^/]+/permissions/domain/HTTP/"
</code>```

(Eg: http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/permissions/domain/HTTP)

and

```<code>"/v1/users/[^/]+/"
</code>```

(Eg: http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363)

I am not able to figure out how to stop the regex matching after "[^/]+/". Both the pattern return the same result. It is as if due to regex both of them are same URL's. The pattern matching happens in mountebank mocking server using a matching predicate. Any help would be appreciated. Thanks.

答:
The regular expression "/v1/users/[^/]+/" matches both urls. You are asking it to match '/v1/users/` plus anything except '/' followed by a slash. This happens in both the longer URL and the short one, which is why it matches.

A couple options:

You can match the longer url and not the shorter one with:

```<code>"/v1/users/[^/]+/.+"
</code>```

This matches http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/permissions/domain/HTTP, but not http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/

You could also match just the short one by anchoring the end:

```<code>"/v1/users/[^/]+/$"
</code>```

This matches the short URL but not the long one.

Title: Regex Pattern Matching for similar URL

Body:
I need to send different Response for different urls. But the Regex that I am using is not working.

The two Regex in question is

"/v1/users/[^/]+/permissions/domain/HTTP/"

(Eg: http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/permissions/domain/HTTP)

and

"/v1/users/[^/]+/"

(Eg: http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363)

I am not able to figure out how to stop the regex matching after "[^/]+/". Both the pattern return the same result. It is as if due to regex both of them are same URL's. The pattern matching happens in mountebank mocking server using a matching predicate. Any help would be appreciated. Thanks.

Body:
The regular expression "/v1/users/[^/]+/" matches both urls. You are asking it to match '/v1/users/` plus anything except '/' followed by a slash. This happens in both the longer URL and the short one, which is why it matches.

A couple options:

You can match the longer url and not the shorter one with:

"/v1/users/[^/]+/.+"

This matches http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/permissions/domain/HTTP, but not http://localhost:4544/v1/users/10feec20-afd9-46a0-a3fc-9b2f18c1d363/

You could also match just the short one by anchoring the end:

"/v1/users/[^/]+/$"

This matches the short URL but not the long one.