问:
IONIC2/Angular2 ngOnChange doesn't work
I'm new to Angular2 and I've been struggling for a while with this problem and have found no solution to it online.

[on ionic2!]

I want to use ngOnChanges() so i can detect changes to zonaid:

estados.html:

```<code><ion-item>
       <ion-label color="branco">Zonas</ion-label>

              <ion-select *ngIf="isTrue2" [(ngModel)]=zonaid>
                 <ion-option value={{bicho.zonas}} *ngFor="let bicho of idespecie">
                    {{bicho.zonas}}
                 </ion-option>
             </ion-select>

              <ion-select *ngIf="!isTrue2" [(ngModel)]="zonaid">
                 <ion-option value={{item.id}} *ngFor="let item of itemsZon" >
                    {{item.codigo}}
                 </ion-option>

              </ion-select>
     </ion-item>
</code>```

idespecie and itemsZon are parts of .json files

estados.ts

```<code>import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';
import { NavController } from 'ionic-angular';
import { IpmaBivService} from '../../app/services/ipmabiv.service'
import { Http } from '@angular/http';

@Component({
  selector: 'page-estados',
  templateUrl: 'estados.html'
})
export class EstadosPage {
   itemsZon: any;
   itemsEsp: any;
   zonaEscolhida: any;

   @Input()
   zonaid: string;

   idzona: '';
   idespecie: any[];

   isTrue1:boolean = false;
   isTrue2:boolean = false;
   constructor(public navCtrl: NavController, private ipmaBivService:IpmaBivService) {
  }
  ngOnChanges(changes: SimpleChanges){
     console.log('ngOnChanges ran');
     if(this.zonaid != ''){
        this.isTrue1 = true;
        this.getJsonZonas(this.zonaid);
     }
     if(this.especie != ''){
        this.isTrue2 = true;
        this.getJsonEspecies(this.especie);
     }
 }

}
  ngOnInit(){
     this.getDataZonas('zonas')
     this.getDataEspecies('especies')
   //   this.getData('especies')
 }
 }
</code>```

app.module.ts

```<code>    import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { HttpModule, JsonpModule } from '@angular/http';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { EstadosPage } from '../pages/estados/estados';
import { OutrosPage } from '../pages/estados/outros';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    EstadosPage,
    OutrosPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    JsonpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    OutrosPage,
    EstadosPage

  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
</code>```

Everything is happening in the same component (ionic page).

My goal is just to be able to run a method whenever zonaid changes. If you think there is a better way than goin through ngOnChanges, pls let me know

Thanks!

答:
ngOnChanges is not required. Angular will automatically update the selected value with binding. Dark Neuron answer will work but code need to change from  [ngModel]="zonaid" to [(ngModel)]="zonaid". You can also find my working version of ionic dropdown here

Your HTML should look like this.

```<code><ion-item>
       <ion-label color="branco">Zonas</ion-label>
              <ion-select *ngIf="isTrue2" [(ngModel)]="zonaid" (ngModelChange)="zonaiChanged()">
                 <ion-option value={{bicho.zonas}} *ngFor="let bicho of idespecie">
                    {{bicho.zonas}}
                 </ion-option>
             </ion-select>

              <ion-select *ngIf="!isTrue2" [(ngModel)]="zonaid" (ngModelChange)="zonaiChanged()">
                 <ion-option value={{item.id}} *ngFor="let item of itemsZon" >
                    {{item.codigo}}
                 </ion-option>

              </ion-select>
     </ion-item>
</code>```

In TS file call zonaiChanged to do something on dropdown change

```<code>zonaiChanged(){
alert(this.zonaid);
}
</code>```

Title: IONIC2/Angular2 ngOnChange doesn't work

Body:
I'm new to Angular2 and I've been struggling for a while with this problem and have found no solution to it online.

[on ionic2!]

I want to use ngOnChanges() so i can detect changes to zonaid:

estados.html:

<ion-item>
       <ion-label color="branco">Zonas</ion-label>

              <ion-select *ngIf="isTrue2" [(ngModel)]=zonaid>
                 <ion-option value={{bicho.zonas}} *ngFor="let bicho of idespecie">
                    {{bicho.zonas}}
                 </ion-option>
             </ion-select>

              <ion-select *ngIf="!isTrue2" [(ngModel)]="zonaid">
                 <ion-option value={{item.id}} *ngFor="let item of itemsZon" >
                    {{item.codigo}}
                 </ion-option>

              </ion-select>
     </ion-item>

idespecie and itemsZon are parts of .json files

estados.ts

import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';
import { NavController } from 'ionic-angular';
import { IpmaBivService} from '../../app/services/ipmabiv.service'
import { Http } from '@angular/http';

@Component({
  selector: 'page-estados',
  templateUrl: 'estados.html'
})
export class EstadosPage {
   itemsZon: any;
   itemsEsp: any;
   zonaEscolhida: any;

   @Input()
   zonaid: string;

   idzona: '';
   idespecie: any[];

   isTrue1:boolean = false;
   isTrue2:boolean = false;
   constructor(public navCtrl: NavController, private ipmaBivService:IpmaBivService) {
  }
  ngOnChanges(changes: SimpleChanges){
     console.log('ngOnChanges ran');
     if(this.zonaid != ''){
        this.isTrue1 = true;
        this.getJsonZonas(this.zonaid);
     }
     if(this.especie != ''){
        this.isTrue2 = true;
        this.getJsonEspecies(this.especie);
     }
 }

}
  ngOnInit(){
     this.getDataZonas('zonas')
     this.getDataEspecies('especies')
   //   this.getData('especies')
 }
 }

app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { HttpModule, JsonpModule } from '@angular/http';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { EstadosPage } from '../pages/estados/estados';
import { OutrosPage } from '../pages/estados/outros';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    EstadosPage,
    OutrosPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    JsonpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    OutrosPage,
    EstadosPage

  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

Everything is happening in the same component (ionic page).

My goal is just to be able to run a method whenever zonaid changes. If you think there is a better way than goin through ngOnChanges, pls let me know

Thanks!

Body:
ngOnChanges is not required. Angular will automatically update the selected value with binding. Dark Neuron answer will work but code need to change from  [ngModel]="zonaid" to [(ngModel)]="zonaid". You can also find my working version of ionic dropdown here

Your HTML should look like this.

<ion-item>
       <ion-label color="branco">Zonas</ion-label>
              <ion-select *ngIf="isTrue2" [(ngModel)]="zonaid" (ngModelChange)="zonaiChanged()">
                 <ion-option value={{bicho.zonas}} *ngFor="let bicho of idespecie">
                    {{bicho.zonas}}
                 </ion-option>
             </ion-select>

              <ion-select *ngIf="!isTrue2" [(ngModel)]="zonaid" (ngModelChange)="zonaiChanged()">
                 <ion-option value={{item.id}} *ngFor="let item of itemsZon" >
                    {{item.codigo}}
                 </ion-option>

              </ion-select>
     </ion-item>

In TS file call zonaiChanged to do something on dropdown change

zonaiChanged(){
alert(this.zonaid);
}


来源: stackexchange

问:
the best way to postpone callback till event
What would you suggest in case we need to postpone a callback in some circumstances and call it later, when an event occurs?
There are currently several queuing modules but I have not found one, which meet requirements as this one. I mean one don't run tasks out of queue till they are done. You run them when there is a suitable parameter value or the callback. For example,     </p>

```<code><html>
<body>
<input type="text" id="id1">
<input type="text" id="id2">
<script type="text/javascript">
    document.getElementById("id1")
        .addEventListener("keydown", function (e) {
            if (e.keyCode === 13) {
                upper(e.target.value);
            }
        });

    document.getElementById("id2")
        .addEventListener("keydown", function (e) {
            if (e.keyCode === 13) {
                delayed(e.target.value);
            }
        });

    function upper(x){
        if (parseInt(x) == x) {
            next_level(x, function(y){
                alert(y);
            });
        } else {
                alert('not int');
        }
    }

    function next_level(x, callback){
        y = Math.random() * 10;
        if (y < x){
            callback(y);
        } else {
            // postpone callback till y comes from id2
            // put it into a queue
        }
    }

    function delayed(y){
        // take 1st element/callback from the queue
        // call it with y
        // if queue is empty, do nothing
    }
</script>
</body>
</html>
</code>```

答:
EDITED

I've edited the code. This is more similar to your code example, but I'm still not sure I understand exactly what desired behavior is. Let me know if comments if this is wrong.

document.getElementById("id1")
  .addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
      upper(e.target.value);
    }
  });

document.getElementById("id2")
  .addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
      delayed(e.target.value);
    }
  });

function upper(x){
  if (parseInt(x) == x) {
    next_level(x, function(y){
      console.log(y);
    });
  } else {
    console.log('not int');
  }
}

const queue = [];

function next_level(x, callback){
  var y = Math.floor(Math.random() * 10);
  if (y < x){
    callback(y);
  } else {
    queue.push(callback);
    // postpone callback till y comes from id2
    // put it into a queue
  }
}

