问:
POSTGRES - Insert only if certain column is filled out
Have:

```<code>ID start_date  end_date     account
1   2016-06-30  null         123
1   2017-04-19  null         111
1   2017-04-26  2017-07-30   789
</code>```

Would like to accomplish:

Is there a way to create a constraint/index/other mechanism that will check that:

If ID and Account exist and end date is null -> do nothing

If ID and Account exist and end date is not null -> insert the row

So:

```<code>insert into table (ID, start_date, account) values (1,2016-08-01,123)
</code>```

-> NOTHING HAPPENS

```<code>insert into table (ID, start_date, account) values (1,2017-04-26, 789)
</code>```

-> INSERT ROW

I was thinking maybe a CHECK constraint with stored function that will check the above or something of that sort? Or index:

```<code>create unique index unique_account on table (ID, account) where end_date is null
</code>```

答:
This is The BEST PRACTICE

WARNING: Use Trigger in highly transaction database will cause performance issue.

Solution: I assume you use PostgreSQL 9.5 or Above

Until this step you almost done

```<code>create unique index unique_account on table (ID, account) where end_date is null
</code>```

All you have to do is using UPSERT query in PostgreSQL 9.5 or Above

ANS CASE 1:

```<code>Insert into insert_only (ID, start_date, account) values (1,'2016-08-01',123) ON CONFLICT DO NOTHING;
</code>```

*we need unique index for "CONFLICT". This Query Mean if you insert same id + acoount + date is null Then "ON CONFLICT" will execute and DO NOTHING.

ANS CASE 2:

```<code>Insert into insert_only (ID, start_date, end_date,account) values (1,'2016-08-01','2016-08-01',789) ON CONFLICT DO NOTHING;
</code>```

*Using the same query we input end_date value on account 789 the insert will be successful.

OUTPUT:

```<code>BEFORE:

stackoverflow=# select * from insert_only;
 id | start_date |  end_date  | account
----+------------+------------+---------
  1 | 2016-08-01 |            |     123
  1 | 2017-08-01 |            |     111
  1 | 2017-04-26 | 2017-07-30 |     789
  1 | 2016-08-01 | 2016-08-01 |     789
(4 rows)

stackoverflow=# Insert into insert_only (ID, start_date, account) values (1,'2016-08-01',123) ON CONFLICT DO NOTHING;
INSERT 0 0

stackoverflow=# Insert into insert_only (ID, start_date, end_date,account) values (1,'2016-08-01','2016-08-01',789) ON CONFLICT DO NOTHING;
INSERT 0 1

AFTER:

stackoverflow=# select * from insert_only;
 id | start_date |  end_date  | account
----+------------+------------+---------
  1 | 2016-08-01 |            |     123
  1 | 2017-08-01 |            |     111
  1 | 2017-04-26 | 2017-07-30 |     789
  1 | 2016-08-01 | 2016-08-01 |     789
  1 | 2016-08-01 | 2016-08-01 |     789
(5 rows)
</code>```

Body:
Have:

ID start_date  end_date     account
1   2016-06-30  null         123
1   2017-04-19  null         111
1   2017-04-26  2017-07-30   789

Would like to accomplish:

Is there a way to create a constraint/index/other mechanism that will check that:

If ID and Account exist and end date is null -> do nothing

If ID and Account exist and end date is not null -> insert the row

So:

insert into table (ID, start_date, account) values (1,2016-08-01,123)

-> NOTHING HAPPENS

insert into table (ID, start_date, account) values (1,2017-04-26, 789)

-> INSERT ROW

I was thinking maybe a CHECK constraint with stored function that will check the above or something of that sort? Or index:

create unique index unique_account on table (ID, account) where end_date is null

Body:
This is The BEST PRACTICE

WARNING: Use Trigger in highly transaction database will cause performance issue.

Solution: I assume you use PostgreSQL 9.5 or Above

Until this step you almost done

create unique index unique_account on table (ID, account) where end_date is null

All you have to do is using UPSERT query in PostgreSQL 9.5 or Above

ANS CASE 1:

Insert into insert_only (ID, start_date, account) values (1,'2016-08-01',123) ON CONFLICT DO NOTHING;

*we need unique index for "CONFLICT". This Query Mean if you insert same id + acoount + date is null Then "ON CONFLICT" will execute and DO NOTHING.

ANS CASE 2:

Insert into insert_only (ID, start_date, end_date,account) values (1,'2016-08-01','2016-08-01',789) ON CONFLICT DO NOTHING;

*Using the same query we input end_date value on account 789 the insert will be successful.

OUTPUT:

BEFORE:

stackoverflow=# select * from insert_only;
 id | start_date |  end_date  | account
----+------------+------------+---------
  1 | 2016-08-01 |            |     123
  1 | 2017-08-01 |            |     111
  1 | 2017-04-26 | 2017-07-30 |     789
  1 | 2016-08-01 | 2016-08-01 |     789
(4 rows)

stackoverflow=# Insert into insert_only (ID, start_date, account) values (1,'2016-08-01',123) ON CONFLICT DO NOTHING;
INSERT 0 0

stackoverflow=# Insert into insert_only (ID, start_date, end_date,account) values (1,'2016-08-01','2016-08-01',789) ON CONFLICT DO NOTHING;
INSERT 0 1

AFTER:

stackoverflow=# select * from insert_only;
 id | start_date |  end_date  | account
----+------------+------------+---------
  1 | 2016-08-01 |            |     123
  1 | 2017-08-01 |            |     111
  1 | 2017-04-26 | 2017-07-30 |     789
  1 | 2016-08-01 | 2016-08-01 |     789
  1 | 2016-08-01 | 2016-08-01 |     789
(5 rows)


来源: stackexchange

问:
Instruct WCF to deserialize type T1 as T2
Let's have a very simplified example:

```<code>[ServiceContract]
public interface IMyService
{
    [OperationContract]
    T1 GetData();
}

[DataContract]
[KnownType(typeof(T2))]
public class T1
{
    [DataMember]
    int Value { get; set; }
}

[DataContract]
public class T2: T1
{ }
</code>```

I need to be able to send T1, but receive it as T2 on client side (simplified reasons: fast conversion of business objects to client readonly types; convert server pooled objects to client unpooled types. I can elaborate further if needed).

To make it little more complicated - type tree for the data being sent has more types, e.g.:

```<code>[OperationContract]
TBase GetData();

[DataContract]
[KnownType(typeof(T1))]
[KnownType(typeof(T2))]
[KnownType(typeof(T3))]
[KnownType(typeof(Tn))]
public class TBase
{
    [DataMember]
    int Value { get; set; }
}

[DataContract]
public class T1: TBase { }

[DataContract]
public class T2: TBase { }

[DataContract]
public class T3: TBase { }

[DataContract]
public class Tn: TBase { }
</code>```

And I need to receive all types as is, with exception of T1, that needs to be received as T2.

I tested that serialization/deserialization part is easily doable with DataContractSerializer, but I cannot find out how to instruct WCF to use different DataContractSerializer to deserialize T1.

Edit1:
It looks like this should be doable byderiving custom DataContractResolver and injecting this to Operations contracts on both (client-server) WCF sides. I got this almost working - serialization-deserialization itself works as expected, WCF still fails. I'll try to post answer once I find out the reason

答:
Two WCF extensibility points that come to mind:

Deriving from DataContractResolver (as mentioned in your own answer) - lets you define a new matching between XML and its desired .Net type. Read more here.

Implementing IDataContractSurrogate - substitutes one .Net type with another for serialization purposes. No XML is involved. Read more here.

They are both injected in a similar way, via properties on the DataContractSerializerOperationBehavior.

ContentLicense: CC BY-SA 3.0

Body:
Let's have a very simplified example:

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    T1 GetData();
}

[DataContract]
[KnownType(typeof(T2))]
public class T1
{
    [DataMember]
    int Value { get; set; }
}

[DataContract]
public class T2: T1
{ }

I need to be able to send T1, but receive it as T2 on client side (simplified reasons: fast conversion of business objects to client readonly types; convert server pooled objects to client unpooled types. I can elaborate further if needed).

To make it little more complicated - type tree for the data being sent has more types, e.g.:

[OperationContract]
TBase GetData();

[DataContract]
[KnownType(typeof(T1))]
[KnownType(typeof(T2))]
[KnownType(typeof(T3))]
[KnownType(typeof(Tn))]
public class TBase
{
    [DataMember]
    int Value { get; set; }
}

[DataContract]
public class T1: TBase { }

[DataContract]
public class T2: TBase { }

[DataContract]
public class T3: TBase { }

[DataContract]
public class Tn: TBase { }

And I need to receive all types as is, with exception of T1, that needs to be received as T2.

I tested that serialization/deserialization part is easily doable with DataContractSerializer, but I cannot find out how to instruct WCF to use different DataContractSerializer to deserialize T1.

Edit1:
It looks like this should be doable byderiving custom DataContractResolver and injecting this to Operations contracts on both (client-server) WCF sides. I got this almost working - serialization-deserialization itself works as expected, WCF still fails. I'll try to post answer once I find out the reason


问:
Anugularjs ng-disabled not working as expected for a button element
I have created a new button which should be enabled on loading on page and should get disabled while data on page is getting saved (there is a save button). So basically this new button should be disabled whenever save button is enabled.

Angular code :

```<code><input id="save" class="btn " type="button"
                        value="SAVE BUTTON" ng-click="saveData()" ng-disabled="isSaveButtonDisabled"  />
<input id="create" class="btn " type="button"
                    value="NEW BUTTON" ng-click="createNewButton()" ng-disabled="isCreateButtonDisabled" />
</code>```

In the controller, it is getting attached to scope :

