问:
Material UI doesn't support colored text on multiline textfield (React)
So I am trying to use the material ui library in a react app. I have found that seemingly the styling of the colored text doesnt work for multiline textfields. Look at this example:

```<code>import React, { Component } from 'react';
import axios from 'axios';
import ListContact from './ListContact';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import Button from './Button';
import {orange500, blue500} from 'material-ui/styles/colors';

const styles = {
  textInput: {
    marginRight: '10px',
    color: orange500,
    // #F3C677
  },
  textInputInput: {
    color: orange500,
    // #F3C677
  },
};

class ContactsPage extends Component {

    {/*.......*/}

                  <TextField
                    hintText="notes"
                    onChange={(e)=>this.setState({notes: e.target.value })}
                    style={styles.textInput}
                    inputStyle={styles.textInputInput}
                    multiLine={true}
                    rows={2}
                    /><br/>

    {/*.......*/}
</code>```

So the above doesn't properly style the textfield text color. However if I get rid of the multiLine and rows attributes it works correctly (either with the hex color or the color supplied by the material UI library). This is very frustrating for me as it breaks the style I was aiming at. If anyone knows a fix for this I would really appreciate it. I think there might not be however. If you go to http://www.material-ui.com/#/components/text-field you will notice that they have very not included an example of a multiline with styled background text color, although they have almost every other example. Hmm.....

答:
As per DOC:

```<code>inputStyle:
</code>```

Override the inline-styles of the TextField's input element.

When multiLine is false: define the style of the input element.

When multiLine is true: define the style of the container of the textarea.

```<code>textareaStyle:
</code>```

Override the inline-styles of the TextField's textarea element. The
  TextField use either a textarea or an input, this property has
  effects only when multiLine is true.

So you need to use textareaStyle for styling of text when multiline is true, like this:

```<code><TextField
    rows={2}
    hintText="notes"
    multiLine={true}
    style={styles.textInput}
    textareaStyle={styles.textInputInput}
    onChange={(e)=>this.setState({notes: e.target.value })}
/>
</code>```

Body:
So I am trying to use the material ui library in a react app. I have found that seemingly the styling of the colored text doesnt work for multiline textfields. Look at this example:

import React, { Component } from 'react';
import axios from 'axios';
import ListContact from './ListContact';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import Button from './Button';
import {orange500, blue500} from 'material-ui/styles/colors';

const styles = {
  textInput: {
    marginRight: '10px',
    color: orange500,
    // #F3C677
  },
  textInputInput: {
    color: orange500,
    // #F3C677
  },
};

class ContactsPage extends Component {

    {/*.......*/}

                  <TextField
                    hintText="notes"
                    onChange={(e)=>this.setState({notes: e.target.value })}
                    style={styles.textInput}
                    inputStyle={styles.textInputInput}
                    multiLine={true}
                    rows={2}
                    />

    {/*.......*/}

So the above doesn't properly style the textfield text color. However if I get rid of the multiLine and rows attributes it works correctly (either with the hex color or the color supplied by the material UI library). This is very frustrating for me as it breaks the style I was aiming at. If anyone knows a fix for this I would really appreciate it. I think there might not be however. If you go to http://www.material-ui.com/#/components/text-field you will notice that they have very not included an example of a multiline with styled background text color, although they have almost every other example. Hmm.....

Body:
As per DOC:

inputStyle:

Override the inline-styles of the TextField's input element.

When multiLine is false: define the style of the input element.

When multiLine is true: define the style of the container of the textarea.

textareaStyle:

Override the inline-styles of the TextField's textarea element. The
  TextField use either a textarea or an input, this property has
  effects only when multiLine is true.

So you need to use textareaStyle for styling of text when multiline is true, like this:

<TextField
    rows={2}
    hintText="notes"
    multiLine={true}
    style={styles.textInput}
    textareaStyle={styles.textInputInput}
    onChange={(e)=>this.setState({notes: e.target.value })}
/>


来源: stackexchange

问:
Vue.js how to define methods on the instance
Hi I am trying to add json data to an element. I get the data via a jsonp call to an external API. but somehow vue does not recognize that the variable is there. Since the app is in laravel I read on laracasts forum that the data and methods properties should be defined in components, but that does not also solve my problem. I am using vue.js2 and laravel 5.4
I get the following error:

app.js: [Vue warn]: Property or method "names" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

here is my code:

app.js

```<code>Vue.component('search',
 {
    template: '<div class="panel-heading" ></div>',
      data: function(){
        return {
           names: []
        }
    },

    methods:  {
         getData: function(){
             var self = this;
              // GET request
           this.$http.jsonp(url,
           {
            jsonpCallback: "JSON_CALLBACK"
            })
           .then(
               response=>{
                  this.names = response.body
               })}

      }
 });

const app = new Vue({
    el: '#search'
});
</code>```

blade template

```<code><div id='search'>
<search v-for='name in names'>
@{{name.label.eng}}
</search>
</div>
</code>```

答:
You are trying to reference the names property in your parent template, but names is a property of your component.

However, there is no need for a component here. Obviously you could use a component, but in that case you would need to move the template that references names down into the component. Instead, here I am removing the component.

```<code>const app = new Vue({
  el: '#search',
  data:{
    names: []
  },
  methods:  {
    getData(){
      this.$http.jsonp(url, {jsonpCallback: "JSON_CALLBACK"})
       .then(response => this.names = response.body)
    }
  },
  mounted(){
    this.getData()
  }
});
</code>```

And your template

```<code><div id='search'>
  <div v-for='name in names' class="panel-heading">
    @{{name.label.eng}}
  </div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I am trying to add json data to an element. I get the data via a jsonp call to an external API. but somehow vue does not recognize that the variable is there. Since the app is in laravel I read on laracasts forum that the data and methods properties should be defined in components, but that does not also solve my problem. I am using vue.js2 and laravel 5.4
I get the following error:

app.js: [Vue warn]: Property or method "names" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

here is my code:

app.js

Vue.component('search',
 {
    template: '

',
      data: function(){
        return {
           names: []
        }
    },

    methods:  {
         getData: function(){
             var self = this;
              // GET request
           this.$http.jsonp(url,
           {
            jsonpCallback: "JSON_CALLBACK"
            })
           .then(
               response=>{
                  this.names = response.body
               })}

      }
 });

const app = new Vue({
    el: '#search'
});

blade template

<search v-for='name in names'>
@{{name.label.eng}}
</search>

Body:
You are trying to reference the names property in your parent template, but names is a property of your component.

However, there is no need for a component here. Obviously you could use a component, but in that case you would need to move the template that references names down into the component. Instead, here I am removing the component.

const app = new Vue({
  el: '#search',
  data:{
    names: []
  },
  methods:  {
    getData(){
      this.$http.jsonp(url, {jsonpCallback: "JSON_CALLBACK"})
       .then(response => this.names = response.body)
    }
  },
  mounted(){
    this.getData()
  }
});

And your template

<div id='search'>
  <div v-for='name in names' class="panel-heading">
    @{{name.label.eng}}
  </div>
</div>


问:
How to implement the Adobe HTTP Streaming spec without using their Streaming server
As of Flash 10.1, they have added the ability to add bytes into the NetStream object via the appendBytes method (described here http://www.bytearray.org/?p=1689).  The main reason for this addition is that Adobe is finally supporting HTTP streaming of video.  This is great, but it seems that you need to use the Adobe Media Streaming Server (http://www.adobe.com/products/httpdynamicstreaming/) to create the correct video chunks from your existing video to allow for smooth streaming.

I have tried to do a hacked version of HTTP streaming in the past where I swap out the NetStream objects (similar to here http://video.leizhu.com/video.html), but there is always a momentary pause between the chunks.  With the new appendBytes, I tried to do a quick mock up with the two sections of video from the preceding site, but even then, the skip still remains.

Does anyone know how the two consecutive .FLV files needs to be formated in order for the appendBytes method on the NetStream object to create a nice smooth video without a noticeable skip between the segments?

答:
You don't need to use their server.  Wowza supports Adobe's version of HTTP Streaming and you can implement it yourself by segmenting the videos properly and loading all the segments on a standard HTTP server.

Links to all the specs for Adobe's HTTP Streaming are here:

http://help.adobe.com/en_US/HTTPStreaming/1.0/Using/WS9463dbe8dbe45c4c-1ae425bf126054c4d3f-7fff.html

Trying to hack the client to do some custom style http streaming will be a lot more troublesome.

Note that HTTP Streaming does not support streaming several different videos but streams a single file that was broken off into separate segments.

File Packager

A command-line tool that translates on-demand media files into fragments and writes the fragments to F4F files. The File Packager is an offline tool. You can use the File Packager to encrypt files for use with Flash Access. For more information, see Packaging on-demand media.

The File Packager is available from adobe.com and is installed with Adobe® Flash® Media Server to the rootinstall/tools/f4fpackager folder.

Packager download link is on right here: Download File Packager for HTTP Dynamic Streaming

http://www.adobe.com/products/httpdynamicstreaming/

ContentLicense: CC BY-SA 2.5


问:
Does TensorFlow allow definition of variables with undefined size?
Does TensorFlow allow definition of variables with undefined size? For example I can easily define a placeholder with None values in shape - this means that these values can be specified at run time, after the graph is built. But shapes of variables must be supplied before construction of the graph. Is the previous statement true? If it is, why is it so?

答:
Variable shapes can actually be changed after constructing the graph.

Example:

```<code>value = tf.placeholder("float", [None])
x = tf.Variable(value, validate_shape=False)
with_assign_op = tf.assign(x, [1,2,3,4,5], validate_shape=False)

sess = tf.Session()

sess.run(tf.variables_initializer([x]), feed_dict={value: [1,2,3]})
print(sess.run(x)) # [ 1.  2.  3.]

sess.run(tf.variables_initializer([x]), feed_dict={value: [1,2,3,4]})
print(sess.run(x)) # [ 1.  2.  3.  4.]

sess.run(with_assign_op)
print(sess.run(x)) # [ 1.  2.  3.  4.  5.]
</code>```

Body:
Variable shapes can actually be changed after constructing the graph.

Example:

value = tf.placeholder("float", [None])
x = tf.Variable(value, validate_shape=False)
with_assign_op = tf.assign(x, [1,2,3,4,5], validate_shape=False)

sess = tf.Session()

sess.run(tf.variables_initializer([x]), feed_dict={value: [1,2,3]})
print(sess.run(x)) # [ 1.  2.  3.]

sess.run(tf.variables_initializer([x]), feed_dict={value: [1,2,3,4]})
print(sess.run(x)) # [ 1.  2.  3.  4.]

sess.run(with_assign_op)
print(sess.run(x)) # [ 1.  2.  3.  4.  5.]


问:
SSIS 2012 connection manager red arrow
I have project where there is allready connection manager created called ODS, and this connection manager used domain account before, now I have to switch it to user and password, the problem is that when I simple go to edit and change it doesn't work, but when I create new then it works. I saw that there are two icons near the connection manager, red arrow and fx , what does it mean ?

Edit:
OK I assume that fx means that it is parametrized and red arrow means problem with connection. Unfortunally there seems to be a bug, when connection manager is paramterized and there is connection string in parameter it doesn't work locally.

答:
Cause:

Your connection manager goes offline when you make a change to the connection string that is incorrect, ex. spelling error in the server name, and the system can not validate the connection.

To fix it:

Correct the mistake in the connection string

Right click on the connection in the connection manager and un-select the "Work OffLine" option. This remove the "Red Arrow" icon and make your connection "live" again.

Title: SSIS 2012 connection manager red arrow


问:
How to get the value of the attribute of element in angular 2?
I have an HTML span, which has two hyperlinks.

Shirley Setia
Harry
```
</div>
</div>

I have created one angular directive. Which reads the DOM element and the href link. But it only reads the first href only how do I read the second href from the above span so that I can parse it.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Directive, ElementRef, Renderer, HostListener } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Input, Output, EventEmitter } from '@angular/core';