function delayed(y){
  if (queue.length > 0) {
    const cb = queue.shift();
    cb(y);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="id1" />
<input type="text" id="id2" /></code>```

ContentLicense: CC BY-SA 3.0

Body:
What would you suggest in case we need to postpone a callback in some circumstances and call it later, when an event occurs?
There are currently several queuing modules but I have not found one, which meet requirements as this one. I mean one don't run tasks out of queue till they are done. You run them when there is a suitable parameter value or the callback. For example,

<input type="text" id="id1">
<input type="text" id="id2">

Body:
EDITED

I've edited the code. This is more similar to your code example, but I'm still not sure I understand exactly what desired behavior is. Let me know if comments if this is wrong.

document.getElementById("id1")
  .addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
      upper(e.target.value);
    }
  });

document.getElementById("id2")
  .addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
      delayed(e.target.value);
    }
  });

function upper(x){
  if (parseInt(x) == x) {
    next_level(x, function(y){
      console.log(y);
    });
  } else {
    console.log('not int');
  }
}

const queue = [];

function next_level(x, callback){
  var y = Math.floor(Math.random() * 10);
  if (y < x){
    callback(y);
  } else {
    queue.push(callback);
    // postpone callback till y comes from id2
    // put it into a queue
  }
}

function delayed(y){
  if (queue.length > 0) {
    const cb = queue.shift();
    cb(y);
  }
}

<input type="text" id="id1" />
<input type="text" id="id2" />


问:
REACT ERROR  cannot appear as a child of
. See (unknown) > thead > th
I am working on a react - rails app and I keep getting this error in my console:

```<code>```
Warning: validateDOMNesting(...):  cannot appear as a child of
.
See (unknown) > thead > th.
```

<p>I'm not sure why this isn't working..I want to use header (thead) for a table and it worked for someone else. I would put tbody but I need that for the actual body of the table.</p>

<p>here is my code for this table: </p>

``````
     React.DOM.table
        className: 'table table-bordered'
        React.DOM.thead null,
          React.DOM.th null, 'Description'
          React.DOM.th null, 'Actions'
        React.DOM.tbody null,
          for post in @state.posts
            React.createElement Post, key: post.id, post: post,
            handleDeletePost: @deletePost
</code>```

**EDIT
I have tried adding the tr tag under thead and that causes an extra added error. this is what I changed my code to:

```<code>```
   React.DOM.table
      className: 'table table-bordered'
      React.DOM.thead null
        React.DOM.tr null
          React.DOM.th null, 'Description'
          React.DOM.th null, 'Actions'
        React.DOM.tbody null,
          for post in @state.posts
            React.createElement Post, key: post.id, post: post,
            handleDeletePost: @deletePost
```

and the next error i get is: Warning: validateDOMNesting(...): tr cannot appear as a child of table. See (unknown) > table > tr. Add a  to your code to match the DOM tree generated by the browser.

I'm new to react and not familiar with coffeescript so I'm wondering if it has to do with the spacing or something. Tested out different spacing and that didn't help. I took out the thead all together and that caused my app to break so..not sure what's the problem

答:
I've had this error come up because of mistakes elsewhere in my list.

For example @Sag1v has
 instead of
 to close the body of his list and I bet that is causing the error.

Title: REACT ERROR <th> cannot appear as a child of <thead>. See (unknown) > thead > th

Body:
I am working on a react - rails app and I keep getting this error in my console:

```
Warning: validateDOMNesting(...): <th> cannot appear as a child of <thead>.
See (unknown) > thead > th.
</code></pre>

<p>I'm not sure why this isn't working..I want to use header (thead) for a table and it worked for someone else. I would put tbody but I need that for the actual body of the table.</p>

<p>here is my code for this table: </p>

<pre><code>```
     React.DOM.table
        className: 'table table-bordered'
        React.DOM.thead null,
          React.DOM.th null, 'Description'
          React.DOM.th null, 'Actions'
        React.DOM.tbody null,
          for post in @state.posts
            React.createElement Post, key: post.id, post: post,
            handleDeletePost: @deletePost

**EDIT
I have tried adding the tr tag under thead and that causes an extra added error. this is what I changed my code to:

```
   React.DOM.table
      className: 'table table-bordered'
      React.DOM.thead null
        React.DOM.tr null
          React.DOM.th null, 'Description'
          React.DOM.th null, 'Actions'
        React.DOM.tbody null,
          for post in @state.posts
            React.createElement Post, key: post.id, post: post,
            handleDeletePost: @deletePost

and the next error i get is: Warning: validateDOMNesting(...): tr cannot appear as a child of table. See (unknown) > table > tr. Add a  to your code to match the DOM tree generated by the browser.

I'm new to react and not familiar with coffeescript so I'm wondering if it has to do with the spacing or something. Tested out different spacing and that didn't help. I took out the thead all together and that caused my app to break so..not sure what's the problem

Body:
I've had this error come up because of mistakes elsewhere in my list.

For example @Sag1v has <tbody> instead of </tbody> to close the body of his list and I bet that is causing the error.


问:
How do I pass parameters (e.g. -o CDNW) from Buildr to ScalaTest?
Currently I'm only able to say:

```<code>test.using(:scalatest)
</code>```

Buildr documentation says that class Buildr::Scala::ScalaTest supports the following options:

:properties - Hash of system properties available to the test case.

:environment - Hash of environment variables available to the test case.

:java_args - Arguments passed as is to the JVM.

But those are parameters to test cases and JVM only, not to ScalaTest ?

```<code>D:\>buildr --version
C:/Ruby186/lib/ruby/gems/1.8/gems/buildr-1.4.4-x86-mswin32/lib/buildr/java/packaging.rb:62: warning: parenthesize argument(s) for future version
Buildr 1.4.4
</code>```

答:
See my discussion on Twitter with Alex: http://twitter.com/#!/boia01/status/27605157764145153

If you still need this, please open an issue in Buildr's bug tracker, and we'll address it :)

ContentLicense: CC BY-SA 2.5

Body:
Currently I'm only able to say:

test.using(:scalatest)

Buildr documentation says that class Buildr::Scala::ScalaTest supports the following options:

:properties - Hash of system properties available to the test case.

:environment - Hash of environment variables available to the test case.

:java_args - Arguments passed as is to the JVM.

But those are parameters to test cases and JVM only, not to ScalaTest ?

D:\>buildr --version
C:/Ruby186/lib/ruby/gems/1.8/gems/buildr-1.4.4-x86-mswin32/lib/buildr/java/packaging.rb:62: warning: parenthesize argument(s) for future version
Buildr 1.4.4


问:
Generic Crud in spring data jpa
I have a lot of tables and almost of them i have just to save or delete them without another query.

So I use spring data jpa like this :

```<code> public interface SecteurAlerteRepository extends
     JpaRepository<SecteurAlerte, Integer>, QueryDslPredicateExecutor<SecteurAlerte>
     { }
</code>```

But i have to cretae a lot of interface about 50 ones and it's too much !!

there is not a generic way to use just standard query CRUD in Spring data or in a other way ?

答: There is no way to do this in Spring Data. The inner mechanics of Spring Data need the type parameters from the interface definition and if there is no interface definition with specific type parameters only the bound of the type parameters (Object in case of doubt) is available which is not usable.

Title: Generic Crud in spring data jpa

Body:
I have a lot of tables and almost of them i have just to save or delete them without another query.

So I use spring data jpa like this :

 public interface SecteurAlerteRepository extends
     JpaRepository<SecteurAlerte, Integer>, QueryDslPredicateExecutor<SecteurAlerte>
     { }

But i have to cretae a lot of interface about 50 ones and it's too much !!

there is not a generic way to use just standard query CRUD in Spring data or in a other way ?


问:
Merge the two different JSON using node JS
I have two requests that return their data as JSON using NodeJS Seriate.

The first response is:

```<code>{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014"
                    }
                }
            }
        }
    ]
}
</code>```

The second response is:

```<code>{
    "statusCode": 200,
    "body": {
        "errors": [],
        "detail": [
            {
                "repositories": [
                    {
                        "name": "registry",
                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                        "avatarDescription": "services"
                    }
                ]
            }
        ]
    }
}
</code>```

I want to merge the two responses, that would have the following structure:

```<code>{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014",
                        "detail": [
                            {
                                "repositories": [
                                    {
                                        "name": "registry",
                                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                                        "avatarDescription": "services"
                                    }
                                ]
                            }
                        ]
                    }
                }
            }
        }
    ]
}
</code>```

I searched and found several methods of joining or extending two JSON objects but nothing similar to that.

How can I achieve this?

My Actual Code is,

```<code>exports.getIssues = function(req, res) {
    console.log(filename + '>>get Issues>>');
    var response = {
        status : Boolean,
        message : String,
        data : String
    };
    var request = require('request');
    var username = const.username ;
    var password = const.password ;
    var options = {
        url : 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
        auth : {
            username : username,
            password : password
        }
    };

    request( options, function(error, obj) {
                if (error) {
                    response.message = appmsg.DATA_NT_FOUND;
                    response.status = false;
                    response.data = obj;
                    res.send(response);
                } else {
                     response.message = appmsg.DATA_FOUND;
                     response.status = true;
                     response.data = JSON.parse(obj.body);
                     //res.send(response);
                    var issueKey = response.data.issues;

                    // var keyData = issueKey[0].key;
                    // console.log(response.data.issues);
                    // console.log(keyData);
                    var output = [];
                    for(var i = 0; i < issueKey.length; i++) {
                        var issue = issueKey[i].key;
                        //var key = [];
                        //key.push(issue);
                        console.log(issue);

                        var respon = {
                            status : Boolean,
                            message : String,
                            data : String
                        };
                            var request = require('request'),
                                username = const.username ,
                                password = const.username ,
                                url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
                                auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                            //console.log(url);
                            request({url : url,headers : {"Authorization" : auth}}, function(err, object){
                                if (object) {

                                        var info = object;
                                        output.push(info); // this is not working as ouput is undefined at this    point
                                        //var pout = JSON.parse(output);
                                        //console.log(info);
                                        console.log("==============================================================================");
                                        //console.log(output);
                                        console.log("******************************************************************************");
                                            if(issueKey.length === output.length){
                                                respon.message = appmsg.DATA_FOUND;
                                                respon.status = true;
                                                respon.data = output;
                                                //console.log(output);
                                                //res.send(respon);

                                                  var id = issueKey[0].id;
                                                  console.log(id);

                                                   var commitout = [];
                                                    for(var i = 0; i < issueKey.length; i++) {
                                                        var commits = issueKey[i].id;
                                                        console.log(commits);

                                                      var request = require('request'),
                                                      username = const.username ,
                                                      password = const.password ,
                                                      url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                                                      auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                                                    //console.log(url);
                                                    var test = [];
                                                    request({url : url,headers : {"Authorization" : auth}}, function(err, obj1){
                                                      if (obj1) {

                                                              var info1 = obj1.body;
                                                              commitout.push(info1);
                                                              if(issueKey.length === commitout.length){
                                                                respon.message = appmsg.DATA_FOUND;
                                                                respon.status = true;
                                                                respon.data = commitout;
                                                                // console.log(commitout);
                                                                  //var test = merge(output, commitout);

                                                                  var text = output.body;
                                                                  var resultdone = output;

                                                                  resultdone.data = resultdone + commitout.body;

                                                                  console.log(resultdone.data);

                                                                res.send(resultdone.data);
                                                              }
                                                            }
                                                   });
                                                  }

                                    }
                                }

                        });

                }
            }

        });
</code>```

};

How can i merge the two arrays? in one response. That is my question..

答:
var result1 =

```<code>{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014"
                    }
                }
            }
        }
    ]
}
</code>```

var text = result1.data[0].body;

var result2 =

```<code>{
    "statusCode": 200,
    "body": {
        "errors": [],
        "detail": [
            {
                "repositories": [
                    {
                        "name": "registry",
                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                        "avatarDescription": "services"
                    }
                ]
            }
        ]
    }
};
</code>```

var resultdone = result1;

resultdone.data[0].body.fields.parent=  result2.body.detail;

Body:
I have two requests that return their data as JSON using NodeJS Seriate.

The first response is:

{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014"
                    }
                }
            }
        }
    ]
}

The second response is:

{
    "statusCode": 200,
    "body": {
        "errors": [],
        "detail": [
            {
                "repositories": [
                    {
                        "name": "registry",
                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                        "avatarDescription": "services"
                    }
                ]
            }
        ]
    }
}

I want to merge the two responses, that would have the following structure:

{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014",
                        "detail": [
                            {
                                "repositories": [
                                    {
                                        "name": "registry",
                                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                                        "avatarDescription": "services"
                                    }
                                ]
                            }
                        ]
                    }
                }
            }
        }
    ]
}

I searched and found several methods of joining or extending two JSON objects but nothing similar to that.

How can I achieve this?

My Actual Code is,

exports.getIssues = function(req, res) {
    console.log(filename + '>>get Issues>>');
    var response = {
        status : Boolean,
        message : String,
        data : String
    };
    var request = require('request');
    var username = const.username ;
    var password = const.password ;
    var options = {
        url : 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
        auth : {
            username : username,
            password : password
        }
    };

    request( options, function(error, obj) {
                if (error) {
                    response.message = appmsg.DATA_NT_FOUND;
                    response.status = false;
                    response.data = obj;
                    res.send(response);
                } else {
                     response.message = appmsg.DATA_FOUND;
                     response.status = true;
                     response.data = JSON.parse(obj.body);
                     //res.send(response);
                    var issueKey = response.data.issues;

                    // var keyData = issueKey[0].key;
                    // console.log(response.data.issues);
                    // console.log(keyData);
                    var output = [];
                    for(var i = 0; i < issueKey.length; i++) {
                        var issue = issueKey[i].key;
                        //var key = [];
                        //key.push(issue);
                        console.log(issue);

                        var respon = {
                            status : Boolean,
                            message : String,
                            data : String
                        };
                            var request = require('request'),
                                username = const.username ,
                                password = const.username ,
                                url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
                                auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                            //console.log(url);
                            request({url : url,headers : {"Authorization" : auth}}, function(err, object){
                                if (object) {

                                        var info = object;
                                        output.push(info); // this is not working as ouput is undefined at this    point
                                        //var pout = JSON.parse(output);
                                        //console.log(info);
                                        console.log("==============================================================================");
                                        //console.log(output);
                                        console.log("******************************************************************************");
                                            if(issueKey.length === output.length){
                                                respon.message = appmsg.DATA_FOUND;
                                                respon.status = true;
                                                respon.data = output;
                                                //console.log(output);
                                                //res.send(respon);

                                                  var id = issueKey[0].id;
                                                  console.log(id);

                                                   var commitout = [];
                                                    for(var i = 0; i < issueKey.length; i++) {
                                                        var commits = issueKey[i].id;
                                                        console.log(commits);

                                                      var request = require('request'),
                                                      username = const.username ,
                                                      password = const.password ,
                                                      url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                                                      auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                                                    //console.log(url);
                                                    var test = [];
                                                    request({url : url,headers : {"Authorization" : auth}}, function(err, obj1){
                                                      if (obj1) {

                                                              var info1 = obj1.body;
                                                              commitout.push(info1);
                                                              if(issueKey.length === commitout.length){
                                                                respon.message = appmsg.DATA_FOUND;
                                                                respon.status = true;
                                                                respon.data = commitout;
                                                                // console.log(commitout);
                                                                  //var test = merge(output, commitout);

                                                                  var text = output.body;
                                                                  var resultdone = output;

                                                                  resultdone.data = resultdone + commitout.body;

                                                                  console.log(resultdone.data);

                                                                res.send(resultdone.data);
                                                              }
                                                            }
                                                   });
                                                  }

                                    }
                                }

                        });

                }
            }

        });

};

How can i merge the two arrays? in one response. That is my question..

Body:
var result1 =

{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014"
                    }
                }
            }
        }
    ]
}

var text = result1.data[0].body;

var result2 =

{
    "statusCode": 200,
    "body": {
        "errors": [],
        "detail": [
            {
                "repositories": [
                    {
                        "name": "registry",
                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                        "avatarDescription": "services"
                    }
                ]
            }
        ]
    }
};

var resultdone = result1;

resultdone.data[0].body.fields.parent=  result2.body.detail;


问:
site domain issue in Django project
I started django server with following command:

```<code>python manage.py runserver 192.168.31.79:8030
</code>```

when I use following code,

```<code>   from django.contrib.sites.models import Site
   current_site = Site.objects.get_current()
   print (current_site.domain)