```<code>$scope.isSaveButtonDisabled= isSaveButtonDisabled;
$scope.isCreateButtonDisabled= isCreateButtonDisabled;
</code>```

and there are two function which defines the value of this attribute :

```<code>function isSaveButtonDisabled(){
        $scope.isSaveButtonDisabled= true;
}
function isCreateButtonDisabled(){
        $scope.isCreateButtonDisabled= false;
}
</code>```

But the Create Button remains disabled, not matter what.

What am i missing?

答: For both buttons, you have functions defined with the same name as the 'true/false' bool properties? If so, then you need to change the two wrapper functions to something different (possibly disableSaveButton(), disableCreateButton()) and call those two functions in your existing saveData() / createNewButton()</p>

Body:
I have created a new button which should be enabled on loading on page and should get disabled while data on page is getting saved (there is a save button). So basically this new button should be disabled whenever save button is enabled.

Angular code :

<input id="save" class="btn " type="button"
                        value="SAVE BUTTON" ng-click="saveData()" ng-disabled="isSaveButtonDisabled"  />
<input id="create" class="btn " type="button"
                    value="NEW BUTTON" ng-click="createNewButton()" ng-disabled="isCreateButtonDisabled" />

In the controller, it is getting attached to scope :

$scope.isSaveButtonDisabled= isSaveButtonDisabled;
$scope.isCreateButtonDisabled= isCreateButtonDisabled;

and there are two function which defines the value of this attribute :

function isSaveButtonDisabled(){
        $scope.isSaveButtonDisabled= true;
}
function isCreateButtonDisabled(){
        $scope.isCreateButtonDisabled= false;
}

But the Create Button remains disabled, not matter what.

What am i missing?


问:
Android - Ajax style auto check of username availability
I am building an Android app in which user are required to choose a nick name. Now, two users cannot have same nick name. I have seen forms on .net where we can verify the availability of a particular username while user types or presses tab using Ajax calls.

My questions is - is anything like that available for Android. Can I query my server on the fly and verify the availability of a nick name.

Thanks a lot for your responses. If there are any tutorials, samples or Android doc references I need to look at please guide me to that.

答:
you could query your server's database of users with the currently entered username on every keypress event for the specified input component(EditText, etc), but that might be pretty network intensive and spawn a lot of threads to handle:

add a TextWatcher to your input EditText or whatever the user is entering his name into

in the onTextChanged method, you would spawn a thread to contact your database sending along the CharSequence value.  the response from your server would output some JSON perhaps with a boolean property which says if the username is available or not

user hits "ok" and expects their name to be registered for themself.  a final check needs to be made before they actually get this nickname, as the availability may have changed since(say a ton of people are registering all at once)

or...

let the user type in their desired name

let them hit "save" or "register"

at this point, send along the registration data and save it in the database if their name is available. otherwise, let the user know that it isn't and they must try again

or...

when you app starts(right before they must pick a name), contact your server's database and send the app a response holding a list of names that are already taken.

this way, you can easily check if the name is taken locally on the phone rather then sending off a request to check.

you must still always check the availability of the nickname right before saving it on the server side

edit:
I've implemented #2, which seems like that's what the majority of apps do for registering a unique name(that ive seen)

problem with #1
 - user enters in 1 letter(network thread started)
 - user enteres another letter(another thread started)
 - user enters a 3rd letter(another thread)
 - thread 2 finishes first, name is valid, user is notified
 - thread 1 finishes, name is invalid, user is notified
 - thread 3 finishes, name is invalid, user is notified

thread 2 took 4 seconds
thread 1 took 5 seconds
thread 3 took 5 seconds

say user keeps typing for 25 letters, there is a lot you have to keep track of in terms if the name is valid or not, if and what threads are still running, etc

this approach seems a bit too tedious for such a simple registration task, too much hassle

problem with #3
 - requires 1 extra network request to the server

i like this approach because you can easily and quickly notify the user if their name is available without any threading(depending how large your user list is) or worrying about how long it will take to check

number 2 is simple, easy, and can have the chance to only require 1 server request

ContentLicense: CC BY-SA 2.5


问:
How can I perform click on input using xpath
I have used the below code to click the element.But it failed to locate the element and shows element not visible.

```<code>elem3=driver.find_element_by_xpath(".//*[@id='check-box']")
elem3.click()
</code>```

The html code:

```<code><span id="Some-span" class="urCWhl" title="Indicator">
<input id="check-box" class="urC" type="checkbox" hidefocus="hidefocus" ti="-1" tabindex="-1" ct="C"/>
<span id="label-lbl" class="name_class" style="width:100%;box-sizing:border-box;" unselectable="on" f="some-id" ti="0" tabindex="0" title="Indicator"></span>
</code>```

答:
The input might be inside a frame? If so switch to that frame by doing:

```<code>driver.switch_to_frame('framename')
</code>```

or if not, try to find via id then click the element:

```<code>driver.find_element_by_id('check-box').click()
</code>```

one thing to remember is that if the checkbox is already have a value, if you click the checkbox, the check will be removed. if you want to have the checkbox to have a true value always, you may do this:

```<code>driver.execute_script("document.getElementById('check-box').setAttribute('checked','');")
</code>```

This will execute a javascript to always have a true value on the checkbox

Body:
I have used the below code to click the element.But it failed to locate the element and shows element not visible.

elem3=driver.find_element_by_xpath(".//*[@id='check-box']")
elem3.click()

The html code:

<input id="check-box" class="urC" type="checkbox" hidefocus="hidefocus" ti="-1" tabindex="-1" ct="C"/>

Body:
The input might be inside a frame? If so switch to that frame by doing:

driver.switch_to_frame('framename')

or if not, try to find via id then click the element:

driver.find_element_by_id('check-box').click()

one thing to remember is that if the checkbox is already have a value, if you click the checkbox, the check will be removed. if you want to have the checkbox to have a true value always, you may do this:

driver.execute_script("document.getElementById('check-box').setAttribute('checked','');")

This will execute a javascript to always have a true value on the checkbox


问:
save results in an array in Angular 4 after http.get()
I retrieve from an api with http.get() an array of objects. Each of item has only one property inside it: "number". I want that property to be stored in an array in my app.component. I will then use that array as data for a chart using chart.js, which for now works fine. It's more than a day that I am trying but can't figure out how to do it. Can you tell me please?

app.component.ts

