答:
You could make use of a fixed height for each of the images, and also apply this height to the broken images by targeting the attribute selector img[src='']:

```<code>img[src=''] {
  height: 217px; /* The height of the actual images in the snippet */
}
</code>```

.myForm {
  position: relative;
  font-size: 0;
  line-height: 0;
}

.imgWrapper {
  position: relative;
  display: inline-block;
  width: 33.3333333%;
  box-sizing: border-box;
  background: tomato;
}

img {
  width: 100%;
  height: 100%;
}

img[src=''] {
  height: 217px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="myForm">
  <div class="imgWrapper">
    <img src="https://i.pinimg.com/736x/1d/58/f1/1d58f1bb767a1bc2231226c4fc9ae85a--film-photography-vintage-photography.jpg">
  </div>
  <div class="imgWrapper">
    <img src="">
  </div>
  <div class="imgWrapper">
    <img src="https://i.pinimg.com/736x/1d/58/f1/1d58f1bb767a1bc2231226c4fc9ae85a--film-photography-vintage-photography.jpg">
  </div>
</form></code>```

However, in my opinion, it would be much better to simply hide broken images entirely, which can be done with:

```<code>img[src=''] {
  display: none;
}
</code>```

This can be seen in the following:

.myForm {
  position: relative;
  font-size: 0;
  line-height: 0;
}

.imgWrapper {
  position: relative;
  display: inline-block;
  width: 33.3333333%;
  box-sizing: border-box;
  background: tomato;
}

img {
  width: 100%;
  height: 100%;
}

img[src=''] {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="myForm">
  <div class="imgWrapper">
    <img src="https://i.pinimg.com/736x/1d/58/f1/1d58f1bb767a1bc2231226c4fc9ae85a--film-photography-vintage-photography.jpg">
  </div>
  <div class="imgWrapper">
    <img src="">
  </div>
  <div class="imgWrapper">
    <img src="https://i.pinimg.com/736x/1d/58/f1/1d58f1bb767a1bc2231226c4fc9ae85a--film-photography-vintage-photography.jpg">
  </div>
</form></code>```

Hope this helps! :)

Title: Force image dimensions when empty

Body:
You could make use of a fixed height for each of the images, and also apply this height to the broken images by targeting the attribute selector img[src='']:

img[src=''] {
  height: 217px; /* The height of the actual images in the snippet */
}

.myForm {
  position: relative;
  font-size: 0;
  line-height: 0;
}

.imgWrapper {
  position: relative;
  display: inline-block;
  width: 33.3333333%;
  box-sizing: border-box;
  background: tomato;
}

img {
  width: 100%;
  height: 100%;
}

img[src=''] {
  height: 217px;
}

<form class="myForm">
  <div class="imgWrapper">
    <img src="https://i.pinimg.com/736x/1d/58/f1/1d58f1bb767a1bc2231226c4fc9ae85a--film-photography-vintage-photography.jpg">
  </div>
  <div class="imgWrapper">
    <img src="">
  </div>
  <div class="imgWrapper">
    <img src="https://i.pinimg.com/736x/1d/58/f1/1d58f1bb767a1bc2231226c4fc9ae85a--film-photography-vintage-photography.jpg">
  </div>
</form>

However, in my opinion, it would be much better to simply hide broken images entirely, which can be done with:

img[src=''] {
  display: none;
}

This can be seen in the following:

.myForm {
  position: relative;
  font-size: 0;
  line-height: 0;
}

.imgWrapper {
  position: relative;
  display: inline-block;
  width: 33.3333333%;
  box-sizing: border-box;
  background: tomato;
}

img {
  width: 100%;
  height: 100%;
}

img[src=''] {
  display: none;
}

<form class="myForm">
  <div class="imgWrapper">
    <img src="https://i.pinimg.com/736x/1d/58/f1/1d58f1bb767a1bc2231226c4fc9ae85a--film-photography-vintage-photography.jpg">
  </div>
  <div class="imgWrapper">
    <img src="">
  </div>
  <div class="imgWrapper">
    <img src="https://i.pinimg.com/736x/1d/58/f1/1d58f1bb767a1bc2231226c4fc9ae85a--film-photography-vintage-photography.jpg">
  </div>
</form>

Hope this helps! :)


来源: stackexchange

问:
python distinguish between '300' and '300.0' for a dataframe column
Recently I have been developing some code to read a csv file and store key data columns in a dataframe. Afterwards I plan to have some mathematical functions performed on certain columns in the dataframe.

I've been fairly successful in storing the correct columns in the dataframe. I have been able to have it do whatever maths is necessary such as summations, additions of dataframe columns, averaging etc.

My problem lies in accessing specific columns once they are stored in the dataframe. I was working with a test file to get everything working and managed this no problem. The problems arise when I open a different csv file, it will store the data in the dataframe, but the accessing the column I want no longer works and it stops at the calculation part.

From what I can tell the problem lies with how it reads the column name. The column names are all numbers. For example, df['300'], df['301'] etc. When accessing the column df['300'] works fine in the testfile, while the next file requires df['300.0']. If I switch to a different file it may require df['300'] again. All the data was obtained in the same way so I am not certain why some are read as 300 and the others 300.0.

Short of constantly changing the column labels each time I open a different file, is there anyway to have it automatically distinguish between '300' and '300.0' when opening the file, or force '300.0' = '300'?

Thanks

答:
Some solutions:

Go through all the files, change the columns names, then save the result in a new folder. Now when you read a file, you can go to the new folder and read it from there.

Wrap the normal file read function in another function that automatically changes the column names, and call that new function when you read a file.

Wrap column selection in a function. Use a try/except block to have the function try to access the given column, and if it fails, use the other form.

ContentLicense: CC BY-SA 3.0


问:
Newtonsoft JSON Deserialize Interface
I have a problem with deserializing the following sample JSON snippet:

```<code>{
   "list":{
       "A":{"ClassA":{"PropertyA":"test"}},
       "B":{"ClassB":{"PropertyB":"test"}}
    }
}
</code>```

With my ClassA:

```<code>public class ClassA:IInterface{
   public String PropertyA{get; set;}
}
public class ClassB:IInterface{
   public String PropertyB{get; set;}
}
</code>```

I want the JsonConverter to create a ClassA or ClassB with the PropertyA or PropertyB from the JSON. The ClassA or ClassB is embedded in a Dictionary.

I can also put the full class name with namespace there but I wasn't really able to make it work.

Thanks in advance for any help

答:
You need a wrapper class:

```<code>public class ListClass
{
    public WrapperList List { get; set; }
}

public class WrapperList
{
    public WrapperA A { get; set; }
    public WrapperB B { get; set; }
}

public class WrapperA
{
    public ClassA ClassA { get; set; }
}

public class WrapperB
{
    public ClassB ClassB { get; set; }
}

public class ClassA : IInterface
{
    public String PropertyA { get; set; }
}

public class ClassB : IInterface
{
    public String PropertyB { get; set; }
}
</code>```

Then:

```<code>var list = JsonConvert.DeserializeObject<ListClass>(json);
</code>```

Title: Newtonsoft JSON Deserialize Interface

Body:
I have a problem with deserializing the following sample JSON snippet:

{
   "list":{
       "A":{"ClassA":{"PropertyA":"test"}},
       "B":{"ClassB":{"PropertyB":"test"}}
    }
}

With my ClassA:

public class ClassA:IInterface{
   public String PropertyA{get; set;}
}
public class ClassB:IInterface{
   public String PropertyB{get; set;}
}

I want the JsonConverter to create a ClassA or ClassB with the PropertyA or PropertyB from the JSON. The ClassA or ClassB is embedded in a Dictionary.

I can also put the full class name with namespace there but I wasn't really able to make it work.

Thanks in advance for any help

Body:
You need a wrapper class:

public class ListClass
{
    public WrapperList List { get; set; }
}

public class WrapperList
{
    public WrapperA A { get; set; }
    public WrapperB B { get; set; }
}

public class WrapperA
{
    public ClassA ClassA { get; set; }
}

public class WrapperB
{
    public ClassB ClassB { get; set; }
}

public class ClassA : IInterface
{
    public String PropertyA { get; set; }
}

public class ClassB : IInterface
{
    public String PropertyB { get; set; }
}

Then:

var list = JsonConvert.DeserializeObject<ListClass>(json);


问:
Tomcat server shutdown.sh: no permission
I am trying to run the shutdown.sh file to stop tomcat server but I always get this error.

I have tried all kind of chmods command but nothing works:

I really don't undertand where doest that come from.

答:
Try using sudo shutdown.sh

If you are unable to stop it you can always kill the process, follow this link if you need help.


问:
Getting state of a text input when pressing enter key in React
I'm taking my first steps with React and I struggle with setting and getting states of an input element.

The application shall render a simple input element without a submit button.

When pressing Enter the current value of the text field shall be written to the console.

So far I've added two event handlers for onKeyUp (checking if Enter was pressed) and another for onChange to output the text field's value.

This is my current code:

```<code>import React, { Component } from "react";
import ReactDOM from "react-dom";

class Terminal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ""};
    this.handleChange = this.handleChange.bind(this);
  }

  handleKey(e) {
    if (e.key === "Enter") {
      console.log("Enter key pressed");
      console.log(this.state.value);
    }
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  render() {
    return (
      <div>
        <span>My Prompt: > </span>
        <input type="text" value={this.state.value} onKeyUp={this.handleKey} onChange={this.handleChange} />
      </div>
    );
  }
}

ReactDOM.render(
  <Terminal />,
  document.getElementById("root")
);
</code>```

Pressing Enter is recognized but logging to the console gives me:

```<code>Uncaught TypeError: Cannot read property 'state' of undefined
    at handleKey (index.js:24)
</code>```

What am I missing here?

答:
You have to bind the function to the context of the class.

```<code><input type="text" value={this.state.value} onKeyUp={this.handleKey.bind(this)} onChange={this.handleChange.bind(this)} />
</code>```

Body:
I'm taking my first steps with React and I struggle with setting and getting states of an input element.

The application shall render a simple input element without a submit button.

When pressing Enter the current value of the text field shall be written to the console.

So far I've added two event handlers for onKeyUp (checking if Enter was pressed) and another for onChange to output the text field's value.

This is my current code:

import React, { Component } from "react";
import ReactDOM from "react-dom";

class Terminal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ""};
    this.handleChange = this.handleChange.bind(this);
  }

  handleKey(e) {
    if (e.key === "Enter") {
      console.log("Enter key pressed");
      console.log(this.state.value);
    }
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  render() {
    return (

        My Prompt: >
        <input type="text" value={this.state.value} onKeyUp={this.handleKey} onChange={this.handleChange} />

    );
  }
}

ReactDOM.render(
  <Terminal />,
  document.getElementById("root")
);

Pressing Enter is recognized but logging to the console gives me:

Uncaught TypeError: Cannot read property 'state' of undefined
    at handleKey (index.js:24)

What am I missing here?

Body:
You have to bind the function to the context of the class.

<input type="text" value={this.state.value} onKeyUp={this.handleKey.bind(this)} onChange={this.handleChange.bind(this)} />