</code>```

the result will be 192.168.31.79:8000, why not port is 8030? Anyone could explain it for me? how could I retrieve 192.168.31.79:8030 via coding. many thanks.

答:
When resolving the Site with get_current Django will first check if a SITE_ID is set in the settings file. If there is a SITE_ID it will return what is stored in the domain field (obtaining the cached version in SITE_CACHE or adding it to the cache and returning it).

If SITE_ID is not present Django will resolve the host with request.get_host() and first query to see if the domain exists within the cache then check if it is in a Site object.

If this does not produce a result it will remove the port and check again in the same manner.

I would try looking at each of your Site objects to see if the port has made it into the domain. If not look into what is being stored in SITE_CACHE.

Documentation at https://docs.djangoproject.com/en/dev/ref/contrib/sites/#django.contrib.sites.shortcuts.get_current_site

Title: site domain issue in Django project

Body:
I started django server with following command:

python manage.py runserver 192.168.31.79:8030

when I use following code,

   from django.contrib.sites.models import Site
   current_site = Site.objects.get_current()
   print (current_site.domain)

the result will be 192.168.31.79:8000, why not port is 8030? Anyone could explain it for me? how could I retrieve 192.168.31.79:8030 via coding. many thanks.


问:
React: Auto update date and view with new information called from json API
I am calling data from coinmarketcap.com API and can not find a way to make the code auto update.  I would like to get this code to update the information every 30 seconds or so.

If I call something the wrong thing... or this is a basic question, sorry this is my first week with React.

Here is what I have and it works great at loading the information from coinmarketcap.com on the when the app first loads.

Main Component (file: Crypto.jsx)

```<code>import React, { Component } from 'react';