```<code>import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  nrs: any;
  count: any;
  public listNrs: Array<number> = [];

  private apiAllUrl: string = 'http://localhost:3000/api/all';
  private apiCountUrl: string = 'http://localhost:3000/api/count';
  //private apiBothUrl: string = 'http://localhost:3000/api/both';

  constructor(private http:Http) {
    let now = moment.locale("it");
  }

  ngOnInit() {
    this.getAllNrs();
    this.getCountNrs();
    this.getDataNumbers();
    //this.getCount();
    //this.loadData();
  }

  getAllNrs() {
    this.http.get(this.apiAllUrl)
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.nrs = data},
        err => console.error(err),
        () => console.log(this.nrs)
      );
  }

  getCountNrs(){
    this.http.get(this.apiCountUrl)
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.count = data},
        err => console.error(err),
        () => console.log(this.count)
      );
  }

  getDataNumbers(){

  }

  //tried using jsonp
  /*loadData() {
    this.jsonp.get(this.apiAllUrl)
        .map(res => res.json())
        .subscribe(data => console.log(data));
  }*/

  /*getCount(){
    this.getAllNrs();
    for(let nr of this.nrs){
      console.log(this.nrs.nr[1]);
    }
  }*/

  newDate(days) {
    return moment().add(days, 'days');
  }

  public lineChartData:Array<any> = [
    {data: [4, 5, 56, -23, 4,], label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: [-23, 4, 4, 5, 56], label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: [4, 5, 4, 56, -23], label: 'Real-Time served links'},
  ];

  public lineChartLabels:Array<any> = ['1 Lug 2017', '2 Lug 2017', '3 Lug 2017', '4 Lug 2017', '5 Lug 2017'];

  public lineChartOptions:any = {
    responsive: true,
    /*
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },
    */
  };

  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  // events
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ChartsModule } from 'ng2-charts/ng2-charts';

/*import { DataService } from './data.service';
import { DataComponent } from './data/data.component';*/

@NgModule({
  declarations: [
    AppComponent,
    /*DataComponent*/,
  ],
  imports: [
    BrowserModule,
    HttpModule,
    ChartsModule
  ],
  providers: [/*DataService*/],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

getAllNrs() gets an array of objects where each of those has a property named number.

getAllCount() gets an array of objects where each of those has a property named count.

The problem is that even if I try to map it into an array it tells me that this.nrs is undefined and cannot get its length (Err: Cannot read property 'length' of undefined). Do you have any idea why it does so?

If there is anything else you need let me know and I'll provide it.
Thanks!

答:
From your comment, you will need to initialize your all your properties in your constructor, else it will get undefined. Typescript cannot magically know the default values of it even if you give it a type.

```<code>export class AppComponent {
    title = 'app';
    nrs: any;
    count: any;
    public listNrs: Array<number> = [];
    constructor(private http: Http) {
        let now = moment.locale("it");
        //initialize your values.
        this.nrs = [];
        this.count = 0;
    }
    //other codes
}
</code>```

After that, you can use .map() to return an array of numbers in your getAllNrs()

```<code>getAllNrs() {
    this.http.get(this.apiAllUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                this.nrs = data.map(nrObj => nrObj.number)
            },
        );
}
</code>```

Body:
I retrieve from an api with http.get() an array of objects. Each of item has only one property inside it: "number". I want that property to be stored in an array in my app.component. I will then use that array as data for a chart using chart.js, which for now works fine. It's more than a day that I am trying but can't figure out how to do it. Can you tell me please?

app.component.ts

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  nrs: any;
  count: any;
  public listNrs: Array<number> = [];

  private apiAllUrl: string = 'http://localhost:3000/api/all';
  private apiCountUrl: string = 'http://localhost:3000/api/count';
  //private apiBothUrl: string = 'http://localhost:3000/api/both';

  constructor(private http:Http) {
    let now = moment.locale("it");
  }

  ngOnInit() {
    this.getAllNrs();
    this.getCountNrs();
    this.getDataNumbers();
    //this.getCount();
    //this.loadData();
  }

  getAllNrs() {
    this.http.get(this.apiAllUrl)
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.nrs = data},
        err => console.error(err),
        () => console.log(this.nrs)
      );
  }

  getCountNrs(){
    this.http.get(this.apiCountUrl)
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.count = data},
        err => console.error(err),
        () => console.log(this.count)
      );
  }

  getDataNumbers(){

  }

  //tried using jsonp
  /*loadData() {
    this.jsonp.get(this.apiAllUrl)
        .map(res => res.json())
        .subscribe(data => console.log(data));
  }*/

  /*getCount(){
    this.getAllNrs();
    for(let nr of this.nrs){
      console.log(this.nrs.nr[1]);
    }
  }*/

  newDate(days) {
    return moment().add(days, 'days');
  }

  public lineChartData:Array<any> = [
    {data: [4, 5, 56, -23, 4,], label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: [-23, 4, 4, 5, 56], label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: [4, 5, 4, 56, -23], label: 'Real-Time served links'},
  ];

  public lineChartLabels:Array<any> = ['1 Lug 2017', '2 Lug 2017', '3 Lug 2017', '4 Lug 2017', '5 Lug 2017'];

  public lineChartOptions:any = {
    responsive: true,
    /*
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },
    */
  };

  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  // events
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}

app.module.ts

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

import { AppComponent } from './app.component';
import { ChartsModule } from 'ng2-charts/ng2-charts';

/*import { DataService } from './data.service';
import { DataComponent } from './data/data.component';*/

@NgModule({
  declarations: [
    AppComponent,
    /*DataComponent*/,
  ],
  imports: [
    BrowserModule,
    HttpModule,
    ChartsModule
  ],
  providers: [/*DataService*/],
  bootstrap: [AppComponent]
})
export class AppModule { }

getAllNrs() gets an array of objects where each of those has a property named number.

getAllCount() gets an array of objects where each of those has a property named count.

The problem is that even if I try to map it into an array it tells me that this.nrs is undefined and cannot get its length (Err: Cannot read property 'length' of undefined). Do you have any idea why it does so?

If there is anything else you need let me know and I'll provide it.
Thanks!

Body:
From your comment, you will need to initialize your all your properties in your constructor, else it will get undefined. Typescript cannot magically know the default values of it even if you give it a type.

export class AppComponent {
    title = 'app';
    nrs: any;
    count: any;
    public listNrs: Array<number> = [];
    constructor(private http: Http) {
        let now = moment.locale("it");
        //initialize your values.
        this.nrs = [];
        this.count = 0;
    }
    //other codes
}

After that, you can use .map() to return an array of numbers in your getAllNrs()

getAllNrs() {
    this.http.get(this.apiAllUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                this.nrs = data.map(nrObj => nrObj.number)
            },
        );
}


问:
Plot factor proportion in R
I have a dataset which looks like this:

```<code>     edu   default
1    1      0
2    3      1
3    1      1
4    1      0
5    2      1
6    2      0
...
</code>```

and I could make a plot using R :

```<code>ggplot(rawdata, aes(x = edu, fill = default)) +
  geom_bar() +
  labs(x = 'Education') +
  theme_excel()
</code>```

Instead of counts of 1s and 0s in default, I want to plot the proportion of 1s like this:

I calculated the proportion separately, store the results in another data frame and made this plot.

My question is: Is there a compact way that I could do this in a single ggplot() command like I did in the previous plot?

Update:
I forgot to mention that the data type of default is factor. So applying mean does not work.

答:
We recall that the proportion of 1's in a binary vector is simply its mean. The way to plot mean values per x in ggplot is using the stat_summary function. So we get:

```<code>ggplot(rawdata, aes(x = edu, y = default)) +
  stat_summary(fun.y = 'mean', geom = 'bar')
</code>```

Or:

```<code>ggplot(rawdata, aes(x = edu, y = default)) +
    geom_bar(stat = 'summary')               #include fun.y = 'mean' to avoid the message