问:
oozie-4.2.0 fails during compilation
While building oozie 4.2.0 on my macbookpron , I experienced this issue below.
I am using

Apache Maven 3.2.1 (ea8b2b07643dbb1b84b6d16e1f08391b666bc1e9;
2014-02-14T18:37:52+01:00)

Java version: 1.8.0_25, vendor: Oracle
Corporation

Apache oozie-4.2.0

```<code>$ bin/mkdistro.sh -DskipTests

...
Downloaded: https://repository.cloudera.com/artifactory/ext-release-local/org/apache/maven/doxia/doxia-core/1.0-alpha-9.2y/doxia-core-1.0-alpha-9.2y.jar (66 KB at 34.8 KB/sec)
[INFO] Unable to load parent project from a relative path: 1 problem was encountered while building the effective model
[FATAL] Non-readable POM /Users/abd_adebiyi/sw/apache/oozie/oozie-4.2.0/docs/../../pom.xml: /Users/abd_adebiyi/sw/apache/oozie/oozie-4.2.0/docs/../../pom.xml (No such file or directory) @
 for project  at /Users/abd_adebiyi/sw/apache/oozie/oozie-4.2.0/docs/../../pom.xml for project  at /Users/abd_adebiyi/sw/apache/oozie/oozie-4.2.0/docs/../../pom.xml
[INFO] Parent project loaded from repository.
Downloading: http://repo1.maven.org/maven2/org/apache/apache/16/apache-16-site_en.xml
Downloading: http://repository.codehaus.org/org/apache/apache/16/apache-16-site_en.xml
Downloading: https://repository.apache.org/content/groups/snapshots/org/apache/apache/16/apache-16-site_en.xml
Downloading: http://www.datanucleus.org/downloads/maven2/org/apache/apache/16/apache-16-site_en.xml
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Apache Oozie Client ............................... SUCCESS [ 33.457 s]
[INFO] Apache Oozie Share Lib Oozie ...................... SUCCESS [ 28.037 s]
[INFO] Apache Oozie Share Lib HCatalog ................... SUCCESS [ 10.853 s]
[INFO] Apache Oozie Share Lib Distcp ..................... SUCCESS [  1.538 s]
[INFO] Apache Oozie Core ................................. SUCCESS [04:58 min]
[INFO] Apache Oozie Share Lib Streaming .................. SUCCESS [  8.507 s]
[INFO] Apache Oozie Share Lib Pig ........................ SUCCESS [  7.247 s]
[INFO] Apache Oozie Share Lib Hive ....................... SUCCESS [  8.976 s]
[INFO] Apache Oozie Share Lib Hive 2 ..................... SUCCESS [  8.926 s]
[INFO] Apache Oozie Share Lib Sqoop ...................... SUCCESS [  2.571 s]
[INFO] Apache Oozie Examples ............................. SUCCESS [ 13.693 s]
[INFO] Apache Oozie Share Lib Spark ...................... SUCCESS [ 20.181 s]
[INFO] Apache Oozie Share Lib ............................ SUCCESS [ 30.188 s]
[INFO] Apache Oozie Docs ................................. FAILURE [  9.458 s]
[INFO] Apache Oozie WebApp ............................... SKIPPED
[INFO] Apache Oozie Tools ................................ SKIPPED
[INFO] Apache Oozie MiniOozie ............................ SKIPPED
[INFO] Apache Oozie Distro ............................... SKIPPED
[INFO] Apache Oozie ZooKeeper Security Tests ............. SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 08:04 min
[INFO] Finished at: 2015-12-04T23:52:57+01:00
[INFO] Final Memory: 339M/1028M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-site-plugin:2.0-beta-6:site (default) on project oozie-docs: The site descriptor cannot be resolved from the repository: Could not transfer artifact org.apache:apache:xml:site_en:16 from/to Codehaus repository (http://repository.codehaus.org/): repository.codehaus.org: unknown error
[ERROR] org.apache:apache:xml:16
[ERROR]
[ERROR] from the specified remote repositories:
[ERROR] central (http://repo1.maven.org/maven2, releases=true, snapshots=false),
[ERROR] Codehaus repository (http://repository.codehaus.org/, releases=true, snapshots=false),
[ERROR] apache.snapshots.repo (https://repository.apache.org/content/groups/snapshots, releases=true, snapshots=true),
[ERROR] datanucleus (http://www.datanucleus.org/downloads/maven2, releases=true, snapshots=false),
[ERROR] apache.snapshots (http://repository.apache.org/snapshots, releases=false, snapshots=true): Unknown host repository.codehaus.org: unknown error
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :oozie-docs

ERROR, Oozie distro creation failed
</code>```

I will appreciate if anyone can advise what I should do. I need this bugger out of the way.

I opened JIRA 2415 https://issues.apache.org/jira/browse/OOZIE-2415.The of release of ooze-4.2 on 2015-Jun-03  was a few days shy of codehause (http://www.codehaus.org/history/) end of days (2015-May-31)

答:
In your ~/.m2/settings.xml, add a mirror entry for codehaus. This avoids editing the parent POM.

Example:

```<code>...
  <mirror>
    <id>codehaus</id>
    <mirrorOf>Codehaus repository</mirrorOf>
    <name>Codehaus repository</name>
    <url>http://central.maven.org/maven2/</url> <!-- Point to Maven central instead -->
  </mirror>
...
</code>```

Title: oozie-4.2.0 fails during compilation

Body:
While building oozie 4.2.0 on my macbookpron , I experienced this issue below.
I am using

Apache Maven 3.2.1 (ea8b2b07643dbb1b84b6d16e1f08391b666bc1e9;
2014-02-14T18:37:52+01:00)

Java version: 1.8.0_25, vendor: Oracle
Corporation

Apache oozie-4.2.0

$ bin/mkdistro.sh -DskipTests

...
Downloaded: https://repository.cloudera.com/artifactory/ext-release-local/org/apache/maven/doxia/doxia-core/1.0-alpha-9.2y/doxia-core-1.0-alpha-9.2y.jar (66 KB at 34.8 KB/sec)
[INFO] Unable to load parent project from a relative path: 1 problem was encountered while building the effective model
[FATAL] Non-readable POM /Users/abd_adebiyi/sw/apache/oozie/oozie-4.2.0/docs/../../pom.xml: /Users/abd_adebiyi/sw/apache/oozie/oozie-4.2.0/docs/../../pom.xml (No such file or directory) @
 for project  at /Users/abd_adebiyi/sw/apache/oozie/oozie-4.2.0/docs/../../pom.xml for project  at /Users/abd_adebiyi/sw/apache/oozie/oozie-4.2.0/docs/../../pom.xml