import CryptoItem from './parts/CryptoItem';

class Crypto extends Component{
render(){

return(
    <div id="CryptoItems">
        <div id="data">
            <CryptoItem cryptocoin="bitcoin" />
            <CryptoItem cryptocoin="ethereum" />
            <CryptoItem cryptocoin="ripple" />
            <CryptoItem cryptocoin="iconomi" />
            <CryptoItem cryptocoin="litecoin" />
            <CryptoItem cryptocoin="bitcoin-cash" />
        </div>
    </div>
    );
  }
}

export default Crypto;
</code>```

Child Component (file: /parts/CryptoItem.jsx)

```<code>        import React, { Component } from 'react';

    const urlForUsername = cryptocoin => `https://api.coinmarketcap.com/v1/ticker/${cryptocoin}/`

    class CryptoItem extends Component {

        constructor(props){
            super(props)
            this.state = {
                requestFailed: false
            }
        }

        componentDidMount(){
            fetch(urlForUsername(this.props.cryptocoin))
            .then(response =>{
                if(!response.ok){
                    throw Error("Network request failed")
                }
                return response
            })
            .then(d => d.json())
            .then(d => {
                this.setState({
                    cryptoData: d[0]
                })
            },() => {
                this.setState({
                    requestFailed: true
                })
            })
        }

        render() {
            if(this.state.requestFailed) return <p>Failed...</p>
            if(!this.state.cryptoData) return <p>Loading...</p>

            return(
                <ul className="CryptoItem" data-sort={ `${this.state.cryptoData.percent_change_24h}` } id={ `${this.state.cryptoData.symbol}PriceChangeID` }>
                    <li>
                        {this.state.cryptoData.name}:
                    </li>
                    <li>
                        $ <span id={ `${this.state.cryptoData.symbol}Price` }>{this.state.cryptoData.price_usd}</span>
                    </li>
                    <li className="PreCentChange">
                        <span id={ `${this.state.cryptoData.symbol}PriceChange` }>{this.state.cryptoData.percent_change_24h}</span><b>%</b>
                    </li>
                </ul>
            );
        }
    }
    export default CryptoItem;
</code>```

答:
First, extract out the logic in componentDidMount method in child component to a separate method as below.

fetchResult = () => {
    fetch(urlForUsername(this.props.cryptocoin))
    .then(response =>{
        if(!response.ok){
            throw Error("Network request failed")
        }
        return response
    })
    .then(d => d.json())
    .then(d => {
        this.setState({
            cryptoData: d[0]
        })
    },() => {
        this.setState({
            requestFailed: true
        })
    })
}```
</div>
</div>
</p>

<p>After that modify the <strong>componentDidMount</strong> method as below.</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>componentDidMount(){
  this.fetchResult()
  setInterval(this.fetchResult, 30000)
}</code>```

Note that, setInterval method can be used to execute a logic periodically. The first argument is the function which contains the logic that needs to be executed periodically. Second argument is the time interval in milliseconds.

Body:
I am calling data from coinmarketcap.com API and can not find a way to make the code auto update.  I would like to get this code to update the information every 30 seconds or so.

If I call something the wrong thing... or this is a basic question, sorry this is my first week with React.

Here is what I have and it works great at loading the information from coinmarketcap.com on the when the app first loads.

Main Component (file: Crypto.jsx)

import React, { Component } from 'react';

import CryptoItem from './parts/CryptoItem';

class Crypto extends Component{
render(){

return(

            <CryptoItem cryptocoin="bitcoin" />
            <CryptoItem cryptocoin="ethereum" />
            <CryptoItem cryptocoin="ripple" />
            <CryptoItem cryptocoin="iconomi" />
            <CryptoItem cryptocoin="litecoin" />
            <CryptoItem cryptocoin="bitcoin-cash" />

    );
  }
}

export default Crypto;

Child Component (file: /parts/CryptoItem.jsx)

        import React, { Component } from 'react';

    const urlForUsername = cryptocoin => `https://api.coinmarketcap.com/v1/ticker/${cryptocoin}/`

    class CryptoItem extends Component {

        constructor(props){
            super(props)
            this.state = {
                requestFailed: false
            }
        }

        componentDidMount(){
            fetch(urlForUsername(this.props.cryptocoin))
            .then(response =>{
                if(!response.ok){
                    throw Error("Network request failed")
                }
                return response
            })
            .then(d => d.json())
            .then(d => {
                this.setState({
                    cryptoData: d[0]
                })
            },() => {
                this.setState({
                    requestFailed: true
                })
            })
        }

        render() {
            if(this.state.requestFailed) return
Failed...

            if(!this.state.cryptoData) return
Loading...

            return(
                <ul className="CryptoItem" data-sort={ `${this.state.cryptoData.percent_change_24h}` } id={ `${this.state.cryptoData.symbol}PriceChangeID` }>

                        {this.state.cryptoData.name}:

                        $ <span id={ `${this.state.cryptoData.symbol}Price` }>{this.state.cryptoData.price_usd}

                        <span id={ `${this.state.cryptoData.symbol}PriceChange` }>{this.state.cryptoData.percent_change_24h}%

            );
        }
    }
    export default CryptoItem;

Body:
First, extract out the logic in componentDidMount method in child component to a separate method as below.

fetchResult = () => {
    fetch(urlForUsername(this.props.cryptocoin))
    .then(response =>{
        if(!response.ok){
            throw Error("Network request failed")
        }
        return response
    })
    .then(d => d.json())
    .then(d => {
        this.setState({
            cryptoData: d[0]
        })
    },() => {
        this.setState({
            requestFailed: true
        })
    })
}

After that modify the componentDidMount method as below.

componentDidMount(){
  this.fetchResult()
  setInterval(this.fetchResult, 30000)
}

Note that, setInterval method can be used to execute a logic periodically. The first argument is the function which contains the logic that needs to be executed periodically. Second argument is the time interval in milliseconds.


问:
dompdf - just getting two pages in pdf
i want to print a html to a pdf. In the project i use symfony and twig to render the template. When i return the html to browser it's looking good.
And it should be about 10 pages.

But when i try to create the PDF, i just get two pages.

```<code>$html = $this->render('offer/print.html.twig', array('offer' => $Offer ));

$options = new Options();
$options->setIsRemoteEnabled( false );

// instantiate and use the dompdf class
$dompdf = new Dompdf( $options );
$dompdf->setPaper('A4');

// Render the HTML as PDF
$dompdf->loadHtml( $html );
$dompdf->render();
$dompdf->stream();
</code>```

PHP 7
Symfony 3.0.9
dompdf 0.7.0

It doesn't looks like the html in the browser. I have to debug the css later.
Can anyone tell me why i just getting two pages in the pdf?

答: Please upload you twig file. I think the issues with you twig css.</p>

Title: dompdf - just getting two pages in pdf

Body:
i want to print a html to a pdf. In the project i use symfony and twig to render the template. When i return the html to browser it's looking good.
And it should be about 10 pages.

But when i try to create the PDF, i just get two pages.

$html = $this->render('offer/print.html.twig', array('offer' => $Offer ));

$options = new Options();
$options->setIsRemoteEnabled( false );

// instantiate and use the dompdf class
$dompdf = new Dompdf( $options );
$dompdf->setPaper('A4');

// Render the HTML as PDF
$dompdf->loadHtml( $html );
$dompdf->render();
$dompdf->stream();

PHP 7
Symfony 3.0.9
dompdf 0.7.0

It doesn't looks like the html in the browser. I have to debug the css later.
Can anyone tell me why i just getting two pages in the pdf?


问:
C++ Move semantics and Exceptions
In the forthcoming C++0x standard, what happens when an exception is thrown within/during the move constructor?

Will the original object remain? or are both the original and move-to object in an undefined state? what are the guarantees afforded by the language?

答:
Depends on the type being moved from.  It's possible to explicitly throw an exception, of course, from a move ctor, but also to implicitly call a copy ctor for a subobject from a move ctor.  That copy ctor might do something that may throw, such as allocate memory.  So, for the source object, the minimum guarantee is the original value may or may not remain, but it should still be in a destructable state.

For the object being moved to, it's the same as throwing from a ctor in current C++: destroy any constructed bases and members, execute the ctor's function try handler, if any, then propagate the exception.  Details are in N3225 §15.2p2.

In particular, note that containers require their allocator types not have throwing move ctors:

Such move construction of the allocator shall not exit via an exception. [N3225 §23.2p8]

This allows the containers to move allocators around and use those allocators to clean up their items in the case of an exception when moving or copying items.

OwnerDisplayName: Matthieu N.

Title: C++ Move semantics and Exceptions


问:
How to get Facebook first and last name values using ASP.NET MVC 5 and OWIN?
I know that a 'Name' field is provided, but I would prefer to access the first and last names explicitly. Can someone help with this? I'm still wrapping my head around ASP.Net MVC.</p>

答:
Facebook has changed the way their Graph API returns value in upgrade 2.4. Now you need to explicitly specify all the fields that you want to get back.