</code>```

Both give:

Title: Plot factor proportion in R

Body:
I have a dataset which looks like this:

     edu   default
1    1      0
2    3      1
3    1      1
4    1      0
5    2      1
6    2      0
...

and I could make a plot using R :

ggplot(rawdata, aes(x = edu, fill = default)) +
  geom_bar() +
  labs(x = 'Education') +
  theme_excel()

Instead of counts of 1s and 0s in default, I want to plot the proportion of 1s like this:

I calculated the proportion separately, store the results in another data frame and made this plot.

My question is: Is there a compact way that I could do this in a single ggplot() command like I did in the previous plot?

Update:
I forgot to mention that the data type of default is factor. So applying mean does not work.

Body:
We recall that the proportion of 1's in a binary vector is simply its mean. The way to plot mean values per x in ggplot is using the stat_summary function. So we get:

ggplot(rawdata, aes(x = edu, y = default)) +
  stat_summary(fun.y = 'mean', geom = 'bar')

Or:

ggplot(rawdata, aes(x = edu, y = default)) +
    geom_bar(stat = 'summary')               #include fun.y = 'mean' to avoid the message

Both give:


问:
Kendo DropDownList Conditional if else template
Currently my template looks like this:

```<code>template: '#:data.Name# (#:data.Code#)'
</code>```

What I would like to do is to check the data.Code parameter if it's empty.
If (data.Code == '') then

```<code>template: '#:data.Name#
</code>```

else the first template that contains both name and code.

I've been trying something like this but it doesn't seem to work.

```<code>template: "#if(#:data.Code#==''){ #:data.Name# (#:data.Code#)}else {#:data.Name#}#"
</code>```

Help would be very appreciated.

答:
Do it like this:

```<code>tempalte: "#: Name # # if (data.Code) { # (#= Code #) # } #"
</code>```

If I break it down it will be more clear:

```<code>#: Name #
# if (data.Code) { #
    (#: Code #)
# } #
</code>```

As you see, the rules are as follows:

JS code should be placed between two #.

Values should be placed between a #: and a #.

Body:
Currently my template looks like this:

template: '#:data.Name# (#:data.Code#)'

What I would like to do is to check the data.Code parameter if it's empty.
If (data.Code == '') then

template: '#:data.Name#

else the first template that contains both name and code.

I've been trying something like this but it doesn't seem to work.

template: "#if(#:data.Code#==''){ #:data.Name# (#:data.Code#)}else {#:data.Name#}#"

Help would be very appreciated.

Body:
Do it like this:

tempalte: "#: Name # # if (data.Code) { # (#= Code #) # } #"

If I break it down it will be more clear:

#: Name #
# if (data.Code) { #
    (#: Code #)
# } #

As you see, the rules are as follows:

JS code should be placed between two #.

Values should be placed between a #: and a #.


问:
How to get Textinputlayout hint android in multiple lines?
I have tried many options available online but none of them seem to be working.

I have used this XML for this purpose.

```<code><android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:hintTextAppearance="@style/TextLabel">

    <com.projects.fonts.RobotoEditText
        style="@style/EditText"
        android:hint="@string/description"
        android:singleLine="false"
        app:font="@string/roboto_regular" />

</android.support.design.widget.TextInputLayout>
</code>```

I have also set

```<code><item name="android:singleLine">false</item>
</code>```

in both TextLabel and EditText. But none of them are working.

答:
You can't.

TextInputLayout uses CollapsingTextLayout which measures the hint as a CharSequence:

```<code>mTextPaint.measureText(mTextToDraw, 0, mTextToDraw.length())
</code>```

CharSequence has no notion of a line, thus you can't add more.

It's not quite a hint if it's so long.
If you still want to display it consider adding a separate TextView below/above/over and animating it (if want/need to).

Body:
I have tried many options available online but none of them seem to be working.

I have used this XML for this purpose.

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:hintTextAppearance="@style/TextLabel">

    <com.projects.fonts.RobotoEditText
        style="@style/EditText"
        android:hint="@string/description"
        android:singleLine="false"
        app:font="@string/roboto_regular" />

</android.support.design.widget.TextInputLayout>

I have also set

<item name="android:singleLine">false</item>

in both TextLabel and EditText. But none of them are working.

Body:
You can't.

TextInputLayout uses CollapsingTextLayout which measures the hint as a CharSequence:

mTextPaint.measureText(mTextToDraw, 0, mTextToDraw.length())

CharSequence has no notion of a line, thus you can't add more.

It's not quite a hint if it's so long.
If you still want to display it consider adding a separate TextView below/above/over and animating it (if want/need to).


问:
How to print output of Subprocess Python?
```<code>`import subprocess
subprocess.check_call(
['/home/kadia/tensorflow/bazelbin/tensorflow/examples/label_image/label_image',
'--graph=/home/kadia/Desktop/TrainedShadowModel-1/output_graph.pb',
'--labels=/home/kadia/Desktop/TrainedShadowModel-1/output_labels.txt',
'--output_layer=final_result',
'--input_layer=Mul',
'--image=/home/kadia/Desktop/2.jpg']`
</code>```

How can I print the output from this? Output right now going in console. I want to save the output in file

答:
You can use popen:</p>

```<code>from subprocess import Popen, PIPE

    p = Popen(['/home/kadia/tensorflow/bazelbin/tensorflow/examples/label_image/label_image',
'--graph=/home/kadia/Desktop/TrainedShadowModel-1/output_graph.pb',
'--labels=/home/kadia/Desktop/TrainedShadowModel-1/output_labels.txt',
'--output_layer=final_result',
'--input_layer=Mul',
'--image=/home/kadia/Desktop/2.jpg'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
    output, err = p.communicate(b"input data that is passed to subprocess' stdin")
    rc = p.returncode
</code>```

Body:
`import subprocess
subprocess.check_call(
['/home/kadia/tensorflow/bazelbin/tensorflow/examples/label_image/label_image',
'--graph=/home/kadia/Desktop/TrainedShadowModel-1/output_graph.pb',
'--labels=/home/kadia/Desktop/TrainedShadowModel-1/output_labels.txt',
'--output_layer=final_result',
'--input_layer=Mul',
'--image=/home/kadia/Desktop/2.jpg']`

How can I print the output from this? Output right now going in console. I want to save the output in file

Body:
You can use popen:

from subprocess import Popen, PIPE

    p = Popen(['/home/kadia/tensorflow/bazelbin/tensorflow/examples/label_image/label_image',
'--graph=/home/kadia/Desktop/TrainedShadowModel-1/output_graph.pb',
'--labels=/home/kadia/Desktop/TrainedShadowModel-1/output_labels.txt',
'--output_layer=final_result',
'--input_layer=Mul',
'--image=/home/kadia/Desktop/2.jpg'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
    output, err = p.communicate(b"input data that is passed to subprocess' stdin")
    rc = p.returncode


问:
How to store the value in datagridview in to a collection class C#
First, I import a csv file to the datagridview and changed it to the format that I want.

I'm able to filter out the data that i do not want by clicking a button, i get the data i want in the console by using console.writeline. (just for testing so  i can see what's actually happen). There are quite numbers of column that do not content the data i want for calculation, so i use .contains() and .replace to filter it out.

Now, i want to store the cell.value.toString()  which hold the value to an array but i have no idea how to implant array to it.

Here is the code

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test2
{
    public partial class Form1 : Form
    {
        OpenFileDialog openFile = new OpenFileDialog();

        public int colC { get; private set; }

        public Form1()
        {
            InitializeComponent();
        }

        public void Button1_Click(object sender, EventArgs e)
        {
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                List<string[]> rows = File.ReadLines(openFile.FileName).Select(x => x.Split(',')).ToList();
                DataTable dt = new DataTable();
                List<string> headerNames = rows[0].ToList();

                foreach (var headers in rows[0])
                {
                    dt.Columns.Add(headers);
                }
                foreach (var x in rows.Skip(1).OrderBy(r => r.First()))
                {
                    if (x[0] == "Lot ID")   //linq to check if 2 lists are have the same elements (perfect for strings)
                        continue;     //skip the row with repeated headers
                    if (x.All(val => string.IsNullOrWhiteSpace(val))) //if all columns of the row are whitespace / empty, skip this row
                        continue;
                    dt.Rows.Add(x);
                }

                dataGridView1.DataSource = dt;
                dataGridView1.ReadOnly = true;
               // dataGridView1.Columns["Lot ID"].ReadOnly = true;
                //dataGridView1.Columns[" Magazine ID"].ReadOnly = true;
                //dataGridView1.Columns["Frame ID"].ReadOnly = true;

            }
        }

        public void Form1_Load_1(object sender, EventArgs e)
        {
            openFile.Filter = "CSV|*.csv";

        }

        public void Button2_Click(object sender, EventArgs e)
        {

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "txt files (*.txt)|*.txt|Csv files (*.csv)|*.csv";
            sfd.FilterIndex = 2;

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    StreamWriter sw = new StreamWriter(sfd.FileName, false);
                    {
                        string columnHeaderText = "";

                        int countColumn = dataGridView1.ColumnCount - 1;

                        if (countColumn >= 0)
                        {
                            columnHeaderText = dataGridView1.Columns[0].HeaderText;
                        }

                        for (int i = 1; i <= countColumn; i++)
                        {
                            columnHeaderText = columnHeaderText + ',' + dataGridView1.Columns[i].HeaderText;
                        }

                        sw.WriteLine(columnHeaderText);

                        foreach (DataGridViewRow dataRowObject in dataGridView1.Rows)
                        {
                            if (!dataRowObject.IsNewRow)
                            {
                                string dataFromGrid = "";

                                dataFromGrid = dataRowObject.Cells[0].Value.ToString();

                                for (int i = 1; i <= countColumn; i++)
                                {
                                    dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();

                                }
                                sw.WriteLine(dataFromGrid);
                            }
                        }

                        sw.Flush();
                        sw.Close();
                    }
                }
                catch (Exception exceptionObject)
                {
                    MessageBox.Show(exceptionObject.ToString());
                }
                }
            }

        public void Button3_Click(object sender, EventArgs e)
        {

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    //prevent error occur coz , only execute the not null line
                    if(cell.Value != null)
                    {
                        string cellV = cell.Value.ToString();

                        //do operations with cell, filter out the unnecessary data
                        if (!cellV.Contains("="))
                        {
                            continue;
                        }
                       else if (cellV.Contains("P = "))
                        {
                            cellV = cellV.Replace("P = ", "");
                        }
                        else if (cellV.Contains("F = n/a"))
                        {
                            cellV =cellV.Replace("F = n/a", "0");

                        }
                        else if (cellV.Contains("F = "))
                        {
                            cellV = cellV.Replace("F = ", "");

                        }

                        Console.WriteLine(cellV + "\n");
                    }

                }
            }

        }

    }
    }
</code>```

Please have a look in the last method and the Picture.

Here is the output.

I skip all the data which is not related to calculation by using continue

How do i store the data that i filtered out in array???

Please do not hesitate to ask if you have any inquiry about the question.

答:
I hope that this may help. First and more important, is that when you loop through a DataGridView that has a DataSource, it is better to do modifications/additions, etc… through the DataSource instead of the grid. In this example it will make no difference, however, the code below loops through the DataSource (the DataTable) and not the grid.

Below is a revised button 3 click that will convert the strings that contain equal “=” signs to decimal values. If the string that contains an equal “=” character and does not have a valid decimal number after the equal sign… zero (0) is returned. A helper method is used to take the string “P = XX.xx” and returns a valid decimal number or zero (0) if the number is invalid. Hope this makes sense.

```<code>private void button3_Click(object sender, EventArgs e) {
  decimal decimalNumber = 0.0m;
  foreach (DataRow row in dt.Rows) {
    for (int i = 0; i < dt.Columns.Count; i++) {
      if (row.ItemArray[i] != null) {
        if (row.ItemArray[i].ToString().Contains("=")) {
          decimalNumber = GetDecimalFromEquation(row.ItemArray[i].ToString());
          textBox1.Text += decimalNumber.ToString() + Environment.NewLine;
        }
      }
    }
    textBox1.Text += Environment.NewLine;
  }
}

private decimal GetDecimalFromEquation(string numberString) {
  decimal parsedValue = 0.0m;
  if (numberString.Contains("=")) {
    numberString = numberString.Replace(" ", "");
    string[] splitArray = numberString.Split('=');
    if (splitArray.Length >= 2) {
      decimal.TryParse(splitArray[1], out parsedValue);
    }
  }
  return parsedValue;
}
</code>```

Possible cleaner version of the read csv method.

```<code>private void button1_Click(object sender, EventArgs e) {
  if (openFile.ShowDialog() == DialogResult.OK) {
    List<string[]> rows = File.ReadLines(openFile.FileName).Select(x => x.Split(',')).ToList();
    List<string> headerNames = rows[0].ToList();
    foreach (var headers in rows[0]) {
      dt.Columns.Add(headers);
    }
    foreach (var x in rows.Skip(1).OrderBy(r => r.First())) {
      if ((!(x[0] == "Lot ID")) || (!(x.All(val => string.IsNullOrWhiteSpace(val)))))
        dt.Rows.Add(x);
    }
    dataGridView1.DataSource = dt;
    dataGridView1.ReadOnly = true;
  }
}
</code>```

Lastly, possible cleaner version of the write method. It uses the DataTable instead of the grid itself.

```<code>private void button2_Click(object sender, EventArgs e) {
  SaveFileDialog sfd = new SaveFileDialog();
  sfd.Filter = "txt files (*.txt)|*.txt|Csv files (*.csv)|*.csv";
  sfd.FilterIndex = 2;
  if (sfd.ShowDialog() == DialogResult.OK) {
    try {
      using (StreamWriter sw = new StreamWriter(sfd.FileName, false)) {
        string columnString = "";
        for (int i = 0; i < dt.Columns.Count - 1; i++) {
          columnString += dt.Columns[i].ColumnName;
          if (i < dataGridView1.Columns.Count - 2)
            columnString += ",";
        }
        sw.WriteLine(columnString);
        string rowString = "";
        foreach (DataRow dr in dt.Rows) {
          rowString = "";
          for (int i = 0; i < dt.Columns.Count - 1; i++) {
            rowString += dr.ItemArray[i].ToString();
            if (i < dt.Columns.Count - 2)
              rowString += ",";
          }
          sw.WriteLine(rowString);
        }
      }
    }
    catch (Exception exceptionObject) {
      MessageBox.Show(exceptionObject.ToString());
    }
  }
}
</code>```

Body:
First, I import a csv file to the datagridview and changed it to the format that I want.

I'm able to filter out the data that i do not want by clicking a button, i get the data i want in the console by using console.writeline. (just for testing so  i can see what's actually happen). There are quite numbers of column that do not content the data i want for calculation, so i use .contains() and .replace to filter it out.

Now, i want to store the cell.value.toString()  which hold the value to an array but i have no idea how to implant array to it.

Here is the code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test2
{
    public partial class Form1 : Form
    {
        OpenFileDialog openFile = new OpenFileDialog();

        public int colC { get; private set; }

        public Form1()
        {
            InitializeComponent();
        }

        public void Button1_Click(object sender, EventArgs e)
        {
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                List<string[]> rows = File.ReadLines(openFile.FileName).Select(x => x.Split(',')).ToList();
                DataTable dt = new DataTable();
                List<string> headerNames = rows[0].ToList();

                foreach (var headers in rows[0])
                {
                    dt.Columns.Add(headers);
                }
                foreach (var x in rows.Skip(1).OrderBy(r => r.First()))
                {
                    if (x[0] == "Lot ID")   //linq to check if 2 lists are have the same elements (perfect for strings)
                        continue;     //skip the row with repeated headers
                    if (x.All(val => string.IsNullOrWhiteSpace(val))) //if all columns of the row are whitespace / empty, skip this row
                        continue;
                    dt.Rows.Add(x);
                }

                dataGridView1.DataSource = dt;
                dataGridView1.ReadOnly = true;
               // dataGridView1.Columns["Lot ID"].ReadOnly = true;
                //dataGridView1.Columns[" Magazine ID"].ReadOnly = true;
                //dataGridView1.Columns["Frame ID"].ReadOnly = true;

            }
        }

        public void Form1_Load_1(object sender, EventArgs e)
        {
            openFile.Filter = "CSV|*.csv";

        }

        public void Button2_Click(object sender, EventArgs e)
        {

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "txt files (*.txt)|*.txt|Csv files (*.csv)|*.csv";
            sfd.FilterIndex = 2;

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    StreamWriter sw = new StreamWriter(sfd.FileName, false);
                    {
                        string columnHeaderText = "";

                        int countColumn = dataGridView1.ColumnCount - 1;

                        if (countColumn >= 0)
                        {
                            columnHeaderText = dataGridView1.Columns[0].HeaderText;
                        }

                        for (int i = 1; i <= countColumn; i++)
                        {
                            columnHeaderText = columnHeaderText + ',' + dataGridView1.Columns[i].HeaderText;
                        }

                        sw.WriteLine(columnHeaderText);

                        foreach (DataGridViewRow dataRowObject in dataGridView1.Rows)
                        {
                            if (!dataRowObject.IsNewRow)
                            {
                                string dataFromGrid = "";

                                dataFromGrid = dataRowObject.Cells[0].Value.ToString();

                                for (int i = 1; i <= countColumn; i++)
                                {
                                    dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();

                                }
                                sw.WriteLine(dataFromGrid);
                            }
                        }

                        sw.Flush();
                        sw.Close();
                    }
                }
                catch (Exception exceptionObject)
                {
                    MessageBox.Show(exceptionObject.ToString());
                }
                }
            }

        public void Button3_Click(object sender, EventArgs e)
        {

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    //prevent error occur coz , only execute the not null line
                    if(cell.Value != null)
                    {
                        string cellV = cell.Value.ToString();

                        //do operations with cell, filter out the unnecessary data
                        if (!cellV.Contains("="))
                        {
                            continue;
                        }
                       else if (cellV.Contains("P = "))
                        {
                            cellV = cellV.Replace("P = ", "");
                        }
                        else if (cellV.Contains("F = n/a"))
                        {
                            cellV =cellV.Replace("F = n/a", "0");

                        }
                        else if (cellV.Contains("F = "))
                        {
                            cellV = cellV.Replace("F = ", "");

                        }

                        Console.WriteLine(cellV + "\n");
                    }

                }
            }

        }

    }
    }