@Directive({
  selector: '[stream-link]' // Attribute selector
})

export class StreamLink {
  constructor(public element: ElementRef, public renderer: Renderer) {

    renderer.listen(element.nativeElement, 'click', (event) => {

      let anchorUrl = this.element.nativeElement.querySelector('a');
      // This anchorUrl shows only first href url
    }
  }
}</code>```

答:
Where on your template are you calling the directive? Is it directly on the  element or is it on a higher level?

The querySelector API only selects the first instance of a html node given a selector, so if you're applying the directive directly on the , there should be no problem with your current implementation cause basically there's just one tag inside the .

If the directive is hosting multiple span tags like:

```<code><div stream-link>
  <span><a href="...">Link 1</a></span>
  <span><a href="...">Link 2</a></span>
  <span><a href="...">Link 3</a></span>
</div>
</code>```

You should use querySelectorAll instead, and that would select all nodes that are nested inside your directive element.

Update:

The output of this.element.nativeElement.querySelectorAll('a') is a NodeList which has the forEach array method built in. Just iterate over the list and get the href property of each element.

```<code>let urls = [];
let nodes = this.element.nativeElement.querySelectorAll('a');
nodes.forEach(node => urls.push(node.href));
</code>```

Body:
I have an HTML span, which has two hyperlinks.

Shirley Setia
Harry

I have created one angular directive. Which reads the DOM element and the href link. But it only reads the first href only how do I read the second href from the above span so that I can parse it.

import { Directive, ElementRef, Renderer, HostListener } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Input, Output, EventEmitter } from '@angular/core';

@Directive({
  selector: '[stream-link]' // Attribute selector
})

export class StreamLink {
  constructor(public element: ElementRef, public renderer: Renderer) {

    renderer.listen(element.nativeElement, 'click', (event) => {

      let anchorUrl = this.element.nativeElement.querySelector('a');
      // This anchorUrl shows only first href url
    }
  }
}

Body:
Where on your template are you calling the directive? Is it directly on the <span> element or is it on a higher level?

The querySelector API only selects the first instance of a html node given a selector, so if you're applying the directive directly on the <span>, there should be no problem with your current implementation cause basically there's just one <a>tag inside the <span>.

If the directive is hosting multiple span tags like:

<div stream-link>
  <span><a href="...">Link 1</a></span>
  <span><a href="...">Link 2</a></span>
  <span><a href="...">Link 3</a></span>
</div>

You should use querySelectorAll instead, and that would select all nodes that are nested inside your directive element.

Update:

The output of this.element.nativeElement.querySelectorAll('a') is a NodeList which has the forEach array method built in. Just iterate over the list and get the href property of each element.

let urls = [];
let nodes = this.element.nativeElement.querySelectorAll('a');
nodes.forEach(node => urls.push(node.href));


问:
How to maximise ChromeDriver while setting up GEB/SPOCK/GROOVY Selenium tests
I am having some issues with ChromeDriver maximising when setting up my tests. The screen just doesn't get any bigger unlike FireFox driver. This is how I have it set up:

```<code>chrome {
        driver = {
            System.setProperty('webdriver.chrome.driver', '.....)
            def chromeDriver = new ChromeDriver()
            chromeDriver.switchTo().window(chromeDriver.getWindowHandle());
            chromeDriver.manage().window().maximize()
            chromeDriver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS)
            chromeDriver
        }
</code>```

Is there something I am missing or doing wrong?

Thanks

答:
You set the size by using this command

driver.manage().window().setSize(new Dimension(1920, 1080))

You can set to your desired dimensions.

Body:
I am having some issues with ChromeDriver maximising when setting up my tests. The screen just doesn't get any bigger unlike FireFox driver. This is how I have it set up:

chrome {
        driver = {
            System.setProperty('webdriver.chrome.driver', '.....)
            def chromeDriver = new ChromeDriver()
            chromeDriver.switchTo().window(chromeDriver.getWindowHandle());
            chromeDriver.manage().window().maximize()
            chromeDriver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS)
            chromeDriver
        }

Is there something I am missing or doing wrong?

Thanks


问:
R customized constraints optim function
Goal: Estimate sigma1 and sigma2 with the "optim" function, while sigma2 must be greater than sigma1

Simulate data (y)

I have the following kind of data y:

```<code>N<-50

delta<-matrix(rep(0, N*N), nrow=N, ncol=N)
 for(i in 1:(N )){
  for (j in 1:N)
    if (i == j+1 | i == j-1){
    delta[i,j] <- 1;
    }
 }

sigma1<-5
sigma2<-10
diagonal=2*sigma1^2+sigma2^2
nondiag<--sigma1^2*delta
Lambda_i<-(diag(diagonal,N)+-nondiag)/diagonal
sig<-as.matrix(diagonal*Lambda_i)
sig

mu<-rep(0, N)
y<-as.vector(mvnfast::rmvn(1,mu, sig))
</code>```

Create maximum likelihood function

```<code>mle<-function(par){
  sigma1<-par[1]
  sigma2<-par[2]
  diagonal=2*sigma1^2+sigma2^2
  nondiag<--sigma1^2*delta
  Lambda_i<-(diag(diagonal,N)+-nondiag)/diagonal
  sig<-as.matrix(diagonal*Lambda_i)

  #lokli
  loglik<--as.numeric(mvnfast::dmvn(matrix(y, byrow=T, ncol=N),mu, sig, log=T))
  loglik
}
</code>```

Optimization

```<code>par <- c(5,5)
fit<-optim(par,mle,hessian=T,
       method="L-BFGS-B",lower=c(0.01,0.01),
       upper=c(30,30))
fit$par
</code>```

Question: How I can set the constraint: "sigma2 always greater sigma1" in the optimization procedure?

答:
Just to follow-up on my comment. We can use two tricks:

Replace all occurrences of sigma2 in your likelihood with (sigma1 + sigma2) to ensure that sigma2 now represents the amount that is added to sigma1

Use exp on sigma2 to ensure that it is non-negative.

The likelihood becomes

```<code>mlenew<-function(par){
  sigma1<-par[1]
  sigma2<-par[2]
  diagonal=2*sigma1^2+(sigma1 + exp(sigma2))^2
  nondiag<--sigma1^2*delta
  Lambda_i<-(diag(diagonal,N)+-nondiag)/diagonal
  sig<-as.matrix(diagonal*Lambda_i)
  #lokli
  loglik<--as.numeric(mvnfast::dmvn(matrix(y, byrow=T, ncol=N),mu, sig, log=T))
  loglik
}
</code>```

If I run you code I get

```<code>> fit<-optim(par,mle,hessian=T,
+        method="L-BFGS-B",lower=c(0.01,0.01),
+        upper=c(30,30))
> fit$par
[1]  1.738656 12.672040
</code>```

With the new code I get

```<code>> fit<-optim(par,mlenew,hessian=T,
+        method="L-BFGS-B",lower=c(0.01,0.01),
+        upper=c(30,30))
> fit$par
[1] 1.737843 2.391921
</code>```

and then you need to "back-transform": The actual value of the old version of sigma2 using the new code is

```<code>> exp(2.391921) + 1.737843
[1] 12.67232
</code>```

Hope this helps.

Title: R customized constraints optim function

Body:
Goal: Estimate sigma1 and sigma2 with the "optim" function, while sigma2 must be greater than sigma1

Simulate data (y)

I have the following kind of data y:

N<-50

delta<-matrix(rep(0, N*N), nrow=N, ncol=N)
 for(i in 1:(N )){
  for (j in 1:N)
    if (i == j+1 | i == j-1){
    delta[i,j] <- 1;
    }
 }

sigma1<-5
sigma2<-10
diagonal=2*sigma1^2+sigma2^2
nondiag<--sigma1^2*delta
Lambda_i<-(diag(diagonal,N)+-nondiag)/diagonal
sig<-as.matrix(diagonal*Lambda_i)
sig

mu<-rep(0, N)
y<-as.vector(mvnfast::rmvn(1,mu, sig))

Create maximum likelihood function

mle<-function(par){
  sigma1<-par[1]
  sigma2<-par[2]
  diagonal=2*sigma1^2+sigma2^2
  nondiag<--sigma1^2*delta
  Lambda_i<-(diag(diagonal,N)+-nondiag)/diagonal
  sig<-as.matrix(diagonal*Lambda_i)

  #lokli
  loglik<--as.numeric(mvnfast::dmvn(matrix(y, byrow=T, ncol=N),mu, sig, log=T))
  loglik
}

Optimization

par <- c(5,5)
fit<-optim(par,mle,hessian=T,
       method="L-BFGS-B",lower=c(0.01,0.01),
       upper=c(30,30))
fit$par

Question: How I can set the constraint: "sigma2 always greater sigma1" in the optimization procedure?

Body:
Just to follow-up on my comment. We can use two tricks:

Replace all occurrences of sigma2 in your likelihood with (sigma1 + sigma2) to ensure that sigma2 now represents the amount that is added to sigma1

Use exp on sigma2 to ensure that it is non-negative.

The likelihood becomes

mlenew<-function(par){
  sigma1<-par[1]
  sigma2<-par[2]
  diagonal=2*sigma1^2+(sigma1 + exp(sigma2))^2
  nondiag<--sigma1^2*delta
  Lambda_i<-(diag(diagonal,N)+-nondiag)/diagonal
  sig<-as.matrix(diagonal*Lambda_i)
  #lokli
  loglik<--as.numeric(mvnfast::dmvn(matrix(y, byrow=T, ncol=N),mu, sig, log=T))
  loglik
}

If I run you code I get

> fit<-optim(par,mle,hessian=T,
+        method="L-BFGS-B",lower=c(0.01,0.01),
+        upper=c(30,30))
> fit$par
[1]  1.738656 12.672040

With the new code I get

> fit<-optim(par,mlenew,hessian=T,
+        method="L-BFGS-B",lower=c(0.01,0.01),
+        upper=c(30,30))
> fit$par
[1] 1.737843 2.391921

and then you need to "back-transform": The actual value of the old version of sigma2 using the new code is

> exp(2.391921) + 1.737843
[1] 12.67232

Hope this helps.


问:
Cognos security issue
How to restrict query studio to only one group in Cognos. My manager wants me to give the access to query studio only to one group and no other user who is not part of that group should have access to query studio? If i delete the existing capabilities of query studio and add that group to the capabilities,. Will that affect the whole system?  It has authors,directory administrators, Everyone, query users and report administrators in its permissions. What happens if i delete all of them and add just the group that needs access? Any help will be greatly appreciated.</p>

答:
Cognos security is a union of all of the groups and capabilities a user belongs to.  So if you only want certain users to have the capability to use Query Studio, you need to have a group that is assigned the capability for Query Studio and remove other groups who should not have access.

You will likely end up with some users who belong to more than one LDAP group (for instance, a user may belong to "Department A" which gives them object visibility to reports for their department, and "Query Studio Users" which gives them the capability to use Query Studio).

The way I approach it is to identify each user between two functions: their "capability" i.e. what they can do in Cognos, and their "visibilty" i.e. what they should see.  You should have enough LDAP groups to cover all combinations.

Title: Cognos security issue


问:
Long-running operation to update an Android appwidget
I have a widget that needs to perform a potentially long-running operation in onUpdate(). Just performing the operation directly resulted in ANR's. To solve this, my first attempt was to create a thread therein. I noticed that the widget would not get updated in some cases. My guess here is that once onUpdate() exits, Android may kill the process along with the unfinished thread.

My next attempt was to create an intent service. The widget's onUpdate() just starts the intent service, which does the work directly and updates the widget when done. This works, but much to my surprise it appears that onHandleIntent() is single-threaded. If I have two widgets, and then both update and start the intent service, they update sequentially ...

The two widgets case is not really important, but I'm just wondering about a best practice for this type of pattern.

To solve the two widgets case I ended up updating all the widget instances with the same data whenever any one of them is clicked. e.g., I perform the long-running process once and apply the results to all the widget instances. In my scenario this doesn't matter, but for many widgets, it might be important not to do that.

Thoughts?

答:
make onUpdate call your own function to cycle through the widgets and update them.  Do your async task before the cycle.  You will want two separate actions, one that asks for the update to start, and one that your IntentService will broadcast to let the widgets know they are finished.  Hope this helps.

```<code>    @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    updateWidget(context, appWidgetManager, appWidgetIds);
}

private void updateWidget(Context context){
    ComponentName widget = new ComponentName(context, MyWidget.class);
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(widget);
    updateWidget(context, appWidgetManager, appWidgetIds);
}

private void updateWidget(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    final boolean isEnabled = true; //took out code didn't want you to see
    // start intent service here
    for(int i = 0; i< appWidgetIds.length; i++){
        int appWidgetId = appWidgetIds[i];
        Intent intent = new Intent(isEnabled ? ACTION_TOGGLE_OFF : ACTION_TOGGLE_ON);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setOnClickPendingIntent(R.id.widget , pi);
        views.setImageViewResource(R.id.widget_image, isEnabled? R.drawable.widget_on : R.drawable.widget_off);

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
make onUpdate call your own function to cycle through the widgets and update them.  Do your async task before the cycle.  You will want two separate actions, one that asks for the update to start, and one that your IntentService will broadcast to let the widgets know they are finished.  Hope this helps.

    @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    updateWidget(context, appWidgetManager, appWidgetIds);
}

private void updateWidget(Context context){
    ComponentName widget = new ComponentName(context, MyWidget.class);
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(widget);
    updateWidget(context, appWidgetManager, appWidgetIds);
}

private void updateWidget(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    final boolean isEnabled = true; //took out code didn't want you to see
    // start intent service here
    for(int i = 0; i< appWidgetIds.length; i++){
        int appWidgetId = appWidgetIds[i];
        Intent intent = new Intent(isEnabled ? ACTION_TOGGLE_OFF : ACTION_TOGGLE_ON);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setOnClickPendingIntent(R.id.widget , pi);
        views.setImageViewResource(R.id.widget_image, isEnabled? R.drawable.widget_on : R.drawable.widget_off);

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}


问:
Word VBA macro button only works once
I am trying to create a button that copies the contents of an entire page, and pastes it to a new page within the same document. When I first formatted this as a MacroButton (CTRL + F9) it would work multiple times. Now I have tried it using a command button under Legacy forms (Developer tab) as a click event, and it will only work once. I am not sure why this is occuring. Here is my code:

```<code>Private Sub AddPage3_Click()
 Const wdPageBreak = 7
 ActiveDocument.Bookmarks("\page").Range.Copy
 Selection.InsertBreak (wdPageBreak)
 Selection.Paste
 Selection.TypeBackspace
 Selection.TypeBackspace
End Sub
</code>```

When I press the button, it will create another page in the document with the contents of the active page (the page the button is located on), but it will not work a second time. If you have any suggestions please let me know :)!

答:
After copy/paste, you can rename your commandbutton as follows and the commandbutton keeps running each time:</p>

```<code>Private Sub AddPage3_Click()
Dim shp As InlineShape
Const wdPageBreak = 7
ActiveDocument.Bookmarks("\page").Range.Copy
Selection.InsertBreak (wdPageBreak)
Selection.Paste
Selection.TypeBackspace
Selection.TypeBackspace
For Each shp In ActiveDocument.InlineShapes
    On Error Resume Next
    If shp.OLEFormat.ClassType = "Forms.CommandButton.1" Then
        If shp.OLEFormat.Object.Name = "AddPage31" Then
            shp.OLEFormat.Object.Name = "AddPage3"
        End If
    End If
Next
End Sub
</code>```

Title: Word VBA macro button only works once

Body:
I am trying to create a button that copies the contents of an entire page, and pastes it to a new page within the same document. When I first formatted this as a MacroButton (CTRL + F9) it would work multiple times. Now I have tried it using a command button under Legacy forms (Developer tab) as a click event, and it will only work once. I am not sure why this is occuring. Here is my code:

Private Sub AddPage3_Click()
 Const wdPageBreak = 7
 ActiveDocument.Bookmarks("\page").Range.Copy
 Selection.InsertBreak (wdPageBreak)
 Selection.Paste
 Selection.TypeBackspace
 Selection.TypeBackspace
End Sub

When I press the button, it will create another page in the document with the contents of the active page (the page the button is located on), but it will not work a second time. If you have any suggestions please let me know :)!

Body:
After copy/paste, you can rename your commandbutton as follows and the commandbutton keeps running each time:

Private Sub AddPage3_Click()
Dim shp As InlineShape
Const wdPageBreak = 7
ActiveDocument.Bookmarks("\page").Range.Copy
Selection.InsertBreak (wdPageBreak)
Selection.Paste
Selection.TypeBackspace
Selection.TypeBackspace
For Each shp In ActiveDocument.InlineShapes
    On Error Resume Next
    If shp.OLEFormat.ClassType = "Forms.CommandButton.1" Then
        If shp.OLEFormat.Object.Name = "AddPage31" Then
            shp.OLEFormat.Object.Name = "AddPage3"
        End If
    End If
Next
End Sub


问:
Can you create dictionaries with just a single function?
As a total beginner I'm quite proud of this function. Although I believe there's probably an easier, more pythonic way of doing the exact same thing:

```<code>Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def RawDict(keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)
    return zip(dictKeys, dictValues)

GenDict = dict(RawDict(Genes, Mutations))

print(GenDict)
</code>```

The function above is a rather overcomplicated (I think) way of putting several values (mutations) within keys (genes). However I was wondering if I could tweak this so I could get a dictionary by just doing this:

```<code>dict(GenDict, Genes, Mutations)

print(GenDict)
</code>```

My struggle involves that when I use dict within the function, this won't work:

```<code>Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def fullDict(dictName, keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)
    dictName = dict(RawDict(Genes, Mutations))

fullDict(GenDict, Genes, Mutations)

print(GenDict)
</code>```

The above just won't work as GenDict is not defined.

答:
From what I understand, you want to move from this:

```<code>gen_dict = make_dictionary(genes, mutations)
</code>```

to this:

```<code>make_dictionary(gen_dict, genes, mutations)
</code>```

where the make_dictionary function "creates" the variable gen_dict.

Unfortunately, this isn't really how variables work. If you want to define a variable called GenDict, the way to do this is to use GenDict = .... You could do something like this:

```<code>gen_dict = {}
fill_dictionary(gen_dict, genes, mutations)
</code>```

This creates a variable called gen_dict and assigns it to a new, empty dictionary. Your function would then go through and add things to that dictionary:

```<code>def fill_dictionary(d, genes, mutations):
    for g in genes:
      d[g] = [m for m in mutations if m.startswith(g)]
</code>```

But calling a function cannot cause a new variable to appear in the caller's scope. (This is not completely true, because of globals(), but for most intents and purposes, it is.)

(By the way, there is a one-liner that will create the dictionary: dictionary = { g : [m for m in mutations if m.startswith(g+".")] for g in genes }. Search for list comprehensions and dictionary comprehensions on Google or StackOverflow -- they are amazing!)

Body:
As a total beginner I'm quite proud of this function. Although I believe there's probably an easier, more pythonic way of doing the exact same thing:

Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def RawDict(keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)
    return zip(dictKeys, dictValues)

GenDict = dict(RawDict(Genes, Mutations))

print(GenDict)

The function above is a rather overcomplicated (I think) way of putting several values (mutations) within keys (genes). However I was wondering if I could tweak this so I could get a dictionary by just doing this:

dict(GenDict, Genes, Mutations)

print(GenDict)

My struggle involves that when I use dict within the function, this won't work:

Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def fullDict(dictName, keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)
    dictName = dict(RawDict(Genes, Mutations))

fullDict(GenDict, Genes, Mutations)

print(GenDict)

The above just won't work as GenDict is not defined.

Body:
From what I understand, you want to move from this:

gen_dict = make_dictionary(genes, mutations)

to this:

make_dictionary(gen_dict, genes, mutations)

where the make_dictionary function "creates" the variable gen_dict.

Unfortunately, this isn't really how variables work. If you want to define a variable called GenDict, the way to do this is to use GenDict = .... You could do something like this:

gen_dict = {}
fill_dictionary(gen_dict, genes, mutations)

This creates a variable called gen_dict and assigns it to a new, empty dictionary. Your function would then go through and add things to that dictionary:

def fill_dictionary(d, genes, mutations):
    for g in genes:
      d[g] = [m for m in mutations if m.startswith(g)]

But calling a function cannot cause a new variable to appear in the caller's scope. (This is not completely true, because of globals(), but for most intents and purposes, it is.)

(By the way, there is a one-liner that will create the dictionary: dictionary = { g : [m for m in mutations if m.startswith(g+".")] for g in genes }. Search for list comprehensions and dictionary comprehensions on Google or StackOverflow -- they are amazing!)


问:
Working with linked list + struct C
Here is the linked list and the struct:

```<code>#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)
struct Frame
{
    char *name;
    unsigned int duration;
    char *path;  // may change to FILE*
};

typedef struct Frame frame_t;
struct Link
{
    frame_t *frame;
    struct Link *next;
};

typedef struct Link link_t;
</code>```

And here's my function:

```<code>link_t* createFrame(char name[], int duration, char path[]){
frame_t * temp = (frame_t*)malloc(sizeof(frame_t));
temp->duration = duration;

strncpy(temp->name, name,MAX_NAME_SIZE);
strncpy(temp->path, path,MAX_PATH_SIZE);
link_t* newFrame = (link_t*)malloc(sizeof(link_t));

newFrame->frame = temp;
return newFrame;
}
</code>```

The problem is that the function stop working in the line "strncpy(temp->name)..", the weird thing is that the temp->duration is working but it doesn't work with strings. Error: "Unhandled exception at 0x0F744645 (msvcr120d.dll)"

答:
You need to allocate memory to store strings with strncpy(), in your malloc you allocated only enough to store sizeof(struct Frame) bytes.

You may want to try this instead of strncpy...

```<code>temp->name = strndup(name, MAX_NAME_SIZE);
temp->path = strndup(path,MAX_PATH_SIZE);
</code>```

...if you are insisting on restricting the max size of strings.

Title: Working with linked list + struct C

Body:
Here is the linked list and the struct:

#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)
struct Frame
{
    char *name;
    unsigned int duration;
    char *path;  // may change to FILE*
};

typedef struct Frame frame_t;
struct Link
{
    frame_t *frame;
    struct Link *next;
};

typedef struct Link link_t;

And here's my function:

link_t* createFrame(char name[], int duration, char path[]){
frame_t * temp = (frame_t*)malloc(sizeof(frame_t));
temp->duration = duration;

strncpy(temp->name, name,MAX_NAME_SIZE);
strncpy(temp->path, path,MAX_PATH_SIZE);
link_t* newFrame = (link_t*)malloc(sizeof(link_t));

newFrame->frame = temp;
return newFrame;
}

The problem is that the function stop working in the line "strncpy(temp->name)..", the weird thing is that the temp->duration is working but it doesn't work with strings. Error: "Unhandled exception at 0x0F744645 (msvcr120d.dll)"

Body:
You need to allocate memory to store strings with strncpy(), in your malloc you allocated only enough to store sizeof(struct Frame) bytes.

You may want to try this instead of strncpy...

temp->name = strndup(name, MAX_NAME_SIZE);
temp->path = strndup(path,MAX_PATH_SIZE);

...if you are insisting on restricting the max size of strings.


问:
Persistent button color changes in C# WPF
I am designing a simple application in C# and WPF with multiple buttons that change their color when clicked.

Each individual button changes colors independently to red (1st click) and then to green (on the 2nd click).

I am looking for a way to make this changes persistent between application runs.
In other words, if 1 button has been set to green and 1 button to red, I would like them to keep their color (unless i change it) regardless of how many times I open and close the application. Examples of code that i can use are more than welcomed. Any help or example of code is highly appreciated. Thank you!

This is the WPF:

```<code>    <Button x:Name="btn0" Focusable="False"  Margin="277,100,173,148" Click="btn0_Click" Content="access"/>
    <Button x:Name="btn1" Focusable="False"  Margin="189,100,253,148" Click="btn1_Click" Content="access"/>
</code>```

And here is the code (i know it's a bit messy):

```<code>    namespace WpfApp7
    {
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private bool _IsOn;
    public bool IsOn
    {
        get
        {
            return _IsOn;
        }
        set
        {
            _IsOn = value;
            btn0.Background = _IsOn ? Brushes.Green : Brushes.Red;
        }
    }
    private void btn0_Click(object sender, RoutedEventArgs e)
    {
        IsOn = !IsOn;
    }
    private bool _IsOn1;
    public bool IsOn1
    {
        get
        {
            return _IsOn1;
        }
        set
        {
            _IsOn1 = value;
            btn1.Background = _IsOn1 ? Brushes.Green : Brushes.Red;
        }
    }
    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        IsOn1 = !IsOn1;
    }
}
}
</code>```

答:
First you need to add go to your project settings and add a property:

You can enter the name of the color or the hex value ("#FF007CE4")

Then you bind the color to the property:

```<code><Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        xmlns:properties="clr-namespace:WpfApplication1.Properties"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Name="button" Width="100" Height="30" Background="{Binding Source={x:Static properties:Settings.Default}, Path=Color1, Mode=TwoWay}" Click="button_Click" />
    </Grid>
</Window>
</code>```

To set the color:

```<code>private void button_Click(object sender, RoutedEventArgs e)
{
   if(Properties.Settings.Default.Color1 == "White")
   {
      Properties.Settings.Default.Color1 = "Black";
   }
   else
   {
      Properties.Settings.Default.Color1 = "White";
   }
}
</code>```

Edit:

To save the change of the color you need:

```<code>Properties.Settings.Default.Save();
</code>```

Body:
I am designing a simple application in C# and WPF with multiple buttons that change their color when clicked.

Each individual button changes colors independently to red (1st click) and then to green (on the 2nd click).

I am looking for a way to make this changes persistent between application runs.
In other words, if 1 button has been set to green and 1 button to red, I would like them to keep their color (unless i change it) regardless of how many times I open and close the application. Examples of code that i can use are more than welcomed. Any help or example of code is highly appreciated. Thank you!

This is the WPF:

    <Button x:Name="btn0" Focusable="False"  Margin="277,100,173,148" Click="btn0_Click" Content="access"/>
    <Button x:Name="btn1" Focusable="False"  Margin="189,100,253,148" Click="btn1_Click" Content="access"/>

And here is the code (i know it's a bit messy):

    namespace WpfApp7
    {
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private bool _IsOn;
    public bool IsOn
    {
        get
        {
            return _IsOn;
        }
        set
        {
            _IsOn = value;
            btn0.Background = _IsOn ? Brushes.Green : Brushes.Red;
        }
    }
    private void btn0_Click(object sender, RoutedEventArgs e)
    {
        IsOn = !IsOn;
    }
    private bool _IsOn1;
    public bool IsOn1
    {
        get
        {
            return _IsOn1;
        }
        set
        {
            _IsOn1 = value;
            btn1.Background = _IsOn1 ? Brushes.Green : Brushes.Red;
        }
    }
    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        IsOn1 = !IsOn1;
    }
}
}

Body:
First you need to add go to your project settings and add a property:

You can enter the name of the color or the hex value ("#FF007CE4")

Then you bind the color to the property:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        xmlns:properties="clr-namespace:WpfApplication1.Properties"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Name="button" Width="100" Height="30" Background="{Binding Source={x:Static properties:Settings.Default}, Path=Color1, Mode=TwoWay}" Click="button_Click" />
    </Grid>
</Window>

To set the color:

private void button_Click(object sender, RoutedEventArgs e)
{
   if(Properties.Settings.Default.Color1 == "White")
   {
      Properties.Settings.Default.Color1 = "Black";
   }
   else
   {
      Properties.Settings.Default.Color1 = "White";
   }
}

Edit:

To save the change of the color you need:

Properties.Settings.Default.Save();


问:
Auto increment row and column results to csv file in javascript
I'm converting XML results to CSV using the following code. It will automatically increment the 'row' but I am having to set each 'column' value. I attempted to alter the code but the outcome was not functional. I believe the issue lies within the 'new XML' line but I haven't been able to find any information relating to this. So my question is can how can this be coded to auto increment the column value as well?'

Thank you - Matt

```<code>var length = msg['result'].length();
var x = 0;

for(var i=0;i<length;i++)
{

tmp['row'][x] = new XML("<row/>");
tmp['row'][x]['column1'] = '"'+msg['result'][i]['this'].toString()+'"';
tmp['row'][x]['column2'] = '"'+msg['result'][i]['that'].toString()+'"';
tmp['row'][x]['column3'] = '"'+msg['result'][i]['other'].toString()+'"';

x++;

}
</code>```

答:
So after some more testing and guesswork, I came up with the following that is fucntional and returns the output I am needing:</p>

```<code>var length = msg['result'].length();
var x = 0;
// This is the number of columns I know will be returned
var z = 3;

for(var i=0;i<length;i++)
{

tmp['row'][x] = new XML("<row/>");
tmp['column'][z] = new XML("<column/>");

tmp['row'][x]['column'][z] = '"'+msg['result'][i]['this'].toString()+'"';
tmp['row'][x]['column'][z] = '"'+msg['result'][i]['that'].toString()+'"';
tmp['row'][x]['column'][z] = '"'+msg['result'][i]['other'].toString()+'"';

z++;
x++;
}
</code>```

Body:
I'm converting XML results to CSV using the following code. It will automatically increment the 'row' but I am having to set each 'column' value. I attempted to alter the code but the outcome was not functional. I believe the issue lies within the 'new XML' line but I haven't been able to find any information relating to this. So my question is can how can this be coded to auto increment the column value as well?'

Thank you - Matt

var length = msg['result'].length();
var x = 0;

for(var i=0;i<length;i++)
{

tmp['row'][x] = new XML("<row/>");
tmp['row'][x]['column1'] = '"'+msg['result'][i]['this'].toString()+'"';
tmp['row'][x]['column2'] = '"'+msg['result'][i]['that'].toString()+'"';
tmp['row'][x]['column3'] = '"'+msg['result'][i]['other'].toString()+'"';

x++;

}

Body:
So after some more testing and guesswork, I came up with the following that is fucntional and returns the output I am needing:

var length = msg['result'].length();
var x = 0;
// This is the number of columns I know will be returned
var z = 3;

for(var i=0;i<length;i++)
{

tmp['row'][x] = new XML("<row/>");
tmp['column'][z] = new XML("<column/>");

tmp['row'][x]['column'][z] = '"'+msg['result'][i]['this'].toString()+'"';
tmp['row'][x]['column'][z] = '"'+msg['result'][i]['that'].toString()+'"';
tmp['row'][x]['column'][z] = '"'+msg['result'][i]['other'].toString()+'"';

z++;
x++;
}


问:
angular form how to show changed save button text?
I use angular 1 form to show changed save button text.
The button text should be the follow:

(disabled) save - when initial

(enable) save - when edited or re-edit after saved

(enable) saved - click save button

How can I use a simple method to resolve it?

sample JSFiddle here or the follow code

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
 $scope.buttonText = 'save';

