问:
Send image in email through web service
I am a email web services which allows html content and one method that allows

```<code>byte[][] lstAttachment, string attachmentName, string[] contentType
</code>```

I want to send email with inline image.
I know I can send using system.net.mail by using AlternateView and LinkedResources but I can't use them because I have custom web service to send email.

I tried putting absolute address like :

body = "<htm>  ";

but it didn't work either.

So how can I embed image in email without using AlternateView or without using system.net for sending email

Update :

I tried converting image to base64 but didn't work that.. here is my html with base64

```<code><htm><body>  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAAZCAYAAABtnU33AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAHCSURBVHja5NgvbBNRGADwH0clAoJDkZBDgEBhEFzQhIBEEhwWMUGKGblkwayG1ZHKVrGF1JFAKk6sglZsYmEJqcCRTmAmliH2ujRho39WWHv3JU9c8/W7/vou7973Lrz6slPGG8WI1xG2FSe2I3TRLwC2j26EXWQFAGdpEu9G4aJVAHALBuDP2Msxdi8Yj8FtNHMMbqZJ3B4Gw8ccg49tw+B1bOQQuxFsf4D3UcdBjrAHqKdJvH8SWADXcgSupUlcH/4gOiHpPbZygN0KFqPAGao5AFfTJM7GAcMaKguMrQSDccGHWEVjAbENrKZJfDgJGHpYWbANSRMraRL3TkuIRhToYHlB0E0sp0nc+VtSNEahTZTn/PFuoJwm8eaoxGjMgh0szelCVsHSqJkdRGmCwj28xDe8wO05eM9WsXbaAnVW8GD1foeveI5nuHgO28Va2FRkaRJP9OXSlDfNwviEp3j8HxuBehhTRemMP6COD3iCR3iIy/+geW+GFm89NDnOCzzoshph3MUD3Mc9XJmyZj88Qa1wUtGe1b9XmvFstMN4ixu4g1u4ieu4hqu4FPJ/4Sd+4Dt2HB0bdx0dLs48fg8Ax9hvy8gn+qUAAAAASUVORK5CYII=" /></body></html>
</code>```

答:
You need to try HtmlAgilityPack and image Pass as base 64 string</p>

```<code>                #region Create mail body using LinkedResource
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();

                doc.LoadHtml(mailBody);
                var i = 1;
                AlternateView htmlview = default(AlternateView);
                var imageResourceList = new List<LinkedResource>();
                if (doc.DocumentNode.SelectNodes("//img") != null)
                {
                    foreach (HtmlNode img in doc.DocumentNode.SelectNodes("//img"))
                    {
                        var base64String = img.GetAttributeValue("src", null);
                        base64String = base64String.Replace("data:image/png;base64,", "");

                        var bytes = Convert.FromBase64String(base64String);

                        var stream = new MemoryStream(bytes);

                        LinkedResource imageResourceEs = new LinkedResource(stream, MediaTypeNames.Image.Jpeg);
                        imageResourceEs.ContentId = "img" + i;
                        imageResourceEs.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
                        imageResourceList.Add(imageResourceEs);
                        img.SetAttributeValue("src", "cid:img" + i);
                        i++;

                    }
                }
                htmlview = AlternateView.CreateAlternateViewFromString(doc.DocumentNode.OuterHtml, null, "text/html");

                foreach (var imgSource in imageResourceList)
                {
                    htmlview.LinkedResources.Add(imgSource);
                }
                #endregion

                //split email address
                var newIds = emailIds.Split(',');

                //create new MailMessage object
                var mail = new MailMessage { From = new MailAddress(emailTemplate.FromEmail, emailTemplate.FromText) };

                //set email address of reciver to mail message
                foreach (var email in newIds)
                {
                    mail.To.Add(email);
                }
                //set mail subject
                mail.Subject = subject;

                mail.IsBodyHtml = true;
                mail.BodyEncoding = System.Text.Encoding.UTF8;

                //set mail body
                mail.Body = doc.DocumentNode.OuterHtml;

                //Add AlternateViews
                mail.AlternateViews.Add(htmlview);

                //send mail
                SendEmail(mail);
</code>```

Title: Send image in email through web service

Body:
I am a email web services which allows html content and one method that allows

byte[][] lstAttachment, string attachmentName, string[] contentType

I want to send email with inline image.
I know I can send using system.net.mail by using AlternateView and LinkedResources but I can't use them because I have custom web service to send email.

I tried putting absolute address like :

body = "<htm>  ";

but it didn't work either.

So how can I embed image in email without using AlternateView or without using system.net for sending email

Update :

I tried converting image to base64 but didn't work that.. here is my html with base64

<htm>  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAAZCAYAAABtnU33AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAHCSURBVHja5NgvbBNRGADwH0clAoJDkZBDgEBhEFzQhIBEEhwWMUGKGblkwayG1ZHKVrGF1JFAKk6sglZsYmEJqcCRTmAmliH2ujRho39WWHv3JU9c8/W7/vou7973Lrz6slPGG8WI1xG2FSe2I3TRLwC2j26EXWQFAGdpEu9G4aJVAHALBuDP2Msxdi8Yj8FtNHMMbqZJ3B4Gw8ccg49tw+B1bOQQuxFsf4D3UcdBjrAHqKdJvH8SWADXcgSupUlcH/4gOiHpPbZygN0KFqPAGao5AFfTJM7GAcMaKguMrQSDccGHWEVjAbENrKZJfDgJGHpYWbANSRMraRL3TkuIRhToYHlB0E0sp0nc+VtSNEahTZTn/PFuoJwm8eaoxGjMgh0szelCVsHSqJkdRGmCwj28xDe8wO05eM9WsXbaAnVW8GD1foeveI5nuHgO28Va2FRkaRJP9OXSlDfNwviEp3j8HxuBehhTRemMP6COD3iCR3iIy/+geW+GFm89NDnOCzzoshph3MUD3Mc9XJmyZj88Qa1wUtGe1b9XmvFstMN4ixu4g1u4ieu4hqu4FPJ/4Sd+4Dt2HB0bdx0dLs48fg8Ax9hvy8gn+qUAAAAASUVORK5CYII=" />

Body:
You need to try HtmlAgilityPack and image Pass as base 64 string

                #region Create mail body using LinkedResource
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();

                doc.LoadHtml(mailBody);
                var i = 1;
                AlternateView htmlview = default(AlternateView);
                var imageResourceList = new List<LinkedResource>();
                if (doc.DocumentNode.SelectNodes("//img") != null)
                {
                    foreach (HtmlNode img in doc.DocumentNode.SelectNodes("//img"))
                    {
                        var base64String = img.GetAttributeValue("src", null);
                        base64String = base64String.Replace("data:image/png;base64,", "");

                        var bytes = Convert.FromBase64String(base64String);

                        var stream = new MemoryStream(bytes);

                        LinkedResource imageResourceEs = new LinkedResource(stream, MediaTypeNames.Image.Jpeg);
                        imageResourceEs.ContentId = "img" + i;
                        imageResourceEs.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
                        imageResourceList.Add(imageResourceEs);
                        img.SetAttributeValue("src", "cid:img" + i);
                        i++;

                    }
                }
                htmlview = AlternateView.CreateAlternateViewFromString(doc.DocumentNode.OuterHtml, null, "text/html");

                foreach (var imgSource in imageResourceList)
                {
                    htmlview.LinkedResources.Add(imgSource);
                }
                #endregion

                //split email address
                var newIds = emailIds.Split(',');

                //create new MailMessage object
                var mail = new MailMessage { From = new MailAddress(emailTemplate.FromEmail, emailTemplate.FromText) };

                //set email address of reciver to mail message
                foreach (var email in newIds)
                {
                    mail.To.Add(email);
                }
                //set mail subject
                mail.Subject = subject;

                mail.IsBodyHtml = true;
                mail.BodyEncoding = System.Text.Encoding.UTF8;

                //set mail body
                mail.Body = doc.DocumentNode.OuterHtml;

                //Add AlternateViews
                mail.AlternateViews.Add(htmlview);

                //send mail
                SendEmail(mail);


来源: stackexchange

问:
Angular 4 - setting withCredentials on every request - cors cookie
My angular client is separated from the backend and I have enabled cors on the backend, everything works fine except the fact that my authentication fails because the cookie is not added to requests.

After searching online I found that I should set {withCredentials : true} on every http request. I managed to do it on a single request and it works, but not on all the requests.

I tried using BrowserXhr How to send "Cookie" in request header for all the requests in Angular2? but it doesn't work and it's also deprecated afaik.

I also tried RequestOptions but it didn't work.

What can I do to set {withCredentials: true} on every http request?

Later Edit:

```<code>@Injectable()
export class ConfigInterceptor implements HttpInterceptor {

  constructor(private csrfService: CSRFService) {

  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let token = this.csrfService.getCSRF() as string;
    const credentialsReq = req.clone({withCredentials : true, setHeaders: { "X-XSRF-TOKEN": token } });
    return next.handle(credentialsReq);
  }
}
</code>```

答:
You can use an HttpInterceptor.

```<code>@Injectable()
export class CustomInterceptor implements HttpInterceptor {

    constructor() {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            withCredentials: true
        });

        return next.handle(request);
    }
}
</code>```

Next you have to provide it:

```<code>@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CustomInterceptor ,
      multi: true
    }
  ]
})
export class AppModule {}
</code>```

Source and full explanation

ContentLicense: CC BY-SA 4.0

Body:
My angular client is separated from the backend and I have enabled cors on the backend, everything works fine except the fact that my authentication fails because the cookie is not added to requests.

After searching online I found that I should set {withCredentials : true} on every http request. I managed to do it on a single request and it works, but not on all the requests.

I tried using BrowserXhr How to send "Cookie" in request header for all the requests in Angular2? but it doesn't work and it's also deprecated afaik.

I also tried RequestOptions but it didn't work.

What can I do to set {withCredentials: true} on every http request?

Later Edit:

@Injectable()
export class ConfigInterceptor implements HttpInterceptor {

  constructor(private csrfService: CSRFService) {

  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let token = this.csrfService.getCSRF() as string;
    const credentialsReq = req.clone({withCredentials : true, setHeaders: { "X-XSRF-TOKEN": token } });
    return next.handle(credentialsReq);
  }
}

Body:
You can use an HttpInterceptor.

@Injectable()
export class CustomInterceptor implements HttpInterceptor {

    constructor() {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            withCredentials: true
        });

        return next.handle(request);
    }
}