Please have a look in the last method and the Picture.

Here is the output.

I skip all the data which is not related to calculation by using continue

How do i store the data that i filtered out in array???

Please do not hesitate to ask if you have any inquiry about the question.

Body:
I hope that this may help. First and more important, is that when you loop through a DataGridView that has a DataSource, it is better to do modifications/additions, etc… through the DataSource instead of the grid. In this example it will make no difference, however, the code below loops through the DataSource (the DataTable) and not the grid.

Below is a revised button 3 click that will convert the strings that contain equal “=” signs to decimal values. If the string that contains an equal “=” character and does not have a valid decimal number after the equal sign… zero (0) is returned. A helper method is used to take the string “P = XX.xx” and returns a valid decimal number or zero (0) if the number is invalid. Hope this makes sense.

private void button3_Click(object sender, EventArgs e) {
  decimal decimalNumber = 0.0m;
  foreach (DataRow row in dt.Rows) {
    for (int i = 0; i < dt.Columns.Count; i++) {
      if (row.ItemArray[i] != null) {
        if (row.ItemArray[i].ToString().Contains("=")) {
          decimalNumber = GetDecimalFromEquation(row.ItemArray[i].ToString());
          textBox1.Text += decimalNumber.ToString() + Environment.NewLine;
        }
      }
    }
    textBox1.Text += Environment.NewLine;
  }
}

private decimal GetDecimalFromEquation(string numberString) {
  decimal parsedValue = 0.0m;
  if (numberString.Contains("=")) {
    numberString = numberString.Replace(" ", "");
    string[] splitArray = numberString.Split('=');
    if (splitArray.Length >= 2) {
      decimal.TryParse(splitArray[1], out parsedValue);
    }
  }
  return parsedValue;
}

Possible cleaner version of the read csv method.

private void button1_Click(object sender, EventArgs e) {
  if (openFile.ShowDialog() == DialogResult.OK) {
    List<string[]> rows = File.ReadLines(openFile.FileName).Select(x => x.Split(',')).ToList();
    List<string> headerNames = rows[0].ToList();
    foreach (var headers in rows[0]) {
      dt.Columns.Add(headers);
    }
    foreach (var x in rows.Skip(1).OrderBy(r => r.First())) {
      if ((!(x[0] == "Lot ID")) || (!(x.All(val => string.IsNullOrWhiteSpace(val)))))
        dt.Rows.Add(x);
    }
    dataGridView1.DataSource = dt;
    dataGridView1.ReadOnly = true;
  }
}

Lastly, possible cleaner version of the write method. It uses the DataTable instead of the grid itself.

private void button2_Click(object sender, EventArgs e) {
  SaveFileDialog sfd = new SaveFileDialog();
  sfd.Filter = "txt files (*.txt)|*.txt|Csv files (*.csv)|*.csv";
  sfd.FilterIndex = 2;
  if (sfd.ShowDialog() == DialogResult.OK) {
    try {
      using (StreamWriter sw = new StreamWriter(sfd.FileName, false)) {
        string columnString = "";
        for (int i = 0; i < dt.Columns.Count - 1; i++) {
          columnString += dt.Columns[i].ColumnName;
          if (i < dataGridView1.Columns.Count - 2)
            columnString += ",";
        }
        sw.WriteLine(columnString);
        string rowString = "";
        foreach (DataRow dr in dt.Rows) {
          rowString = "";
          for (int i = 0; i < dt.Columns.Count - 1; i++) {
            rowString += dr.ItemArray[i].ToString();
            if (i < dt.Columns.Count - 2)
              rowString += ",";
          }
          sw.WriteLine(rowString);
        }
      }
    }
    catch (Exception exceptionObject) {
      MessageBox.Show(exceptionObject.ToString());
    }
  }
}


问:
HTML Structure how do i wrap whole content inside div or section
i am little confused with html structure, should i wrap whole content inside inside div or section, because am making body 90% width apart from footer</p>

```<code><body>
    <div class="homepage">
        <nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
            navigation
        </nav> <!-- Nav End -->
        <header>
            Header content
        </header> <!-- Header End -->
        <section class="product">
            Main content
        </section>
        <!-- <hr class="Hhr"> -->
    </div> <!-- Homepage End -->
    <footer>
        Footer copyrights annd social icons
    </footer>
    </div>
</body>
</code>```

答:
Why don't you style the .homepage class only? Like this:

```<code><style>
.homepage{
    width:90%;
    /*more styling here...*/
}
</style>
</code>```

Body:
i am little confused with html structure, should i wrap whole content inside inside div or section, because am making body 90% width apart from footer

            navigation

            Header content

            Main content

        Footer copyrights annd social icons

Body:
Why don't you style the .homepage class only? Like this:

<style>
.homepage{
    width:90%;
    /*more styling here...*/
}
</style>


问:
calling javascript function defined in html script tag from angular controller
I have a.html that defines javascript function inside script tag.
Since apparently xxx() is not inside bCtrl, does anyone know how to call xxx()?
The point is I can't move function xxx to controller or directive because someone who does not know angular is in charge of this function.

a.html

```<code><html ng-app="myApp">
    <div ng-controller="bCtrl">
    .....
    </div>
    <script>
        (function($) {
            $(function(){
                function xxx () {
                    // do something
                }
            });
        })(jQuery);
    </script>
</html>
</code>```

bCtrl

```<code>angular
.module('myApp')
.controller('bCtrl', [
    '$scope',
    function ($scope) {
        // wanna call xxx() if possible
    }
]);
</code>```

答:
The issue isn't that it's defined within a script tag, it's that it's defined within a function (the callback being passed to $). That means it's entirely private to that function. Unless something makes a reference to it available from outside that function, it's impossible to call it from outside the function.

One way you could make it possible would be to assign it to a global variable:

```<code>window.xxx = xxx;
</code>```

...but in general, global variables are a solution of last resort.

Instead, perhaps you could move that function into a module (ideally, all the things being done in that non-Angular block), and inject a dependency on that module into  your controller, and then call it that way.

Body:
I have a.html that defines javascript function inside script tag.
Since apparently xxx() is not inside bCtrl, does anyone know how to call xxx()?
The point is I can't move function xxx to controller or directive because someone who does not know angular is in charge of this function.

a.html

    .....

bCtrl