See this note from: facebook for developers Upgrade Info:

Graph API changes in version 2.4

In the past, responses from Graph API calls returned a set of default fields. In order to reduce payload size and improve latency on mobile
  networks we have reduced the number of default fields returned for
  most Graph API calls. In v2.4 you will need to declaratively list the
  response fields for your calls.

To get Email, FirstName and LastName from facebook:

First, you need to install Facebook SDK for .NET nuget package

Then, in your startup.Auth.cs, change the configuration of Facebook Authentication as follow:

```<code>     app.UseFacebookAuthentication(new FacebookAuthenticationOptions
        {
            // put your AppId and AppSecret here. I am reading them from AppSettings
            AppId = ConfigurationManager.AppSettings["FacebookAppId"],
            AppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"],
            Scope = { "email" },
            Provider = new FacebookAuthenticationProvider
            {
                OnAuthenticated = context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                    return Task.FromResult(true);
                }
            }
        });

        // this is no longer needed
        //app.UseFacebookAuthentication(
        //   appId: ConfigurationManager.AppSettings["FacebookAppId"],
        //   appSecret: ConfigurationManager.AppSettings["FacebookAppSecret"]);
</code>```

Finally, in your AccountController, add the following code to
   ExternalLoginCallback method:

```<code>if (string.Equals(loginInfo.Login.LoginProvider, "facebook", StringComparison.CurrentCultureIgnoreCase))
        {
            var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
            var access_token = identity.FindFirstValue("FacebookAccessToken");
            var fb = new FacebookClient(access_token);

            // you need to specify all the fields that you want to get back
            dynamic myInfo = fb.Get("/me?fields=email,first_name,last_name");
            string email = myInfo.email;
            string firstName = myInfo.first_name;
            string lastName = myInfo.last_name;
        }
</code>```

See facebook API Guid for more parameters that you can get back.

Body:
Facebook has changed the way their Graph API returns value in upgrade 2.4. Now you need to explicitly specify all the fields that you want to get back.

See this note from: facebook for developers Upgrade Info:

Graph API changes in version 2.4

In the past, responses from Graph API calls returned a set of default fields. In order to reduce payload size and improve latency on mobile
  networks we have reduced the number of default fields returned for
  most Graph API calls. In v2.4 you will need to declaratively list the
  response fields for your calls.

To get Email, FirstName and LastName from facebook:

First, you need to install Facebook SDK for .NET nuget package

Then, in your startup.Auth.cs, change the configuration of Facebook Authentication as follow:

     app.UseFacebookAuthentication(new FacebookAuthenticationOptions
        {
            // put your AppId and AppSecret here. I am reading them from AppSettings
            AppId = ConfigurationManager.AppSettings["FacebookAppId"],
            AppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"],
            Scope = { "email" },
            Provider = new FacebookAuthenticationProvider
            {
                OnAuthenticated = context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                    return Task.FromResult(true);
                }
            }
        });

        // this is no longer needed
        //app.UseFacebookAuthentication(
        //   appId: ConfigurationManager.AppSettings["FacebookAppId"],
        //   appSecret: ConfigurationManager.AppSettings["FacebookAppSecret"]);

Finally, in your AccountController, add the following code to
   ExternalLoginCallback method:

if (string.Equals(loginInfo.Login.LoginProvider, "facebook", StringComparison.CurrentCultureIgnoreCase))
        {
            var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
            var access_token = identity.FindFirstValue("FacebookAccessToken");
            var fb = new FacebookClient(access_token);

            // you need to specify all the fields that you want to get back
            dynamic myInfo = fb.Get("/me?fields=email,first_name,last_name");
            string email = myInfo.email;
            string firstName = myInfo.first_name;
            string lastName = myInfo.last_name;
        }

See facebook API Guid for more parameters that you can get back.


问:
Occasionally not getting output from processes running in parallel
I'm trying to get the output from several process that are running in parallel. As soon as each process is done I want to print its output to the console. Unfortunatelly none of the popular approaches work.

Using the TaskCompletionSource

With TaskCompletionSource the output can arrive asynchronously when the Exited event is called but it's often missing because the execution does not wait for the buffers to flush. Adding a Task.Delay for a few (hundred) milliseconds doesn't seem right and also does not always work.

Using WaitForExit

The isssue with WaitForExit is that it indeed works in parallel but it waits for all processes to finish. Only then you can print their results so you don't see any progress until they all exited.

In order to demonstrate it I created a demo application. It calls a misspelled ipconfig. If you run it a few times in LINQPad you'll see at some point that this line will kick-in informing you that there was no output.

```<code>if (temp.OutputLength == 0 && temp.ErrorLength == 0) temp.Dump();
</code>```

Here's the test application reproducing the issue. It's intentional that ipconfig is mispelled to provoke the Output problem.

```<code>void Main()
{
    var testCount = 30;

    var tasks = Enumerable.Range(0, testCount).Select(i => Task.Run(() => RunTestProcess()));

    Task.WaitAll(tasks.ToArray());

    Console.WriteLine("Done!");

}

private static object _consoleSyncLock = new object();
private static volatile int counter = 0;

public static async Task RunTestProcess()
{

    var stopwatch = Stopwatch.StartNew();
    var result = await CmdExecutor.Execute("ipconfigf", $"", "/Q", "/C");

    lock (_consoleSyncLock)
    {
        var temp = new
        {
            OutputLength = result.Output.Length,
            ErrorLength = result.Error.Length,
            Thread.CurrentThread.ManagedThreadId,
            stopwatch.Elapsed,
            Counter = counter++
        };

        if (temp.OutputLength == 0 && temp.ErrorLength == 0) temp.Dump();
    }
}

public class CmdExecutor
{
    public static Task<CmdResult> Execute(string fileName, string arguments, params string[] cmdSwitches)
    {
        Console.WriteLine(nameof(Execute) + " - " + Thread.CurrentThread.ManagedThreadId);

        if (cmdSwitches == null) throw new ArgumentNullException(nameof(cmdSwitches));
        if (fileName == null) throw new ArgumentNullException(nameof(fileName));
        if (arguments == null) throw new ArgumentNullException(nameof(arguments));

        arguments = $"{string.Join(" ", cmdSwitches)} {fileName} {arguments}";
        var startInfo = new ProcessStartInfo("cmd", arguments)
        {
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
        };

        var tcs = new TaskCompletionSource<CmdResult>();

        var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
        {
            var output = new StringBuilder();
            var error = new StringBuilder();

            process.OutputDataReceived += (sender, e) =>
            {
                output.AppendLine(e.Data);
            };

            process.ErrorDataReceived += (sender, e) =>
            {
                error.AppendLine(e.Data);
            };

            process.Exited += (sender, e) =>
            {
                tcs.SetResult(new CmdResult
                {
                    Arguments = arguments,
                    Output = output.ToString(),
                    Error = error.ToString(),
                    ExitCode = process.ExitCode
                });
                process.Dispose();
            };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return tcs.Task;
        }
    }
}

[Serializable]
public class CmdResult
{
    public string Arguments { get; set; }
    public string Output { get; set; }
    public string Error { get; set; }
    public int ExitCode { get; set; }
}
</code>```

I don't consider this code working because it does not do what it should be doing. This is, showing the entire output of each process as soon as it's finished.

I'm curious what can be done to solve this? I don't want to simply run processes in parallel, I already can do it but I'm interested in their ouput.

答:
You can wait for process to exit in Exited event itself:

```<code>process.Exited += (sender, e) =>
{
    // here
    ((Process)sender).WaitForExit();
    tcs.SetResult(new CmdResult
    {
        Arguments = arguments,
        Output = output.ToString(),
        Error = error.ToString(),
        ExitCode = process.ExitCode
    });
    process.Dispose();
};
</code>```

With that addition I'm always getting entire output with your sample code.

Body:
I'm trying to get the output from several process that are running in parallel. As soon as each process is done I want to print its output to the console. Unfortunatelly none of the popular approaches work.

Using the TaskCompletionSource

With TaskCompletionSource the output can arrive asynchronously when the Exited event is called but it's often missing because the execution does not wait for the buffers to flush. Adding a Task.Delay for a few (hundred) milliseconds doesn't seem right and also does not always work.

Using WaitForExit

The isssue with WaitForExit is that it indeed works in parallel but it waits for all processes to finish. Only then you can print their results so you don't see any progress until they all exited.

In order to demonstrate it I created a demo application. It calls a misspelled ipconfig. If you run it a few times in LINQPad you'll see at some point that this line will kick-in informing you that there was no output.

if (temp.OutputLength == 0 && temp.ErrorLength == 0) temp.Dump();

Here's the test application reproducing the issue. It's intentional that ipconfig is mispelled to provoke the Output problem.

void Main()
{
    var testCount = 30;

    var tasks = Enumerable.Range(0, testCount).Select(i => Task.Run(() => RunTestProcess()));

    Task.WaitAll(tasks.ToArray());

    Console.WriteLine("Done!");

}

private static object _consoleSyncLock = new object();
private static volatile int counter = 0;