Next you have to provide it:

@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CustomInterceptor ,
      multi: true
    }
  ]
})
export class AppModule {}

Source and full explanation

ContentLicense: CC BY-SA 3.0


问:
Accessing array object value in typescript model
I am newbie to typescript and angular 2. I am finding it hard to access an array object value from a http response. Below is the code.

Below is the rdcModel defition

```<code>class RdcModel {
    constructor(
        public rdcList: Array<RdcList>
    ) { }
}
class RdcList {
    constructor(
        public rdcNumber: number,
        public rdcName: string,
    ) {}
}
export { RdcModel, RdcList };
</code>```

using the below Api service to retrive the data and returning the rdcModel.

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { RdcModel } from './model/rdc.model';

@Injectable()
export class ApiService {
    constructor(
        private http: HttpClient) {}
    getRdc$(): Observable<RdcModel[]> {
        return this.http
          .get('https://web.server.com/RDCUI/rs/rdc')
          .catch(this._handleError);
      }
      private _handleError(err: HttpErrorResponse | any) {
        const errorMsg = err.message || 'Error: Unable to complete request.';
        return Observable.throw(errorMsg);
      }
}
</code>```

Below is the response that I get when I call the api.

```<code>{
   "rdcList":[
      {
         "rdcNumber":8756,
         "rdcName":"DALLAS"
      },
      {
         "rdcNumber":4251,
         "rdcName":"TOPEKA"
      }
   ]
}
</code>```

In the component, I am trying to access the rdclist[1]

```<code>rdcModel: RdcModel[] = [];
  this.dcSub = this.api
      .getRdc$().subscribe(
      res => {
        this.rdcModel = res;
        console.log(this.rdcModel[0]);
      },
      err => {console.error(err); }
      );
</code>```

It gives me undefined when I try to acess [0]. How should I access the values of each RDC and store it an array? Any help is much appreciated.

答:
check the below code. I am not sure whether your response is array of objects or not. if it's array of objects just iterate the rdcModel and put console to check</p>

```<code>rdcModel: any;
  this.dcSub = this.api
      .getRdc$().subscribe(
      res => {
        this.rdcModel = res;
        console.log(this.rdcModel.rdcList[0]);
      },
      err => {console.error(err); }
      );
</code>```

Body:
I am newbie to typescript and angular 2. I am finding it hard to access an array object value from a http response. Below is the code.

Below is the rdcModel defition

class RdcModel {
    constructor(
        public rdcList: Array<RdcList>
    ) { }
}
class RdcList {
    constructor(
        public rdcNumber: number,
        public rdcName: string,
    ) {}
}
export { RdcModel, RdcList };

using the below Api service to retrive the data and returning the rdcModel.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { RdcModel } from './model/rdc.model';

@Injectable()
export class ApiService {
    constructor(
        private http: HttpClient) {}
    getRdc$(): Observable<RdcModel[]> {
        return this.http
          .get('https://web.server.com/RDCUI/rs/rdc')
          .catch(this._handleError);
      }
      private _handleError(err: HttpErrorResponse | any) {
        const errorMsg = err.message || 'Error: Unable to complete request.';
        return Observable.throw(errorMsg);
      }
}

Below is the response that I get when I call the api.

{
   "rdcList":[
      {
         "rdcNumber":8756,
         "rdcName":"DALLAS"
      },
      {
         "rdcNumber":4251,
         "rdcName":"TOPEKA"
      }
   ]
}

In the component, I am trying to access the rdclist[1]

rdcModel: RdcModel[] = [];
  this.dcSub = this.api
      .getRdc$().subscribe(
      res => {
        this.rdcModel = res;
        console.log(this.rdcModel[0]);
      },
      err => {console.error(err); }
      );

It gives me undefined when I try to acess [0]. How should I access the values of each RDC and store it an array? Any help is much appreciated.

Body:
check the below code. I am not sure whether your response is array of objects or not. if it's array of objects just iterate the rdcModel and put console to check

rdcModel: any;
  this.dcSub = this.api
      .getRdc$().subscribe(
      res => {
        this.rdcModel = res;
        console.log(this.rdcModel.rdcList[0]);
      },
      err => {console.error(err); }
      );


问:
Mariadb master-slave replication stopped without errors
I have setup mariadb master slave replication about a week back.It worked fine for 3-4 days but later the replication has stopped without giving any errors.The value of seconds behind master parameter is increasing.
I have posted the screenshot of

SHOW SLAVE STATUS;

below for reference.

Below is the result of SHOW PROCESSLIST;

Doing mysqlbinlog mysql-relay-bin.000040 > slave.txt this is the error i got

```<code>ERROR: Error in Log_event::read_log_event(): 'Found invalid event in binary log', data_len: 39, event_type: -93
ERROR: Could not read entry at offset 535: Error in log format or read error.
</code>```

How to get the replication to work again?This problem is because of master or slave db?

答: The problem seems to be because of corrupted mysql binary log.I ended up skipping a counter and replication continued from there.Also shifted to row based replication which seems like much safer option than statement based(this has nothing to do with replication stopping).</p>

Body:
I have setup mariadb master slave replication about a week back.It worked fine for 3-4 days but later the replication has stopped without giving any errors.The value of seconds behind master parameter is increasing.
I have posted the screenshot of

SHOW SLAVE STATUS;

below for reference.

Below is the result of SHOW PROCESSLIST;

Doing mysqlbinlog mysql-relay-bin.000040 > slave.txt this is the error i got

ERROR: Error in Log_event::read_log_event(): 'Found invalid event in binary log', data_len: 39, event_type: -93
ERROR: Could not read entry at offset 535: Error in log format or read error.

How to get the replication to work again?This problem is because of master or slave db?


问:
Sql Design Question
I have a table with 25 columns where 20 columns can have null values for some (30-40%) rows.
Now what is the cost of having rows with 20 null columns? Is this OK?

Or

is it a good design to have another table to store those 20 columns and add a ref to the first table?
This way I will only write to the second table only when there is are values.

I am using SQL server 2005. Will migrate to 2008 in future.

Only 20 columns are varchar, rest smallint, smalldate

What I am storing:
  These columns store different attributes of the row it belongs to. These attributes can be null sometimes.

The table will hold ~billion of rows

Please comment.

答:
You should describe the type of data you are storing. It sounds like some of those columns should be moved to another table.

For example, if you have several columns that represent multiple columns for the same type of data, then I would say move it to another table On the other hand, if you need this many columns to describe different types of data, then you may need to keep it as it is.

So it kind of depends on what you are modelling.

ContentLicense: CC BY-SA 2.5

Title: Sql Design Question


问:
Angular - Using a component across multiple modules
What I'm using

Angular

What I'm trying to do

I have a loading component I want to reuse across multiple modules

What I've done

I've created a new module called 'loading-overlay'

Inside this module I export the overlay component

I add this module to app.module

When adding the component to multiple modules I receive the following error:

Type LoadingOverlayComponent is part of the declarations of 2 modules: LoadingOverlayModule and ProjectsModule! Please consider moving LoadingOverlayComponent to a higher module that imports LoadingOverlayModule and ProjectsModule. You can also create a new NgModule that exports and includes LoadingOverlayComponent then import that NgModule in LoadingOverlayModule and ProjectsModule.

I've tried removing it from app.module and importing it into the other modules I need without much luck. I must be missing some obvious.

Overlay Module

// Modules
import { NgModule } from '@angular/core';

// Components
import { LoadingOverlayComponent } from './loading-overlay.component';

@NgModule({
  declarations: [
    LoadingOverlayComponent,
  ],

  imports: [

  ],

  exports: [
    LoadingOverlayComponent
  ],

  providers: [ ],

})

export class LoadingOverlayModule { }
```

<p><strong>App Module</strong></p>

<pre class="lang-js prettyprint-override"><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// Routing
import { AppRouting } from './routing/app-routing';

// Modules
import { ProjectsModule } from './projects/projects.module';
import { UserModule } from './user/user.module';
import { LoadingOverlayModule } from './loading-overlay/loading-overlay.module';