angular
.module('myApp')
.controller('bCtrl', [
    '$scope',
    function ($scope) {
        // wanna call xxx() if possible
    }
]);

Body:
The issue isn't that it's defined within a script tag, it's that it's defined within a function (the callback being passed to $). That means it's entirely private to that function. Unless something makes a reference to it available from outside that function, it's impossible to call it from outside the function.

One way you could make it possible would be to assign it to a global variable:

window.xxx = xxx;

...but in general, global variables are a solution of last resort.

Instead, perhaps you could move that function into a module (ideally, all the things being done in that non-Angular block), and inject a dependency on that module into  your controller, and then call it that way.


问:
OnPlatform in xamarin forms for input transparent property
I want input transperant to be true for ios and false for android i tried  OnPlatform but i could not make it work

```<code><PopupPage.InputTransparent>
                    <OnPlatform x:TypeArguments="false">
                    <OnPlatform.iOS>false</OnPlatform.iOS>
                    <OnPlatform.Android>true</OnPlatform.Android>
                </OnPlatform>
    </PopupPage.InputTransparent>
</code>```

I am wondering what should i give in this place

```<code> <OnPlatform x:TypeArguments="false">
</code>```

Any ideas are welcome.

答:
The TypeArguments needs the type of the argument you're giving in the platform specific parts. Xamarin wants to know what the string value of "false" or "true" should be casted too. In this case that's a Boolean which means you should put down x:Boolean as the value.

```<code><PopupPage.InputTransparent>
    <OnPlatform x:TypeArguments="x:Boolean">
        <OnPlatform.iOS>false</OnPlatform.iOS>
        <OnPlatform.Android>true</OnPlatform.Android>
    </OnPlatform>
</PopupPage.InputTransparent>
</code>```

The "x:" part refers back to the namespace defined at the top of your XAML file:

```<code>xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
</code>```

Body:
I want input transperant to be true for ios and false for android i tried  OnPlatform but i could not make it work

<PopupPage.InputTransparent>
                    <OnPlatform x:TypeArguments="false">
                    <OnPlatform.iOS>false</OnPlatform.iOS>
                    <OnPlatform.Android>true</OnPlatform.Android>
                </OnPlatform>
    </PopupPage.InputTransparent>

I am wondering what should i give in this place

 <OnPlatform x:TypeArguments="false">

Any ideas are welcome.

Body:
The TypeArguments needs the type of the argument you're giving in the platform specific parts. Xamarin wants to know what the string value of "false" or "true" should be casted too. In this case that's a Boolean which means you should put down x:Boolean as the value.

<PopupPage.InputTransparent>
    <OnPlatform x:TypeArguments="x:Boolean">
        <OnPlatform.iOS>false</OnPlatform.iOS>
        <OnPlatform.Android>true</OnPlatform.Android>
    </OnPlatform>
</PopupPage.InputTransparent>

The "x:" part refers back to the namespace defined at the top of your XAML file:

xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"


问:
How to revoke login/connection access to SQL Server Analysis Services (SSAS)
I've got a SQL Server Analysis Services Server 2014. I revoked the access of a user by going into the security tab of properties window of the SSAS server instance and then performing remove operation.

Then I launched SQL Server Management Studio (SSMS) in the context of the user which I had removed by using Run as different user option from context menu.

To my surprise I'm still able to connect to the SSAS server though that user( which has no access to the SSAS server) through windows integrated security. How come it is possible? Does a user need to be removed from somewhere else as well to revoke access of a user to SSAS server?

I also restarted SQL Server as well as SSAS service from services.msc console by there was no change in the outcome.

答:
TL;DR; My initial assumption that removing a user from security tab of SSAS server instance will also revoke his ability to connect to the SSAS server through SSMS was incorrect.

The Complete story: Ok. So here is what I found out finally. The main confusion arises because how SQL Server Management Studio(SSMS) behaves differently for user logins in case of Database Engine and Analysis Services (SSAS).

In case of database engine if the user with which you are trying to login using SSMS is not present inside Security -> Logins node then you can't move forward at all beyond the login screen. It gives below mentioned error:

Cannot connect to ..

------------------------------ ADDITIONAL INFORMATION:

Login failed for user 'yourMachineName\jayceeka'. (Microsoft SQL Server,
  Error: 18456)

Even if the user is present in Security -> Logins node and its login is disabled or the permission to connect to DB engine is set as Deny in the properties pages of the login then also you can't move forward. You will remain stuck on the login screen itself.

SSMS behaves differently while connecting to SSAS server. It doesn't matter whether a user is added in the Security tab of SSAS server properties (shown in my question post) or not, but as long as the user can login on the machine where SSAS server is running then he will be able to connect the SSAS server through SSMS and go past the login screen using Windows Integrated Security.

The Security tab in the properties window of SSAS server doesn't control a  user's ability to be able to connect to SSAS server through SSMS but it does control everything else like ability to connect to any DB, Cube and other things inside the SSAS server instance.

So in case the user is not present in Security tab of SSAS server properties window then he will not be able to see the databases, Cubes etc in the SSAS server even if he is able to go past the login screen in SSMS using Windows Integrated  authentication as shown below:

After I removed user Jayceeka from the SSAS server then she can't see anything inside the Databases node or Assemblies node when actually one database is present there as shown below:

Even in ADOMD.Net code - The Open() calls succeeds for Jayceeka user but fails to execute the query as she doesn't have rights on the SSAS server:

```<code>DataSet ds = new DataSet();
AdomdConnection myconnect = new AdomdConnection(@"provider=olap;datasource=.;Catalog=myDbInSsasServer");
AdomdDataAdapter mycommand = new AdomdDataAdapter();
var adomdCommand = new AdomdCommand();
adomdCommand.CommandText = "SELECT [CATALOG_NAME] AS [DATABASE],CUBE_CAPTION AS [CUBE/PERSPECTIVE],BASE_CUBE_NAME FROM $system.MDSchema_Cubes WHERE CUBE_SOURCE = 1";
mycommand.SelectCommand = adomdCommand;
mycommand.SelectCommand.Connection = myconnect;

try
{
  //Open call succeeds. This is akin to be able to connect in SSMS and go past the login screen using Windows Integrated authentication
  myconnect.Open();
  //this call fails. This is akin to the fact that she can't see databases so of course can't query it.
  adomdCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
   MessageBox.Show("error in executing query on the SSAS Server");
}
</code>```

Body:
TL;DR; My initial assumption that removing a user from security tab of SSAS server instance will also revoke his ability to connect to the SSAS server through SSMS was incorrect.

The Complete story: Ok. So here is what I found out finally. The main confusion arises because how SQL Server Management Studio(SSMS) behaves differently for user logins in case of Database Engine and Analysis Services (SSAS).

In case of database engine if the user with which you are trying to login using SSMS is not present inside Security -> Logins node then you can't move forward at all beyond the login screen. It gives below mentioned error:

Cannot connect to ..

------------------------------ ADDITIONAL INFORMATION:

Login failed for user 'yourMachineName\jayceeka'. (Microsoft SQL Server,
  Error: 18456)

Even if the user is present in Security -> Logins node and its login is disabled or the permission to connect to DB engine is set as Deny in the properties pages of the login then also you can't move forward. You will remain stuck on the login screen itself.

SSMS behaves differently while connecting to SSAS server. It doesn't matter whether a user is added in the Security tab of SSAS server properties (shown in my question post) or not, but as long as the user can login on the machine where SSAS server is running then he will be able to connect the SSAS server through SSMS and go past the login screen using Windows Integrated Security.

The Security tab in the properties window of SSAS server doesn't control a  user's ability to be able to connect to SSAS server through SSMS but it does control everything else like ability to connect to any DB, Cube and other things inside the SSAS server instance.

So in case the user is not present in Security tab of SSAS server properties window then he will not be able to see the databases, Cubes etc in the SSAS server even if he is able to go past the login screen in SSMS using Windows Integrated  authentication as shown below:

After I removed user Jayceeka from the SSAS server then she can't see anything inside the Databases node or Assemblies node when actually one database is present there as shown below:

Even in ADOMD.Net code - The Open() calls succeeds for Jayceeka user but fails to execute the query as she doesn't have rights on the SSAS server:

DataSet ds = new DataSet();
AdomdConnection myconnect = new AdomdConnection(@"provider=olap;datasource=.;Catalog=myDbInSsasServer");
AdomdDataAdapter mycommand = new AdomdDataAdapter();
var adomdCommand = new AdomdCommand();
adomdCommand.CommandText = "SELECT [CATALOG_NAME] AS [DATABASE],CUBE_CAPTION AS [CUBE/PERSPECTIVE],BASE_CUBE_NAME FROM $system.MDSchema_Cubes WHERE CUBE_SOURCE = 1";
mycommand.SelectCommand = adomdCommand;
mycommand.SelectCommand.Connection = myconnect;

try
{
  //Open call succeeds. This is akin to be able to connect in SSMS and go past the login screen using Windows Integrated authentication
  myconnect.Open();
  //this call fails. This is akin to the fact that she can't see databases so of course can't query it.
  adomdCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
   MessageBox.Show("error in executing query on the SSAS Server");
}


问:
Failed to integrate spring on a mybatis+jersey web app
I've managed to complete my web application with Jersey and Mybatis, and now i've to integrate Spring on it but i get this error: org.apache.catalina.LifecycleException: A child container failed during start
Considering this is my first time with spring i'm sure i've done something wrong.
This is my AppContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.3.xsd
    http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close" p:driverClass="${app.jdbc.driverClassName}"
    p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}"
    p:acquireIncrement="10" p:idleConnectionTestPeriod="60" p:maxPoolSize="100"
    p:maxStatements="50" p:minPoolSize="10" />

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="dao/config.xml" />
</bean>