[INFO] Parent project loaded from repository.
Downloading: http://repo1.maven.org/maven2/org/apache/apache/16/apache-16-site_en.xml
Downloading: http://repository.codehaus.org/org/apache/apache/16/apache-16-site_en.xml
Downloading: https://repository.apache.org/content/groups/snapshots/org/apache/apache/16/apache-16-site_en.xml
Downloading: http://www.datanucleus.org/downloads/maven2/org/apache/apache/16/apache-16-site_en.xml
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Apache Oozie Client ............................... SUCCESS [ 33.457 s]
[INFO] Apache Oozie Share Lib Oozie ...................... SUCCESS [ 28.037 s]
[INFO] Apache Oozie Share Lib HCatalog ................... SUCCESS [ 10.853 s]
[INFO] Apache Oozie Share Lib Distcp ..................... SUCCESS [  1.538 s]
[INFO] Apache Oozie Core ................................. SUCCESS [04:58 min]
[INFO] Apache Oozie Share Lib Streaming .................. SUCCESS [  8.507 s]
[INFO] Apache Oozie Share Lib Pig ........................ SUCCESS [  7.247 s]
[INFO] Apache Oozie Share Lib Hive ....................... SUCCESS [  8.976 s]
[INFO] Apache Oozie Share Lib Hive 2 ..................... SUCCESS [  8.926 s]
[INFO] Apache Oozie Share Lib Sqoop ...................... SUCCESS [  2.571 s]
[INFO] Apache Oozie Examples ............................. SUCCESS [ 13.693 s]
[INFO] Apache Oozie Share Lib Spark ...................... SUCCESS [ 20.181 s]
[INFO] Apache Oozie Share Lib ............................ SUCCESS [ 30.188 s]
[INFO] Apache Oozie Docs ................................. FAILURE [  9.458 s]
[INFO] Apache Oozie WebApp ............................... SKIPPED
[INFO] Apache Oozie Tools ................................ SKIPPED
[INFO] Apache Oozie MiniOozie ............................ SKIPPED
[INFO] Apache Oozie Distro ............................... SKIPPED
[INFO] Apache Oozie ZooKeeper Security Tests ............. SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 08:04 min
[INFO] Finished at: 2015-12-04T23:52:57+01:00
[INFO] Final Memory: 339M/1028M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-site-plugin:2.0-beta-6:site (default) on project oozie-docs: The site descriptor cannot be resolved from the repository: Could not transfer artifact org.apache:apache:xml:site_en:16 from/to Codehaus repository (http://repository.codehaus.org/): repository.codehaus.org: unknown error
[ERROR] org.apache:apache:xml:16
[ERROR]
[ERROR] from the specified remote repositories:
[ERROR] central (http://repo1.maven.org/maven2, releases=true, snapshots=false),
[ERROR] Codehaus repository (http://repository.codehaus.org/, releases=true, snapshots=false),
[ERROR] apache.snapshots.repo (https://repository.apache.org/content/groups/snapshots, releases=true, snapshots=true),
[ERROR] datanucleus (http://www.datanucleus.org/downloads/maven2, releases=true, snapshots=false),
[ERROR] apache.snapshots (http://repository.apache.org/snapshots, releases=false, snapshots=true): Unknown host repository.codehaus.org: unknown error
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :oozie-docs

ERROR, Oozie distro creation failed

I will appreciate if anyone can advise what I should do. I need this bugger out of the way.

I opened JIRA 2415 https://issues.apache.org/jira/browse/OOZIE-2415.The of release of ooze-4.2 on 2015-Jun-03  was a few days shy of codehause (http://www.codehaus.org/history/) end of days (2015-May-31)

Body:
In your ~/.m2/settings.xml, add a mirror entry for codehaus. This avoids editing the parent POM.

Example:

...
  <mirror>
    <id>codehaus</id>
    <mirrorOf>Codehaus repository</mirrorOf>
    <name>Codehaus repository</name>
    <url>http://central.maven.org/maven2/</url> <!-- Point to Maven central instead -->
  </mirror>
...


问:
How to implement GRU that takes fixed size input tensor and outputs a variable size tensor - in Tensorflow? (Implementation of Kumar et al., 2015)

Detailed explanation

I'm attempting to implement the dynamic memory network described in Xiong et al. (2016) and Kumar et al. (2015) for QA tasks. I've made it work for the bAbi dataset with one-word answers, and get somewhat similar results as the ones described in the papers (and I believe some hyperparameter tuning can close the rest of the gap). This was done using a linear output layer as the answer module. I want to extend the model to produce multi-word answers.

For this my intention has been to use the GRU described in equation 9 and 10 in Kumar et al. (2015), to decode the output from the episodic memory (m^T in Kumar et al. (2015) and Xiong et al (2016)).

This GRU needs to take a 3D tensor of size [batch_size x 1 x embedding_size] as input, i.e. the reshaped output from the episodic memory, m^T, and output a 3D tensor of size [batch_size x answer_length x vocab_size].

Thus far I've tried to implement my own GRU to be called by Tensorflow's dynamic_rnn method, however I've been unable to do this. In the current state of affairs the call method hereof looks like this:

def call(self, inputs, state, scope=None):
    with vs.variable_scope(scope or "decoder_gru_cell"):
        with vs.variable_scope("gates"):
            z = math_ops.sigmoid(_linear([inputs, state], self._num_units, True))
            r = math_ops.sigmoid(_linear([inputs, state], self._num_units, True))
        with vs.variable_scope("candidate"):
            r = r*_linear(state, self._num_units, False)
        with vs.variable_scope("input"):
            x = _linear(inputs, self._num_units, True)
        h_hat = math_ops.tanh(r + x)
        new_h = z * h_hat + (1 - z) * state
        output = tf.nn.softmax(_linear(new_h))
    return output, new_h
```

I can't seem to make it use the output from time step t-1 concatenated with the question vector as input for the cell at time step t, as described in the papers.

Futhermore, I'm uncertain how I can implement it such that it takes a fixed size input tensor and outputs a variable size tensor (since not all answers necessarily are of the same length). Based on the following sentence from Xiong et al. (2016), this ought to be possible:

For tasks requiring a sequence output,
  an RNN may be used to decode a = [q; m^T], the concatenation of vectors q and m^T, to an ordered set of tokens.

tl; dr

How do I implement a GRU that takes a fixed size input tensor and outputs a variable size tensor in Tensorflow?

Any help would be greatly appreciated, thanks!

答: To access the output up to time step t-1 in time step t you must use TensorArrays to store the previous activations.</p>

Body:
Detailed explanation

I'm attempting to implement the dynamic memory network described in Xiong et al. (2016) and Kumar et al. (2015) for QA tasks. I've made it work for the bAbi dataset with one-word answers, and get somewhat similar results as the ones described in the papers (and I believe some hyperparameter tuning can close the rest of the gap). This was done using a linear output layer as the answer module. I want to extend the model to produce multi-word answers.

For this my intention has been to use the GRU described in equation 9 and 10 in Kumar et al. (2015), to decode the output from the episodic memory (m^T in Kumar et al. (2015) and Xiong et al (2016)).

This GRU needs to take a 3D tensor of size [batch_size x 1 x embedding_size] as input, i.e. the reshaped output from the episodic memory, m^T, and output a 3D tensor of size [batch_size x answer_length x vocab_size].

Thus far I've tried to implement my own GRU to be called by Tensorflow's dynamic_rnn method, however I've been unable to do this. In the current state of affairs the call method hereof looks like this:

def call(self, inputs, state, scope=None):
    with vs.variable_scope(scope or "decoder_gru_cell"):
        with vs.variable_scope("gates"):
            z = math_ops.sigmoid(_linear([inputs, state], self._num_units, True))
            r = math_ops.sigmoid(_linear([inputs, state], self._num_units, True))
        with vs.variable_scope("candidate"):
            r = r*_linear(state, self._num_units, False)
        with vs.variable_scope("input"):
            x = _linear(inputs, self._num_units, True)
        h_hat = math_ops.tanh(r + x)
        new_h = z * h_hat + (1 - z) * state
        output = tf.nn.softmax(_linear(new_h))
    return output, new_h

I can't seem to make it use the output from time step t-1 concatenated with the question vector as input for the cell at time step t, as described in the papers.

Futhermore, I'm uncertain how I can implement it such that it takes a fixed size input tensor and outputs a variable size tensor (since not all answers necessarily are of the same length). Based on the following sentence from Xiong et al. (2016), this ought to be possible:

For tasks requiring a sequence output,
  an RNN may be used to decode a = [q; m^T], the concatenation of vectors q and m^T, to an ordered set of tokens.

tl; dr

How do I implement a GRU that takes a fixed size input tensor and outputs a variable size tensor in Tensorflow?

Any help would be greatly appreciated, thanks!


问:
css sed unterminated address regex
The following sed command works great most of the time except when I try it with the following script. I get the error </p>

```<code>sed: -e expression #1, char 3495: unterminated address regex
</code>```

<p>It points at the last character } but I can't figure out how to terminate the sed command. Usually its not a problem. Hep would be appreciated. </p>

```<code>sed -i '/body *{/,/}/c \
body{\
    z-index:1;\
    margin:0;\
    background-image: url("http://www.calmchess.com/images/frgrnd1366.png");\
    background-repeat:repeat;\
    }\
    \
#header0{\
    position:relative; \
    width:1100px; \
    height:114px; \
    text-align:center; \
    font-size:16px; \
    color:000000; \
    background-size:1100px 114px; \
    background-image: url("http://www.calmchess.com/images/854x480/header854x480_114_0.png"); \
    background-repeat: no-repeat; \
    }\
     \
#fullcontentcontainer0{ \
    position:relative; \
    z-index:0; \
    text-align:center; \
    font-size:16px; \
    color:000000;  \
    width:1100px; \
    height:135%; \
      } \
 \
 #lrgcontentimgcontainer0{ \
   position:relative; \
   top:75px; \
   margin:0 auto 0 auto; \
   font-size:16px;  \
   color:000000;  \
   width:530px;  \
   height:575px;  \
   background-size:530px 575px; \
   background-image: url("http://www.calmchess.com/images/lrgcontent0.png"); \
   background-repeat: no-repeat; \
     } \
 \
 #nav0{ \
     width:1100px; \
     height:60px; \
     position:absolute; \
     color:000000; \
     z-index:6; \
     font-size:16px; \
     border-top:1px solid 000000; \
     border-bottom:1px solid 000000; \
     background-image:url("http://www.calmchess.com/images/mediumformbak0.png");\
     background-repeat: no-repeat; \
     } \
 \
 .btncon0{ \
     position:relative; \
     width:205px; \
     height:60px; \
     margin:0 auto 0 auto; \
     } \
 \
#footer0{ \
    position:absolute; \
    top:100%; \
    width:100%; \
    height:180px; \
    font-size:16px; \
    border-top:1px solid 000000; \
    background-image: url("http://www.calmchess.com/images/mediumformbak0.png"); \
    background-repeat: no-repeat; \
    } \
    \
 .foliotop0{ \
     position:absolute; \
     width:100px; \
     height:35px;  \
     top:5px; \
     left:0px; \
     font-size:16px; \
     z-index:2; \
     background-size:100px 35px; \
     background-image: url("http://www.calmchess.com/images/port0.png"); \
     background-repeat: no-repeat; \
       } \
\
.foliobottom0{ \
    position:absolute; \
    width:100px; \
    height:35px;  \
    top:5px; \
    left:0px; \
    font-size:16px; \
    z-index:1; \
    background-size:100px 35px; \
    background-image: url("http://www.calmchess.com/images/buttonbottom0.png"); \
    background-repeat: no-repeat; \
    } \
\
.contacttop0{ \
    position:absolute; \
    width:100px; \
    height:35px; \
    top:5px; \
    left:105px; \
    font-size:16px; \
    z-index:2; background-size:100px 35px; \
    background-image: url("http://www.calmchess.com/images/contact0.png"); \
    background-repeat: no-repeat; \
    } \
\
.contactbottom0{ \
    position:absolute; \
    width:100px; \
    height:35px;  \
    top:5px; \
    left:105px; \
    font-size:16px; \
    z-index:1; \
    background-size:100px 35px; \
    background-image: url("http://www.calmchess.com/images/buttonbottom0.png"); \
    background-repeat: no-repeat; \
    } \
\
#paypal0{ \
    position:absolute; \
    left:460px; \
    top:840px; \
    font-size:21pt;\
    } \
\
#paypal0 input{ \
    width:300px; \
    height:150px; \
      } \
\
#para0{ \
    font-size:21pt; \
    position:absolute; \
    width:500px; \
    left:15px; \
    top:10px; \
    text-align:left; \
    } \
\
#para1{ \
    font-size:21pt; \
    position:absolute; \
    width:500px; \
    left:15px; \
    top:110px; \
    text-align:left; \
      } \
\
#para2{ \
    font-size:21pt; \
    position:absolute; \
    width:500px; \
    left:15px; \
    top:350px; \
    text-align:left; \
    } \
    \
#para3{ \
    font-size:21pt; \
    position:absolute; \
    width:500px; \
    left:15px; \
    top:445px; \
    text-align:left; \
    } \
    \
.businesscard0{ \
    width:640px; \
    height:480px; \
    margin:0 auto 0 auto; \
    font-size:16px; \
      }' $file0
</code>```

答:
If you want a backslash to mark a line break, no trailing spaces are allowed.</p>

```<code>cat -n file_with_sed_code | grep '\\ \+$'
</code>```

Title: css sed unterminated address regex

Body:
The following sed command works great most of the time except when I try it with the following script. I get the error

sed: -e expression #1, char 3495: unterminated address regex

It points at the last character } but I can't figure out how to terminate the sed command. Usually its not a problem. Hep would be appreciated.

sed -i '/body *{/,/}/c \
body{\
    z-index:1;\
    margin:0;\
    background-image: url("http://www.calmchess.com/images/frgrnd1366.png");\
    background-repeat:repeat;\
    }\
    \
#header0{\
    position:relative; \
    width:1100px; \
    height:114px; \
    text-align:center; \
    font-size:16px; \
    color:000000; \
    background-size:1100px 114px; \
    background-image: url("http://www.calmchess.com/images/854x480/header854x480_114_0.png"); \
    background-repeat: no-repeat; \
    }\
     \
#fullcontentcontainer0{ \
    position:relative; \
    z-index:0; \
    text-align:center; \
    font-size:16px; \
    color:000000;  \
    width:1100px; \
    height:135%; \
      } \
 \
 #lrgcontentimgcontainer0{ \
   position:relative; \
   top:75px; \
   margin:0 auto 0 auto; \
   font-size:16px;  \
   color:000000;  \
   width:530px;  \
   height:575px;  \
   background-size:530px 575px; \
   background-image: url("http://www.calmchess.com/images/lrgcontent0.png"); \
   background-repeat: no-repeat; \
     } \
 \
 #nav0{ \
     width:1100px; \
     height:60px; \
     position:absolute; \
     color:000000; \
     z-index:6; \
     font-size:16px; \
     border-top:1px solid 000000; \
     border-bottom:1px solid 000000; \
     background-image:url("http://www.calmchess.com/images/mediumformbak0.png");\
     background-repeat: no-repeat; \
     } \
 \
 .btncon0{ \
     position:relative; \
     width:205px; \
     height:60px; \
     margin:0 auto 0 auto; \
     } \
 \
#footer0{ \
    position:absolute; \
    top:100%; \
    width:100%; \
    height:180px; \
    font-size:16px; \
    border-top:1px solid 000000; \
    background-image: url("http://www.calmchess.com/images/mediumformbak0.png"); \
    background-repeat: no-repeat; \
    } \
    \
 .foliotop0{ \
     position:absolute; \
     width:100px; \
     height:35px;  \
     top:5px; \
     left:0px; \
     font-size:16px; \
     z-index:2; \
     background-size:100px 35px; \
     background-image: url("http://www.calmchess.com/images/port0.png"); \
     background-repeat: no-repeat; \
       } \
\
.foliobottom0{ \
    position:absolute; \
    width:100px; \
    height:35px;  \
    top:5px; \
    left:0px; \
    font-size:16px; \
    z-index:1; \
    background-size:100px 35px; \
    background-image: url("http://www.calmchess.com/images/buttonbottom0.png"); \
    background-repeat: no-repeat; \
    } \
\
.contacttop0{ \
    position:absolute; \
    width:100px; \
    height:35px; \
    top:5px; \
    left:105px; \
    font-size:16px; \
    z-index:2; background-size:100px 35px; \
    background-image: url("http://www.calmchess.com/images/contact0.png"); \
    background-repeat: no-repeat; \
    } \
\
.contactbottom0{ \
    position:absolute; \
    width:100px; \
    height:35px;  \
    top:5px; \
    left:105px; \
    font-size:16px; \
    z-index:1; \
    background-size:100px 35px; \
    background-image: url("http://www.calmchess.com/images/buttonbottom0.png"); \
    background-repeat: no-repeat; \
    } \
\
#paypal0{ \
    position:absolute; \
    left:460px; \
    top:840px; \
    font-size:21pt;\
    } \
\
#paypal0 input{ \
    width:300px; \
    height:150px; \
      } \
\
#para0{ \
    font-size:21pt; \
    position:absolute; \
    width:500px; \
    left:15px; \
    top:10px; \
    text-align:left; \
    } \
\
#para1{ \
    font-size:21pt; \
    position:absolute; \
    width:500px; \
    left:15px; \
    top:110px; \
    text-align:left; \
      } \
\
#para2{ \
    font-size:21pt; \
    position:absolute; \
    width:500px; \
    left:15px; \
    top:350px; \
    text-align:left; \
    } \
    \
#para3{ \
    font-size:21pt; \
    position:absolute; \
    width:500px; \
    left:15px; \
    top:445px; \
    text-align:left; \
    } \
    \
.businesscard0{ \
    width:640px; \
    height:480px; \
    margin:0 auto 0 auto; \
    font-size:16px; \
      }' $file0

Body:
If you want a backslash to mark a line break, no trailing spaces are allowed.

cat -n file_with_sed_code | grep '\\ \+$'


问:
Include external CSS library in only one Vue component
I have a Vue app with many components. Currently I have Font-Awesome included in the head of the index.html file however only ONE page, or component, actually needs it. Is it possible to move it to the component itself so that it only loads when it's needed?

MOVE THIS

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
</code>```

TO THIS

```<code><template></template>
<link rel="stylesheet" href="../../static/css/font-awesome-4.7.0/css/font-awesome-min.css"></link>
<script>
    export default {
        name: 'SingleComponent',
        data: function() {
            return{}
        }
    }
</script>
<style scoped>
</style>
</code>```

I've tried downloading Font-Awesome and adding a link tag in the component like above ^^^^ I don't get any errors but the icons still don't work.

答: Instead of trying to include Font-Awesome directly in the component, I discovered there is already a Vue wrapper for it called vue-awesome so I used that. </p>

Body:
I have a Vue app with many components. Currently I have Font-Awesome included in the head of the index.html file however only ONE page, or component, actually needs it. Is it possible to move it to the component itself so that it only loads when it's needed?

MOVE THIS

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

TO THIS

<template></template>
<link rel="stylesheet" href="../../static/css/font-awesome-4.7.0/css/font-awesome-min.css"></link>

I've tried downloading Font-Awesome and adding a link tag in the component like above ^^^^ I don't get any errors but the icons still don't work.


问:
Uncaught (in promise): Error: No provider for AngularFireAuth
We are tried login with google authentication using (Firebase/ionic2/angularjs2).Our code

```<code> import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
   user: Observable<firebase.User>;
  constructor(public navCtrl: NavController,public afAuth: AngularFireAuth) {
    this.user = afAuth.authState;
  }
  login() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }

  logout() {
    this.afAuth.auth.signOut();
  }
}
</code>```

but we are getting error :

```<code>Error: Uncaught (in promise): Error: No provider for AngularFireAuth!
Error: No provider for AngularFireAuth!
</code>```

Please guide to us what working in our code .

答:
resolve here https://github.com/iglewski/Annotator/issues/3

app.component.spec.ts :

```<code>import { FirebaseApp, FirebaseAppConfig, AngularFireModule } from 'angularfire2';
import { AngularFireAuth, AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import * as firebase from 'firebase/app';
import { firebaseConfig } from './app.module';
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [
        AngularFireModule.initializeApp(firebaseConfig), //ajout
        AngularFireAuthModule, //ajout
        AngularFireDatabaseModule //ajout
      ],
    }).compileComponents();

  }));
</code>```

Body:
We are tried login with google authentication using (Firebase/ionic2/angularjs2).Our code

 import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
   user: Observable<firebase.User>;
  constructor(public navCtrl: NavController,public afAuth: AngularFireAuth) {
    this.user = afAuth.authState;
  }
  login() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }

  logout() {
    this.afAuth.auth.signOut();
  }
}

but we are getting error :

Error: Uncaught (in promise): Error: No provider for AngularFireAuth!
Error: No provider for AngularFireAuth!

Please guide to us what working in our code .

Body:
resolve here https://github.com/iglewski/Annotator/issues/3

app.component.spec.ts :

import { FirebaseApp, FirebaseAppConfig, AngularFireModule } from 'angularfire2';
import { AngularFireAuth, AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import * as firebase from 'firebase/app';
import { firebaseConfig } from './app.module';
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [
        AngularFireModule.initializeApp(firebaseConfig), //ajout
        AngularFireAuthModule, //ajout
        AngularFireDatabaseModule //ajout
      ],
    }).compileComponents();

  }));