// Services / Providers
import { AuthService } from './user/auth.service'

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRouting,
    LoadingOverlayModule
  ],
  providers: [
    AuthService,

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Project Module

// Modules
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { LoadingOverlayModule } from '../loading-overlay/loading-overlay.module';

import { LoadingOverlayComponent } from '../loading-overlay/loading-overlay.component';

@NgModule({
  declarations: [

    LoadingOverlayComponent
  ],

  imports: [
    CommonModule,
    RouterModule,

    LoadingOverlayModule
  ],

  providers: [ ],

})

export class ProjectsModule { }
```

Any help pointing out what I've stupidly missed would be greatly appreciated.

答:
Remove :

LoadingOverlayModule from AppModule

LoadingOverlayComponent from ProjectsModule

And :

import LoadingOverlayModule Where its required

Body:
What I'm using

Angular

What I'm trying to do

I have a loading component I want to reuse across multiple modules

What I've done

I've created a new module called 'loading-overlay'

Inside this module I export the overlay component

I add this module to app.module

When adding the component to multiple modules I receive the following error:

Type LoadingOverlayComponent is part of the declarations of 2 modules: LoadingOverlayModule and ProjectsModule! Please consider moving LoadingOverlayComponent to a higher module that imports LoadingOverlayModule and ProjectsModule. You can also create a new NgModule that exports and includes LoadingOverlayComponent then import that NgModule in LoadingOverlayModule and ProjectsModule.

I've tried removing it from app.module and importing it into the other modules I need without much luck. I must be missing some obvious.

Overlay Module

// Modules
import { NgModule } from '@angular/core';

// Components
import { LoadingOverlayComponent } from './loading-overlay.component';

@NgModule({
  declarations: [
    LoadingOverlayComponent,
  ],

  imports: [

  ],

  exports: [
    LoadingOverlayComponent
  ],

  providers: [ ],

})

export class LoadingOverlayModule { }

App Module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// Routing
import { AppRouting } from './routing/app-routing';

// Modules
import { ProjectsModule } from './projects/projects.module';
import { UserModule } from './user/user.module';
import { LoadingOverlayModule } from './loading-overlay/loading-overlay.module';

// Services / Providers
import { AuthService } from './user/auth.service'

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRouting,
    LoadingOverlayModule
  ],
  providers: [
    AuthService,

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Project Module

// Modules
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { LoadingOverlayModule } from '../loading-overlay/loading-overlay.module';

import { LoadingOverlayComponent } from '../loading-overlay/loading-overlay.component';

@NgModule({
  declarations: [

    LoadingOverlayComponent
  ],

  imports: [
    CommonModule,
    RouterModule,

    LoadingOverlayModule
  ],

  providers: [ ],

})

export class ProjectsModule { }

Any help pointing out what I've stupidly missed would be greatly appreciated.


问:
Choosing the correct NodePort
Usually we expose our Kubenretes services through an managed K8s/GCP Ingress with auto-assigned NodePorts, but for some use cases we need to specify a static NodePort ourselves.

The documentation says that we need to make sure to avoid port collissions:

you need to take care about possible port collisions yourself

Q: How should how we choose the correct NodePort?

Should we / do we have to allocate our static NodePort from the flag-configured range (default: 30000-32767)?

Or rather not from this range to avoid collisions with these auto-assigned ports?

答: It is more about not assigning the same port manually to multiple services then anything else. If you have a manualy defined NodePort it will not get assigned to dynamic service, so yes, you should use port from this range.</p>

Title: Choosing the correct NodePort


问:
Probability and Machine Learning
I am using python to do a bit of machine learning.

I have a python nd array with 2000 entries.  Each entry has information about some subjects and at the end has a boolean to tell me if they are a vampire or not.

Each entry in the array looks like this:

```<code>[height(cm), weight(kg), stake aversion, garlic aversion, reflectance, shiny, IS_VAMPIRE?]
</code>```

My goal is to be able to give a probability that a new subject is a vampire given the data shown above for the subject.

I have used sklearn to do some machine learning for me:

```<code>clf = tree.DecisionTreeRegressor()

clf=clf.fit(X,Y)

print clf.predict(W)
</code>```

Where W is an array of data for the new subject.  The script I have written returns booleans, but I would like it to return probabilities.  How can I modify it?

答:
If you are using DecisionTreeRegressor() then you may use the score function to determine the coefficient of determination R^2 of the prediction.

Please find the below link to the documentation.

http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html#sklearn.tree.DecisionTreeRegressor

Also you can list out the cross validation score (for 10 samples) as below

```<code>from sklearn.model_selection import cross_val_score

clf = tree.DecisionTreeRegressor()

clf=clf.fit(X,Y)

cross_val_score(clf, X, Y, cv=10)

print clf.predict(W)
</code>```

Which gives an output something similar to this,

```<code>array([ 0.61..., 0.57..., -0.34..., 0.41..., 0.75...,
        0.07..., 0.29..., 0.33..., -1.42..., -1.77...])
</code>```

Title: Probability and Machine Learning

Body:
I am using python to do a bit of machine learning.

I have a python nd array with 2000 entries.  Each entry has information about some subjects and at the end has a boolean to tell me if they are a vampire or not.

Each entry in the array looks like this:

[height(cm), weight(kg), stake aversion, garlic aversion, reflectance, shiny, IS_VAMPIRE?]

My goal is to be able to give a probability that a new subject is a vampire given the data shown above for the subject.

I have used sklearn to do some machine learning for me:

clf = tree.DecisionTreeRegressor()

clf=clf.fit(X,Y)

print clf.predict(W)

Where W is an array of data for the new subject.  The script I have written returns booleans, but I would like it to return probabilities.  How can I modify it?

Body:
If you are using DecisionTreeRegressor() then you may use the score function to determine the coefficient of determination R^2 of the prediction.

Please find the below link to the documentation.

http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html#sklearn.tree.DecisionTreeRegressor

Also you can list out the cross validation score (for 10 samples) as below

from sklearn.model_selection import cross_val_score

clf = tree.DecisionTreeRegressor()

clf=clf.fit(X,Y)

cross_val_score(clf, X, Y, cv=10)

print clf.predict(W)

Which gives an output something similar to this,

array([ 0.61..., 0.57..., -0.34..., 0.41..., 0.75...,
        0.07..., 0.29..., 0.33..., -1.42..., -1.77...])


问:
Passing a list to a JSON file in C#
I want to write to and read from a JSON file.

I use the Newtonsoft.Json package

I have a list containing an object

```<code>private List<LinkElement> links = new List<LinkElement>();
</code>```

the object structure is

```<code>public class LinkElement
{
public LinkElement(string link, string key, string description, string type, string[] tags)
{
       Link = link;
       Description = description;
       Type = type;
       Tags = tags;
}

public string Link { get; set; }

public string Key { get; set; }

public string Description { get; set; }

public string Type { get; set; }

public string[] Tags { get; set; }
}
</code>```

So when reading from the file I would go for

```<code>string data = File.ReadAllText(path);
links = JsonConvert.DeserializeObject<List<LinkElement>>(data);
</code>```

and when writing to the file I would go for

```<code>string newData = JsonConvert.SerializeObject(links);
File.WriteAllText(path, newData);
</code>```

but it seems lists are not the right element to take. Dictionaries would be possible.

Could someone help me out passing the list to the JSON file?

答:
Here is what you can do.

First of all you do not need the constructor in your model.

```<code>public class LinkElement
{
    public string Key { get; set; }
    public LinkElementInfo Info { get; set; }
}

public class LinkElementInfo
{
   public string Link { get; set; }

   public string Description { get; set; }

   public string Type { get; set; }

   public string[] Tags { get; set; }
}

//Example Data
Dictionary<string, LinkElementInfo> links = new Dictionary<string, LinkElementInfo>()
{
  {'a',{...}}
};
</code>```

Title: Passing a list to a JSON file in C#

Body:
I want to write to and read from a JSON file.

I use the Newtonsoft.Json package

I have a list containing an object

private List<LinkElement> links = new List<LinkElement>();

the object structure is

public class LinkElement
{
public LinkElement(string link, string key, string description, string type, string[] tags)
{
       Link = link;
       Description = description;
       Type = type;
       Tags = tags;
}

public string Link { get; set; }

public string Key { get; set; }

public string Description { get; set; }

public string Type { get; set; }

public string[] Tags { get; set; }
}

So when reading from the file I would go for

string data = File.ReadAllText(path);
links = JsonConvert.DeserializeObject<List<LinkElement>>(data);

and when writing to the file I would go for

string newData = JsonConvert.SerializeObject(links);
File.WriteAllText(path, newData);

but it seems lists are not the right element to take. Dictionaries would be possible.

Could someone help me out passing the list to the JSON file?

Body:
Here is what you can do.

First of all you do not need the constructor in your model.

public class LinkElement
{
    public string Key { get; set; }
    public LinkElementInfo Info { get; set; }
}

public class LinkElementInfo
{
   public string Link { get; set; }

   public string Description { get; set; }

   public string Type { get; set; }

   public string[] Tags { get; set; }
}

//Example Data
Dictionary<string, LinkElementInfo> links = new Dictionary<string, LinkElementInfo>()
{
  {'a',{...}}
};


问:
CPU usage per application in android
I am new for android programming.How can we get CPU usage per application in android?
your help will be more helpful</p>

答: Using the new Android Studio 3.0 profiler you can achieve a higher information about the CPU usage and CPU inspection of your APP.

Title: CPU usage per application in android


问:
how to set Linear layout child's height as tallest child height
I have four textviews in my Linear Layout and they have equal
width as follows,

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView86" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>
</code>```

My problem is, The textviews should be displayed with the same height.The content(text) for that textview will be set programmatically. I tried with Relative layout but the width of textview couldn't be same. I need both height and width should be same as tallest child.

Guide me please. Thanks!

答:
Checkout below xml Code , You set the child height to wrap_content that should be match_parent :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:background="@drawable/bluebackground"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView86" />
    <LinearLayout
        android:background="@color/colorPrimaryDark"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:background="@drawable/bluebackground"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            />
        <TextView
            android:background="@drawable/bluebackground"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            />
        <TextView
            android:background="@drawable/bluebackground"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            />
        <TextView
            android:background="@drawable/bluebackground"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            />
    </LinearLayout>
</LinearLayout>
</code>```

Body:
I have four textviews in my Linear Layout and they have equal
width as follows,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView86" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

My problem is, The textviews should be displayed with the same height.The content(text) for that textview will be set programmatically. I tried with Relative layout but the width of textview couldn't be same. I need both height and width should be same as tallest child.

Guide me please. Thanks!

Body:
Checkout below xml Code , You set the child height to wrap_content that should be match_parent :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:background="@drawable/bluebackground"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView86" />
    <LinearLayout
        android:background="@color/colorPrimaryDark"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:background="@drawable/bluebackground"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            />
        <TextView
            android:background="@drawable/bluebackground"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            />
        <TextView
            android:background="@drawable/bluebackground"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            />
        <TextView
            android:background="@drawable/bluebackground"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            />
    </LinearLayout>
</LinearLayout>


问:
Azure Oracle v12 Instance Auto scaling
I am trying to find options of auto scaling available for Oracle v12 instance on Azure.

Is auto scaling in Oracle DB instance, automatically available or can be done only manually or is it is not at all available??
I am trying to google this topic, but not yet found any thing??

答: it look likes there is no automatic auto scaling in Oracle only thing which can be done is to use a VM with good storage and manually mount disks later on based on requirement. It is an assumption I am still looking for a better answer.</p>

Title: Azure Oracle v12 Instance Auto scaling


问:
Validation pattern for date in DD/MM/YYYY format using angular2
How to add validation pattern for Date in DD/MM/YYYY format using angular2 Validator.pattern.

I have the "required" validator in place. Cannot find one for date pattern. Code as below:

```<code>this.txtDob = new Control("", Validators.compose([Validators.required]));
</code>```

答:
You can create a simple custom validator as below

```<code>import {Injectable} from "@angular/core";
import {FormControl} from "@angular/forms";

@Injectable()
export class DateValidator {

  constructor() {
  }

  static date(c: FormControl) {
    const dateRegEx = new RegExp(/^\d{1,2}\.\d{1,2}\.\d{4}$/);
    return dateRegEx.test(c.value) ? null : {date: true}
  }
}
</code>```

and call it in your form

```<code>senddate: new FormControl(new Date(), Validators.compose([Validators.required, DateValidator.date])),
</code>```

And then simply show the error in your html

```<code>      <mat-error *ngIf="form.controls.senddate.dirty && form.controls.senddate.errors?.date">
        La date d'envoi n'est pas <strong>valide</strong>
      </mat-error>
</code>```

I hope this could help.

Body:
How to add validation pattern for Date in DD/MM/YYYY format using angular2 Validator.pattern.

I have the "required" validator in place. Cannot find one for date pattern. Code as below:

this.txtDob = new Control("", Validators.compose([Validators.required]));

Body:
You can create a simple custom validator as below

import {Injectable} from "@angular/core";
import {FormControl} from "@angular/forms";

@Injectable()
export class DateValidator {

  constructor() {
  }

  static date(c: FormControl) {
    const dateRegEx = new RegExp(/^\d{1,2}\.\d{1,2}\.\d{4}$/);
    return dateRegEx.test(c.value) ? null : {date: true}
  }
}

and call it in your form

senddate: new FormControl(new Date(), Validators.compose([Validators.required, DateValidator.date])),

And then simply show the error in your html

      <mat-error *ngIf="form.controls.senddate.dirty && form.controls.senddate.errors?.date">
        La date d'envoi n'est pas <strong>valide</strong>
      </mat-error>

I hope this could help.


问:
GCHandle to get address(pointer) of .net object
I managed to get the address of a .net object by

```<code>GCHandle objHandle = GCHandle.Alloc(obj,GCHandleType.WeakTrackResurrection);
int address = GCHandle.ToIntPtr(objHandle).ToInt32();
</code>```

and I can recall the object by

```<code>Object obj = GCHandle.FromIntPtr(IntPtr(address)).Target;
</code>```

Well, the purpose is to store the address in a native class and have an information of which native object is releated to which .net object.

AFAIK the address does not change because of allocing, is it true or does anyone have a better idea to serve my purpose?

Thanks

答:
What you are getting is not actually an address.

As you notice, it seems to act like an address most of the time, and you can recall the object, by using GCHandle.FromIntPtr. However, the interesting issue is that you are using GCHandleType.WeakTrackResurrection.

If your weakly referenced object gets collected (it presumably can, since it is only weakly referenced by the GCHandle), you still have the IntPtr, and you can pass it to GCHandle.FromIntPtr(). If you do so, then you get back null, assuming the IntPtr has not been recycled.

(If the IntPtr has been recycled by the CLR for some reason, then you are in trouble. I'm not sure whether this can happen.)

You are better off using either GCHandleType.Normal, or GCHandleType.Pinned (if you need to take the address of the object in unmanaged code), if you want a strong reference to the object.

(To use GCHandleType.Pinned, your object must e.g. be primitive, or have [StructLayout] attribute, or be an array of such objects.)

Body:
I managed to get the address of a .net object by

GCHandle objHandle = GCHandle.Alloc(obj,GCHandleType.WeakTrackResurrection);
int address = GCHandle.ToIntPtr(objHandle).ToInt32();

and I can recall the object by

Object obj = GCHandle.FromIntPtr(IntPtr(address)).Target;

Well, the purpose is to store the address in a native class and have an information of which native object is releated to which .net object.

AFAIK the address does not change because of allocing, is it true or does anyone have a better idea to serve my purpose?

Thanks


问:
How to save dynamically added div elements?
This function add new div dynamically:

$(document).ready(function() {
  i = '1';
  x = '0';

  $("#btn3").click(function() {
    i++;
    x++;

    z = x * 2;
    r = z + 1;

    $('

Obwód ' + i + '  <button class="btn btn-block btn-lg btn-primary" type="button" id=' + z + ' onClick="relayClick(this.id)">Wł</button> <button class="btn btn-block btn-lg btn-danger" type="button" id=' + r + ' onClick="relayClick(this.id)">Wył</button>

').appendTo("#container");
  });
});
```

How can I save the new created "div" ? New "div" must be visible after refreshing page.

答:
```<code>$(document).ready(function() {
  i = '1';
  x = '0';

  $("#btn3").click(function() {
    i++;
    x++;

    z = x * 2;
    r = z + 1;

    $("#container").append('<div class="mainContainer"><div class="relayBlock"><span class="relayTitle">Obwód ' + i + ' </span> <button class="btn btn-block btn-lg btn-primary" type="button" id=' + z + ' onClick="relayClick(this.id)">Wł</button> <button class="btn btn-block btn-lg btn-danger" type="button" id=' + r + ' onClick="relayClick(this.id)">Wył</button></div></div>');
  });
});
</code>```

need to change which is appending element

Body:
This function add new div dynamically:

$(document).ready(function() {
  i = '1';
  x = '0';

  $("#btn3").click(function() {
    i++;
    x++;

    z = x * 2;
    r = z + 1;

    $('

Obwód ' + i + '  <button class="btn btn-block btn-lg btn-primary" type="button" id=' + z + ' onClick="relayClick(this.id)">Wł</button> <button class="btn btn-block btn-lg btn-danger" type="button" id=' + r + ' onClick="relayClick(this.id)">Wył</button>

').appendTo("#container");
  });
});

How can I save the new created "div" ? New "div" must be visible after refreshing page.

Body:
$(document).ready(function() {
  i = '1';
  x = '0';

  $("#btn3").click(function() {
    i++;
    x++;

    z = x * 2;
    r = z + 1;

    $("#container").append('<div class="mainContainer"><div class="relayBlock"><span class="relayTitle">Obwód ' + i + ' </span> <button class="btn btn-block btn-lg btn-primary" type="button" id=' + z + ' onClick="relayClick(this.id)">Wł</button> <button class="btn btn-block btn-lg btn-danger" type="button" id=' + r + ' onClick="relayClick(this.id)">Wył</button></div></div>');
  });
});

need to change which is appending element


问:
Video View not working under Proguard
There seems to be a problem in VideoView which doesn't work under Proguard. The following screen comes when a video is being started.

The code for Video View is as follows:

```<code>        mediaController= new MediaController(this);
        mediaController.hide();
        mediaController.setAnchorView(video_animation);
        Uri uri= Uri.parse("android.resource://" + getPackageName() + "/"
                + R.raw.splash_min);
        video_animation.setMediaController(mediaController);
        video_animation.setVideoURI(uri);
        video_animation.requestFocus();

        video_animation.start();
</code>```

Also there is no specific ProGuard setting added for VideoView to run.

Excerpts of build.gradle

```<code>buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-project.txt'
            resValue "string", "FB_APP_ID", getFbAppKey()
        }
        debug {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-project.txt'
            resValue "string", "FB_APP_ID", getFbAppKey()
        }
    }
</code>```

Also there are product flavours being used just to manipulate with the application ID.

答:
I'm not sure if it's still relevant to you, but it might be useful for other people. I had the same issue. In my case, the root cause is something to do with one of my library I used and proguard config.

So, I got this error when building an apk with proguard.

The way I tried to eliminate that error was by adding -ignorewarning. The error was solved but it made my video can't be played.

There are 2 ways to solve this issue:

remove shrinkResources true from gradle

or

remove -ignorewarning and fix the warnings generated by your library.

Title: Video View not working under Proguard

Body:
There seems to be a problem in VideoView which doesn't work under Proguard. The following screen comes when a video is being started.

The code for Video View is as follows:

        mediaController= new MediaController(this);
        mediaController.hide();
        mediaController.setAnchorView(video_animation);
        Uri uri= Uri.parse("android.resource://" + getPackageName() + "/"
                + R.raw.splash_min);
        video_animation.setMediaController(mediaController);
        video_animation.setVideoURI(uri);
        video_animation.requestFocus();

        video_animation.start();

Also there is no specific ProGuard setting added for VideoView to run.

Excerpts of build.gradle

buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-project.txt'
            resValue "string", "FB_APP_ID", getFbAppKey()
        }
        debug {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-project.txt'
            resValue "string", "FB_APP_ID", getFbAppKey()
        }
    }