 $scope.save = function (myForm) {
   myForm.$setPristine();
    $scope.buttonText = 'saved';
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
  <form name="myForm">

    <input type="text" ng-model="text1" name="text1">
    <input type="text" ng-model="text2" name="text2">

    <button ng-click="save(myForm)" ng-disabled="myForm.$pristine">
     {{buttonText}}
    </button>

  </form>
</div>
</body></code>```

答:
Change your button markup to this:

```<code><button ng-click="save(myForm)" ng-disabled="myForm.$pristine">
 {{myForm.$pristine?buttonText:'save'}}
</button>
</code>```

Working fiddle

Body:
I use angular 1 form to show changed save button text.
The button text should be the follow:

(disabled) save - when initial

(enable) save - when edited or re-edit after saved

(enable) saved - click save button

How can I use a simple method to resolve it?

sample JSFiddle here or the follow code

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
 $scope.buttonText = 'save';

 $scope.save = function (myForm) {
   myForm.$setPristine();
    $scope.buttonText = 'saved';
  }
});

  <form name="myForm">

    <input type="text" ng-model="text1" name="text1">
    <input type="text" ng-model="text2" name="text2">

    <button ng-click="save(myForm)" ng-disabled="myForm.$pristine">
     {{buttonText}}
    </button>

  </form>

Body:
Change your button markup to this:

<button ng-click="save(myForm)" ng-disabled="myForm.$pristine">
 {{myForm.$pristine?buttonText:'save'}}
</button>

Working fiddle


问:
Does Boost or STL provide a functionlity similar to QString?
Using QString, one can do the following:

```<code>QString const sentence = QString("First name: %1, Last name: %2")
                           .arg("John")
                           .arg("Doe");

// sentence is now "First name: John, Last name: Doe"
</code>```

Does Boost / STL have something similar? I would like to construct a string similar to this way without using sstream << operator.

答: Seems like you want boost.format</p>

Body:
Using QString, one can do the following:

QString const sentence = QString("First name: %1, Last name: %2")
                           .arg("John")
                           .arg("Doe");

// sentence is now "First name: John, Last name: Doe"

Does Boost / STL have something similar? I would like to construct a string similar to this way without using sstream << operator.

Body: Seems like you want boost.format


问:
Check if device can decode video or not using Cordova
I'm using VR view in my Ionic (Cordova) app. VR view's docs state that "some older devices cannot decode video larger than 1080p (1920x1080)".

In my app, the user downloads the video file first, so it's not streaming the video.

I have two videos: one for newer devices (in 4k), and one for the older devices (in 1080p). I want to check if the device is capable of decoding the 4k video. If not, it should download the 1080p video.

How could I check if a device is capable of decoding 4k? I was thinking about trying to play a very short baked-in 4k video and catching the error, but I can't get it to work without the video player showing up. It should be done in the background.

Is there a more elegant solution to this?

答:
I don't see much for native Cordova APIs that respond with what is the maximum supported playback resolution. I personally would try a more elegant approach, just getting the device's resolution and seeing if it is above HD or equal-below HD resolution.

Use the following to figure out the display size in pixels:

function getDeviceDimension() {
    console.log("Device Dimension using PhoneGap");
    console.log("Width = " + screen.width);
    console.log("Height = " + screen.height);
}
```


问:
How to create a completely empty (or close to it) response from asp.net?
I created an HttpModule to restrict access from certain IPs. I want to use as little bandwidth as possible and not return the default IIS 404 page. I would rather return no content at all.

```<code>    private static void OnBeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        app.Response.StatusCode = 404;
        app.Context.Response.Clear();
        app.Context.Response.End();
    }
</code>```

Changing the status code to 200 works and create 0 bytes of content in the response but now I'm curious as to how to do it no matter the statuscode.

答:
```<code><customErrors mode="On" defaultRedirect="~/Error/Index.html">
    <error statusCode="404" redirect="~/Error/404Error.html" />
</customErrors>
</code>```

Add this to your web.config. And of course, adjust urls based on your project.

Body:
I created an HttpModule to restrict access from certain IPs. I want to use as little bandwidth as possible and not return the default IIS 404 page. I would rather return no content at all.

    private static void OnBeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        app.Response.StatusCode = 404;
        app.Context.Response.Clear();
        app.Context.Response.End();
    }

Changing the status code to 200 works and create 0 bytes of content in the response but now I'm curious as to how to do it no matter the statuscode.

Body:
<customErrors mode="On" defaultRedirect="~/Error/Index.html">
    <error statusCode="404" redirect="~/Error/404Error.html" />
</customErrors>

Add this to your web.config. And of course, adjust urls based on your project.


问:
Text Analysis in R - word frequency
I only have R available at work and I have done this before in Python. I need to get a count of each set of incidents in a CSV file. I have done a sentiment analysis in Python, where I had a dictionary Python searched in a  provided a table with the count for each phrase. I am researching how to do this in R and have only found ways to do a general word count using a predetermined frequency. </p>

<p>Please let me know if anyone has any resource links on how to perform this in R. Thank you :) </p>