问:
iOS Firebase get data where value equals to something
How can I get data in swift3 from firebase where the value equals something.

In MySQL that would be "SELECT * FROM users WHERE type = 'brown'"; how can I write that where part in Firebase?

I have this DB

And I want to get all the data from it where month == currentMonth (I have a currentMonth variable)

答:
As far as I'm aware firebase realtime database doesn't have support for querying like this.  Instead you need to call down the whole ref 'budget' then filter it locally in your app.

FireStore apparently has better query support although its in Beta.


问:
Using Intel RDRAND in Python 2.7
I want to make use of Intel's RDRAND feature on Windows and generate true random numbers (since Python's random module isn't so random). Is there any API in Python which can access this feature?

I've tried installing the rdrand module mentioned in the comment below, but I keep getting an error. Log: http://pastebin.com/A2Vqsqec

The error seems to be thrown by these lines in rdrand.c:

```<code>#ifdef __GNUC__
#define USING_GCC 1
#elif __clang__
#define USING_CLANG 1
#else
#error Only support for gcc or clang currently
#error if you port to another compiler, please
#error send back the patch to https://github.com/stillson/rdrand
#endif
</code>```

Why is this happening?

UPDATE: I've checked and made sure that __GNUC__ is defined

答:
You will probably want to use Python to wrap a C/C++ routine, instead of using the Python implementation of RdRand().  A research paper here (http://iopscience.iop.org/article/10.3847/1538-4357/aa7ede/meta;jsessionid=A9DA9DDB925E6522D058F3CEEC7D0B21.ip-10-40-2-120), or non-paywalled version here (https://arxiv.org/abs/1707.02212) recently showed how poor the performance of RdRand() in Python is.  Even so, as the paper mentions, the RdRand and RdSeed instructions are not quite "truly" random...

Hope that helps.

Title: Using Intel RDRAND in Python 2.7

Body:
I want to make use of Intel's RDRAND feature on Windows and generate true random numbers (since Python's random module isn't so random). Is there any API in Python which can access this feature?

I've tried installing the rdrand module mentioned in the comment below, but I keep getting an error. Log: http://pastebin.com/A2Vqsqec

The error seems to be thrown by these lines in rdrand.c:

#ifdef __GNUC__
#define USING_GCC 1
#elif __clang__
#define USING_CLANG 1
#else
#error Only support for gcc or clang currently
#error if you port to another compiler, please
#error send back the patch to https://github.com/stillson/rdrand
#endif

Why is this happening?

UPDATE: I've checked and made sure that __GNUC__ is defined


问:
Allow dropdown content to stay outside of nav bar
This is probably abominably obvious to everyone, but I am very new to HTML. How would I allow my webpage to start from the very top and very left, rather than ~10px after, while using position:relative?

答: By default, browsers put an 8px margin on body. To counter this, you'll need to add body { margin: 0; } to your stylesheet.


问:
Using T-SQL REPLACE with wildcard lookup to replace field values
I have table with schema:

```<code>CREATE TABLE InvestorDetails
(
    [ID] INT PRIMARY KEY,
    [Created] DATETIME,
    [Updated] DATETIME,
    [ToEmail] VARCHAR(MAX)
)
</code>```

Records in InvestorDetails look like the following:

```<code>1, 2017-01-01, 2017-02-02, ames@gmail.com;mark@gmail.com;tom@gmail.com;mitchel@gmail.com
2, 2017,01-02, 2017-02-02, ben@gmail.com;michael@gmail.com;mark@gmail.com
3, 2017-02-02, 2017,02-03, test@gmail.com;matthew@gmail.com;dan@gmail.com;jay@gmail.com;mark@gmail.com
</code>```

I want to write a query that will go through and update each record in the table that has 'mark@gmail.com' in field 'ToEmail' with 'markTest@gmail.com'

So for example in record 1 above, I want it to look like:

```<code>1, 2017-01-01, 2017-02-02, ames@gmail.com;markTest@gmail.com;tom@gmail.com;mitchel@gmail.com
</code>```

I can find the records with mark@gmail.com in 'EmailRecipients'using the following query:

```<code>SELECT I.ID, I.EmailRecipients
FROM InvestorDetails I
WHERE I.EmailRecipients LIKE '%mark@gmail.com%'
</code>```

The tricky part is ensuring only the mark@gmail.com is changed, and the rest remains. I believe this can be achieved with TSQL REPLACE, but I'm having trouble writing the SQL, particularly what to use as the string_pattern and string_replacement parameters.

Any help is greatly appreciated!

Thanks!

答:
You can use the following query

```<code>UPDATE InvestorDetails
SET EmailRecipients =
       REPLACE(';' + EmailRecipients  + ';', ';mark@gmail.com;' , ';markTest@gmail.com;' )
WHERE EmailRecipients LIKE '%;mark@gmail.com;%'
</code>```

This is made to ensure that mails that contains mark such as drmark@gmail.com are not updated.

If you want to remove the added leadin and trailing semicolons you can use the following query

You can use the following query

```<code>UPDATE InvestorDetails
SET EmailRecipients =
       SUBSTRING(REPLACE(';' + EmailRecipients  + ';', ';mark@gmail.com;' , ';markTest@gmail.com;'),2, LEN( REPLACE(';' + EmailRecipients  + ';', ';mark@gmail.com;' , ';markTest@gmail.com;' ) - 2 )
WHERE EmailRecipients LIKE '%;mark@gmail.com;%' AND ISNULL(EmailRecipients,'') <> ''
</code>```

Another query was provided by @MartinSmith in the comments

```<code>UPDATE InvestorDetails
SET ToEmail = SUBSTRING(replaced, 2, LEN(replaced) -2)
FROM InvestorDetails
    CROSS APPLY
(SELECT REPLACE(';'+ ToEmail + ';',';mark@gmail.com;' , ';markTest@gmail.com;')) CA(replaced)
WHERE ToEmail LIKE '%mark@gmail.com%'
</code>```

Body:
I have table with schema:

CREATE TABLE InvestorDetails
(
    [ID] INT PRIMARY KEY,
    [Created] DATETIME,
    [Updated] DATETIME,
    [ToEmail] VARCHAR(MAX)
)

Records in InvestorDetails look like the following:

1, 2017-01-01, 2017-02-02, ames@gmail.com;mark@gmail.com;tom@gmail.com;mitchel@gmail.com
2, 2017,01-02, 2017-02-02, ben@gmail.com;michael@gmail.com;mark@gmail.com
3, 2017-02-02, 2017,02-03, test@gmail.com;matthew@gmail.com;dan@gmail.com;jay@gmail.com;mark@gmail.com

I want to write a query that will go through and update each record in the table that has 'mark@gmail.com' in field 'ToEmail' with 'markTest@gmail.com'

So for example in record 1 above, I want it to look like:

1, 2017-01-01, 2017-02-02, ames@gmail.com;markTest@gmail.com;tom@gmail.com;mitchel@gmail.com

I can find the records with mark@gmail.com in 'EmailRecipients'using the following query:

SELECT I.ID, I.EmailRecipients
FROM InvestorDetails I
WHERE I.EmailRecipients LIKE '%mark@gmail.com%'

The tricky part is ensuring only the mark@gmail.com is changed, and the rest remains. I believe this can be achieved with TSQL REPLACE, but I'm having trouble writing the SQL, particularly what to use as the string_pattern and string_replacement parameters.

Any help is greatly appreciated!

Thanks!

Body:
You can use the following query

UPDATE InvestorDetails
SET EmailRecipients =
       REPLACE(';' + EmailRecipients  + ';', ';mark@gmail.com;' , ';markTest@gmail.com;' )
WHERE EmailRecipients LIKE '%;mark@gmail.com;%'

This is made to ensure that mails that contains mark such as drmark@gmail.com are not updated.

If you want to remove the added leadin and trailing semicolons you can use the following query

You can use the following query

UPDATE InvestorDetails
SET EmailRecipients =
       SUBSTRING(REPLACE(';' + EmailRecipients  + ';', ';mark@gmail.com;' , ';markTest@gmail.com;'),2, LEN( REPLACE(';' + EmailRecipients  + ';', ';mark@gmail.com;' , ';markTest@gmail.com;' ) - 2 )
WHERE EmailRecipients LIKE '%;mark@gmail.com;%' AND ISNULL(EmailRecipients,'') <> ''

Another query was provided by @MartinSmith in the comments

UPDATE InvestorDetails
SET ToEmail = SUBSTRING(replaced, 2, LEN(replaced) -2)
FROM InvestorDetails
    CROSS APPLY
(SELECT REPLACE(';'+ ToEmail + ';',';mark@gmail.com;' , ';markTest@gmail.com;')) CA(replaced)
WHERE ToEmail LIKE '%mark@gmail.com%'


问:
Google Sheets Script to return sheet name will not automatically update on creating a new sheet
I have written a script in Google Sheets to return the name of a given sheet (see below).

The function is written into a summary sheet, where the input given as the index of the sheet required. I have all the functions pre-written e.g.

A1 = GetSheet(1) B1 = GetSheet(2) C1 = GetSheet(3) ...etc

Obviously, when the sheet with the index in question does not yet exist, I get an error. However, when I do create that sheet, the cell does not automatically update with the name of the new sheet, it still returns an error. To get the name to appear, I have to delete the function and re-paste it in.

Is there a way for the cells to automatically update when a new sheet is added, without re-typing the function?

Apologies if I am missing something obvious, I am very new to this!

```<code>function GetSheet(input)
{
  var spread = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = SpreadsheetApp.getActiveSheet();
  var sourceIndex = sourceSheet.getIndex();
  var nextIndex = sourceIndex + 1;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  SpreadsheetApp.setActiveSheet(ss.getSheets()[input]);
  var active = ss.getActiveSheet();
  var name = active.getName();
  return name
}
</code>```

答:
Not Changing because their inputs are not changing

The reason that your custom functions are not returning anything when you create another sheet is because the input to these kinds of function are generally expected to be cell references and the functions will recalculate when the value of those cell references change.  But your inputs are just numbers (indexes to the allSheets() array and creating another sheets doesn't change any of their inputs so they never get a chance to run.  I don't think that creating a new sheet will trigger an onChange I think these are the only things that trigger an onChange event.

EDIT, INSERT_ROW, INSERT_COLUMN, REMOVE_ROW, REMOVE_COLUMN, INSERT_GRID, REMOVE_GRID, FORMAT and OTHER

Admittedly, I don't know what OTHER is so maybe there's hope.

Body:
I have written a script in Google Sheets to return the name of a given sheet (see below).

The function is written into a summary sheet, where the input given as the index of the sheet required. I have all the functions pre-written e.g.

A1 = GetSheet(1) B1 = GetSheet(2) C1 = GetSheet(3) ...etc

Obviously, when the sheet with the index in question does not yet exist, I get an error. However, when I do create that sheet, the cell does not automatically update with the name of the new sheet, it still returns an error. To get the name to appear, I have to delete the function and re-paste it in.

Is there a way for the cells to automatically update when a new sheet is added, without re-typing the function?

Apologies if I am missing something obvious, I am very new to this!

function GetSheet(input)
{
  var spread = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = SpreadsheetApp.getActiveSheet();
  var sourceIndex = sourceSheet.getIndex();
  var nextIndex = sourceIndex + 1;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  SpreadsheetApp.setActiveSheet(ss.getSheets()[input]);
  var active = ss.getActiveSheet();
  var name = active.getName();
  return name
}


问:
Promise pending; promise function wont do any of the callbacks
I'm calling the post('/audit') and then calling the getSignature (Promise) function, which returns the body of the signature to print out (with console.log(audit_signature). However, my Promise remains pending and my audit_signature remains undefined. What is causing the issue with the promise and the audit_signature? How do I fix it?

(error):

```<code>start /audit
[stdout] jwtPayload: { description: 'admin',
[stdout]   id: '1508959916',
[stdout]   signature: '4d4a542f-d738-4736-8df5-84575b4d90fd' }
[stdout] ids:  4d4a542f-d738-4736-8df5-84575b4d90fd
[stdout] start: getSignature
[stdout] getAudit: Promise { <pending> }
[stdout] audit_signature: undefined
[stdout] start: responseWithJSON
</code>```

(server.js)

```<code> function getSignature(uuid){
    console.log('start getSignature');
     return new Promise(function (resolve, reject){
        request.post({
            url: `http://${ksiIP}:${ksiPort}/KsiProxy/rest/util/getSignature`,
            headers: {
                'Content-Type': 'application/json',
                'Authorization' : 'Basic Og=='
            }, json: {'uuid': uuid}
        }), function(error, response, body){
            console.log(error);
            console.log(response);
            console.log(body);

            if(error || (response.statusCode != 200)){
                return reject((error ? error : body));
            }
            if(body.resultcode != 0){
                console.log("Error: " + requestResult.info);
                console.log("Asset could not be verified.");
                return reject(new Error(body.info));
            }
            if(response == 'undefined') {
                console.log('ksi unavailable');
                return reject(error);
            }
            //add identification as well
            resolve(body.signature);
            //resolve('resolve is here');
        }
    })
}