Also there are product flavours being used just to manipulate with the application ID.


问:
ResultSet only showing 1 row when there are actually many rows
I'm doing a project for my college. I'm using resultSet to select all the rows from a newspaper table and I'm adding each newspaper name to a JComboBox. I  have many newspapers added but the resultSet selects only the first row.

```<code>    try{
        combobox1.removeAllItems();
        ResultSet r1= MysqlCon.run("select * from "+pub);
        while(r1.next())
        {
            combobox1.addItem(r1.getString("name"));
            System.out.println(r1.getString(2));
        }
        //TODO
    }
    catch(Exception e){}
</code>```

Here is the class which takes connection to the database

```<code> import java.sql.*;
class MysqlCon{
    static ResultSet rs;
    public static ResultSet run(String query)
    {
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/project","gijo","root");
            Statement stmt=con.createStatement();
            rs=stmt.executeQuery(query);

        }catch(Exception e){ System.out.println(e);}
        return rs;
    }
</code>```

I'm using the same class to add values to a JTable and there is no problem there.

Please help me!

答:
It is wrong, totally wrong, to return a ResultSet from a function and lost the reference of the Statement and Connection.

GC might come across these objects and consider mark them not in use and run their finalize method. As a result the connection may have dropped at random point in time.

You might rewrite your API, or you can study about CachedResultSet form Oracle.

Body:
I'm doing a project for my college. I'm using resultSet to select all the rows from a newspaper table and I'm adding each newspaper name to a JComboBox. I  have many newspapers added but the resultSet selects only the first row.

    try{
        combobox1.removeAllItems();
        ResultSet r1= MysqlCon.run("select * from "+pub);
        while(r1.next())
        {
            combobox1.addItem(r1.getString("name"));
            System.out.println(r1.getString(2));
        }
        //TODO
    }
    catch(Exception e){}

Here is the class which takes connection to the database

 import java.sql.*;
class MysqlCon{
    static ResultSet rs;
    public static ResultSet run(String query)
    {
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/project","gijo","root");
            Statement stmt=con.createStatement();
            rs=stmt.executeQuery(query);

        }catch(Exception e){ System.out.println(e);}
        return rs;
    }

I'm using the same class to add values to a JTable and there is no problem there.

Please help me!


问:
jqgrid treeGrid Cannot read property 'rowIndex' of undefined
I try to use local data with treeGrid, when i click the unfold
    button . I get the tips "Cannot read property 'rowIndex' of
    undefined"</p>