<bean id="test" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="dao" />
</bean>
</beans>
</code>```

For the datasource i've made a file.properties with the information of the server i want to connect ( and obv. added the c3p0 jar)

I've made the Interfaces with the same name of the .xml mapper files and the methods have the same name as the id for the select/insert/update ecc.

then i've made a manager who @Autowire the above mentioned interfaces

What i am missing ? Thanks in advance

EDIT: my web.xml is structured like that:

```<code><display-name>MostraPersone</display-name>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:AppContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>TestJersey</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>logic</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>TestJersey</servlet-name>
    <url-pattern>/mostra/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>/Index.html</welcome-file>
</welcome-file-list>
</code>```

答: The cause of this exception is usually caused by the  and  errors in the web.xml, or no corresponding or word errors or other reasons, the  and , < Servlet> and  correspond to good, it should not appear this exception</p>

Body:
I've managed to complete my web application with Jersey and Mybatis, and now i've to integrate Spring on it but i get this error: org.apache.catalina.LifecycleException: A child container failed during start
Considering this is my first time with spring i'm sure i've done something wrong.
This is my AppContext.xml

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.3.xsd
    http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close" p:driverClass="${app.jdbc.driverClassName}"
    p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}"
    p:acquireIncrement="10" p:idleConnectionTestPeriod="60" p:maxPoolSize="100"
    p:maxStatements="50" p:minPoolSize="10" />

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="dao/config.xml" />
</bean>

<bean id="test" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="dao" />
</bean>
</beans>

For the datasource i've made a file.properties with the information of the server i want to connect ( and obv. added the c3p0 jar)

I've made the Interfaces with the same name of the .xml mapper files and the methods have the same name as the id for the select/insert/update ecc.

then i've made a manager who @Autowire the above mentioned interfaces

What i am missing ? Thanks in advance

EDIT: my web.xml is structured like that:

<display-name>MostraPersone</display-name>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:AppContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>TestJersey</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>logic</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>TestJersey</servlet-name>
    <url-pattern>/mostra/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>/Index.html</welcome-file>
</welcome-file-list>


问:
Include functions
EDIT
Due to the overwhelming amount of advice I have received, I have fixed my problem. (After realizing the horrible php code I had written.) :D

Thanks to all!

Is there a reason that a function that is inside an included php file won't work on the parent page? I have two functions inside a php file that is included at the top of the page. However, when I try to call the function, it doesn't do anything. Here's the basic layout:

Main page:

```<code><?php include 'includes/header.php'; ?>
<?php getPosts();?>
<div>Some HTML Code</div>
<?php endPosts(); ?>
</code>```

Header.php

```<code>function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
     while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*End while statement */
};
</code>```

Any idea why this won't work? I'm getting a blank white screen right now.

答:
That's not really how PHP works. After including the header file, PHP will see something like this:

```<code><?php
function getPosts() {
     $result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
     while($row = mysql_fetch_array($result)) {
     };

     function endPosts() {

     } /*This is just an empty function */

}; /*And here is where getPosts ends*/
?>
</code>```

You seem to be confused between what includes and function calls achieve.

What I think you want to be doing is something like:

```<code><?php
getPosts();
while($row = mysql_fetch_array($result)) {
    ?><div>Some HTML Code</div><?php
}
?>
</code>```

Title: Include functions

Body:
EDIT
Due to the overwhelming amount of advice I have received, I have fixed my problem. (After realizing the horrible php code I had written.) :D

Thanks to all!

Is there a reason that a function that is inside an included php file won't work on the parent page? I have two functions inside a php file that is included at the top of the page. However, when I try to call the function, it doesn't do anything. Here's the basic layout:

Main page:

<?php include 'includes/header.php'; ?>
<?php getPosts();?>

Some HTML Code

<?php endPosts(); ?>

Header.php

function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
     while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*End while statement */
};

Any idea why this won't work? I'm getting a blank white screen right now.

Body:
That's not really how PHP works. After including the header file, PHP will see something like this:

<?php
function getPosts() {
     $result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
     while($row = mysql_fetch_array($result)) {
     };

     function endPosts() {

     } /*This is just an empty function */

}; /*And here is where getPosts ends*/
?>

You seem to be confused between what includes and function calls achieve.

What I think you want to be doing is something like:

<?php
getPosts();
while($row = mysql_fetch_array($result)) {
    ?><div>Some HTML Code</div><?php
}
?>


问:
Azure CosmosDB, Python - Replace a document: document_link?
I have a JSON document in my database that I want to modify frequently from my python program, once every 25 seconds. I know how to upload a document to the database and read a document from it, but I do not know how to modify/replace a document.

This link shows the functions offered in the python module. I see the ReplaceDocument function, but it takes in a document-link. Though how can I get the document link? Where am I suppose to look for this information?

Thanks.

答:
It sounds like you had resolved it. Just as summary, the code below.</p>

```<code># Query a document
query = { 'query': 'SELECT * FROM <collection name> ....'}
docs = client.QueryDocuments(coll_link, query)
doc = list(docs)[0]

# Get the document link from attribute `_self`
doc_link = doc['_self']
# Modify the document
.....
# Replace the document via document link
client.ReplaceDocument(doc_link, doc)
</code>```

Body:
It sounds like you had resolved it. Just as summary, the code below.

# Query a document
query = { 'query': 'SELECT * FROM <collection name> ....'}
docs = client.QueryDocuments(coll_link, query)
doc = list(docs)[0]

# Get the document link from attribute `_self`
doc_link = doc['_self']
# Modify the document
.....
# Replace the document via document link
client.ReplaceDocument(doc_link, doc)


问:
Linq left join with multiple tables
Hi I am developing web application in .net. I have come across with below scenario.

Below is my first table.

```<code>perm_levelid  scrn_id  perm_id  perm_read  perm_write
40               1        2         1         1
41               2        2         1         1
42               3        2         1         1
</code>```

Below is my second table.

```<code>scrn_id   scrn_name
1         UserProfile
2         Change Password
3         Dashboard
4         Lease request
</code>```

The relation between above two table is scrn_id

The output i am expecting is

```<code>scrn_id  perm_id  perm_read  perm_write
1           2           1      1
2           2           1      1
3           2           1      1
4           0           0      0
</code>```

I want total 4 rows in the result. scrn_id 1,2,3 matching in both tables so i should retrieve first table perm_read  and perm_write values. Remaining value from 2 nd table also i want to get.

I tried as below.

```<code>List<screendetails> obj = new List<screendetails>();
obj = (from c in db.rolsp_perm_levelmapping
       join mapdetails in db.rolsp_scrn_screen on c.scrn_id equals mapdetails.scrn_id
       into mapObj
       from wt in mapObj.DefaultIfEmpty()
       where c.perm_id== permisssionID
       select new screendetails {
            scrn_id=c.scrn_id,
            scrn_name= wt.scrn_name,
            Read=c.perm_read,
            Write=c.perm_write
}).ToList();
return obj;
</code>```

Above query does not yields correct result. May i get some help here to fix this? Thank you

答:
```<code>obj= (from scrn in db.rolsp_scrn_screen
  from rmap in db.rolsp_perm_levelmapping
  .Where(rl=>rl.scrn_id==scrn_id).DefaultIfEmpty() select new screendetails {
                        scrn_id=scrn.scrn_id,
                        scrn_name= scrn.scrn_name,
                        Read=rmap.perm_read,
                        Write=rmap.perm_write
            }).ToList();