答:
Here's a place to start: http://tidytextmining.com</p>

```<code>library(tidytext)

text_df %>%
  unnest_tokens(word, text)

library(tidytext)
tidy_books <- original_books %>%
  unnest_tokens(word, text)

tidy_books

tidy_books %>%
  count(word, sort = TRUE)
</code>```

Title: Text Analysis in R - word frequency

Body:
I only have R available at work and I have done this before in Python. I need to get a count of each set of incidents in a CSV file. I have done a sentiment analysis in Python, where I had a dictionary Python searched in a  provided a table with the count for each phrase. I am researching how to do this in R and have only found ways to do a general word count using a predetermined frequency.

Please let me know if anyone has any resource links on how to perform this in R. Thank you :)

Body:
Here's a place to start: http://tidytextmining.com

library(tidytext)

text_df %>%
  unnest_tokens(word, text)

library(tidytext)
tidy_books <- original_books %>%
  unnest_tokens(word, text)

tidy_books

tidy_books %>%
  count(word, sort = TRUE)


问:
DocuSign: Rest API C# get permanent links for signers
I'm using DocuSign's REST API to create envelopes in embedded signing mode. With the function CreateRecipientView i get only a temporary link. But i would prefer to get an permanent link like in the notification mail. How can i get this link/URL? </p>