答:
```<code><!DOCTYPE html>

<html lang="en">

<head>
    <!-- The jQuery library is a prerequisite for all jqSuite products -->
    <script type="text/ecmascript" src="./js/jquery.min.js"></script>
    <!-- This is the Javascript file of jqGrid -->
    <script type="text/ecmascript" src="./js/jquery.jqGrid.min.js"></script>
    <!-- This is the localization file of the grid controlling messages, labels, etc.
    <!-- We support more than 40 localizations -->
    <script type="text/ecmascript" src="./js/i18n/grid.locale-en.js"></script>
    <!-- A link to a jQuery UI ThemeRoller theme, more than 22 built-in and many more custom -->
    <link rel="stylesheet" type="text/css" media="screen" href="./css/jquery-ui-1.10.4.custom.min.css" />
    <!-- The link to the CSS that the grid needs -->
    <link rel="stylesheet" type="text/css" media="screen" href="./css/ui.jqgrid.css" />
    <meta charset="utf-8" />
    <title>jqTreeGrid - Load On Demand - Load all Rows at once collapsed</title>
</head>

<body>

    <table id="tree"></table>
    <div id="pager"></div>

    <script type="text/javascript">

        var rows = [
            {
                "category_id": "1",
                "name": "ELECTRONICS",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "1",
                "rgt": "44",
                "level": "0",
                "uiicon": ""
            },
            {
                "category_id": "2",
                "name": "TELEVISIONS",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "2",
                "rgt": "19",
                "level": "1",
                "uiicon": ""
            },
            {
                "category_id": "3",
                "name": "TUBE",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "3",
                "rgt": "8",
                "level": "2",
                "uiicon": ""
            },
            {
                "category_id": "11",
                "name": "26 \" TV",
                "price": "200.00",
                "qty_onhand": "1",
                "color": "black",
                "lft": "4",
                "rgt": "5",
                "level": "3",
                "uiicon": "ui-icon-image"
            },
            {
                "category_id": "12",
                "name": "30 \" TV",
                "price": "350.00",
                "qty_onhand": "2",
                "color": "black",
                "lft": "6",
                "rgt": "7",
                "level": "3",
                "uiicon": "ui-icon-document"
            },
            {
                "category_id": "4",
                "name": "LCD",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "9",
                "rgt": "12",
                "level": "2",
                "uiicon": ""
            },
            {
                "category_id": "13",
                "name": "Super-LCD 42\" ",
                "price": "400.00",
                "qty_onhand": "10",
                "color": "all",
                "lft": "10",
                "rgt": "11",
                "level": "3",
                "uiicon": "ui-icon-video"
            },
            {
                "category_id": "5",
                "name": "PLASMA",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "13",
                "rgt": "18",
                "level": "2",
                "uiicon": ""
            },
            {
                "category_id": "14",
                "name": "Ultra-Plasma 62\" ",
                "price": "440.00",
                "qty_onhand": "2",
                "color": "silver",
                "lft": "14",
                "rgt": "15",
                "level": "3",
                "uiicon": "ui-icon-clipboard"
            },
            {
                "category_id": "15",
                "name": "Value Plasma 38\" ",
                "price": "312.00",
                "qty_onhand": "0",
                "color": "silver",
                "lft": "16",
                "rgt": "17",
                "level": "3",
                "uiicon": "ui-icon-clipboard"
            },
            {
                "category_id": "6",
                "name": "PORTABLE ELECTRONICS",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "20",
                "rgt": "43",
                "level": "1",
                "uiicon": ""
            },
            {
                "category_id": "7",
                "name": "MP3 PLAYERS",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "21",
                "rgt": "32",
                "level": "2",
                "uiicon": ""
            },
            {
                "category_id": "8",
                "name": "FLASH",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "22",
                "rgt": "29",
                "level": "3",
                "uiicon": ""
            },
            {
                "category_id": "17",
                "name": "Super-Shuffle 1gb",
                "price": "20.00",
                "qty_onhand": "11",
                "color": "all",
                "lft": "23",
                "rgt": "24",
                "level": "4",
                "uiicon": "ui-icon-note"
            },
            {
                "category_id": "21",
                "name": "5Gb Flash",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "25",
                "rgt": "26",
                "level": "4",
                "uiicon": "ui-icon-comment"
            },
            {
                "category_id": "22",
                "name": "10Gb  flash ",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "27",
                "rgt": "28",
                "level": "4",
                "uiicon": "ui-icon-tag"
            },
            {
                "category_id": "16",
                "name": " Power-MP3 128mb",
                "price": "123.00",
                "qty_onhand": "2",
                "color": "withe",
                "lft": "30",
                "rgt": "31",
                "level": "3",
                "uiicon": "ui-icon-signal-diag"
            },
            {
                "category_id": "9",
                "name": "CD PLAYERS",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "33",
                "rgt": "38",
                "level": "2",
                "uiicon": ""
            },
            {
                "category_id": "18",
                "name": " Porta CD ",
                "price": "10.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "34",
                "rgt": "35",
                "level": "3",
                "uiicon": "ui-icon-eject"
            },
            {
                "category_id": "19",
                "name": "CD To go!",
                "price": "110.00",
                "qty_onhand": "11",
                "color": "",
                "lft": "36",
                "rgt": "37",
                "level": "3",
                "uiicon": "ui-icon-power"
            },
            {
                "category_id": "10",
                "name": "2 WAY RADIOS",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "39",
                "rgt": "42",
                "level": "2",
                "uiicon": ""
            },
            {
                "category_id": "20",
                "name": "Family Talk 360 ",
                "price": "200.00",
                "qty_onhand": "15",
                "color": "",
                "lft": "40",
                "rgt": "41",
                "level": "3",
                "uiicon": "ui-icon-volume-on"
            },
            {
                "category_id": "23",
                "name": "COMPUTERS",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "45",
                "rgt": "50",
                "level": "0",
                "uiicon": ""
            },
            {
                "category_id": "25",
                "name": "DESKTOP ",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "46",
                "rgt": "47",
                "level": "1",
                "uiicon": ""
            },
            {
                "category_id": "26",
                "name": "LAPTOPS",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "48",
                "rgt": "49",
                "level": "1",
                "uiicon": ""
            },
            {
                "category_id": "24",
                "name": "APPLIANCES",
                "price": "0.00",
                "qty_onhand": "0",
                "color": "",
                "lft": "51",
                "rgt": "52",
                "level": "0",
                "uiicon": ""
            }
        ]

        jQuery(document).ready(function ($) {
            jQuery('#tree').jqGrid({
                // "url":"data.json",
                "colModel": [
                    {
                        "name": "category_id",
                        "index": "accounts.account_id",
                        "sorttype": "int",
                        "key": true,
                        "hidden": true,
                        "width": 50
                    }, {
                        "name": "name",
                        "index": "name",
                        "sorttype": "string",
                        "label": "Name",
                        "width": 170
                    }, {
                        "name": "price",
                        "index": "price",
                        "sorttype": "numeric",
                        "label": "Price",
                        "width": 90,
                        "align": "right"
                    }, {
                        "name": "qty_onhand",
                        "index": "qty_onhand",
                        "sorttype": "int",
                        "label": "Qty",
                        "width": 90,
                        "align": "right"
                    }, {
                        "name": "color",
                        "index": "color",
                        "sorttype": "string",
                        "label": "Color",
                        "width": 100
                    }, {
                        "name": "lft",
                        "hidden": true
                    }, {
                        "name": "rgt",
                        "hidden": true
                    }, {
                        "name": "level",
                        "hidden": true
                    }, {
                        "name": "uiicon",
                        "hidden": true
                    }
                ],
                "width": "780",
                "hoverrows": false,
                "viewrecords": false,
                "gridview": true,
                "height": "auto",
                "sortname": "lft",
                "loadonce": true,
                "rowNum": 100,
                "scrollrows": true,
                // enable tree grid
                "treeGrid": true,
                // which column is expandable
                "ExpandColumn": "name",
                // datatype
                "treedatatype": "json",
                // the model used
                "treeGridModel": "nested",

                // configuration of the data comming from server
                "treeReader": {
                    "left_field": "lft",
                    "right_field": "rgt",
                    "level_field": "level",
                    "leaf_field": "isLeaf",
                    "expanded_field": "expanded",
                    "loaded": "loaded",
                    "icon_field": "icon"
                },
                // "sortorder": "asc",
                "datatype": "local",
                "data": rows,
                "pager": "#pager"
            });

        });

    </script>

</body>

</html>
</code>```


问:
VTK Volume Visualization Issue
I am using vtk library with C++ to generate and visualize some synthetic voxel data with given color and transparency mapping. An example is shown below:

As shown in the figure, the data is 3D in general, and it works great. However, in specific cases when the data becomes 2D, the visualization windows shows nothing.

I am posting few lines of my code which may be helpful.

```<code>imageData = vtkSmartPointer<vtkImageData>::New();
imageData->SetDimensions(X1, X2, X3); //For 2D, one of X1,X2 & X3=1
imageData->AllocateScalars(VTK_INT, 1);
int* I = new int[X1X2X3](); //int X1X2X3 = X1*X2*X3
I = static_cast<int*>(imageData->GetScalarPointer());
</code>```

Please note that for 2D, either X1=1 or X2=1 or X3=1.
Any suggestions?

EDIT:
I am adding an equivalent code, which will demonstrate the exact problem I am facing:

main.cpp