public static async Task RunTestProcess()
{

    var stopwatch = Stopwatch.StartNew();
    var result = await CmdExecutor.Execute("ipconfigf", $"", "/Q", "/C");

    lock (_consoleSyncLock)
    {
        var temp = new
        {
            OutputLength = result.Output.Length,
            ErrorLength = result.Error.Length,
            Thread.CurrentThread.ManagedThreadId,
            stopwatch.Elapsed,
            Counter = counter++
        };

        if (temp.OutputLength == 0 && temp.ErrorLength == 0) temp.Dump();
    }
}

public class CmdExecutor
{
    public static Task<CmdResult> Execute(string fileName, string arguments, params string[] cmdSwitches)
    {
        Console.WriteLine(nameof(Execute) + " - " + Thread.CurrentThread.ManagedThreadId);

        if (cmdSwitches == null) throw new ArgumentNullException(nameof(cmdSwitches));
        if (fileName == null) throw new ArgumentNullException(nameof(fileName));
        if (arguments == null) throw new ArgumentNullException(nameof(arguments));

        arguments = $"{string.Join(" ", cmdSwitches)} {fileName} {arguments}";
        var startInfo = new ProcessStartInfo("cmd", arguments)
        {
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
        };

        var tcs = new TaskCompletionSource<CmdResult>();

        var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
        {
            var output = new StringBuilder();
            var error = new StringBuilder();

            process.OutputDataReceived += (sender, e) =>
            {
                output.AppendLine(e.Data);
            };

            process.ErrorDataReceived += (sender, e) =>
            {
                error.AppendLine(e.Data);
            };

            process.Exited += (sender, e) =>
            {
                tcs.SetResult(new CmdResult
                {
                    Arguments = arguments,
                    Output = output.ToString(),
                    Error = error.ToString(),
                    ExitCode = process.ExitCode
                });
                process.Dispose();
            };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return tcs.Task;
        }
    }
}

[Serializable]
public class CmdResult
{
    public string Arguments { get; set; }
    public string Output { get; set; }
    public string Error { get; set; }
    public int ExitCode { get; set; }
}

I don't consider this code working because it does not do what it should be doing. This is, showing the entire output of each process as soon as it's finished.

I'm curious what can be done to solve this? I don't want to simply run processes in parallel, I already can do it but I'm interested in their ouput.

Body:
You can wait for process to exit in Exited event itself:

process.Exited += (sender, e) =>
{
    // here
    ((Process)sender).WaitForExit();
    tcs.SetResult(new CmdResult
    {
        Arguments = arguments,
        Output = output.ToString(),
        Error = error.ToString(),
        ExitCode = process.ExitCode
    });
    process.Dispose();
};

With that addition I'm always getting entire output with your sample code.


问:
using !! symbol before the scope variable in ng-show what would represent this ( !! )symbol
what is the real meaning of using (!)before the scope variable in angularjs.
ng-show="!!file". What would indicate if I use this symbol in angularjs ng-directives</p>

答: ! is for reverse Boolean and !! double reverse Boolean, Please check here: Click</p>


答:
you can get the same using left join with same table but some tweaks in on clause to pick the highest numOfStars row

```<code>select a.*
from demo a
left join demo b
       on a.userId = b.userId
       and a.level = b.level
       and case when a.numOfStars = b.numOfStars
                then a.score < b.score
                else a.numOfStars < b.numOfStars
                end
where b.id is null
and a.userId = 23
</code>```

Demo

Note i have added a case clause for a scenario if user id, level and numOfStars are equal then it will pick the row on basis of highest score

Title: using JOIN, how do I get the max numOfStars for each level for this table?

Body:
Here is the table with some data

+-----+-------+--------+-----------+------------+-------+------------+---------------------+-------------------+
| id  | level | userId | numOfSecs | numOfStars | score | mostRecent | creationTime        | allLevelsFinished |
+-----+-------+--------+-----------+------------+-------+------------+---------------------+-------------------+
| 113 |     1 | 21     |        12 |          3 |  1000 |          1 | 2017-11-14 17:39:06 |                 0 |
| 114 |    10 | 21     |        25 |          3 |  1000 |          1 | 2017-11-14 17:41:21 |                 0 |
| 115 |     5 | 21     |        16 |          3 |  1000 |          1 | 2017-11-14 18:37:40 |                 0 |
| 119 |     1 | 23     |       194 |          1 |   200 |          0 | 2017-11-15 13:21:50 |                 0 |
| 120 |     1 | 23     |       121 |          1 |   444 |          0 | 2017-11-15 13:16:01 |                 0 |
| 121 |     1 | 23     |       221 |          3 |   333 |          0 | 2017-11-15 18:14:48 |                 0 |
| 122 |     1 | 23     |       343 |          2 |   555 |          0 | 2017-11-15 13:19:54 |                 0 |
| 123 |     1 | 23     |       355 |          1 |   555 |          1 | 2017-11-15 13:21:19 |                 0 |
| 124 |     2 | 23     |       333 |          1 |   333 |          0 | 2017-11-15 15:25:59 |                 0 |
| 125 |     2 | 23     |       444 |          2 |   444 |          0 | 2017-11-15 15:26:26 |                 0 |
| 126 |     2 | 23     |       222 |          2 |  2222 |          0 | 2017-11-15 15:26:59 |                 0 |
| 127 |     2 | 23     |        44 |          1 |   444 |          1 | 2017-11-15 15:27:24 |                 0 |
+-----+-------+--------+-----------+------------+-------+------------+---------------------+-------------------+

I'm aware that I could use

SELECT id, userId, numOfSecs, level, max(numOfStars)
WHERE userId=23
GROUP BY level

However, I'm interested in becoming more familiar with JOIN, even though JOIN is typically used with 2 or more tables.  What I would like to do with my query is select all the rows where userId=23 and then do a second query on the results of the first query to find the max number of stars for each level listed.  From the research I've done, a left inner join could do the job, but I'm having difficulty with aliases using a single table.

Body:
you can get the same using left join with same table but some tweaks in on clause to pick the highest numOfStars row

select a.*
from demo a
left join demo b
       on a.userId = b.userId
       and a.level = b.level
       and case when a.numOfStars = b.numOfStars
                then a.score < b.score
                else a.numOfStars < b.numOfStars
                end
where b.id is null
and a.userId = 23

Demo

Note i have added a case clause for a scenario if user id, level and numOfStars are equal then it will pick the row on basis of highest score


问:
How to finish an android application?
I need to finish an android application. For that i wrote

```<code>@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure You want to exit")
        .setCancelable(false)
        .setPositiveButton("YES"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "Yes"
            // button

            public void onClick(DialogInterface dialog,int id) {
                System.out.println(" onClick ");
                closeApplication(); // Close Application method called
            }
        })
        .setNegativeButton("NO"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "No"
            // button
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private void closeApplication() {
        System.out.println("closeApplication ");
        this.finish();
    }
}
</code>```

But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application

答:
Android is made in such a way that virtually NO application that was once opened, is closed.

Before mis-interpreting the statement, understand this.

"Whenever you exit your app, Android saves all the things the app was doing (called its state) and pushes the app in the background, calling the onStop() method. this is the new state of the application then, where the app isn't running, but isn't flushed out of the memory too. whenever you start the app again, it is resumed from the frozen state. Only when the memory, where frozen apps are kept, starts getting full, the Android GC flushes the app."

So conceptually, nothing goes out. when you hit "back" button while ur on the first activity, Android bundles the app and data, and freezes it.

Title: How to finish an android application?

Body:
I need to finish an android application. For that i wrote

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure You want to exit")
        .setCancelable(false)
        .setPositiveButton("YES"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "Yes"
            // button

            public void onClick(DialogInterface dialog,int id) {
                System.out.println(" onClick ");
                closeApplication(); // Close Application method called
            }
        })
        .setNegativeButton("NO"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "No"
            // button
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private void closeApplication() {
        System.out.println("closeApplication ");
        this.finish();
    }
}

But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application


问:
how to convert double quoted vectors in df to numpy array?
I have the following csv file.

```<code>index, vector, label
0, "[0,5,7]", class1
0, "[3,8,10]", class2
0, "[3,8,15]", class2
0, "[3,2,1]", class1
</code>```

I would like to parse and get the vector column such as:

```<code>[[0,5,7],[3,8,10],[3,8,15],[3,2,1]]
</code>```

However, whatever I tried, I get an object like:

```<code>['[0,5,7]','[3,8,10]','[3,8,15]','[3,2,1]']
</code>```

It parses the vector as a string instead of array.

I tried to cast it list/np.array but none of them worked. I also tried to apply the following in order to escape quotes:

```<code>replace.replace("'",'')
replace.replace('"','')
</code>```

They did not have any effect at all.

Therefore, I am open your suggestions to try more.

答:
Assuming you already have it in a pandas dataframe, you can apply a function that converts it to a list/array.

```<code>import numpy as np
def string_list(x): # '[1,2,3]'
    x = x[1:-1]
    x = x.split(",")
    x = list(map(np.float,x)) # [1,2,3]
    return x
</code>```

Then you apply this function to the dataframe