dcServer.post('/audit', function(req,res){
    console.log('start /audit');
    if(req.jwtPayload.description != "admin"){
        respondWithJSON(401, 401, "Not authorised for this functionality.", res);
        return;
    }
    let toAudit = req.jwtPayload.signature;
    var audit_signature;
    console.log('jwtPayload:', req.jwtPayload);
    console.log("ids: ", toAudit);

    let failed = 0;//counter to increase if signatures couldnt be retreived.

    var getAudit = getSignature(toAudit).then(
                (result) => {return audit_signature = result;} ,
                (error) => {
                        failed++;
                        audit_signature = 'unavailable';
                        console.log(error);
        });
    console.log('getAudit:', getAudit);
    console.log('audit_signature:', audit_signature);

   });
</code>```

答:
getAudit  is a Promise and when you print it you will see getAudit: Promise { <pending> }
and getSignature is async so you have to wait until the promise resolves and print audit_signature like this :

```<code> var getAudit = getSignature(toAudit).then(
                (result) => {return audit_signature = result;} ,
                (error) => {
                        failed++;
                        audit_signature = 'unavailable';
                        console.log(error);
        });

    getAudit.then(audit_signature =>{
        console.log('audit_signature:', audit_signature);
    })
</code>```

Body:
I'm calling the post('/audit') and then calling the getSignature (Promise) function, which returns the body of the signature to print out (with console.log(audit_signature). However, my Promise remains pending and my audit_signature remains undefined. What is causing the issue with the promise and the audit_signature? How do I fix it?

(error):

start /audit
[stdout] jwtPayload: { description: 'admin',
[stdout]   id: '1508959916',
[stdout]   signature: '4d4a542f-d738-4736-8df5-84575b4d90fd' }
[stdout] ids:  4d4a542f-d738-4736-8df5-84575b4d90fd
[stdout] start: getSignature
[stdout] getAudit: Promise { <pending> }
[stdout] audit_signature: undefined
[stdout] start: responseWithJSON

(server.js)

 function getSignature(uuid){
    console.log('start getSignature');
     return new Promise(function (resolve, reject){
        request.post({
            url: `http://${ksiIP}:${ksiPort}/KsiProxy/rest/util/getSignature`,
            headers: {
                'Content-Type': 'application/json',
                'Authorization' : 'Basic Og=='
            }, json: {'uuid': uuid}
        }), function(error, response, body){
            console.log(error);
            console.log(response);
            console.log(body);

            if(error || (response.statusCode != 200)){
                return reject((error ? error : body));
            }
            if(body.resultcode != 0){
                console.log("Error: " + requestResult.info);
                console.log("Asset could not be verified.");
                return reject(new Error(body.info));
            }
            if(response == 'undefined') {
                console.log('ksi unavailable');
                return reject(error);
            }
            //add identification as well
            resolve(body.signature);
            //resolve('resolve is here');
        }
    })
}