```<code>//#include <vtkAutoInit.h> // if not using CMake to compile, necessary to use this macro
//#define vtkRenderingCore_AUTOINIT 3(vtkInteractionStyle, vtkRenderingFreeType, vtkRenderingOpenGL2)
//#define vtkRenderingVolume_AUTOINIT 1(vtkRenderingVolumeOpenGL2)
//#define vtkRenderingContext2D_AUTOINIT 1(vtkRenderingContextOpenGL2)
#include <vtkSmartPointer.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartVolumeMapper.h>
#include <vtkColorTransferFunction.h>
#include <vtkVolumeProperty.h>
#include <vtkSampleFunction.h>
#include <vtkPiecewiseFunction.h>
#include <vtkImageData.h>
#include <stdlib.h>
using namespace std;

int main()
{
    //Declaring Variables
    vtkSmartPointer<vtkImageData> imageData;
    vtkSmartPointer<vtkVolumeProperty> volumeProperty;
    vtkSmartPointer<vtkPiecewiseFunction> compositeOpacity;
    vtkSmartPointer<vtkColorTransferFunction> color;
    vtkSmartPointer<vtkVolume> volume;
    vtkSmartPointer<vtkSmartVolumeMapper> mapper;
    vtkSmartPointer<vtkActor> actor;
    vtkSmartPointer<vtkRenderer> renderer;
    vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor;
    vtkSmartPointer<vtkRenderWindow> renderWindow;
    int* I;
    int X1, X2, X3, X1X2X3;

    //Assigning Values , Allocating Memory
    X1 = 10;
    X2 = 10;
    X3 = 10;
    X1X2X3 = X1*X2*X3;
    I = new int[X1X2X3]();
    imageData = vtkSmartPointer<vtkImageData>::New();
    volumeProperty = vtkSmartPointer<vtkVolumeProperty>::New();
    compositeOpacity = vtkSmartPointer<vtkPiecewiseFunction>::New();
    color = vtkSmartPointer<vtkColorTransferFunction>::New();
    volume = vtkSmartPointer<vtkVolume>::New();
    mapper = vtkSmartPointer<vtkSmartVolumeMapper>::New();
    actor = vtkSmartPointer<vtkActor>::New();
    renderer = vtkSmartPointer<vtkRenderer>::New();
    renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
    renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
    volumeProperty->ShadeOff();
    volumeProperty->SetInterpolationType(0);
    volumeProperty->SetColor(color);
    volumeProperty->SetScalarOpacity(compositeOpacity);
    imageData->SetDimensions(X1, X2, X3);
    imageData->AllocateScalars(VTK_INT, 1);
    I = static_cast<int*>(imageData->GetScalarPointer());
    renderWindow->AddRenderer(renderer);
    renderWindowInteractor->SetRenderWindow(renderWindow);
    renderer->SetBackground(0.5, 0.5, 0.5);
    renderWindow->SetSize(800, 800);
    mapper->SetBlendModeToComposite();
    imageData->UpdateCellGhostArrayCache();
    mapper->SetRequestedRenderModeToRayCast();
    mapper->SetInputData(imageData);
    volume->SetMapper(mapper);
    volume->SetProperty(volumeProperty);
    renderer->AddViewProp(volume);
    volumeProperty->ShadeOff();

    //Setting Voxel Data and Its Properties
    for (int i = 0; i < X1X2X3; i++)
    {
        I[i] = i;
        compositeOpacity->AddPoint(i, 1);
        color->AddRGBPoint(i, double( rand()) / RAND_MAX, double(rand()) / RAND_MAX, double(rand()) / RAND_MAX);
    }

    renderer->ResetCamera();
    renderWindow->Render();
    renderWindowInteractor->Start();
    getchar();
    return 0;
}
</code>```

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.0)
project(EvoSim)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
set(CMAKE_USE_RELATIVE_PATHS ON)
#GRABBING VTK
find_package(VTK REQUIRED)
include(${VTK_USE_FILE})

add_executable(MAIN main.cpp)
target_link_libraries(MAIN ${VTK_LIBRARIES})
</code>```

This leads to an output like below (for, X1=X2=X3=10)

However if I make X1=1, the output window is empty.

EDIT:

I just observed that the number of voxels along a certain dimension, displayed on the screen are always one less than the maximum number of voxels in that dimensions. For example, if X1=X2=X3=10, the number of voxels in each dimensions which are displayed on vtkwindow is 9. This is not what I would expect. I think this is the problem with X1=1, which makes 1-1=0 voxel display.
Any suggestions??

答:
This remained unanswered for long. So I am adding my solution/workaround.
I had to add an extra dummy layer in each dimension of imagedata. [See this line in the code imageData->SetDimensions(X1 +1 , X2 + 1, X3 + 1);]. Rest is self explanatory.

```<code>#pragma once
//#include <vtkAutoInit.h> // if not using CMake to compile, necessary to use this macro
//#define vtkRenderingCore_AUTOINIT 3(vtkInteractionStyle, vtkRenderingFreeType, vtkRenderingOpenGL2)
//#define vtkRenderingVolume_AUTOINIT 1(vtkRenderingVolumeOpenGL2)
//#define vtkRenderingContext2D_AUTOINIT 1(vtkRenderingContextOpenGL2)
#include <vtkSmartPointer.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartVolumeMapper.h>
#include <vtkColorTransferFunction.h>
#include <vtkVolumeProperty.h>
#include <vtkSampleFunction.h>
#include <vtkPiecewiseFunction.h>
#include <vtkImageData.h>
#include <stdlib.h>
#include <numeric>      // std::iota
using namespace std;