答:
Getting permanent signing links is not possible using the DocuSign rest API.

For remote signers, only the signer can receive the signing link through email. No one else will have access to the signing URL.

Setting permanent signing/access link is possible with "embeddedRecipientStartURL" by using a captive recipient aka "clientUserId" and your own URL endpoint whereby you authenticate your users and determine if they can access the envelope via a Request Recipient View.

Documentation here.

You can also request emails be sent per captive recipients as well as many other "Portal" centric options that put you in full control of the user experience.


问:
how to access string indexer on a collection in Powershell
Slowly learning Powershell ... I'm working on a script to query a third party AD/AM database (ldap). The specific LDAP property name that I want has a hyphen in the name.

I can do this in c# without thinking about it, but I don't want to fire up Visual Studio just to do some simple scripting stuff that changes frequently.

```<code>$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
.....
$results = $objSearcher.FindAll()
foreach($result in $results) {
   $item = $result.Properties
   $item.some-property         # this fails because of '-'
   $result['some-property']    # 'Unable to index into an object of type System.DirectoryServices.SearchResult.'
}
</code>```

答:
You need to place curly braces around the hyphenated property name. This should work:</p>

```<code>$item.{some-property}
</code>```

Body:
Slowly learning Powershell ... I'm working on a script to query a third party AD/AM database (ldap). The specific LDAP property name that I want has a hyphen in the name.