dcServer.post('/audit', function(req,res){
    console.log('start /audit');
    if(req.jwtPayload.description != "admin"){
        respondWithJSON(401, 401, "Not authorised for this functionality.", res);
        return;
    }
    let toAudit = req.jwtPayload.signature;
    var audit_signature;
    console.log('jwtPayload:', req.jwtPayload);
    console.log("ids: ", toAudit);

    let failed = 0;//counter to increase if signatures couldnt be retreived.

    var getAudit = getSignature(toAudit).then(
                (result) => {return audit_signature = result;} ,
                (error) => {
                        failed++;
                        audit_signature = 'unavailable';
                        console.log(error);
        });
    console.log('getAudit:', getAudit);
    console.log('audit_signature:', audit_signature);

   });

Body:
getAudit  is a Promise and when you print it you will see getAudit: Promise { <pending> }
and getSignature is async so you have to wait until the promise resolves and print audit_signature like this :

 var getAudit = getSignature(toAudit).then(
                (result) => {return audit_signature = result;} ,
                (error) => {
                        failed++;
                        audit_signature = 'unavailable';
                        console.log(error);
        });

    getAudit.then(audit_signature =>{
        console.log('audit_signature:', audit_signature);
    })


问:
T SQL - converting a String comma delimited into a Table with multiples columns
I have a string that is comma separated (they are records), for example,

```<code>0,CSVSO67695,97971,2014-03-05 00:00:00.000,WB-H098,1,4.99,Individual,Sales extract OK!,255.0,1,CSVSO53485,47747,2013-07-31 00:00:00.000,SJ-0194-L,10,323.94,Store,Sales extract OK!,255.0
</code>```

and I want to parse the string and put the values into a table.
Here are the variable names:

```<code>ID int
SalesOrderNumber  varchar(15)
SalesOrderDetailID int
OrderDate date
ProductNumber varchar(25)
Quantity int
LineTotal money
CustomerType varchar(25)
TestData_1 varchar(50)
TestData_2 varchar(50)
</code>```

答:
If performance is important and you only need the first 10 elements in the string you can use a cascading cross apply like this:

```<code>declare @CommaString varchar(MAX)='0,CSVSO67695,97971,2014-03-05 00:00:00.000,WB-H098,1,4.99,Individual,Sales extract OK!,255.0,1,CSVSO53485,47747,2013-07-31 00:00:00.000,SJ-0194-L,10,323.94,Store,Sales extract OK!,255.00000';

select --d1=d1.d,d2=d2.d,d3=d3.d, d4=d4.d, d5=d5.d,d6=d6.d,d7=d7.d,d8=d8.d,d9=d9.d,d10=d10.d, d11=d11.d,
  ID                 = substring(v.cs, 1, d1.d-1),
  SalesOrderNumber   = substring(v.cs, d1.d+1, d2.d-1-d1.d),
  SalesOrderDetailID = substring(v.cs, d2.d+1, d3.d-1-d2.d),
  OrderDate          = substring(v.cs, d3.d+1, d4.d-1-d3.d),
  ProductNumber      = substring(v.cs, d4.d+1, d5.d-1-d4.d),
  Quantity           = substring(v.cs, d5.d+1, d6.d-1-d5.d),
  LineTotal          = substring(v.cs, d6.d+1, d7.d-1-d6.d),
  CustomerType       = substring(v.cs, d7.d+1, d8.d-1-d7.d),
  TestData_1         = substring(v.cs, d8.d+1, d9.d-1-d8.d),
  TestData_2         = substring(v.cs, d9.d+1, d10.d-1-d9.d)
from (values (@CommaString)) v(cs)
cross apply (values (len(@commastring)-len(replace(@commastring,',',''))+1)) c(commacount)
cross apply (values (charindex(',', v.cs)))          d1(d)
cross apply (values (charindex(',', v.cs, d1.d+1)))  d2(d)
cross apply (values (charindex(',', v.cs, d2.d+1)))  d3(d)
cross apply (values (charindex(',', v.cs, d3.d+1)))  d4(d)
cross apply (values (charindex(',', v.cs, d4.d+1)))  d5(d)
cross apply (values (charindex(',', v.cs, d5.d+1)))  d6(d)
cross apply (values (charindex(',', v.cs, d6.d+1)))  d7(d)
cross apply (values (charindex(',', v.cs, d7.d+1)))  d8(d)
cross apply (values (charindex(',', v.cs, d8.d+1)))  d9(d)
cross apply (values (charindex(',', v.cs, d9.d+1)))  d10(d)
cross apply (values (charindex(',', v.cs, d10.d+1))) d11(d)
where c.commaCount >= 10 -- optional where clause to ensure that there are enough commas
option (recompile);
</code>```

Returns:

```<code>ID  SalesOrderNumber  SalesOrderDetailID  OrderDate                ProductNumber  Quantity   LineTotal  CustomerType  TestData_1         TestData_2
--- ----------------- ------------------- ------------------------ -------------- ---------- ---------- ------------- ------------------ ----------
0   CSVSO67695        97971               2014-03-05 00:00:00.000  WB-H098        1          4.99       Individual    Sales extract OK!  255.0
</code>```

This technique is as efficient as it gets for splitting strings. Note the execution plan below. A one constant scan, a SELECT with a total cost of 0.0000012 is about as efficient as it gets. Especially for varchar(max) and other blob data types.

Body:
I have a string that is comma separated (they are records), for example,

0,CSVSO67695,97971,2014-03-05 00:00:00.000,WB-H098,1,4.99,Individual,Sales extract OK!,255.0,1,CSVSO53485,47747,2013-07-31 00:00:00.000,SJ-0194-L,10,323.94,Store,Sales extract OK!,255.0

and I want to parse the string and put the values into a table.
Here are the variable names:

ID int
SalesOrderNumber  varchar(15)
SalesOrderDetailID int
OrderDate date
ProductNumber varchar(25)
Quantity int
LineTotal money
CustomerType varchar(25)
TestData_1 varchar(50)
TestData_2 varchar(50)

Body:
If performance is important and you only need the first 10 elements in the string you can use a cascading cross apply like this:

declare @CommaString varchar(MAX)='0,CSVSO67695,97971,2014-03-05 00:00:00.000,WB-H098,1,4.99,Individual,Sales extract OK!,255.0,1,CSVSO53485,47747,2013-07-31 00:00:00.000,SJ-0194-L,10,323.94,Store,Sales extract OK!,255.00000';

select --d1=d1.d,d2=d2.d,d3=d3.d, d4=d4.d, d5=d5.d,d6=d6.d,d7=d7.d,d8=d8.d,d9=d9.d,d10=d10.d, d11=d11.d,
  ID                 = substring(v.cs, 1, d1.d-1),
  SalesOrderNumber   = substring(v.cs, d1.d+1, d2.d-1-d1.d),
  SalesOrderDetailID = substring(v.cs, d2.d+1, d3.d-1-d2.d),
  OrderDate          = substring(v.cs, d3.d+1, d4.d-1-d3.d),
  ProductNumber      = substring(v.cs, d4.d+1, d5.d-1-d4.d),
  Quantity           = substring(v.cs, d5.d+1, d6.d-1-d5.d),
  LineTotal          = substring(v.cs, d6.d+1, d7.d-1-d6.d),
  CustomerType       = substring(v.cs, d7.d+1, d8.d-1-d7.d),
  TestData_1         = substring(v.cs, d8.d+1, d9.d-1-d8.d),
  TestData_2         = substring(v.cs, d9.d+1, d10.d-1-d9.d)
from (values (@CommaString)) v(cs)
cross apply (values (len(@commastring)-len(replace(@commastring,',',''))+1)) c(commacount)
cross apply (values (charindex(',', v.cs)))          d1(d)
cross apply (values (charindex(',', v.cs, d1.d+1)))  d2(d)
cross apply (values (charindex(',', v.cs, d2.d+1)))  d3(d)
cross apply (values (charindex(',', v.cs, d3.d+1)))  d4(d)
cross apply (values (charindex(',', v.cs, d4.d+1)))  d5(d)
cross apply (values (charindex(',', v.cs, d5.d+1)))  d6(d)
cross apply (values (charindex(',', v.cs, d6.d+1)))  d7(d)
cross apply (values (charindex(',', v.cs, d7.d+1)))  d8(d)
cross apply (values (charindex(',', v.cs, d8.d+1)))  d9(d)
cross apply (values (charindex(',', v.cs, d9.d+1)))  d10(d)
cross apply (values (charindex(',', v.cs, d10.d+1))) d11(d)
where c.commaCount >= 10 -- optional where clause to ensure that there are enough commas
option (recompile);

Returns:

ID  SalesOrderNumber  SalesOrderDetailID  OrderDate                ProductNumber  Quantity   LineTotal  CustomerType  TestData_1         TestData_2
--- ----------------- ------------------- ------------------------ -------------- ---------- ---------- ------------- ------------------ ----------
0   CSVSO67695        97971               2014-03-05 00:00:00.000  WB-H098        1          4.99       Individual    Sales extract OK!  255.0

This technique is as efficient as it gets for splitting strings. Note the execution plan below. A one constant scan, a SELECT with a total cost of 0.0000012 is about as efficient as it gets. Especially for varchar(max) and other blob data types.


问:
service cannot be cast to android.app.Activity
I am trying to access a editText and a Button in a Service.
I've seen this answer and this answer, and tried to merge and work out, but no gain. What am I missing here? I have seen other similar answers too and been trying to get it done from last 2 days but all in vain. Any other way of accomplishing it will also be welcome.

Here is the relevant code:
MainActivity.java

```<code>btn_start.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                startService(new Intent(getApplicationContext(), MyService.class));
            }
        });
</code>```

MyService.java

```<code>        Context context = MyService.this;
        Activity activity = (Activity) context;
        Button stopButton = activity.findViewById(R.id.btn_stop);
        EditText editTextUsername = activity.findViewById(R.id.edit_name);
</code>```

AndroidManifest.xml

```<code>        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
        </service>
</code>```

But I get this error:
LOGCAT

11-14 02:55:07.835 5906-5906/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.nwagh.myapplication, PID: 5906
                                                   java.lang.RuntimeException: Unable to start service
  com.example.nwagh.myapplication.MyService@32189af with Intent {
  cmp=com.example.nwagh.myapplication/.MyService }:
  java.lang.ClassCastException:
  com.example.nwagh.myapplication.MyService cannot be cast to
  android.app.Activity
                                                       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3060)
                                                       at android.app.ActivityThread.access$2300(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
                                                    Caused by: java.lang.ClassCastException:
  com.example.nwagh.myapplication.MyService cannot be cast to
  android.app.Activity
                                                       at com.example.nwagh.myapplication.MyService.onStartCommand(MyService.java:68)
                                                       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3043)
                                                       at android.app.ActivityThread.access$2300(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)  11-14
  02:55:07.844 5906-5906/? E/MQSEventManagerDelegate: failed to get
  MQSService.

Here is the complete code if you need any more reference.

答:
Services are NOT activities. Services have no UI related to them.

So:

1) you can't cast a service to an activity.
2) there is no UI for your to find in your service.

Why would a service need a button? services run in the background, with no user interaction.

I don't know what you are doing, but in Android it works like this:

1) activity launches a service (like your button press)
2) service carries out a task in the background
3) service reports back to the activity or terminates