int main()
{
    //Declaring Variables
    vtkSmartPointer<vtkImageData> imageData;
    vtkSmartPointer<vtkVolumeProperty> volumeProperty;
    vtkSmartPointer<vtkPiecewiseFunction> compositeOpacity;
    vtkSmartPointer<vtkColorTransferFunction> color;
    vtkSmartPointer<vtkVolume> volume;
    vtkSmartPointer<vtkSmartVolumeMapper> mapper;
    vtkSmartPointer<vtkActor> actor;
    vtkSmartPointer<vtkRenderer> renderer;
    vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor;
    vtkSmartPointer<vtkRenderWindow> renderWindow;
    int X1, X2, X3, X1X2X3;
    //Assigning Values , Allocating Memory
    X1 = 10;
    X2 = 10;
    X3 = 10;
    X1X2X3 = X1*X2*X3;
    imageData = vtkSmartPointer<vtkImageData>::New();
    imageData->SetDimensions(X1 + 1, X2 + 1, X3 + 1);
    imageData->AllocateScalars(VTK_INT, 1);
    volumeProperty = vtkSmartPointer<vtkVolumeProperty>::New();
    compositeOpacity = vtkSmartPointer<vtkPiecewiseFunction>::New();
    color = vtkSmartPointer<vtkColorTransferFunction>::New();
    volume = vtkSmartPointer<vtkVolume>::New();
    mapper = vtkSmartPointer<vtkSmartVolumeMapper>::New();
    actor = vtkSmartPointer<vtkActor>::New();
    renderer = vtkSmartPointer<vtkRenderer>::New();
    renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
    renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
    volumeProperty->ShadeOff();
    volumeProperty->SetInterpolationType(0);
    volumeProperty->SetColor(color);
    volumeProperty->SetScalarOpacity(compositeOpacity);
    imageData->AllocateScalars(VTK_INT, 1);
    renderWindow->AddRenderer(renderer);
    renderWindowInteractor->SetRenderWindow(renderWindow);
    renderer->SetBackground(0.5, 0.5, 0.5);
    renderWindow->SetSize(800, 800);
    mapper->SetBlendModeToComposite();
    imageData->UpdateCellGhostArrayCache();
    mapper->SetRequestedRenderModeToRayCast();
    mapper->SetInputData(imageData);
    volume->SetMapper(mapper);
    volume->SetProperty(volumeProperty);
    renderer->AddViewProp(volume);
    volumeProperty->ShadeOff();

    //I is supposed to store the 3D data which has to be shown as volume visualization. This 3D data is stored
    //as a 1D array in which the order of iteration over 3 dimensions is x->y->z, this leads to the following
    //3D to 1D index conversion farmula index1D =  i + X1*j + X1*X2*k
    vector<int> I(X1X2X3,0); // No need to use int* I = new int[X1X2X3] //Vectors are good
    std::iota(&I[0], &I[0] + X1X2X3, 1); //Creating dummy data as 1,2,3...X1X2X3

    //Setting Voxel Data and Its Properties
    for (int k = 0; k < X3 + 1 ; k++)
    {
        for (int j = 0; j < X2 + 1 ; j++)
        {
            for (int i = 0; i < X1 + 1 ; i++)
            {
                int* voxel = static_cast<int*>(imageData->GetScalarPointer(i, j, k));

                if (i==X1 || j== X2 || k==X3)
                {
                    //Assigning zeros to dummy voxels, these will not be displayed anyways
                    voxel[0] = 0;
                }

                else
                {
                    //copying data from I to imagedata voxel
                    voxel[0] = I[i + X1*j + X1*X2*k];
                }
            }
        }
    }

    //Setting Up Display Properties
    for (int i = 1; i < X1X2X3; i++)
    {
        compositeOpacity->AddPoint(i, 1);
        color->AddRGBPoint(i, double(rand()) / RAND_MAX, double(rand()) / RAND_MAX, double(rand()) / RAND_MAX);
    }

    renderer->ResetCamera();
    renderWindow->Render();
    renderWindowInteractor->Start();
    getchar();
    return 0;
}
</code>```

Now the expected number of voxels in each dimensions (10 as per the code above), are correctly seen

Title: VTK Volume Visualization Issue

Body:
I am using vtk library with C++ to generate and visualize some synthetic voxel data with given color and transparency mapping. An example is shown below:

As shown in the figure, the data is 3D in general, and it works great. However, in specific cases when the data becomes 2D, the visualization windows shows nothing.

I am posting few lines of my code which may be helpful.

imageData = vtkSmartPointer<vtkImageData>::New();
imageData->SetDimensions(X1, X2, X3); //For 2D, one of X1,X2 & X3=1
imageData->AllocateScalars(VTK_INT, 1);
int* I = new int[X1X2X3](); //int X1X2X3 = X1*X2*X3
I = static_cast<int*>(imageData->GetScalarPointer());

Please note that for 2D, either X1=1 or X2=1 or X3=1.
Any suggestions?

EDIT:
I am adding an equivalent code, which will demonstrate the exact problem I am facing:

main.cpp

//#include <vtkAutoInit.h> // if not using CMake to compile, necessary to use this macro
//#define vtkRenderingCore_AUTOINIT 3(vtkInteractionStyle, vtkRenderingFreeType, vtkRenderingOpenGL2)
//#define vtkRenderingVolume_AUTOINIT 1(vtkRenderingVolumeOpenGL2)
//#define vtkRenderingContext2D_AUTOINIT 1(vtkRenderingContextOpenGL2)
#include <vtkSmartPointer.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartVolumeMapper.h>
#include <vtkColorTransferFunction.h>
#include <vtkVolumeProperty.h>
#include <vtkSampleFunction.h>
#include <vtkPiecewiseFunction.h>
#include <vtkImageData.h>
#include <stdlib.h>
using namespace std;

int main()
{
    //Declaring Variables
    vtkSmartPointer<vtkImageData> imageData;
    vtkSmartPointer<vtkVolumeProperty> volumeProperty;
    vtkSmartPointer<vtkPiecewiseFunction> compositeOpacity;
    vtkSmartPointer<vtkColorTransferFunction> color;
    vtkSmartPointer<vtkVolume> volume;
    vtkSmartPointer<vtkSmartVolumeMapper> mapper;
    vtkSmartPointer<vtkActor> actor;
    vtkSmartPointer<vtkRenderer> renderer;
    vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor;
    vtkSmartPointer<vtkRenderWindow> renderWindow;
    int* I;
    int X1, X2, X3, X1X2X3;

    //Assigning Values , Allocating Memory
    X1 = 10;
    X2 = 10;
    X3 = 10;
    X1X2X3 = X1*X2*X3;
    I = new int[X1X2X3]();
    imageData = vtkSmartPointer<vtkImageData>::New();
    volumeProperty = vtkSmartPointer<vtkVolumeProperty>::New();
    compositeOpacity = vtkSmartPointer<vtkPiecewiseFunction>::New();
    color = vtkSmartPointer<vtkColorTransferFunction>::New();
    volume = vtkSmartPointer<vtkVolume>::New();
    mapper = vtkSmartPointer<vtkSmartVolumeMapper>::New();
    actor = vtkSmartPointer<vtkActor>::New();
    renderer = vtkSmartPointer<vtkRenderer>::New();
    renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
    renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
    volumeProperty->ShadeOff();
    volumeProperty->SetInterpolationType(0);
    volumeProperty->SetColor(color);
    volumeProperty->SetScalarOpacity(compositeOpacity);
    imageData->SetDimensions(X1, X2, X3);
    imageData->AllocateScalars(VTK_INT, 1);
    I = static_cast<int*>(imageData->GetScalarPointer());
    renderWindow->AddRenderer(renderer);
    renderWindowInteractor->SetRenderWindow(renderWindow);
    renderer->SetBackground(0.5, 0.5, 0.5);
    renderWindow->SetSize(800, 800);
    mapper->SetBlendModeToComposite();
    imageData->UpdateCellGhostArrayCache();
    mapper->SetRequestedRenderModeToRayCast();
    mapper->SetInputData(imageData);
    volume->SetMapper(mapper);
    volume->SetProperty(volumeProperty);
    renderer->AddViewProp(volume);
    volumeProperty->ShadeOff();

    //Setting Voxel Data and Its Properties
    for (int i = 0; i < X1X2X3; i++)
    {
        I[i] = i;
        compositeOpacity->AddPoint(i, 1);
        color->AddRGBPoint(i, double( rand()) / RAND_MAX, double(rand()) / RAND_MAX, double(rand()) / RAND_MAX);
    }

    renderer->ResetCamera();
    renderWindow->Render();
    renderWindowInteractor->Start();
    getchar();
    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.0)
project(EvoSim)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
set(CMAKE_USE_RELATIVE_PATHS ON)
#GRABBING VTK
find_package(VTK REQUIRED)
include(${VTK_USE_FILE})

add_executable(MAIN main.cpp)
target_link_libraries(MAIN ${VTK_LIBRARIES})

This leads to an output like below (for, X1=X2=X3=10)

However if I make X1=1, the output window is empty.

EDIT:

I just observed that the number of voxels along a certain dimension, displayed on the screen are always one less than the maximum number of voxels in that dimensions. For example, if X1=X2=X3=10, the number of voxels in each dimensions which are displayed on vtkwindow is 9. This is not what I would expect. I think this is the problem with X1=1, which makes 1-1=0 voxel display.
Any suggestions??

Body:
This remained unanswered for long. So I am adding my solution/workaround.
I had to add an extra dummy layer in each dimension of imagedata. [See this line in the code imageData->SetDimensions(X1 +1 , X2 + 1, X3 + 1);]. Rest is self explanatory.

#pragma once
//#include <vtkAutoInit.h> // if not using CMake to compile, necessary to use this macro
//#define vtkRenderingCore_AUTOINIT 3(vtkInteractionStyle, vtkRenderingFreeType, vtkRenderingOpenGL2)
//#define vtkRenderingVolume_AUTOINIT 1(vtkRenderingVolumeOpenGL2)
//#define vtkRenderingContext2D_AUTOINIT 1(vtkRenderingContextOpenGL2)
#include <vtkSmartPointer.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartVolumeMapper.h>
#include <vtkColorTransferFunction.h>
#include <vtkVolumeProperty.h>
#include <vtkSampleFunction.h>
#include <vtkPiecewiseFunction.h>
#include <vtkImageData.h>
#include <stdlib.h>
#include <numeric>      // std::iota
using namespace std;

int main()
{
    //Declaring Variables
    vtkSmartPointer<vtkImageData> imageData;
    vtkSmartPointer<vtkVolumeProperty> volumeProperty;
    vtkSmartPointer<vtkPiecewiseFunction> compositeOpacity;
    vtkSmartPointer<vtkColorTransferFunction> color;
    vtkSmartPointer<vtkVolume> volume;
    vtkSmartPointer<vtkSmartVolumeMapper> mapper;
    vtkSmartPointer<vtkActor> actor;
    vtkSmartPointer<vtkRenderer> renderer;
    vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor;
    vtkSmartPointer<vtkRenderWindow> renderWindow;
    int X1, X2, X3, X1X2X3;
    //Assigning Values , Allocating Memory
    X1 = 10;
    X2 = 10;
    X3 = 10;
    X1X2X3 = X1*X2*X3;
    imageData = vtkSmartPointer<vtkImageData>::New();
    imageData->SetDimensions(X1 + 1, X2 + 1, X3 + 1);
    imageData->AllocateScalars(VTK_INT, 1);
    volumeProperty = vtkSmartPointer<vtkVolumeProperty>::New();
    compositeOpacity = vtkSmartPointer<vtkPiecewiseFunction>::New();
    color = vtkSmartPointer<vtkColorTransferFunction>::New();
    volume = vtkSmartPointer<vtkVolume>::New();
    mapper = vtkSmartPointer<vtkSmartVolumeMapper>::New();
    actor = vtkSmartPointer<vtkActor>::New();
    renderer = vtkSmartPointer<vtkRenderer>::New();
    renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
    renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
    volumeProperty->ShadeOff();
    volumeProperty->SetInterpolationType(0);
    volumeProperty->SetColor(color);
    volumeProperty->SetScalarOpacity(compositeOpacity);
    imageData->AllocateScalars(VTK_INT, 1);
    renderWindow->AddRenderer(renderer);
    renderWindowInteractor->SetRenderWindow(renderWindow);
    renderer->SetBackground(0.5, 0.5, 0.5);
    renderWindow->SetSize(800, 800);
    mapper->SetBlendModeToComposite();
    imageData->UpdateCellGhostArrayCache();
    mapper->SetRequestedRenderModeToRayCast();
    mapper->SetInputData(imageData);
    volume->SetMapper(mapper);
    volume->SetProperty(volumeProperty);
    renderer->AddViewProp(volume);
    volumeProperty->ShadeOff();

    //I is supposed to store the 3D data which has to be shown as volume visualization. This 3D data is stored
    //as a 1D array in which the order of iteration over 3 dimensions is x->y->z, this leads to the following
    //3D to 1D index conversion farmula index1D =  i + X1*j + X1*X2*k
    vector<int> I(X1X2X3,0); // No need to use int* I = new int[X1X2X3] //Vectors are good
    std::iota(&I[0], &I[0] + X1X2X3, 1); //Creating dummy data as 1,2,3...X1X2X3

    //Setting Voxel Data and Its Properties
    for (int k = 0; k < X3 + 1 ; k++)
    {
        for (int j = 0; j < X2 + 1 ; j++)
        {
            for (int i = 0; i < X1 + 1 ; i++)
            {
                int* voxel = static_cast<int*>(imageData->GetScalarPointer(i, j, k));

                if (i==X1 || j== X2 || k==X3)
                {
                    //Assigning zeros to dummy voxels, these will not be displayed anyways
                    voxel[0] = 0;
                }

                else
                {
                    //copying data from I to imagedata voxel
                    voxel[0] = I[i + X1*j + X1*X2*k];
                }
            }
        }
    }

    //Setting Up Display Properties
    for (int i = 1; i < X1X2X3; i++)
    {
        compositeOpacity->AddPoint(i, 1);
        color->AddRGBPoint(i, double(rand()) / RAND_MAX, double(rand()) / RAND_MAX, double(rand()) / RAND_MAX);
    }

    renderer->ResetCamera();
    renderWindow->Render();
    renderWindowInteractor->Start();
    getchar();
    return 0;
}

Now the expected number of voxels in each dimensions (10 as per the code above), are correctly seen


问:
Scrapy excluding blank spaces
I have tried scrape a link(https://www.century21.com/real-estate/rock-spring-ga/LCGAROCKSPRING/). I wanted to extract "beds" data from that. since there are some empty details for some houses in that, only few "beds" details are extracted. But i want to have the details for all. If not there, then it should show "NaN" or something. Another problem is that i have inspected this tag:

            2 beds

```
</div>
</div>
</p>

<p>i used the xpath command to extract "2 beds". Only "beds" is displayed nOT "2 beds". So i used "|" to unify the 2 elements.</p>

```response.xpath('//div[@class="property-beds"]/strong/text() | //div[@class="property-beds"]/text()']
```

this got me the correct output but the problem is it is showing result in 2 seperate lines(2 in one line and beds in another line).how to display in single line?

Title: Scrapy excluding blank spaces