```<code>import pandas as pd
df = df.DataFrame.from_csv("file.csv")
df['vector'] = df['vector'].apply(string_list)
</code>```

Body:
I have the following csv file.

index, vector, label
0, "[0,5,7]", class1
0, "[3,8,10]", class2
0, "[3,8,15]", class2
0, "[3,2,1]", class1

I would like to parse and get the vector column such as:

[[0,5,7],[3,8,10],[3,8,15],[3,2,1]]

However, whatever I tried, I get an object like:

['[0,5,7]','[3,8,10]','[3,8,15]','[3,2,1]']

It parses the vector as a string instead of array.

I tried to cast it list/np.array but none of them worked. I also tried to apply the following in order to escape quotes:

replace.replace("'",'')
replace.replace('"','')

They did not have any effect at all.

Therefore, I am open your suggestions to try more.

Body:
Assuming you already have it in a pandas dataframe, you can apply a function that converts it to a list/array.

import numpy as np
def string_list(x): # '[1,2,3]'
    x = x[1:-1]
    x = x.split(",")
    x = list(map(np.float,x)) # [1,2,3]
    return x

Then you apply this function to the dataframe

import pandas as pd
df = df.DataFrame.from_csv("file.csv")
df['vector'] = df['vector'].apply(string_list)


答:
!! is used as a shorthand for converting values to an explicit boolean value.

If file is "truthy", !!file will be true. If it's "falsy", !!file will be false.

var nonEmptyString = "nonempty string";
var emptyString = "";

console.log(!!nonEmptyString);
console.log(!!emptyString);```

The use of !! in your example is extraneous and pointless because ng-show will take care of checking whether the value is "truthy" or "falsy".

Title: using !! symbol before the scope variable in ng-show what would represent this ( !! )symbol

Body:
what is the real meaning of using (!)before the scope variable in angularjs.
ng-show="!!file". What would indicate if I use this symbol in angularjs ng-directives

Body:
!! is used as a shorthand for converting values to an explicit boolean value.

If file is "truthy", !!file will be true. If it's "falsy", !!file will be false.

var nonEmptyString = "nonempty string";
var emptyString = "";

console.log(!!nonEmptyString);
console.log(!!emptyString);

The use of !! in your example is extraneous and pointless because ng-show will take care of checking whether the value is "truthy" or "falsy".


问:
Twilio call button and user input
so I've created this application that allows me to call a phone number from my Twilio account through localhost. I just have to put a / after the port # and the phone number I want to call(localhost:2222/7786453738) and it will send out a call. but I want the user to be able to make that call by inputting a phone number on to the webpage then clicking a button. is that possible? here's my code so far in the index.js file. I run it by going node index.js in the command terminal.</p>

```<code>const express = require("express");
const app = express();

const port = 2222;

app.get("/", function(req, resp){
resp.end("welcome to my app");
});

app.get("/:data", function(req, resp){

var accountSid = 'accountSid'
var authToken = 'authtoken'

var client = require('twilio')(accountSid, authToken);

client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: req.params.data,
from: '6043302056',
},  function(err, call) {
if(err) {
    console.log(err);
} else {
    console.log(call.sid);
}

})

console.log(req.params.data);
if(req.params.data == "me"){
    resp.end("hi raj");

    //resp.sendFile(__dirname+"/public/index.html)
} else {
    resp.end("Now calling: "+req.params.data);
}
});

app.listen(port, function(err){
if(err){
    console.log("error starting "+err);
    return false;
}

console.log("port is running. "+port);
})
</code>```

答:
Twilio developer evangelist here.

You're most of the way there with what you want to achieve. You can absolutely create a form that will take an input from a user and dial the number they enter.

First up, You will want to update your route as the number you send through a form won't be a part of the path, instead it will come as part of the body of the request. In order to read request bodies in express, you will want the body-parser module. So, install that in your project with:

```<code>npm install body-parser --save
</code>```

Then include it in your file and use it with your app:

```<code>const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
</code>```

Now, form's usually POST their data, rather than working over GET, so let's update your route to receive that POST request and extract the number from the request:

```<code>app.post("/calls", function(req, resp) {
  const accountSid = 'accountSid'
  const authToken = 'authtoken'
  const client = require('twilio')(accountSid, authToken);

  const number = req.body.number;

  client.calls.create({
    url: 'https://demo.twilio.com/welcome/voice/',
    to: number,
    from: '6043302056',
  },  function(err, call) {
    if(err) {
      console.error(err);
    } else {
      console.log(call.sid);
    }
  })

  console.log(number);
  if(req.params.data == "me"){
    resp.end("hi raj");
    //resp.sendFile(__dirname+"/public/index.html)
  } else {
    resp.end("Now calling: " + number);
  }
});
</code>```

Now, you need an HTML file that will include a form to make the request to this endpoint. Create an HTML file called index.html and place it in a new folder in your application called public.

You can load static files from the public directory in express with this line, add it near the top, after you create the app:

```<code>const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
</code>```

Finally we just need the HTML. This is the simplest HTML I could write that would do what you need:

```<code><!DOCTYPE html>
<html>
<head>
  <title>Make a call</title>
</head>
<body>
  <form action="/" method="POST">
    <label for="number">What number do you want to call?</label>
    <input id="number" type="tel" />
    <button type="submit">Make call</button>
  </form>
</body>
</html>
</code>```

As you can see it is just a form with a single input, the number, and a button to submit it.

Give this all a go and let me know how you get on.

Title: Twilio call button and user input

Body:
so I've created this application that allows me to call a phone number from my Twilio account through localhost. I just have to put a / after the port # and the phone number I want to call(localhost:2222/7786453738) and it will send out a call. but I want the user to be able to make that call by inputting a phone number on to the webpage then clicking a button. is that possible? here's my code so far in the index.js file. I run it by going node index.js in the command terminal.

const express = require("express");
const app = express();

const port = 2222;

app.get("/", function(req, resp){
resp.end("welcome to my app");
});

app.get("/:data", function(req, resp){

var accountSid = 'accountSid'
var authToken = 'authtoken'

var client = require('twilio')(accountSid, authToken);

client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: req.params.data,
from: '6043302056',
},  function(err, call) {
if(err) {
    console.log(err);
} else {
    console.log(call.sid);
}

})

console.log(req.params.data);
if(req.params.data == "me"){
    resp.end("hi raj");

    //resp.sendFile(__dirname+"/public/index.html)
} else {
    resp.end("Now calling: "+req.params.data);
}
});

app.listen(port, function(err){
if(err){
    console.log("error starting "+err);
    return false;
}

console.log("port is running. "+port);
})

Body:
Twilio developer evangelist here.

You're most of the way there with what you want to achieve. You can absolutely create a form that will take an input from a user and dial the number they enter.

First up, You will want to update your route as the number you send through a form won't be a part of the path, instead it will come as part of the body of the request. In order to read request bodies in express, you will want the body-parser module. So, install that in your project with:

npm install body-parser --save

Then include it in your file and use it with your app:

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

Now, form's usually POST their data, rather than working over GET, so let's update your route to receive that POST request and extract the number from the request:

app.post("/calls", function(req, resp) {
  const accountSid = 'accountSid'
  const authToken = 'authtoken'
  const client = require('twilio')(accountSid, authToken);

  const number = req.body.number;

  client.calls.create({
    url: 'https://demo.twilio.com/welcome/voice/',
    to: number,
    from: '6043302056',
  },  function(err, call) {
    if(err) {
      console.error(err);
    } else {
      console.log(call.sid);
    }
  })

  console.log(number);
  if(req.params.data == "me"){
    resp.end("hi raj");
    //resp.sendFile(__dirname+"/public/index.html)
  } else {
    resp.end("Now calling: " + number);
  }
});

Now, you need an HTML file that will include a form to make the request to this endpoint. Create an HTML file called index.html and place it in a new folder in your application called public.

You can load static files from the public directory in express with this line, add it near the top, after you create the app:

const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));

Finally we just need the HTML. This is the simplest HTML I could write that would do what you need:

<!DOCTYPE html>
<html>
<head>
  <title>Make a call</title>
</head>
<body>
  <form action="/" method="POST">
    <label for="number">What number do you want to call?</label>
    <input id="number" type="tel" />
    <button type="submit">Make call</button>
  </form>
</body>
</html>

As you can see it is just a form with a single input, the number, and a button to submit it.

Give this all a go and let me know how you get on.


问:
Spread imageViews evenly over tablerow
Like the title says, I have problems in spreading ImageViews evenly over tableRows. My xml is:

```<code>   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
  <ProgressBar/>
  <TextView/>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/progressBar">

    <TableLayout
        android:id="@+id/tableLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
       </TableLayout>

</ScrollView>
</code>```

After the Activity is started a dynamical Table is created with the following code:

```<code>     for (int i = 0; i < 4; i++) {
      tableRow = new TableRow(this);
      tableRow.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
              ViewGroup.LayoutParams.WRAP_CONTENT));

      tableRow.setId(i + 1);
      tableRow.setBackgroundResource(R.mipmap.shelfboard);
      tableRow.setPadding(20, 0, 20, 0);
      tableRow.setOnClickListener(thisvariable);

      tableLayout.addView(tableRow);
  }