Body:
I am trying to access a editText and a Button in a Service.
I've seen this answer and this answer, and tried to merge and work out, but no gain. What am I missing here? I have seen other similar answers too and been trying to get it done from last 2 days but all in vain. Any other way of accomplishing it will also be welcome.

Here is the relevant code:
MainActivity.java

btn_start.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                startService(new Intent(getApplicationContext(), MyService.class));
            }
        });

MyService.java

        Context context = MyService.this;
        Activity activity = (Activity) context;
        Button stopButton = activity.findViewById(R.id.btn_stop);
        EditText editTextUsername = activity.findViewById(R.id.edit_name);

AndroidManifest.xml

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
        </service>

But I get this error:
LOGCAT

11-14 02:55:07.835 5906-5906/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.nwagh.myapplication, PID: 5906
                                                   java.lang.RuntimeException: Unable to start service
  com.example.nwagh.myapplication.MyService@32189af with Intent {
  cmp=com.example.nwagh.myapplication/.MyService }:
  java.lang.ClassCastException:
  com.example.nwagh.myapplication.MyService cannot be cast to
  android.app.Activity
                                                       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3060)
                                                       at android.app.ActivityThread.access$2300(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
                                                    Caused by: java.lang.ClassCastException:
  com.example.nwagh.myapplication.MyService cannot be cast to
  android.app.Activity
                                                       at com.example.nwagh.myapplication.MyService.onStartCommand(MyService.java:68)
                                                       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3043)
                                                       at android.app.ActivityThread.access$2300(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)  11-14
  02:55:07.844 5906-5906/? E/MQSEventManagerDelegate: failed to get
  MQSService.

Here is the complete code if you need any more reference.


问:
How to read a file separated by tabs into a struct
How do you read a file formated like this below seperated by tabs into a struct?
this is the code i have so far i cant get it to work. i can get a whole line in but then how would i seperate the bits of data out??? </p>

```
New England Patriots    6   2       .750    3-2 3-0 1-0 1
Buffalo Bills       5   2       .714    4-0 1-2 1-0 1
```

```<code>ifstream inFile;

string name1;
string conference1;
string division1;
unsigned short wins1;
unsigned short losses1;
float pct1;

int i = 0;
int count = 0;
// this declares the strings we need
string line = "";
int a = 0;
string temp = "";

inFile.open(filename.c_str());

if (!inFile) {
    cerr << "Unable to open file" << filename;
    exit(1);   // call system to stop
}
if (inFile) {

    while (inFile.good())
    {
        //std::getline(inFile, line, '\t'); this is how you get line skipping tabs

        std::getline(inFile, line);
        cout << line;
        cout << endl;
        teams[a].raw = line;
        //cout << teams[a].raw;
        //cout << endl;
        //  teams[a].name = line;

        teams[a].position = a + 1;
        a++;
    }
    cout << teams[20].raw;
    cout << endl;
    cout << a - 1;
    cout << endl;
}
inFile.close();

struct NFL {
    string name;
    string conference;
    string division;
    unsigned short wins;
    string win;
    unsigned short losses;
    string lose;
    float pct;
    string per;
    string home;
    string road;

    string raw;
    int position;
};

struct ExpectedChar { char expected; };

// read a character from a stream and check it has the expected value
std::istream& operator>>(std::istream& in, const ExpectedChar& e)
{
    char c;
    if (in >> c)
        if (c != e.expected)  // failed to read expected character
            in.setstate(std::ios::failbit);
    return in;
}

// read a struct pass from a stream
std::istream& operator>>(std::istream& in, NFL& p)
{
    ExpectedChar tab{ '\t' };
    in >> p.name >> tab >> p.serviceTime >> tab >> p.classType;
    return in;
}
</code>```

答: Add a delimiter character to your getline call. getline(inFile, line, '\t'); should work. Where '\t' is a tab character. Note: This only works when the elements are actually delimited by a tab

Body:
How do you read a file formated like this below seperated by tabs into a struct?
this is the code i have so far i cant get it to work. i can get a whole line in but then how would i seperate the bits of data out???

New England Patriots    6   2       .750    3-2 3-0 1-0 1
Buffalo Bills       5   2       .714    4-0 1-2 1-0 1

ifstream inFile;

string name1;
string conference1;
string division1;
unsigned short wins1;
unsigned short losses1;
float pct1;

int i = 0;
int count = 0;
// this declares the strings we need
string line = "";
int a = 0;
string temp = "";

inFile.open(filename.c_str());

if (!inFile) {
    cerr << "Unable to open file" << filename;
    exit(1);   // call system to stop
}
if (inFile) {

    while (inFile.good())
    {
        //std::getline(inFile, line, '\t'); this is how you get line skipping tabs

        std::getline(inFile, line);
        cout << line;
        cout << endl;
        teams[a].raw = line;
        //cout << teams[a].raw;
        //cout << endl;
        //  teams[a].name = line;

        teams[a].position = a + 1;
        a++;
    }
    cout << teams[20].raw;
    cout << endl;
    cout << a - 1;
    cout << endl;
}
inFile.close();

struct NFL {
    string name;
    string conference;
    string division;
    unsigned short wins;
    string win;
    unsigned short losses;
    string lose;
    float pct;
    string per;
    string home;
    string road;

    string raw;
    int position;
};

struct ExpectedChar { char expected; };

// read a character from a stream and check it has the expected value
std::istream& operator>>(std::istream& in, const ExpectedChar& e)
{
    char c;
    if (in >> c)
        if (c != e.expected)  // failed to read expected character
            in.setstate(std::ios::failbit);
    return in;
}

// read a struct pass from a stream
std::istream& operator>>(std::istream& in, NFL& p)
{
    ExpectedChar tab{ '\t' };
    in >> p.name >> tab >> p.serviceTime >> tab >> p.classType;
    return in;
}


问:
Force image dimensions when empty
I am creating a grid with images. I have the problem of the empty images:

.myForm {
    position: relative;
    font-size: 0;
    line-height: 0;
}

.imgWrapper {
    position: relative;
    display: inline-block;
    width: 33.3333333%;
    box-sizing: border-box;
    background: tomato;
}