Body:
I have tried scrape a link(https://www.century21.com/real-estate/rock-spring-ga/LCGAROCKSPRING/). I wanted to extract "beds" data from that. since there are some empty details for some houses in that, only few "beds" details are extracted. But i want to have the details for all. If not there, then it should show "NaN" or something. Another problem is that i have inspected this tag:

            2 beds

i used the xpath command to extract "2 beds". Only "beds" is displayed nOT "2 beds". So i used "|" to unify the 2 elements.

response.xpath('//div[@class="property-beds"]/strong/text() | //div[@class="property-beds"]/text()']

this got me the correct output but the problem is it is showing result in 2 seperate lines(2 in one line and beds in another line).how to display in single line?

Body: Use string() method.root.xpath('string(//div[@class="property-beds"])')


问:
Tesseract and Php ocr
I am looking to convert a large number of image files into text using Tesseract.

I have looked at their documentation but have not idea how that relates to PHP and how my php script will interact with tesseract ocr. I have seen on other questions that suggest that php exec() might be the way.

```<code>$img = myimage.png;
$text = exec($img,'tesseract');
</code>```

I have downloaded and installed tesseract.
Using windows 7 with a recent version of xampp installed.
I have a beginner to intermediate knowledge of php.
What knowledge am I missing?

Update I now have it working with in powershell and cmd with

```<code>tesseract.exe D:\Documents\Web_Development\Sandbox\php\images\23.png D:\Documents\Web_Development\Sandbox\php\images\23
</code>```

But When I try to run it through exec like this:

```<code><?php
exec('tesseract.exe D:\Documents\Web_Development\Sandbox\images\23.png D:\Documents\Web_Development\Sandbox\images\23');
?>
</code>```

I get a popup from windows that says the tesseract.exe has stopped working. here are the error details if they mean anything to anyone.

```<code>Problem signature:
  Problem Event Name:   BEX
  Application Name: tesseract.exe
  Application Version:  0.0.0.0
  Application Timestamp:    4ca507b3
  Fault Module Name:    MSVCR90.dll
  Fault Module Version: 9.0.30729.4926
  Fault Module Timestamp:   4a1743c1
  Exception Offset: 0002f93e
  Exception Code:   c0000417
  Exception Data:   00000000
  OS Version:   6.1.7600.2.0.0.768.3
  Locale ID:    1033
  Additional Information 1: e958
  Additional Information 2: e95831f9d00a16a326250da660e931c5
  Additional Information 3: 040a
  Additional Information 4: 040a259d27c5ccf749ee18722d5fbec0
</code>```

答:
You should try to get it working without PHP, that is, to run it from the ms windows CLI interface (the ms-dos prompt). After that, you simply put whatever you have typed in the CLI in the PHP runtime, running it via CLI or some other IPC mechanisms, eventually parameterizing it with PHP variables.

For example, if in the CLI you would be typing

```<code>ipconfig /all
</code>```

to get the IP configuration of the system, then in PHP you'd simply use:

```<code><?php
echo '```';
echo exec('ipconfig /all');
echo '```';
</code>```

Back to your problem, if in the CLI you'd be issuing:

```<code>tesseract document.tif result
</code>```

Then in PHP you'd do

```<code><?php
echo '```';
echo exec('tesseract document.tif result');
echo '```';
</code>```

That's about it. It's not specific to tesseract, it works with any program (with a CLI interface).

If you need more control over the output, or the input (as it's the case when the user is asked for input while the program is running), you should use the proc_*() family of functions from http://ch2.php.net/manual/en/function.exec.php

Good luck!

Title: Tesseract and Php ocr

Body:
I am looking to convert a large number of image files into text using Tesseract.

I have looked at their documentation but have not idea how that relates to PHP and how my php script will interact with tesseract ocr. I have seen on other questions that suggest that php exec() might be the way.

$img = myimage.png;
$text = exec($img,'tesseract');

I have downloaded and installed tesseract.
Using windows 7 with a recent version of xampp installed.
I have a beginner to intermediate knowledge of php.
What knowledge am I missing?

Update I now have it working with in powershell and cmd with

tesseract.exe D:\Documents\Web_Development\Sandbox\php\images\23.png D:\Documents\Web_Development\Sandbox\php\images\23

But When I try to run it through exec like this:

<?php
exec('tesseract.exe D:\Documents\Web_Development\Sandbox\images\23.png D:\Documents\Web_Development\Sandbox\images\23');
?>

I get a popup from windows that says the tesseract.exe has stopped working. here are the error details if they mean anything to anyone.

Problem signature:
  Problem Event Name:   BEX
  Application Name: tesseract.exe
  Application Version:  0.0.0.0
  Application Timestamp:    4ca507b3
  Fault Module Name:    MSVCR90.dll
  Fault Module Version: 9.0.30729.4926
  Fault Module Timestamp:   4a1743c1
  Exception Offset: 0002f93e
  Exception Code:   c0000417
  Exception Data:   00000000
  OS Version:   6.1.7600.2.0.0.768.3
  Locale ID:    1033
  Additional Information 1: e958
  Additional Information 2: e95831f9d00a16a326250da660e931c5
  Additional Information 3: 040a
  Additional Information 4: 040a259d27c5ccf749ee18722d5fbec0

Body:
You should try to get it working without PHP, that is, to run it from the ms windows CLI interface (the ms-dos prompt). After that, you simply put whatever you have typed in the CLI in the PHP runtime, running it via CLI or some other IPC mechanisms, eventually parameterizing it with PHP variables.

For example, if in the CLI you would be typing

ipconfig /all

to get the IP configuration of the system, then in PHP you'd simply use:

<?php
echo '<pre>';
echo exec('ipconfig /all');
echo '</pre>';

Back to your problem, if in the CLI you'd be issuing:

tesseract document.tif result

Then in PHP you'd do

<?php
echo '<pre>';
echo exec('tesseract document.tif result');
echo '</pre>';

That's about it. It's not specific to tesseract, it works with any program (with a CLI interface).

If you need more control over the output, or the input (as it's the case when the user is asked for input while the program is running), you should use the proc_*() family of functions from http://ch2.php.net/manual/en/function.exec.php

Good luck!


问:
Order of component scanning in spring
Am new to spring, had defined the ApplicaionConfig.java there I placed the property file details.

```<code>package com.rao.first;

//
//  import statements
//

@Configuration
@ComponentScan(basePackageClasses = { ApplicationConfig.class  }, basePackages = { "com.rao.first" })
@PropertySources({
@PropertySource("file:${webapp.root}/resources/config/application.properties"),
@PropertySource(value = "file:${conf.dir}/someother.properties", ignoreResourceNotFound = true) })
class ApplicationConfig
{
    @Bean
    ServletContextListener logbackConfigListener()
    {
        return new LogbackConfigListener();

    }
}
</code>```

and defined some controller classes.

```<code>package com.rao.first.controller;
//
//  import statements
//
@Controller
@RequestMapping(value = "/first")
public class FirstController
{
    private String viewerUrl;

    @Inject
    public FirstController(Environment env)
    {
        this.viewerUrl = env.getProperty("property1");
    }

    //
    //

}
</code>```

But here first controller is executing, after that ApplicaitonConfig is executing, so unable to get the data from property file.

And spring-servlet.xml file configurations are

```<code><context:component-scan base-package="com.rao.first.view" />
<context:component-scan base-package="com.rao.controller.security" />
<context:component-scan base-package="com.rao.controller" />
</code>```

Please guide me how can set order of execution?

答:
You could use org.springframework.context.annotation.PropertySource annotation to retrieve values from a properties file.

So your controller class could be like following:

```<code>package com.rao.first.controller;
import org.springframework.context.annotation.PropertySource;
//
//  import statements
//
@Controller
@RequestMapping(value = "/first")
@PropertySource("classpath:/com/rao/app.properties")
public class FirstController
{
    private String viewerUrl;

    @Autowired
    Environment env;

    public FirstController()
    {
        this.viewerUrl = env.getProperty("property1");
    }

    //
    //

}
</code>```

I hope it helps you, bye.

Title: Order of component scanning in spring

Body:
Am new to spring, had defined the ApplicaionConfig.java there I placed the property file details.

package com.rao.first;

//
//  import statements
//

@Configuration
@ComponentScan(basePackageClasses = { ApplicationConfig.class  }, basePackages = { "com.rao.first" })
@PropertySources({
@PropertySource("file:${webapp.root}/resources/config/application.properties"),
@PropertySource(value = "file:${conf.dir}/someother.properties", ignoreResourceNotFound = true) })
class ApplicationConfig
{
    @Bean
    ServletContextListener logbackConfigListener()
    {
        return new LogbackConfigListener();

    }
}

and defined some controller classes.

package com.rao.first.controller;
//
//  import statements
//
@Controller
@RequestMapping(value = "/first")
public class FirstController
{
    private String viewerUrl;

    @Inject
    public FirstController(Environment env)
    {
        this.viewerUrl = env.getProperty("property1");
    }

    //
    //

}

But here first controller is executing, after that ApplicaitonConfig is executing, so unable to get the data from property file.

And spring-servlet.xml file configurations are

<context:component-scan base-package="com.rao.first.view" />
<context:component-scan base-package="com.rao.controller.security" />
<context:component-scan base-package="com.rao.controller" />

Please guide me how can set order of execution?

Body:
You could use org.springframework.context.annotation.PropertySource annotation to retrieve values from a properties file.

So your controller class could be like following:

package com.rao.first.controller;
import org.springframework.context.annotation.PropertySource;
//
//  import statements
//
@Controller
@RequestMapping(value = "/first")
@PropertySource("classpath:/com/rao/app.properties")
public class FirstController
{
    private String viewerUrl;

    @Autowired
    Environment env;

    public FirstController()
    {
        this.viewerUrl = env.getProperty("property1");
    }

    //
    //

}

I hope it helps you, bye.


问:
For loop is not working correctly in Laravel Controller
I am saving some input data into database. Using for loop I am trying to save the input data in different rows. </p>

```<code>for ($i=0; $i < $day ; $i++) {
    $activity->event_id = $request->event_id;
    $activity->created_by = $id;
    $activity->index = $request->index[$i];
    $activity->activity_title = $request->activity_title[$i];
    $activity->activity_details = $request->activity_details[$i];

    $activity->save();
}
</code>```

<p>The problem is, it only saves the last value. Suppose if day = 2 it saves the information of the second index of my arrays. Ignores the first index value. Where am I doing wrong?  </p>

答:
Instantiate your $activity within the loop, e.g.

```<code>for ($i=0; $i < $day ; $i++) {
    $activity = new Activity();

    $activity->event_id = $request->event_id;
    $activity->created_by = $id;
    $activity->index = $request->index[$i];
    $activity->activity_title = $request->activity_title[$i];
    $activity->activity_details = $request->activity_details[$i];

    $activity->save();
}
</code>```

Right now, you're just overwriting the same instance every iteration, which explains why only the last value remains.

Body:
I am saving some input data into database. Using for loop I am trying to save the input data in different rows.

for ($i=0; $i < $day ; $i++) {
    $activity->event_id = $request->event_id;
    $activity->created_by = $id;
    $activity->index = $request->index[$i];
    $activity->activity_title = $request->activity_title[$i];
    $activity->activity_details = $request->activity_details[$i];

    $activity->save();
}

The problem is, it only saves the last value. Suppose if day = 2 it saves the information of the second index of my arrays. Ignores the first index value. Where am I doing wrong?

Body:
Instantiate your $activity within the loop, e.g.

for ($i=0; $i < $day ; $i++) {
    $activity = new Activity();

    $activity->event_id = $request->event_id;
    $activity->created_by = $id;
    $activity->index = $request->index[$i];
    $activity->activity_title = $request->activity_title[$i];
    $activity->activity_details = $request->activity_details[$i];

    $activity->save();
}

Right now, you're just overwriting the same instance every iteration, which explains why only the last value remains.