</code>```

Now I want to add different numbers of ImageViews of the same width for each tableRow to each tableRow.

I have 4 TableRows

add 2 ImageViews to tableRow 1

add 5 ImageViews to tableRow 2

add 3 ImageViews to tableRow 3

add 7 ImageViews to tableRow 4

My Code is:

```<code>    for (int i = 0; i < adpList.size(); i++) {
            int row = adpList.get(i).getShelfBoard();
            if (row==1) {
                int productsPerBoard = 2;
                int width = (tableLayout.getWidth()) / productsPerBoard;

                TableRow.LayoutParams tlp = new TableRow.LayoutParams(width, TableRow.LayoutParams.MATCH_PARENT);

                productPicture = new ImageView(this);
                r = (TableRow) findViewById(row);
                productPicture.setLayoutParams(tlp);
            }
            if (row==2) {
                int productsPerBoard = 5;
                int width = (tableLayout.getWidth()) / productsPerBoard;

                TableRow.LayoutParams tlp = new TableRow.LayoutParams(width, TableRow.LayoutParams.MATCH_PARENT);
                productPicture = new ImageView(this);
                productPicture.setBackgroundResource(R.drawable.border);
                r = (TableRow) findViewById(row);

                productPicture.setLayoutParams(tlp);
            }
            if (row==3) {
                int productsPerBoard = 3;
                int width = (tableLayout.getWidth()) / productsPerBoard;
               TableRow.LayoutParams tlp = new TableRow.LayoutParams(width, TableRow.LayoutParams.MATCH_PARENT);

                productPicture = new ImageView(this);
                r = (TableRow) findViewById(row);
                productPicture.setLayoutParams(tlp);
            }
            if (row==4) {
                int productsPerBoard = 7;
                int width = tableLayout.getWidth() / productsPerBoard;

                TableRow.LayoutParams tlp = new TableRow.LayoutParams(width, TableRow.LayoutParams.MATCH_PARENT);

                productPicture = new ImageView(this);
                r = (TableRow) findViewById(row);
                productPicture.setLayoutParams(tlp);
            }
          productPicture.setBackgroundResource(R.mipmap.ic_launcher);
          r.addView(productPicture);
</code>```

Unfortunately every row has only two pictures. It always takes the width of the first board. My Output:

How can I add different numbers of ImageViews to each row?

答:
I thought too complicated. Changing the LayoutParams solved my problem:</p>

```<code>    r = (TableRow) findViewById(shelfboard);
    productPicture = new ImageView(this);

    TableRow.LayoutParams tlp = new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT, 1f);
    tlp.setMargins(0, 20, 0, 50);
    productPicture.setLayoutParams(tlp);
</code>```

Title: Spread imageViews evenly over tablerow

Body:
Like the title says, I have problems in spreading ImageViews evenly over tableRows. My xml is:

   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
  <ProgressBar/>
  <TextView/>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/progressBar">

    <TableLayout
        android:id="@+id/tableLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
       </TableLayout>

</ScrollView>

After the Activity is started a dynamical Table is created with the following code:

     for (int i = 0; i < 4; i++) {
      tableRow = new TableRow(this);
      tableRow.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
              ViewGroup.LayoutParams.WRAP_CONTENT));

      tableRow.setId(i + 1);
      tableRow.setBackgroundResource(R.mipmap.shelfboard);
      tableRow.setPadding(20, 0, 20, 0);
      tableRow.setOnClickListener(thisvariable);

      tableLayout.addView(tableRow);
  }

Now I want to add different numbers of ImageViews of the same width for each tableRow to each tableRow.

I have 4 TableRows

add 2 ImageViews to tableRow 1

add 5 ImageViews to tableRow 2

add 3 ImageViews to tableRow 3

add 7 ImageViews to tableRow 4

My Code is:

    for (int i = 0; i < adpList.size(); i++) {
            int row = adpList.get(i).getShelfBoard();
            if (row==1) {
                int productsPerBoard = 2;
                int width = (tableLayout.getWidth()) / productsPerBoard;

                TableRow.LayoutParams tlp = new TableRow.LayoutParams(width, TableRow.LayoutParams.MATCH_PARENT);

                productPicture = new ImageView(this);
                r = (TableRow) findViewById(row);
                productPicture.setLayoutParams(tlp);
            }
            if (row==2) {
                int productsPerBoard = 5;
                int width = (tableLayout.getWidth()) / productsPerBoard;

                TableRow.LayoutParams tlp = new TableRow.LayoutParams(width, TableRow.LayoutParams.MATCH_PARENT);
                productPicture = new ImageView(this);
                productPicture.setBackgroundResource(R.drawable.border);
                r = (TableRow) findViewById(row);

                productPicture.setLayoutParams(tlp);
            }
            if (row==3) {
                int productsPerBoard = 3;
                int width = (tableLayout.getWidth()) / productsPerBoard;
               TableRow.LayoutParams tlp = new TableRow.LayoutParams(width, TableRow.LayoutParams.MATCH_PARENT);

                productPicture = new ImageView(this);
                r = (TableRow) findViewById(row);
                productPicture.setLayoutParams(tlp);
            }
            if (row==4) {
                int productsPerBoard = 7;
                int width = tableLayout.getWidth() / productsPerBoard;

                TableRow.LayoutParams tlp = new TableRow.LayoutParams(width, TableRow.LayoutParams.MATCH_PARENT);

                productPicture = new ImageView(this);
                r = (TableRow) findViewById(row);
                productPicture.setLayoutParams(tlp);
            }
          productPicture.setBackgroundResource(R.mipmap.ic_launcher);
          r.addView(productPicture);

Unfortunately every row has only two pictures. It always takes the width of the first board. My Output:

How can I add different numbers of ImageViews to each row?

Body:
I thought too complicated. Changing the LayoutParams solved my problem:

    r = (TableRow) findViewById(shelfboard);
    productPicture = new ImageView(this);

    TableRow.LayoutParams tlp = new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT, 1f);
    tlp.setMargins(0, 20, 0, 50);
    productPicture.setLayoutParams(tlp);


问:
How to secure Swagger API UI allow only to a authorize user using ASP.NET Web API?
I'm working on Web API, currently, I just want to learn about Swagger API how's it good in documentation unit test. I found this to a reference online. Can you help me how to secure Swagger API UI from accessing by an anonymous user or public user? Just designated to an authorized user only. </p>

答: You can host the SwaggerUI as a separate instance in IIS and apply appropriate Authorization policy through IIS.</p>


问:
weird behavior when searching with b'\x5e', but with b'\x4e' is ok
```<code>import re

def main():
    with open('test', 'wb') as f:
        f.write(b'\x1e\x2e\x3e\x4e\x5e\x6e')
        f.write(b'\x1e\x2e\x3e\x4e\x5e\x6e')
    with open('test', 'rb') as f:
        s = f.read()
        for i in range((len(s)//8)+1):
            print(' '.join(['{:02x}'.format(j) for j in s[i*8:(i+1)*8]]))
        regex = re.compile(b'\x5e')  # weird
        for match_obj in regex.finditer(s):
            start = match_obj.start()
            end = match_obj.end()
            print(start, end)

if __name__=='__main__':
    main()
</code>```

after I executed the code with pattern b'\x5e', I got

```<code>1e 2e 3e 4e 5e 6e 1e 2e
3e 4e 5e 6e
0 0
</code>```

if i changed the pattern to b'\x4e' and run again, I would get

```<code>1e 2e 3e 4e 5e 6e 1e 2e
3e 4e 5e 6e
3 4
9 10
</code>```

why do they work in different ways?

how do I fix it?

thanks

答:
0x5e is "^" in ASCII, which is a regex metacharacter. You will need to escape it if you want to use it in a pattern literally.</p>

```<code>>>> re.escape(b'\x5e')
b'\\^'
</code>```

Body:
import re

def main():
    with open('test', 'wb') as f:
        f.write(b'\x1e\x2e\x3e\x4e\x5e\x6e')
        f.write(b'\x1e\x2e\x3e\x4e\x5e\x6e')
    with open('test', 'rb') as f:
        s = f.read()
        for i in range((len(s)//8)+1):
            print(' '.join(['{:02x}'.format(j) for j in s[i*8:(i+1)*8]]))
        regex = re.compile(b'\x5e')  # weird
        for match_obj in regex.finditer(s):
            start = match_obj.start()
            end = match_obj.end()
            print(start, end)

if __name__=='__main__':
    main()

after I executed the code with pattern b'\x5e', I got

1e 2e 3e 4e 5e 6e 1e 2e
3e 4e 5e 6e
0 0

if i changed the pattern to b'\x4e' and run again, I would get

1e 2e 3e 4e 5e 6e 1e 2e
3e 4e 5e 6e
3 4
9 10

why do they work in different ways?

how do I fix it?

thanks

Body:
0x5e is "^" in ASCII, which is a regex metacharacter. You will need to escape it if you want to use it in a pattern literally.

>>> re.escape(b'\x5e')
b'\\^'