I can do this in c# without thinking about it, but I don't want to fire up Visual Studio just to do some simple scripting stuff that changes frequently.

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
.....
$results = $objSearcher.FindAll()
foreach($result in $results) {
   $item = $result.Properties
   $item.some-property         # this fails because of '-'
   $result['some-property']    # 'Unable to index into an object of type System.DirectoryServices.SearchResult.'
}

Body:
You need to place curly braces around the hyphenated property name. This should work:

$item.{some-property}


问:
Pagination in JSP using DataTables
I am planning to implement pagination in my JSP using DataTables. I previously implemented it using DisplayTag Library but looks like it is getting old now. I couldn't find a good example or a resource about Datatables on how to do it in a JSP. I have a list of object in my JSP and intended to show 10 records per page. With DisplayTag I did it very easily but with DataTables I am not exactly sure if it is straight forward and the changes would just be in the JSP. I want some thoughts or if there is any other library out there to help accomplish my goal.

Thanks.

答:
Go with this link.
DatabaleExample</p>

Title: Pagination in JSP using DataTables

Body:
Go with this link.
DatabaleExample


答:
I assume you have a background in programming in some other language than Python; a language that lets you change function parameters. Well, Python does not. The problem is not with the use of dict, but rather with the fact that you're assigning to a function parameter. This will not have an effect outside the function. What you want to do is probably this:

```<code>def fullDict(keys, values):
    return { key: [ value for value in values if key in value] for key in keys }

print(fullDict(Genes, Mutations))
</code>```

Title: Can you create dictionaries with just a single function?

Body:
As a total beginner I'm quite proud of this function. Although I believe there's probably an easier, more pythonic way of doing the exact same thing:

Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def RawDict(keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)
    return zip(dictKeys, dictValues)

GenDict = dict(RawDict(Genes, Mutations))

print(GenDict)

The function above is a rather overcomplicated (I think) way of putting several values (mutations) within keys (genes). However I was wondering if I could tweak this so I could get a dictionary by just doing this:

dict(GenDict, Genes, Mutations)

print(GenDict)

My struggle involves that when I use dict within the function, this won't work:

Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def fullDict(dictName, keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)
    dictName = dict(RawDict(Genes, Mutations))

fullDict(GenDict, Genes, Mutations)

print(GenDict)

The above just won't work as GenDict is not defined.

Body:
I assume you have a background in programming in some other language than Python; a language that lets you change function parameters. Well, Python does not. The problem is not with the use of dict, but rather with the fact that you're assigning to a function parameter. This will not have an effect outside the function. What you want to do is probably this:

def fullDict(keys, values):
    return { key: [ value for value in values if key in value] for key in keys }

print(fullDict(Genes, Mutations))


问:
Annoying to set deployment-token
Currently, i've tried to remove the secured token from the deployment-settings. I don't want to share it on public repositorys.

Here is the default configuration:

```<code>deploy:
  provider: GitHub
  auth_token:
      secure: **SECUREDTOKEN***
</code>```

I need to set the secure part as an variable, but nothing work:

```<code>secure: %AUTH_TOKEN%
secure: "%AUTH_TOKEN%"
secure: $env:AUTH_TOKEN
secure: "$env:AUTH_TOKEN"
secure: $($env:AUTH_TOKEN)
secure: "$($env:AUTH_TOKEN)"
secure: $AUTH_TOKEN
</code>```

I don't want to set the token on appveyor.yml like
    environment:
      matrix:
        - env:AUTH_TOKEN: "SECUREDTOKEN*"

I wan't to store it on the Backend, like:

答: You can store secure variables in UI settings (on the Backend in your terms), and they will be available during build. You do not need to prefix them with secure:, you simple address them using variable name like %AUTH_TOKEN%. They are stored in encrypted form, but during build they are decrypted and used as normal variables.

Title: Annoying to set deployment-token

Body:
Currently, i've tried to remove the secured token from the deployment-settings. I don't want to share it on public repositorys.

Here is the default configuration:

deploy:
  provider: GitHub
  auth_token:
      secure: **SECUREDTOKEN***

I need to set the secure part as an variable, but nothing work:

secure: %AUTH_TOKEN%
secure: "%AUTH_TOKEN%"
secure: $env:AUTH_TOKEN
secure: "$env:AUTH_TOKEN"
secure: $($env:AUTH_TOKEN)
secure: "$($env:AUTH_TOKEN)"
secure: $AUTH_TOKEN

I don't want to set the token on appveyor.yml like
    environment:
      matrix:
        - env:AUTH_TOKEN: "SECUREDTOKEN*"

I wan't to store it on the Backend, like:


问:
Full-range comparison operator in C++?
In C++, one can define bool operator<() on a class Foo, and stdlib algorithms like next_permutation() use that to infer ordering.

However, only providing a way to check if one instance of Foo is less than another, does not provide the full range of possible comparisons. For example, the instances may be equal.

Is there a standard or protocol for supporting the full range of comparisons in C++?

This question is motivated by the <=> "spaceship" operator defined in Ruby, which is a method returning -1, 0, or 1, if the receiver is less than, equal, or larger than the argument, respectively.

答: P0515 adds this (spelled, oddly enough, <=>). It should be in C++2x

Title: Full-range comparison operator in C++?


问:
Extracting only the hours and minutes from a Unix Timestamp code.
I'm working with php and want to convert a time scrubbed from an xml file. The time in the XML is  <startTime>0945</startTime>  for 9:45 and   <startTime>1330</startTime>  for 1:30.

I'm using   strtotime(xml_time)   to get the unix timestamp. But now I need to extract only the time itself. I don't need to compare it to the current time, I don't need to include any date information, and I'm not concerned with the timezone. Can anyone help me with which function to use (if different) or how to modify  strtotime()  to accomplish this?

Thanks!

答:
You can use date to extract the time parameters you need:</p>

```<code>echo $time = date("H:i:s",strtotime($xml_time));
</code>```

Body:
You can use date to extract the time parameters you need:

echo $time = date("H:i:s",strtotime($xml_time));


问:
Setting a variable from a string inside a TXT file with a batch file
I'm attempting to create a batch file for my company's users to use to migrate files from their older 'personal folder' network share to our new OneDrive implementation.

The problem is, some of our users have change the default sync folder for OneDrive to whatever drive and path they wanted, instead of keeping the default (*c:\users\username*)...for example, the one I'm using to test my BAT file against is using:

D:\OneDrive - Business

However, it does still have to work when it contains more or less delimiters, like C:\OneDrive or C:\This Is Where I Foolishly Store Stuff.

At this point, I've tried using REG QUERY to output to a text file from the UserFolder key in the registry to get the path, and now I'm trying to extract this path FROM the text file in question and set it to a variable.  The text file that is created looks like the following:

```<code>HKEY_CURRENT_USER\SOFTWARE\Microsoft\OneDrive\Accounts\Business1
    UserFolder    REG_SZ    D:\OneDrive - Business
</code>```

What I want to do is set the "D:\OneDrive - Business" to a variable to use in a scripted MOVE command.

My code is so awful, that I will refrain from posting it unless someone decides its necessary to answer my question.

I'm sure that for at least a DOZEN of you, this is child's play, so I would really appreciate any help that is provided me!!!

Thanks!!

答:
Perhaps:

For /F "EOL=H Tokens=2*" %%A In ('Reg Query "HKCU\SOFTWARE\Microsoft\OneDrive\Accounts\Business1" /V "UserFolder"') Do Set "var=%%B"
Echo(%%var%% = %var%
Pause
```

Body:
I'm attempting to create a batch file for my company's users to use to migrate files from their older 'personal folder' network share to our new OneDrive implementation.

The problem is, some of our users have change the default sync folder for OneDrive to whatever drive and path they wanted, instead of keeping the default (*c:\users\username*)...for example, the one I'm using to test my BAT file against is using:

D:\OneDrive - Business

However, it does still have to work when it contains more or less delimiters, like C:\OneDrive or C:\This Is Where I Foolishly Store Stuff.

At this point, I've tried using REG QUERY to output to a text file from the UserFolder key in the registry to get the path, and now I'm trying to extract this path FROM the text file in question and set it to a variable.  The text file that is created looks like the following:

HKEY_CURRENT_USER\SOFTWARE\Microsoft\OneDrive\Accounts\Business1
    UserFolder    REG_SZ    D:\OneDrive - Business

What I want to do is set the "D:\OneDrive - Business" to a variable to use in a scripted MOVE command.

My code is so awful, that I will refrain from posting it unless someone decides its necessary to answer my question.

I'm sure that for at least a DOZEN of you, this is child's play, so I would really appreciate any help that is provided me!!!

Thanks!!


问:
Read Multiple Byte Arrays from File
How can I read multiple byte arrays from a file?  These byte arrays are images and have the potential to be large.

This is how I'm adding them to the file:

```<code> using (var stream = new FileStream(tempFile, FileMode.Append))
      {
        //convertedImage = one byte array
        stream.Write(convertedImage, 0, convertedImage.Length);
      }
</code>```

So, now they're in tempFile and I don't know how to retrieve them as individual arrays.  Ideally, I'd like to get them as an IEnumerable<byte[]>.  Is there a way to split these, maybe?

答:
To retrieve multiple sets of byte arrays, you will need to know the length when reading. The easiest way to do this (if you can change the writing code) is to add a length value:

```<code>using (var stream = new FileStream(tempFile, FileMode.Append))
{
    //convertedImage = one byte array
    // All ints are 4-bytes
    stream.Write(BitConverter.GetBytes(convertedImage.Length), 0, 4);
    // now, we can write the buffer
    stream.Write(convertedImage, 0, convertedImage.Length);
}
</code>```

Reading the data is then

```<code>using (var stream = new FileStream(tempFile, FileMode.Open))
{
    // loop until we can't read any more
    while (true)
    {
        byte[] convertedImage;
        // All ints are 4-bytes
        int size;
        byte[] sizeBytes = new byte[4];
        // Read size
        int numRead = stream.Read(sizeBytes, 0, 4);
        if (numRead <= 0) {
            break;
        }
        // Convert to int
        size = BitConverter.ToInt32(sizeBytes, 0);
        // Allocate the buffer
        convertedImage = new byte[size];
        stream.Read(convertedImage, 0, size);
        // Do what you will with the array
        listOfArrays.Add(convertedImage);
    } // end while
}
</code>```

If all saved images are the same size, then you can eliminate the first read and write call from each, and hard-code size to the size of the arrays.

Title: Read Multiple Byte Arrays from File

Body:
How can I read multiple byte arrays from a file?  These byte arrays are images and have the potential to be large.

This is how I'm adding them to the file:

 using (var stream = new FileStream(tempFile, FileMode.Append))
      {
        //convertedImage = one byte array
        stream.Write(convertedImage, 0, convertedImage.Length);
      }

So, now they're in tempFile and I don't know how to retrieve them as individual arrays.  Ideally, I'd like to get them as an IEnumerable<byte[]>.  Is there a way to split these, maybe?

Body:
To retrieve multiple sets of byte arrays, you will need to know the length when reading. The easiest way to do this (if you can change the writing code) is to add a length value:

using (var stream = new FileStream(tempFile, FileMode.Append))
{
    //convertedImage = one byte array
    // All ints are 4-bytes
    stream.Write(BitConverter.GetBytes(convertedImage.Length), 0, 4);
    // now, we can write the buffer
    stream.Write(convertedImage, 0, convertedImage.Length);
}

Reading the data is then

using (var stream = new FileStream(tempFile, FileMode.Open))
{
    // loop until we can't read any more
    while (true)
    {
        byte[] convertedImage;
        // All ints are 4-bytes
        int size;
        byte[] sizeBytes = new byte[4];
        // Read size
        int numRead = stream.Read(sizeBytes, 0, 4);
        if (numRead <= 0) {
            break;
        }
        // Convert to int
        size = BitConverter.ToInt32(sizeBytes, 0);
        // Allocate the buffer
        convertedImage = new byte[size];
        stream.Read(convertedImage, 0, size);
        // Do what you will with the array
        listOfArrays.Add(convertedImage);
    } // end while
}

If all saved images are the same size, then you can eliminate the first read and write call from each, and hard-code size to the size of the arrays.


问:
SOAPUI Transferring Property
I am trying to do a transfer property in SOAP UI 3.6 prof. I am able to work it out properly. The question really is to make it random. What I mean is, in the first SOAP response, there will be a list of results and I want to pick one randomly to transfer it to second request. Is there any way to do it?</p>

答:
I don't have SoapUI handy but can't you use 'Groovy Script' step to select random item from your result, assign it to variable and then use in second request?

I was doing similar stuff - there are few Groovy tutorials on SoapUI website - take a look.

Title: SOAPUI Transferring Property


问:
test performance on different methods of obtaining input in Python
Consider a line of input for Python 3 that looks like this:

```<code>1 4 99 8 7
</code>```

Code needs to treat these inputs as numbers, so the following different ways of getting this or like input from the user is devised:

method one:

```<code>inputLst = [int(i) for i in input().split()]
</code>```

method two:

```<code>inputLst = map(int, input().split())
</code>```

How do you get an accurate performance check on code using the two different methods when the user has to interact with the code like this during testing?  Is there an effective way?

答:
You can do this yourself using python's timing functions (import time) and setting runamount to a high number to get consistent results.

```<code>total = 0

for i in range(runamount):
    start = time.time()

    #your code here

    total += time.time() - start
return (total / runamount)
</code>```

Run it for both and see which one goes more quickly to figure out which you should use.

Body:
Consider a line of input for Python 3 that looks like this:

1 4 99 8 7

Code needs to treat these inputs as numbers, so the following different ways of getting this or like input from the user is devised:

method one:

inputLst = [int(i) for i in input().split()]

method two:

inputLst = map(int, input().split())

How do you get an accurate performance check on code using the two different methods when the user has to interact with the code like this during testing?  Is there an effective way?

Body:
You can do this yourself using python's timing functions (import time) and setting runamount to a high number to get consistent results.

total = 0

for i in range(runamount):
    start = time.time()

    #your code here

    total += time.time() - start
return (total / runamount)

Run it for both and see which one goes more quickly to figure out which you should use.


答:
I won't use a text file but directly Reg.exe to read the registry value

```<code>@Echo off
Set "Key=HKCU\SOFTWARE\Microsoft\OneDrive\Accounts\Business1"
Set "Val=UserFolder"
For /f "Tokens=2* delims= " %%A in (
  'Reg query "%Key%" /V %Val% ^|find /i "%Val%" '
) Do Set "%Val%=%%B"
Set %Val%
</code>```

Title: Setting a variable from a string inside a TXT file with a batch file

Body:
I won't use a text file but directly Reg.exe to read the registry value

@Echo off
Set "Key=HKCU\SOFTWARE\Microsoft\OneDrive\Accounts\Business1"
Set "Val=UserFolder"
For /f "Tokens=2* delims= " %%A in (
  'Reg query "%Key%" /V %Val% ^|find /i "%Val%" '
) Do Set "%Val%=%%B"
Set %Val%


问:
Dynamic template reference variable inside ngFor (Angular 9)
How to declare a dynamic template reference variable inside a ngFor element?

I want to use the popover component from ng-bootstrap, the popover code (with Html binding) is as shown:

<ng-template #popContent>Hello, {{name}}!</ng-template>
<button type="button" class="btn btn-secondary" [ngbPopover]="popContent" popoverTitle="Fancy content">
    I've got markup and bindings in my popover!
</button>
```
<p>How can I <strong>wrap</strong> those elements inside <code>ngFor</code>?</p>
<pre class="lang-html prettyprint-override"><code><div *ngFor="let member of members">
    <!-- how to declare the '????' -->
    <ng-template #????>Hello, <b>{{member.name}}</b>!</ng-template>
        <button type="button" class="btn btn-secondary" [ngbPopover]="????" popoverTitle="Fancy content">
        I've got markup and bindings in my popover!
    </button>
</div>
</code>```

Hmmm... any idea?

答:
Template reference variables are scoped to the template they are defined in. A structural directive creates a nested template and, therefore, introduces a separate scope.

So you can just use one variable for your template reference

  <ng-template #popupContent>Hello, {{member.name}}!</ng-template>
  <button type="button" class="btn btn-secondary" [ngbPopover]="popupContent" popoverTitle="Fancy content">
      I've got markup and bindings in my popover!
  </button>

```

and it should work because it has already declared inside <ng-template ngFor

Plunker Example

For more details see also:

angular - conditional duplicate templateref in ng-content with selector

Body:
How to declare a dynamic template reference variable inside a ngFor element?

I want to use the popover component from ng-bootstrap, the popover code (with Html binding) is as shown:

<ng-template #popContent>Hello, {{name}}!</ng-template>
<button type="button" class="btn btn-secondary" [ngbPopover]="popContent" popoverTitle="Fancy content">
    I've got markup and bindings in my popover!
</button>

How can I wrap those elements inside ngFor?

    <ng-template #????>Hello, {{member.name}}!</ng-template>
        <button type="button" class="btn btn-secondary" [ngbPopover]="????" popoverTitle="Fancy content">
        I've got markup and bindings in my popover!
    </button>

Hmmm... any idea?

Body:
Template reference variables are scoped to the template they are defined in. A structural directive creates a nested template and, therefore, introduces a separate scope.

So you can just use one variable for your template reference

<div *ngFor="let member of members">
  <ng-template #popupContent>Hello, <b>{{member.name}}</b>!</ng-template>
  <button type="button" class="btn btn-secondary" [ngbPopover]="popupContent" popoverTitle="Fancy content">
      I've got markup and bindings in my popover!
  </button>
</div>

and it should work because it has already declared inside <ng-template ngFor

Plunker Example

For more details see also:

angular - conditional duplicate templateref in ng-content with selector