img {
    width: 100%;
    height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="myForm">
    <div class="imgWrapper">
        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>
    <div class="imgWrapper">
        <img src="">
    </div>
    <div class="imgWrapper">
        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>

</form></code>```

I would like to force the empty images to have the same size as the others. —I don't know if this can be done with flexbox, but I prefer to avoid it—. I think I can do this adding another wrapper, but I would prefer to avoid it.

Thanks in advance!

答:
I would prefer doing flexboxes. It's as simple as...

CSS:

```<code>.myForm {
    position: relative;
    font-size: 0;
    line-height: 0;
    display: flex;
}

.imgWrapper {

    position: relative;
    display: inline-block;
    width: 33.3333333%;
    box-sizing: border-box;
    background: tomato;
}

img {
    width: 100%;
    height: 100%;
}
</code>```

HTML:

```<code><form class="myForm">
    <div class="imgWrapper">
        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>
    <div class="imgWrapper">
        <img src="">
    </div>
    <div class="imgWrapper">
        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>

</form>
</code>```

Example here. I'm assuming you want the empty background image to have a height. Other solutions suggest hiding it entirely, which is an option as well.

Title: Force image dimensions when empty

Body:
I am creating a grid with images. I have the problem of the empty images:

.myForm {
    position: relative;
    font-size: 0;
    line-height: 0;
}

.imgWrapper {
    position: relative;
    display: inline-block;
    width: 33.3333333%;
    box-sizing: border-box;
    background: tomato;
}

img {
    width: 100%;
    height: 100%;
}

<form class="myForm">

</form>

I would like to force the empty images to have the same size as the others. —I don't know if this can be done with flexbox, but I prefer to avoid it—. I think I can do this adding another wrapper, but I would prefer to avoid it.

Thanks in advance!

Body:
I would prefer doing flexboxes. It's as simple as...

CSS:

.myForm {
    position: relative;
    font-size: 0;
    line-height: 0;
    display: flex;
}

.imgWrapper {

    position: relative;
    display: inline-block;
    width: 33.3333333%;
    box-sizing: border-box;
    background: tomato;
}

img {
    width: 100%;
    height: 100%;
}

HTML:

<form class="myForm">
    <div class="imgWrapper">
        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>
    <div class="imgWrapper">
        <img src="">
    </div>
    <div class="imgWrapper">
        <img src="http://www.whizzpast.com/wordpress/wp-content/uploads/2015/04/vintage-cats-14.jpg">
    </div>

</form>

Example here. I'm assuming you want the empty background image to have a height. Other solutions suggest hiding it entirely, which is an option as well.


问:
Impossible to edit inputs except the first of a ion list
I'm a beginner in ionic. The app works well in Chromium. When android built, it's impossible to edit again the last 3 inputs if all the inputs have been filled.Here the html:

```<code><ion-header>
<ion-navbar color="danger">
<ion-title>Ajouter une seance</ion-title>
</ion-navbar>

</ion-header>

<ion-content padding>
<ion-list>

<ion-item>
<ion-label fixed>Duree</ion-label>
<ion-input type="time" step="2" value="0" ></ion-input>
</ion-item>

<ion-item>
<ion-label fixed>Date</ion-label>
<ion-input type="date" value="0"></ion-input>
</ion-item>
<ion-item>
<ion-label fixed>Distance(km):</ion-label>
<ion-input type="number" ></ion-input>
</ion-item>

<ion-item>
<ion-label fixed>FC moyenne</ion-label>
<ion-input type="number" ></ion-input>
</ion-item>

</ion-list>
</ion-content>
</code>```

It's probably obvious. Thanks for the help.

答:
I found a solution where the ion-inputs don't loose the focus and stay editable . I removed in the given code, the ion-header, ion-content and ion list tags. Now, it works perfectly with Android. But as a new user of ionic, I don't really understand what I loose by removing those tags.

UPDATE

I finally found a solution:
in the scss, add:

```<code>.input-cover {

   position: static;

}
</code>```

Now the input are always focusable and I can use ion-content, ion-header.

Body:
I'm a beginner in ionic. The app works well in Chromium. When android built, it's impossible to edit again the last 3 inputs if all the inputs have been filled.Here the html:

<ion-header>
<ion-navbar color="danger">
<ion-title>Ajouter une seance</ion-title>
</ion-navbar>

</ion-header>

<ion-content padding>
<ion-list>

<ion-item>
<ion-label fixed>Duree</ion-label>
<ion-input type="time" step="2" value="0" ></ion-input>
</ion-item>

<ion-item>
<ion-label fixed>Date</ion-label>
<ion-input type="date" value="0"></ion-input>
</ion-item>
<ion-item>
<ion-label fixed>Distance(km):</ion-label>
<ion-input type="number" ></ion-input>
</ion-item>

<ion-item>
<ion-label fixed>FC moyenne</ion-label>
<ion-input type="number" ></ion-input>
</ion-item>

</ion-list>
</ion-content>

It's probably obvious. Thanks for the help.

Body:
I found a solution where the ion-inputs don't loose the focus and stay editable . I removed in the given code, the ion-header, ion-content and ion list tags. Now, it works perfectly with Android. But as a new user of ionic, I don't really understand what I loose by removing those tags.

UPDATE

I finally found a solution:
in the scss, add:

.input-cover {

   position: static;

}

Now the input are always focusable and I can use ion-content, ion-header.


问:
Kubernetes Autoscaler missing node
I’m having an issue with what I believe to be the k8s the autoscaler.

The autoscaler launched a new cluster after a recent deploy (and I can see that instance on EC2, where our k8s deployment’s hosted), but it doesn’t show up when I do kubectl get nodes.

```<code>kubectl get nodes
NAME                             STATUS    ROLES     AGE       VERSION
ip-172-20-110-212.ec2.internal   Ready     master    322d      v1.5.1
ip-172-20-129-59.ec2.internal    Ready     master    322d      v1.5.1
ip-172-20-153-170.ec2.internal   Ready     <none>    322d      v1.5.1
ip-172-20-160-119.ec2.internal   Ready     master    322d      v1.5.1
ip-172-20-162-94.ec2.internal    Ready     <none>    316d      v1.5.1
ip-172-20-166-194.ec2.internal   Ready     <none>    322d      v1.5.1
ip-172-20-79-1.ec2.internal      Ready     <none>    112d      v1.5.1
ip-172-20-92-163.ec2.internal    Ready     <none>    322d      v1.5.1
</code>```

Further, a kube-proxy pod that matches this “missing” node’s IP does show up, but is killed and relaunched every 30 seconds.

```<code>kubectl get pods
kube-proxy-ip-172-20-181-122.ec2.internal                1/1       Running   0          17s
</code>```

答: I ended up manually deleting the EC2 instance. The autoscaler immediately relaunched a new instance and everything worked fine after. </p>

Title: Kubernetes Autoscaler missing node

Body:
I’m having an issue with what I believe to be the k8s the autoscaler.

The autoscaler launched a new cluster after a recent deploy (and I can see that instance on EC2, where our k8s deployment’s hosted), but it doesn’t show up when I do kubectl get nodes.

kubectl get nodes
NAME                             STATUS    ROLES     AGE       VERSION
ip-172-20-110-212.ec2.internal   Ready     master    322d      v1.5.1
ip-172-20-129-59.ec2.internal    Ready     master    322d      v1.5.1
ip-172-20-153-170.ec2.internal   Ready     <none>    322d      v1.5.1
ip-172-20-160-119.ec2.internal   Ready     master    322d      v1.5.1
ip-172-20-162-94.ec2.internal    Ready     <none>    316d      v1.5.1
ip-172-20-166-194.ec2.internal   Ready     <none>    322d      v1.5.1
ip-172-20-79-1.ec2.internal      Ready     <none>    112d      v1.5.1
ip-172-20-92-163.ec2.internal    Ready     <none>    322d      v1.5.1

Further, a kube-proxy pod that matches this “missing” node’s IP does show up, but is killed and relaunched every 30 seconds.

kubectl get pods
kube-proxy-ip-172-20-181-122.ec2.internal                1/1       Running   0          17s


问:
react component method binding with arrow function (class properties)
I heard that this is the cool way to define function instead of binding them in constructor:

```<code>class Comp extends React.Component {
    delete = id => {

    }

    render() {}
}
</code>```

but when I try to build I get:

Module build failed: SyntaxError: Unexpected token (7:15)

pointing to equal sign after delete

what I am missing?

答:
You need an additional babel plugin for this feature:

https://www.npmjs.com/package/babel-plugin-transform-class-properties

Body:
I heard that this is the cool way to define function instead of binding them in constructor:

class Comp extends React.Component {
    delete = id => {

    }

    render() {}
}

but when I try to build I get:

Module build failed: SyntaxError: Unexpected token (7:15)

pointing to equal sign after delete

what I am missing?


问:
Sudoku solver is slow, needs considering constraints earlier
I have an NxN sudoku solver written in prolog. The code below works fine for 4*4 solving. (I have some Domain infos) But it is slow for 9x9. I've tried many way to improve the create row function, that it is already considering that every value in a row should be unique (and must be contained in its domain), but they did not work.
How could I improve this without any librarys?

```<code>all_distinct(X) :-
    sort(X, Sorted),
    length(X, OriginalLength),
    length(Sorted, SortedLength),
    OriginalLength == SortedLength.

 good_by_coulmns(Solution) :- length(Solution, Length),
                              forall((between(1, Length, X), get_column(Solution, X, Y)),
                              all_distinct(Y)).
get_area(Solution, X, Y, Z) :- length(Solution, Length),
                               SQRootF is sqrt(Length),
                               SQRoot is round(SQRootF),
                               MinCol is SQRoot * (X-1) + 1,
                               MinRow is SQRoot * (Y-1) + 1,
                               matrix_block(MinRow, MinCol, SQRoot, SQRoot, Solution, A), flatten2(A,Z).

good_by_areas(Solution) :- length(Solution, Length),
                           SQRootF is sqrt(Length), SQRoot is round(SQRootF),
                           forall((between(1, SQRoot, X), between(1, SQRoot, Y), get_area(Solution, X, Y, Z)),
                           all_distinct(Z)).

createRow(Solution, Domain, Row) :- maplist(member, Row, Domain),
                                    all_distinct(Row),
                                    good_by_coulmns(Solution).%, write(Solution), nl.

tryToSolve(Domains, Solution) :- length(Solution, L), length(Domains, L), !,
                                 maplist(createRow(Solution), Domains, Solution),
                                 good_by_coulmns(Solution),
                                 good_by_areas(Solution).
</code>```

I can give the missing rules if needed, but this is working fine sofar, so we can use these as building blocks.

答:
The question is more about A.I then programming.

Well, you need some constraints for your sudoku in order to let it work faster. There is a constraint,however it's much work so i will explain and write it in mathematics form and it depends how you implemented your code and you can easily adopt it:

Idea:  The basic idea is that when you are given some sudoku then you can immediately fill few places so that at many branches program will not go into depth and then fail and then backtrack , instead it's better if it fails at some higher node. Look below at the picture, If you place this constraint then it's possible to block the way for prolog at 6 places and allow it only at 3 places because every row has 9 elements. In many cases it will not explore the nodes where i have marked blue.Without constraint it will go down till the end and you see how many extra branches it explores.

How? We exploit the properties of sudoku:

Rules: Every row , every colum and every grid has unique elements.

Algorithm:  When you are given some (sudoku-table) then you have to check first three lines(0,1,2) if they have any element which is same in any of two rows. For example for every element from first row you have to check if that element is in 2nd or third row if not then go to second row and try to find an element which is in second and third row. Here are two possibilities:

You have no match: If first three lines don't have any same element then go to the next three line (3,4,5) and find there and then line (6,7,8).

Note: You have to check only those lines who form a grid(3x3 matrix) together.For example rows (0,1,2) are together then (3,4,5) are together and then (6,7,8) are together.

You have a match: Suppose you found a match in rows (0,2). Since each row can have a unique element then we know that the this element should be in row 1 but how do we know that the resulting row is 1 ,well , we need a formula. see next:

Mathematics form: You can get always resulting row by subtraction. We had a match at row 0  and row 2. Sine these three rows are together so we take sum of their row number (0 + 1 + 2 = 3). Since we work with variables and you match at (i = 0 and j = 2) and your total sum = 3

and sum- i - j = 1 so the new element should be in row 1 . This formula is always valid: think that you have match at row numbers (i = 4 and j = 5) then sum of these three row numbers

is 4 + 5 + 6 = 15 and subtract 15 - 4 -5 = 5. However there are alternative ways but we work with variable so we need to know in which row we have to place the element from which we have a match in other two rows.

Determining grid: Once you have determined in which row your new element will lie then the next step is to check in which grid it will lie because every row is a part of three grids(3x3 matrices). For example rows 0 has elements (0,1,2) in first grid then (3,4,5) in second grid and then (6,7,8) in third grid.

In total you have (9) subgrids and starting from (0 to 8).

Relation between subgrids and rows: We have only infromation about rows so we need to find relation between rows and grid numbers. It's a NxN matrix so height of a grid is equal to the width of the grid(3x3) that means that every three rows together form 3 grids because the length of the rows is 9  and length of the grid in 3 so we get 3 grids of height 3 and length 3.Example: rows (0,1,2) form three girds starting at 0 ,1 ,2 and then rows (4,5,6) from another3 grids: gridnumber(4,5,6) .

We can get their grid number by doing this : (suppose at row 0 we had a match at colum 4  with a row number 2 and colum number 2 then we should get grid 0 and grid 1(respt) because first grid is grid 0(colum: 0 1 2).

We use this formula to get a grid number in one dimensional list.

(mod(x,9)/3) + 3*(x/27)

We know now that grid 1 and 2 can't have this element because in every grid we need a unique elemen from 1 to 9. SO it should be grid 0 but how do get resulting grid, well , we can get that again by taking sum of the three row numbers (because number of rows are equal to number of grid) which is = 3 and subtract the grid number of other two grids which was(0+1) then we get grid 2.

We are not done yet , we need convert this thing to one index because we work mostly with one dimensional list. So this formula give exact place:

formula: x = (newRow)*9 + (newGrid)*3  and x is our place. You can verify this formula by pluging in values.Now we get exact three slots where out our element can be placed.  At this point you say that either list[x] = list[i] or list[x+1] = list[i] or list[x+2] = list[i].

Body:
I have an NxN sudoku solver written in prolog. The code below works fine for 4*4 solving. (I have some Domain infos) But it is slow for 9x9. I've tried many way to improve the create row function, that it is already considering that every value in a row should be unique (and must be contained in its domain), but they did not work.
How could I improve this without any librarys?

all_distinct(X) :-
    sort(X, Sorted),
    length(X, OriginalLength),
    length(Sorted, SortedLength),
    OriginalLength == SortedLength.

 good_by_coulmns(Solution) :- length(Solution, Length),
                              forall((between(1, Length, X), get_column(Solution, X, Y)),
                              all_distinct(Y)).
get_area(Solution, X, Y, Z) :- length(Solution, Length),
                               SQRootF is sqrt(Length),
                               SQRoot is round(SQRootF),
                               MinCol is SQRoot * (X-1) + 1,
                               MinRow is SQRoot * (Y-1) + 1,
                               matrix_block(MinRow, MinCol, SQRoot, SQRoot, Solution, A), flatten2(A,Z).

good_by_areas(Solution) :- length(Solution, Length),
                           SQRootF is sqrt(Length), SQRoot is round(SQRootF),
                           forall((between(1, SQRoot, X), between(1, SQRoot, Y), get_area(Solution, X, Y, Z)),
                           all_distinct(Z)).

createRow(Solution, Domain, Row) :- maplist(member, Row, Domain),
                                    all_distinct(Row),
                                    good_by_coulmns(Solution).%, write(Solution), nl.

tryToSolve(Domains, Solution) :- length(Solution, L), length(Domains, L), !,
                                 maplist(createRow(Solution), Domains, Solution),
                                 good_by_coulmns(Solution),
                                 good_by_areas(Solution).

I can give the missing rules if needed, but this is working fine sofar, so we can use these as building blocks.