</code>```

Try using this... Hope this helps...

Title: Linq left join with multiple tables

Body:
Hi I am developing web application in .net. I have come across with below scenario.

Below is my first table.

perm_levelid  scrn_id  perm_id  perm_read  perm_write
40               1        2         1         1
41               2        2         1         1
42               3        2         1         1

Below is my second table.

scrn_id   scrn_name
1         UserProfile
2         Change Password
3         Dashboard
4         Lease request

The relation between above two table is scrn_id

The output i am expecting is

scrn_id  perm_id  perm_read  perm_write
1           2           1      1
2           2           1      1
3           2           1      1
4           0           0      0

I want total 4 rows in the result. scrn_id 1,2,3 matching in both tables so i should retrieve first table perm_read  and perm_write values. Remaining value from 2 nd table also i want to get.

I tried as below.

List<screendetails> obj = new List<screendetails>();
obj = (from c in db.rolsp_perm_levelmapping
       join mapdetails in db.rolsp_scrn_screen on c.scrn_id equals mapdetails.scrn_id
       into mapObj
       from wt in mapObj.DefaultIfEmpty()
       where c.perm_id== permisssionID
       select new screendetails {
            scrn_id=c.scrn_id,
            scrn_name= wt.scrn_name,
            Read=c.perm_read,
            Write=c.perm_write
}).ToList();
return obj;

Above query does not yields correct result. May i get some help here to fix this? Thank you

Body:
obj= (from scrn in db.rolsp_scrn_screen
  from rmap in db.rolsp_perm_levelmapping
  .Where(rl=>rl.scrn_id==scrn_id).DefaultIfEmpty() select new screendetails {
                        scrn_id=scrn.scrn_id,
                        scrn_name= scrn.scrn_name,
                        Read=rmap.perm_read,
                        Write=rmap.perm_write
            }).ToList();

Try using this... Hope this helps...


问:
jQuery UI : How can I set the resizing limit, aspect ratio when I increase/decrease the size of the div
I have a div tag, it is ( div tag ) resizable and inside that I have a h1 tag ( or it would be any tag ).

The Problem :

I am having 2 problems :

The aspect ratio is not working properly as I want means "when I increase/decrease the size of the div its height gets larger" so how can I set it properly and

I want to fix the smallest width on resizing means "if on decreasing the size it reached to 27px it stop decreasing."

Code

```<code>$('.draggable_element').each(function() {
        $(this).resizable({
        autoHide: true,
      handles: 's,e,w',
      aspectRatio: 1/9
    });
})
</code>```

Here is my jsFiddle

UPDATE :

I think I have not properly explained my first problem to know what's the first problem please visit to my fiddle link try to resize (increase/decrease) the div from left side or right side the height of the div will automatically increase that the problem

答:
As I have seen your fiddle. Why you don't just remove aspectRatio. It will work better for you as you are expecting.

Please update your resize().

```<code>$(this).resizable({
  autoHide: true,
  handles: 's,e,w',
  minWidth: 27
});
</code>```

I think you might be looking something like this one

Thought it will helpful

Body:
I have a div tag, it is ( div tag ) resizable and inside that I have a h1 tag ( or it would be any tag ).

The Problem :

I am having 2 problems :

The aspect ratio is not working properly as I want means "when I increase/decrease the size of the div its height gets larger" so how can I set it properly and

I want to fix the smallest width on resizing means "if on decreasing the size it reached to 27px it stop decreasing."

Code

$('.draggable_element').each(function() {
        $(this).resizable({
        autoHide: true,
      handles: 's,e,w',
      aspectRatio: 1/9
    });
})

Here is my jsFiddle

UPDATE :

I think I have not properly explained my first problem to know what's the first problem please visit to my fiddle link try to resize (increase/decrease) the div from left side or right side the height of the div will automatically increase that the problem

Body:
As I have seen your fiddle. Why you don't just remove aspectRatio. It will work better for you as you are expecting.

Please update your resize().

$(this).resizable({
  autoHide: true,
  handles: 's,e,w',
  minWidth: 27
});

I think you might be looking something like this one

Thought it will helpful


答:
I don't have much experience with OnPlatform but with OnIdiom at Typeargument you say which type your variabel is. For instance here for you it is Boolean

so try this:

```<code><OnPlatform x:TypeArguments="x:Boolean">
</code>```

Let me know if it works

Title: OnPlatform in xamarin forms for input transparent property

Body:
I don't have much experience with OnPlatform but with OnIdiom at Typeargument you say which type your variabel is. For instance here for you it is Boolean

so try this:

<OnPlatform x:TypeArguments="x:Boolean">

Let me know if it works


问:
How to compare two timestamps to see if one is later for more than a specific number of minutes?
I am trying to compare two timestamps (timeA against timeB) in the format of HH:MM without seconds, so that I can see if timeB has a time which is later than 30 minutes or more than the time of timeA. I can assume that timeB will always be equal or (most commonly) later than timeA.

```<code>REM 12:42
set "hourA=12"
set "minA=42"

REM 12:49
set "hourB=12"
set "minB=49"

if %hourA% equ %hourB% (
  if %minA% equ %minB% (
    echo A is equal to B!
  ) else (
    echo A is NOT equal to B!
  )
)
</code>```

I find really hard to implement the logic of checking if timeB is greater or equal than 30 minutes compared to timeB for cases like timeA being 12:42 and timeB being 13:15 where you need to check for the hours first, then the minutes and then do another check for the hours.

Any suggestions or example code would be great (I am relatively new to batch scripts). The batch script is run on Windows.

答:
@ECHO OFF
SETLOCAL
SET "timestra=12:42"
SET "timestrb=03:01"

SET /a timediff=(1%timestrb:~0,2% - 1%timestra:~0,2%) * 60 + (1%timestrb:~-2% - 1%timestra:~-2%)
IF %timediff% lss 0 SET /a timediff+=60*24
ECHO TIME difference=%timediff%

GOTO :EOF
```

<p>Given two valid timestrings in 24-hr format, set the time difference to 60*((100+the last HH) - (100 + the first HH)) + ((100+the last MM) - (100 + the first MM))</p>

<p>The <code>100+</code> is implemented by stringing <code>1</code> in front of the first/last 2 characters of the timestring. This overcomes batch's "leading 0 is octal" dictum since the leading digit in both cases is <code>1</code>.</p>

<p>If the result of the overall calculation is negative, then we have crossed midnight, so add an entire day's worth of minutes. This will of course only work if the distance between the two times is less than 24 hours, which is probably adequate given the presented scenario.</p>

<p><em>then</em> it's a simple matter of</p>

```if %timediff% gtr 30 (echo more than 30) else (echo less than 30)
```

Body:
I am trying to compare two timestamps (timeA against timeB) in the format of HH:MM without seconds, so that I can see if timeB has a time which is later than 30 minutes or more than the time of timeA. I can assume that timeB will always be equal or (most commonly) later than timeA.

REM 12:42
set "hourA=12"
set "minA=42"

REM 12:49
set "hourB=12"
set "minB=49"

if %hourA% equ %hourB% (
  if %minA% equ %minB% (
    echo A is equal to B!
  ) else (
    echo A is NOT equal to B!
  )
)

I find really hard to implement the logic of checking if timeB is greater or equal than 30 minutes compared to timeB for cases like timeA being 12:42 and timeB being 13:15 where you need to check for the hours first, then the minutes and then do another check for the hours.

Any suggestions or example code would be great (I am relatively new to batch scripts). The batch script is run on Windows.

Body:
@ECHO OFF
SETLOCAL
SET "timestra=12:42"
SET "timestrb=03:01"

SET /a timediff=(1%timestrb:~0,2% - 1%timestra:~0,2%) * 60 + (1%timestrb:~-2% - 1%timestra:~-2%)
IF %timediff% lss 0 SET /a timediff+=60*24
ECHO TIME difference=%timediff%

GOTO :EOF

Given two valid timestrings in 24-hr format, set the time difference to 60*((100+the last HH) - (100 + the first HH)) + ((100+the last MM) - (100 + the first MM))

The 100+ is implemented by stringing 1 in front of the first/last 2 characters of the timestring. This overcomes batch's "leading 0 is octal" dictum since the leading digit in both cases is 1.

If the result of the overall calculation is negative, then we have crossed midnight, so add an entire day's worth of minutes. This will of course only work if the distance between the two times is less than 24 hours, which is probably adequate given the presented scenario.

then it's a simple matter of

if %timediff% gtr 30 (echo more than 30) else (echo less than 30)


问:
How to trigger on click event when user clicks on pagination page numbers in datatables?
I am using datatables in which I want to trigger an on click event with alert box when user clicks on the datatable pagination numbers.

Below is the code I tried, but it works for next button.

```<code>$(document).ready(function (){
  var table = $('#example').DataTable({
    drawCallback: function(){
      $('.paginate_button.next', this.api().table().container())
         .on('click', function(){
            alert('next') ;
         });
    }
  });
});
</code>```

Live Example

答:
Issues that must be taken into consideration :

The pagination buttons is generated over and over, so a delegated event handler is needed

dataTables suppress or cancels the click event (I dont know why, it has been issued several times here on SO)

You will need a selector to exclude next and previous buttons

I would do this :

$('.dataTables_wrapper').on('mousedown touchstart', '.paginate_button:not(.previous):not(.next)', function() {
  alert('something')
})
```

<p><strong>http://jsfiddle.net/0f9Ljfjr/943/</strong></p>

<hr>

<p><strong>Update</strong>. Disable previous / next buttons after each draw, including disable functionality :</p>

```var table = $('#example').DataTable({
   ...
   drawCallback: function() {
     $('.paginate_button.next').addClass('disabled').unbind();
     $('.paginate_button.previous').addClass('disabled').unbind();
   }
})
```

Body:
I am using datatables in which I want to trigger an on click event with alert box when user clicks on the datatable pagination numbers.

Below is the code I tried, but it works for next button.

$(document).ready(function (){
  var table = $('#example').DataTable({
    drawCallback: function(){
      $('.paginate_button.next', this.api().table().container())
         .on('click', function(){
            alert('next') ;
         });
    }
  });
});

Live Example

Body:
Issues that must be taken into consideration :

The pagination buttons is generated over and over, so a delegated event handler is needed

dataTables suppress or cancels the click event (I dont know why, it has been issued several times here on SO)

You will need a selector to exclude next and previous buttons

I would do this :

$('.dataTables_wrapper').on('mousedown touchstart', '.paginate_button:not(.previous):not(.next)', function() {
  alert('something')
})

http://jsfiddle.net/0f9Ljfjr/943/

Update. Disable previous / next buttons after each draw, including disable functionality :

var table = $('#example').DataTable({
   ...
   drawCallback: function() {
     $('.paginate_button.next').addClass('disabled').unbind();
     $('.paginate_button.previous').addClass('disabled').unbind();
   }
})


问:
Good architecture for Azure for streaming analytics?
I have JSON data coming from sensors per seconds to Azure IoT hub. Data is time series with 15 variables. I want to process this data real time using c# application which is quite complex and send outputs events to some other service(can be storage or PowerBI)
What do you think is the best architectural approach for it?
1. Try to process the data in stream analytics with c# code, I know there is  .Net support for azure stream analytics but i think is very premature? Any experience in this approach?Does azure stream analytics support complex c# algorithms?
2. Store data to azure data lake and use data lake analytics to process the data?

Your experiences and recommendations are very much appreciated.
Many thanks

答:
Try to process the data in stream analytics with c# code

Azure Stream Analytics uses Stream Analytics Query Language to perform transformations and computations over streams of events. The C# SDK is just a way to create and run a Stream Analytics job. All the transformations and computations work should be written in Stream Analytics Query Language.

Store data to azure data lake and use data lake analytics to process the data?

Stream Analytics is better in real-time data handle scenarios. I suggest you combine these 2 ways together. Use Azure Stream Analytics to do a preliminary and necessary data processing and conversion and output the data to azure data lake and use data lake analytics to further process the data.