问:
How to use Infinite scroll with Virtual scroll in Ionic 3?
I'm new to ionic and angular,so having some trouble with using Infinite scroll with Virtual scroll.No data ie. images,text,click function are fetched from typescript when they are pushed in infinite scroll.Only empty ionic cards are shown.

Code below FYI:

HTML:

```<code><ion-header>
  <ion-navbar color="dark">
    <ion-title><button>Appname</button></ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="card-background-page">
  <ion-list [virtualScroll]="categories">
    <ion-item *virtualItem="let category" class="itemcss">
        <ion-card (click)="category.golink()" class="wallcard">
          <img class='homecardimage' [src]="category.Url" />
            <div class="card-title">{{category.Name}}</div>
          </ion-card>
    </ion-item>
  </ion-list>

  <ion-infinite-scroll (ionInfinite)="doInfinite($event)">
      <ion-infinite-scroll-content></ion-infinite-scroll-content>
    </ion-infinite-scroll>

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

TYPESCRIPT:

```<code>    import { Component } from '@angular/core';
    import { IonicPage, NavController, NavParams,AlertController,LoadingController,ActionSheetController } from 'ionic-angular';
    import { Network } from '@ionic-native/network';
    import {HomePage} from '../home/home';

    @IonicPage()
    @Component({
      selector: 'page-category',
      templateUrl: 'category.html',
    })

      categories = [];
      categories_arr= [
        { Name: 'name1' ,Url:'Cloudinary Link1',golink:()=>this.function1()},
        { Name: 'name2',Url:'Cloudinary Link2',golink:()=>this.function2()},
        { Name: 'name3',Url:'Cloudinary Link3',golink:()=>this.function3() },
        { Name: 'name4',Url:'Cloudinary Link4',golink:()=>this.function4()},
        { Name: 'name5',Url:'Cloudinary Link5',golink:()=>this.function5()}
      ];

    constructor(public navCtrl: NavController, public navParams: NavParams,private network: Network,public alertCtrl: AlertController,public loadingCtrl: LoadingController,public actionSheetCtrl: ActionSheetController)
      {
        for (let category = 0; category < 3; category++) {
          this.categories.push( this.categories.length +'.'+ this.categories_arr[this.categories.length]);
        }
      }

    doInfinite(infiniteScroll) {
        console.log('Begin async operation');

        setTimeout(() => {
          for (let category = 0; category < 3; category++) {
            this.categories.push( this.categories.length +'.'+ this.categories_arr[this.categories.length]);
          }

          console.log('Async operation has ended');
          infiniteScroll.complete();
        }, 500);
      }

function1(){
    this.navCtrl.push('Page1');
   }

function2(){
    this.navCtrl.push('Page2');
   }

function3(){
    this.navCtrl.push('Page3');
   }

function4(){
    this.navCtrl.push('Page4');
   }

function5(){
    this.navCtrl.push('Page5');
   }
</code>```

When i tried this code,no data(name,url image,click function)is shown,only empty ionic cards are displayed.Why? Correct my code.
Thanks.

答:
I think i found an answer to my question.May or may not work in your case.Anyway,
i made changes in typescript code.Everything else is the same.No big differences from the question.

TYPESCRIPT:

```<code>    import { Component } from '@angular/core';
    import { IonicPage, NavController, NavParams,AlertController,LoadingController,ActionSheetController } from 'ionic-angular';
    import { Network } from '@ionic-native/network';
    import {HomePage} from '../home/home';

    @IonicPage()
    @Component({
      selector: 'page-category',
      templateUrl: 'category.html',
    })

      categories = [];
      categories_arr= [
        { Name: 'name1' ,Url:'Cloudinary Link1',golink:()=>this.function1()},
        { Name: 'name2',Url:'Cloudinary Link2',golink:()=>this.function2()},
        { Name: 'name3',Url:'Cloudinary Link3',golink:()=>this.function3() },
        { Name: 'name4',Url:'Cloudinary Link4',golink:()=>this.function4()},
        { Name: 'name5',Url:'Cloudinary Link5',golink:()=>this.function5()}
      ];

    constructor(public navCtrl: NavController, public navParams: NavParams,private network: Network,public alertCtrl: AlertController,public loadingCtrl: LoadingController,public actionSheetCtrl: ActionSheetController)
      {
        for (let category = 0; category < 3; category++) {
  this.categories.push( this.categories_arr[this.categories.length]);
  //Changed in this line.
        }
      }

    doInfinite(infiniteScroll) {
        console.log('Begin async operation');

        setTimeout(() => {
          for (let category = 0; category < 3; category++) {
      if(this.categories_arr[this.categories.length]!=null){//added IF
      this.categories.push( this.categories_arr[this.categories.length]);
      //Changed in this line.
         }
            }

          console.log('Async operation has ended');
          infiniteScroll.complete();
        }, 500);
      }

function1(){
    this.navCtrl.push('Page1');
   }

function2(){
    this.navCtrl.push('Page2');
   }

function3(){
    this.navCtrl.push('Page3');
   }

function4(){
    this.navCtrl.push('Page4');
   }

function5(){
    this.navCtrl.push('Page5');
   }
</code>```

Body:
I'm new to ionic and angular,so having some trouble with using Infinite scroll with Virtual scroll.No data ie. images,text,click function are fetched from typescript when they are pushed in infinite scroll.Only empty ionic cards are shown.

Code below FYI:

HTML:

<ion-header>
  <ion-navbar color="dark">
    <ion-title><button>Appname</button></ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="card-background-page">
  <ion-list [virtualScroll]="categories">
    <ion-item *virtualItem="let category" class="itemcss">
        <ion-card (click)="category.golink()" class="wallcard">

{{category.Name}}

          </ion-card>
    </ion-item>
  </ion-list>

  <ion-infinite-scroll (ionInfinite)="doInfinite($event)">
      <ion-infinite-scroll-content></ion-infinite-scroll-content>
    </ion-infinite-scroll>

</ion-content>

TYPESCRIPT:

    import { Component } from '@angular/core';
    import { IonicPage, NavController, NavParams,AlertController,LoadingController,ActionSheetController } from 'ionic-angular';
    import { Network } from '@ionic-native/network';
    import {HomePage} from '../home/home';

    @IonicPage()
    @Component({
      selector: 'page-category',
      templateUrl: 'category.html',
    })

      categories = [];
      categories_arr= [
        { Name: 'name1' ,Url:'Cloudinary Link1',golink:()=>this.function1()},
        { Name: 'name2',Url:'Cloudinary Link2',golink:()=>this.function2()},
        { Name: 'name3',Url:'Cloudinary Link3',golink:()=>this.function3() },
        { Name: 'name4',Url:'Cloudinary Link4',golink:()=>this.function4()},
        { Name: 'name5',Url:'Cloudinary Link5',golink:()=>this.function5()}
      ];

    constructor(public navCtrl: NavController, public navParams: NavParams,private network: Network,public alertCtrl: AlertController,public loadingCtrl: LoadingController,public actionSheetCtrl: ActionSheetController)
      {
        for (let category = 0; category < 3; category++) {
          this.categories.push( this.categories.length +'.'+ this.categories_arr[this.categories.length]);
        }
      }

    doInfinite(infiniteScroll) {
        console.log('Begin async operation');

        setTimeout(() => {
          for (let category = 0; category < 3; category++) {
            this.categories.push( this.categories.length +'.'+ this.categories_arr[this.categories.length]);
          }

          console.log('Async operation has ended');
          infiniteScroll.complete();
        }, 500);
      }

function1(){
    this.navCtrl.push('Page1');
   }

function2(){
    this.navCtrl.push('Page2');
   }

function3(){
    this.navCtrl.push('Page3');
   }

function4(){
    this.navCtrl.push('Page4');
   }

function5(){
    this.navCtrl.push('Page5');
   }

When i tried this code,no data(name,url image,click function)is shown,only empty ionic cards are displayed.Why? Correct my code.
Thanks.

Body:
I think i found an answer to my question.May or may not work in your case.Anyway,
i made changes in typescript code.Everything else is the same.No big differences from the question.

TYPESCRIPT:

    import { Component } from '@angular/core';
    import { IonicPage, NavController, NavParams,AlertController,LoadingController,ActionSheetController } from 'ionic-angular';
    import { Network } from '@ionic-native/network';
    import {HomePage} from '../home/home';

    @IonicPage()
    @Component({
      selector: 'page-category',
      templateUrl: 'category.html',
    })

      categories = [];
      categories_arr= [
        { Name: 'name1' ,Url:'Cloudinary Link1',golink:()=>this.function1()},
        { Name: 'name2',Url:'Cloudinary Link2',golink:()=>this.function2()},
        { Name: 'name3',Url:'Cloudinary Link3',golink:()=>this.function3() },
        { Name: 'name4',Url:'Cloudinary Link4',golink:()=>this.function4()},
        { Name: 'name5',Url:'Cloudinary Link5',golink:()=>this.function5()}
      ];

    constructor(public navCtrl: NavController, public navParams: NavParams,private network: Network,public alertCtrl: AlertController,public loadingCtrl: LoadingController,public actionSheetCtrl: ActionSheetController)
      {
        for (let category = 0; category < 3; category++) {
  this.categories.push( this.categories_arr[this.categories.length]);
  //Changed in this line.
        }
      }

    doInfinite(infiniteScroll) {
        console.log('Begin async operation');

        setTimeout(() => {
          for (let category = 0; category < 3; category++) {
      if(this.categories_arr[this.categories.length]!=null){//added IF
      this.categories.push( this.categories_arr[this.categories.length]);
      //Changed in this line.
         }
            }

          console.log('Async operation has ended');
          infiniteScroll.complete();
        }, 500);
      }

function1(){
    this.navCtrl.push('Page1');
   }

function2(){
    this.navCtrl.push('Page2');
   }

function3(){
    this.navCtrl.push('Page3');
   }

function4(){
    this.navCtrl.push('Page4');
   }

function5(){
    this.navCtrl.push('Page5');
   }


来源: stackexchange

问:
Dynamic radio VBA
On this internal website it allow me enter a  data and depending on the data the radio box will be enable. How do I know when the radio box is enabled.

Enabled

```<code>input id="Answer1" name="Answer" type="radio" value="C"
</code>```

Disabled

```<code>input id="Answer1" name="Answer" disabled="disabled" type="radio" value="C"
</code>```

When it is disabled the getAttribute will return "disabled" but when it is enabled it will return run time error

Invalid use of Null (Error 94)

if I used

```<code>msgbox ie.document.all("Answer1").getAttribute("disabled")
</code>```

I tried the following if statement and none will caught it when it is enabled

```<code>ie.document.all("Answer1").getAttribute("disabled")  = ""
ie.document.all("Answer1").getAttribute("disabled")  = Null
ie.document.all("Answer1").getAttribute("disabled")  <> "disabled"
ie.document.all("Answer1").getAttribute("disabled")  = "disabled"
</code>```

答:
Reference:HTML  disabled Attribute

Disabled is a boolean attribute. This means that is value should not be set (e.g. disabled="disabled").  If disabled is present then the option is disabled.

```<code><option value="volvo" disabled>Volvo</option>
</code>```

You should be able to use msgbox ie.document.all("Answer1").disabled.  If this doesn't work trap the error

```<code>Function isDisabled(ele As Object) As Boolean
    On Error Resume Next
       isDisabled = ele.getAttribute("disabled")
    On Error GoTo 0
End Function
</code>```

ContentLicense: CC BY-SA 3.0

Title: Dynamic radio VBA

Body:
On this internal website it allow me enter a  data and depending on the data the radio box will be enable. How do I know when the radio box is enabled.

Enabled

input id="Answer1" name="Answer" type="radio" value="C"

Disabled

input id="Answer1" name="Answer" disabled="disabled" type="radio" value="C"

When it is disabled the getAttribute will return "disabled" but when it is enabled it will return run time error

Invalid use of Null (Error 94)

if I used

msgbox ie.document.all("Answer1").getAttribute("disabled")

I tried the following if statement and none will caught it when it is enabled

ie.document.all("Answer1").getAttribute("disabled")  = ""
ie.document.all("Answer1").getAttribute("disabled")  = Null
ie.document.all("Answer1").getAttribute("disabled")  <> "disabled"
ie.document.all("Answer1").getAttribute("disabled")  = "disabled"

Body:
Reference:HTML  disabled Attribute

Disabled is a boolean attribute. This means that is value should not be set (e.g. disabled="disabled").  If disabled is present then the option is disabled.

<option value="volvo" disabled>Volvo</option>

You should be able to use msgbox ie.document.all("Answer1").disabled.  If this doesn't work trap the error

Function isDisabled(ele As Object) As Boolean
    On Error Resume Next
       isDisabled = ele.getAttribute("disabled")
    On Error GoTo 0
End Function


问:
Remove tabindex attribute from hyperlink
I have an oracle apex page. I defined a tabscontainer region in it. There are two sub regions to this region. There is a hyper link inside each sub region, which is coded like

```<code><a class="t-Tabs-link" href="#SR_R1" role="presentation" tabindex="-1">
  <span>1</span>
</a>
</code>```

in first region and

```<code><a class="t-Tabs-link" href="#SR_R2" role="presentation" >
  <span>2</span>
</a>
</code>```

in second region.

I want to remove tabindex property of first region from this code using javascript and add property tabindex="-1" to second region.I can not add an id to this hyper link since oracle apex do not allow to edit default html attributes. How can I do this without assigning id ? or is there any way that I can assign id to this hyper link?

答:
You can use document.querySelector and you don't need to know 's ID.

You can remove tabindex by this.

```<code>document.querySelector('.t-Tabs-link:first-child').removeAttribute('tabindex');
</code>```

You can set tabindex by this.

```<code>document.querySelector('.t-Tabs-link:last-child').setAttribute('tabindex', -1);
</code>```

Body:
I have an oracle apex page. I defined a tabscontainer region in it. There are two sub regions to this region. There is a hyper link inside each sub region, which is coded like

  1

in first region and

  2

in second region.

I want to remove tabindex property of first region from this code using javascript and add property tabindex="-1" to second region.I can not add an id to this hyper link since oracle apex do not allow to edit default html attributes. How can I do this without assigning id ? or is there any way that I can assign id to this hyper link?

Body:
You can use document.querySelector and you don't need to know <a>'s ID.

You can remove tabindex by this.

document.querySelector('.t-Tabs-link:first-child').removeAttribute('tabindex');

You can set tabindex by this.

document.querySelector('.t-Tabs-link:last-child').setAttribute('tabindex', -1);


问:
Using only the top mic in an iPhone
As far as I know there are 2 mics on an iPhone. 1 is near the top next to the audio jack, and the other one is the microphone you speak into.
The default mic seems to be the one you speak into.

How does one choose programmatically which microphone to use? I'm using Core Audio for my app.

Basically I want to use the top mic for recording. Currently when I record the bottom mic is being used. Is there a way to override the default mic setting?

I know that one can override the default speaker setting by the following.

```<code>UInt32 yes = YES;

AudioSessionSetProperty( kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,        sizeof(UInt32),   &yes );
</code>```

Anything similar for microphone on an iPhone?

Thanks.

答:
my 2 cents for swift 4:</p>

```<code>class func test3Mics(){

        guard let inputs = AVAudioSession.sharedInstance().availableInputs else{
            return
        }
        print(inputs.debugDescription)

        for input in inputs{
            print(input.dataSources ?? "??")
        }

        // set preferred:
        let preferredPort = inputs[0]
        if let dataSources = preferredPort.dataSources{
        for source in dataSources {
                if source.dataSourceName=="Back" {
                    do {
                        try preferredPort.setPreferredDataSource(source)
                    }catch _ {
                            print("cannot set frontDataSource")
                    }
                }
            }
        }
    }
</code>```

Title: Using only the top mic in an iPhone

Body:
As far as I know there are 2 mics on an iPhone. 1 is near the top next to the audio jack, and the other one is the microphone you speak into.
The default mic seems to be the one you speak into.

How does one choose programmatically which microphone to use? I'm using Core Audio for my app.

Basically I want to use the top mic for recording. Currently when I record the bottom mic is being used. Is there a way to override the default mic setting?

I know that one can override the default speaker setting by the following.

UInt32 yes = YES;

AudioSessionSetProperty( kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,        sizeof(UInt32),   &yes );

Anything similar for microphone on an iPhone?

Thanks.

Body:
my 2 cents for swift 4:

class func test3Mics(){

        guard let inputs = AVAudioSession.sharedInstance().availableInputs else{
            return
        }
        print(inputs.debugDescription)

        for input in inputs{
            print(input.dataSources ?? "??")
        }

        // set preferred:
        let preferredPort = inputs[0]
        if let dataSources = preferredPort.dataSources{
        for source in dataSources {
                if source.dataSourceName=="Back" {
                    do {
                        try preferredPort.setPreferredDataSource(source)
                    }catch _ {
                            print("cannot set frontDataSource")
                    }
                }
            }
        }
    }


问:
C# Reflection Property.GetValue() Problem
I am having a problem with the following code:

```<code>int errorCount = 0;
foreach (var cinf in client.GetType().GetProperties())
{
    var vinf = viewModel.GetType().GetProperty(cinf.Name);
    if (vinf != null)
    {
        if (cinf.GetValue(client, null) != vinf.GetValue(viewModel, null))
        {
            errorCount++;
        }
    }
}
</code>```

It's for an automated test to see whether mapping a model object from a DTO has worked.  If I use the more cumbersome approch of writing this for each property:

```<code>Assert.AreEqual(viewModel.ClientCompanyID, client.ClientCompanyID);
</code>```

This works fine.

The problem is: the reflection code evaluates "if val1 != val2" statement incorrectly (or so it seems).  If I step through this code, the evaluation basically says "1 does not equal 1", and incorrectly adds an error.  Furthermore, if I test this with this code, I get the same seemingly false result:

```<code>var clientEx = client.GetType().GetProperty("ClientCompanyID");
var viewModelEx = viewModel.GetType().GetProperty("ClientCompanyID");
var clientVal = clientEx.GetValue(client, null);
var viewModelVal = viewModelEx.GetValue(viewModel, null);
bool test = (clientVal == viewModelVal);
</code>```

The bool returns false even when, stepping through the code, clientVal = 1 and viewModelVal = 1.  See attached picture.

Any help with this would be greatly appreciated!

Thanks guys.

Tim.

EDIT:  Could have given you all the answer.  Glad it was simple in the end.  Thanks alot for your help.  Cheers.

答:
You need to compare with object.Equals() instead of using reference equality.  Boxed value types will not compare as equal without using object.Equals().  Try this:

```<code>if (!object.Equals(cinf.GetValue(client, null), vinf.GetValue(viewModel, null)))
</code>```

For example, take this simple case:

```csharp> object a = 1;
csharp> object b = 1;
csharp> a == b;
false
csharp> object.Equals(a, b);
true```

ContentLicense: CC BY-SA 2.5

Body:
I am having a problem with the following code:

int errorCount = 0;
foreach (var cinf in client.GetType().GetProperties())
{
    var vinf = viewModel.GetType().GetProperty(cinf.Name);
    if (vinf != null)
    {
        if (cinf.GetValue(client, null) != vinf.GetValue(viewModel, null))
        {
            errorCount++;
        }
    }
}

It's for an automated test to see whether mapping a model object from a DTO has worked.  If I use the more cumbersome approch of writing this for each property:

Assert.AreEqual(viewModel.ClientCompanyID, client.ClientCompanyID);

This works fine.

The problem is: the reflection code evaluates "if val1 != val2" statement incorrectly (or so it seems).  If I step through this code, the evaluation basically says "1 does not equal 1", and incorrectly adds an error.  Furthermore, if I test this with this code, I get the same seemingly false result:

var clientEx = client.GetType().GetProperty("ClientCompanyID");
var viewModelEx = viewModel.GetType().GetProperty("ClientCompanyID");
var clientVal = clientEx.GetValue(client, null);
var viewModelVal = viewModelEx.GetValue(viewModel, null);
bool test = (clientVal == viewModelVal);

The bool returns false even when, stepping through the code, clientVal = 1 and viewModelVal = 1.  See attached picture.

Any help with this would be greatly appreciated!

Thanks guys.

Tim.

EDIT:  Could have given you all the answer.  Glad it was simple in the end.  Thanks alot for your help.  Cheers.

Body:
You need to compare with object.Equals() instead of using reference equality.  Boxed value types will not compare as equal without using object.Equals().  Try this:

if (!object.Equals(cinf.GetValue(client, null), vinf.GetValue(viewModel, null)))

For example, take this simple case:

csharp> object a = 1;
csharp> object b = 1;
csharp> a == b;
false
csharp> object.Equals(a, b);
true


问:
How to remove multiple header from kendo grid
I am creating a sample application in which I show data in kendo grid.
For this I get the page size data in kendo grid and then load it. when page change I load next data.

When my page change event call the grid is added in already exist grid. By this it shows multiple column header.

My sample is - http://jsfiddle.net/pporwal26/y6KdK/78/

```<code>var jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-174\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\\\\vMbhdo\\\\TgFSW\\\\42Ioulj0w.txt\"},{\"owner\":\"machine-174admin\",\"path\":\"C:\\\\workarea\\\\bada_data\\\\Employee Database - Copy (7) - Copy.mdb\"}],\"Count\":100,\"total\":100,\"page\":4}");

function nextData(page){
jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-170\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\"},{\"owner\":\"machine-170admin\",\"path\":\"C:\\\\workarea\"}],\"Count\":100,\"total\":100,\"page\":5}");
$("#grid").kendoGrid({  dataSource: {
       serverPaging: true,
       schema: {
           data: "FileList",
           total: "total"
       },
       data: jsonData
   } })
}

createGrid(jsonData);
function createGrid(jsonData){
$("#grid").kendoGrid({
   pageable: true,
   scrollable: true,

   pageable: {
         pageSize: 2,
         refresh: true,
         change:function(e){
           nextData(e.index);
         }
     },
   dataSource: {
       serverPaging: true,
       schema: {
           data: "FileList",
           total: "total",
       },
       data: jsonData
   }
});
}
</code>```

How I remove multiple header when page change event call?

答:
http://jsfiddle.net/y6KdK/79/

```<code>var grid = createGrid(jsonData);
</code>```

create the instance of your grid.

```<code>var dataSource = new kendo.data.DataSource({
  data: jsonData
});
grid.setDataSource(dataSource);
</code>```

And set your newly created datasource into your nextData function. please see the above fiddle link.

Body:
I am creating a sample application in which I show data in kendo grid.
For this I get the page size data in kendo grid and then load it. when page change I load next data.

When my page change event call the grid is added in already exist grid. By this it shows multiple column header.

My sample is - http://jsfiddle.net/pporwal26/y6KdK/78/

var jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-174\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\\\\vMbhdo\\\\TgFSW\\\\42Ioulj0w.txt\"},{\"owner\":\"machine-174admin\",\"path\":\"C:\\\\workarea\\\\bada_data\\\\Employee Database - Copy (7) - Copy.mdb\"}],\"Count\":100,\"total\":100,\"page\":4}");

function nextData(page){
jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-170\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\"},{\"owner\":\"machine-170admin\",\"path\":\"C:\\\\workarea\"}],\"Count\":100,\"total\":100,\"page\":5}");
$("#grid").kendoGrid({  dataSource: {
       serverPaging: true,
       schema: {
           data: "FileList",
           total: "total"
       },
       data: jsonData
   } })
}

createGrid(jsonData);
function createGrid(jsonData){
$("#grid").kendoGrid({
   pageable: true,
   scrollable: true,

   pageable: {
         pageSize: 2,
         refresh: true,
         change:function(e){
           nextData(e.index);
         }
     },
   dataSource: {
       serverPaging: true,
       schema: {
           data: "FileList",
           total: "total",
       },
       data: jsonData
   }
});
}

How I remove multiple header when page change event call?

Body:
http://jsfiddle.net/y6KdK/79/

var grid = createGrid(jsonData);

create the instance of your grid.

var dataSource = new kendo.data.DataSource({
  data: jsonData
});
grid.setDataSource(dataSource);

And set your newly created datasource into your nextData function. please see the above fiddle link.


问:
drawable design 3 corners with one same color and else 1 corner with other color
Colour Code : e32b0f, d03559, I want to design its background drawable please help me</p>

答:
```<code>    Try,
    int colors[] = { 0xff255779, 0xfcc6c0cd };

                GradientDrawable gradientDrawable = new GradientDrawable(
                        GradientDrawable.Orientation.TOP_BOTTOM, colors);

                view.setBackgroundDrawable(gradientDrawable);

1. choose color and add color hex code in colors array.
2. GradientDrawable using and set orientation properties.[ex. GradientDrawable.Orientation.TOP_BOTTOM]
3. set view background [ex. Linearlayout.setBackgroundDrawable(gradientDrawable);]
</code>```


问:
Google Assistance integration with Android App
I want to integrate Google Assistant in my app. I am not just for launching the the app, also to operate on it like below:

App: Hi! What are you looking for?
User: T-shirts
App: What is the size?
User: 40
App: What is the color?
User: Any / Red and blue
App: Here is the T-shirts for you
User: Show order by Popularity
App: Here it is.

Is it possible to do so by Google Assistance? Is it possible to start any activity of my app with proper intent extra?

答:
With Actions on Google as you will need to build a server side components to handle the voice/chat interaction. For an example of the voice interaction see: https://developers.google.com/actions/extending-the-assistant

As to actually starting an app from Google Assistant. I don't believe there is a direct way.

Alternatively that seems to be possible for a select set of voice commands through Google Search Voice Actions to reach your app.

Note that Google isn't taking any more requests for custom Voice Actions:
https://developers.google.com/voice-actions/custom-actions

And that the pages doesn't seem to have been updated since 2015 so I'm unclear what is still supported or not.

From what I can tell the only part of Google Search Voice Actions that may be still around in 2017 is the ability to incorporate app data into Google Search via
Firebase App Indexing


问:
Swift 3.0: Type of Expression is ambiguous without more context?
```<code>private func makeRequest<T where T:MappableNetwork>(method method: Alamofire.Method, url: String,
                         parameters: [String: AnyObject]?, keyPath: String, handler: NetworkHandler<T>.handlerArray) -> Request {

    let headers = [
        "Authorization": "",
        ]

    return Alamofire
        .request(method, url, parameters: parameters, encoding: .URL, headers: headers)
        .validate()
        .responseArray(keyPath: keyPath) { (response: Alamofire.Response<[T], NSError>) in
            if let error = response.result.error {
                if let data = response.data {
                    let error = self.getError(data)
                    if error != nil {
                        handler(.Error(error: error!))
                        return
                    }
                }
                handler(.Error(error: error))
            } else if let objects = response.result.value {
                handler(.Success(data: objects))
            }
    }
}
</code>```

I converted code swift 2.x to 3.x and I getting error Type expression is ambiguous without more context.

答:
The error you mentioned tells you that the compiler cannot determine the exact type of the value you entered.

You started with a period, something has to be before the period. Sometimes the compiler can understand without your help. That's not this case, it has several options so it's ambiguous and it asks you to tell exactly the class name that you meant.

Body:
private func makeRequest<T where T:MappableNetwork>(method method: Alamofire.Method, url: String,
                         parameters: [String: AnyObject]?, keyPath: String, handler: NetworkHandler<T>.handlerArray) -> Request {

    let headers = [
        "Authorization": "",
        ]

    return Alamofire
        .request(method, url, parameters: parameters, encoding: .URL, headers: headers)
        .validate()
        .responseArray(keyPath: keyPath) { (response: Alamofire.Response<[T], NSError>) in
            if let error = response.result.error {
                if let data = response.data {
                    let error = self.getError(data)
                    if error != nil {
                        handler(.Error(error: error!))
                        return
                    }
                }
                handler(.Error(error: error))
            } else if let objects = response.result.value {
                handler(.Success(data: objects))
            }
    }
}

I converted code swift 2.x to 3.x and I getting error Type expression is ambiguous without more context.

ContentLicense: CC BY-SA 4.0


问:
XAML Code Behind file and MVC
Does the code behind file have the same purpose as a Control class of MVC or the Boundary-Control-Entity Pattern?

I did some small projects with Silverlight and WPF, and most of the time I pretty much put the logic in the code behind file. Though with references to other classes. Not everything in the code behind.

What was/is the initial purpose of the code behind file and how do most of you use it?

Thanks,

Grant

答: The preferred design pattern for developing Silverlight applications is MVVM, in which the View Model is closer to taking over the role of a controller in MVC.  When using the MVVM pattern, I'd only use the code behind of controls to implement UI-only (view-only) logic that has little to do with the data, such as performing animations and other special effects.</p>

Title: XAML Code Behind file and MVC


问:
Prevent Firebase auth from remembering Google account?
So I'm using Firebase-UI to authenticate and sign in users, I need to use the account chooser in order for them to sign in to a different Google account (not using the account chooser results in it auto-signing them in), however, I want to either prevent it from displaying + saving accounts, or remove them on sign out.

And this is the Firebase-UI web I'm using: Firebase UI web

This isn't a huge issue when the application is running on a user's machine, however, it will also be running on a public machine with many users signing in an out, and we can't have them saved as an easy one-click sign in. The biggest security issue is the fact that I can also log into their emails once they've authenticated with Google. We want it to forget them once they sign out.

My sign-in flow:

```<code>     <script type="text/javascript">
            // FirebaseUI config.
            var uiConfig = {
                callbacks: {
                    signInSuccess: function (user, credential, redirectUrl) {
                        var userSignIn = {
                            displayName: user.displayName,
                            email: user.email,
                            emailVerified: user.emailVerified,
                            photoURL: user.photoURL,
                            uid: user.uid,
                            phoneNumber: user.phoneNumber
                        };
                        /* POST signed in user to Login Controller*/
                        var csrfToken = $('input[name="csrfToken"]').attr('value');
                        $.ajaxSetup({
                            beforeSend: function(xhr) {
                                xhr.setRequestHeader('Csrf-Token', csrfToken);
                            }
                        });
                        $.ajax({
                           url: '/signedIn',
                           type: 'POST',
                           data: JSON.stringify(userSignIn),
                           contentType: 'application/json',
                           error: function(err) {
                               console.log(err);
                           }
                        });
                        return true;
                    }
                },
                signInSuccessUrl: '/Dashboard',
                signInOptions: [{
                    provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
                    scopes: ['https://www.googleapis.com/auth/calendar']
                }],
                // Terms of service url.
                tosUrl: '/Terms'
            };

            // Initialize the FirebaseUI Widget using FirestoreDB.
            var ui = new firebaseui.auth.AuthUI(firebase.auth());
            // The start method will wait until the DOM is loaded.
            ui.start('#firebaseui-auth-container', uiConfig);
    </script>
</code>```

Sign-out flow:

```<code>initApp = function () {
firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
        // User is signed in.
        if (window.location.pathname === "/Login" || window.location.pathname === "/") {
            window.location.href = '/Dashboard';
        }
        $('#sign-out').show();
    } else {
        // User is signed out.
        $('#sign-out').hide();
        disableLinks();
        switch(window.location.pathname){
            case "/Login":
            case "/Terms":
            case "/Help":
                break;
            default:
                window.location.href = '/Login';
        }
    }
}, function (error) {
    console.log(error);
});
};

window.addEventListener('load', function () {
initApp();
document.getElementById('sign-out').addEventListener('click', function () {
    firebase.auth().signOut().then(function() {
        sessionStorage.clear();
        localStorage.clear();
        window.location = "/Logout";
    }).catch(function(error) {
        console.log(error);
        });
    });
  });
</code>```

答:
On sign out from Firebase Auth, redirect to Google single sign out URL:</p>

```<code>firebase.auth().signOut()
  .then(function() {
    window.location.assign('https://accounts.google.com/Logout');
  })
  .catch(function(error) {
    console.log(error);
  });
</code>```

Body:
So I'm using Firebase-UI to authenticate and sign in users, I need to use the account chooser in order for them to sign in to a different Google account (not using the account chooser results in it auto-signing them in), however, I want to either prevent it from displaying + saving accounts, or remove them on sign out.

And this is the Firebase-UI web I'm using: Firebase UI web

This isn't a huge issue when the application is running on a user's machine, however, it will also be running on a public machine with many users signing in an out, and we can't have them saved as an easy one-click sign in. The biggest security issue is the fact that I can also log into their emails once they've authenticated with Google. We want it to forget them once they sign out.

My sign-in flow:

Sign-out flow:

initApp = function () {
firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
        // User is signed in.
        if (window.location.pathname === "/Login" || window.location.pathname === "/") {
            window.location.href = '/Dashboard';
        }
        $('#sign-out').show();
    } else {
        // User is signed out.
        $('#sign-out').hide();
        disableLinks();
        switch(window.location.pathname){
            case "/Login":
            case "/Terms":
            case "/Help":
                break;
            default:
                window.location.href = '/Login';
        }
    }
}, function (error) {
    console.log(error);
});
};

window.addEventListener('load', function () {
initApp();
document.getElementById('sign-out').addEventListener('click', function () {
    firebase.auth().signOut().then(function() {
        sessionStorage.clear();
        localStorage.clear();
        window.location = "/Logout";
    }).catch(function(error) {
        console.log(error);
        });
    });
  });

Body:
On sign out from Firebase Auth, redirect to Google single sign out URL:

firebase.auth().signOut()
  .then(function() {
    window.location.assign('https://accounts.google.com/Logout');
  })
  .catch(function(error) {
    console.log(error);
  });


问:
How do you use go-sql-driver when you have a sharded MySQL database solution?
Reading this article: http://go-database-sql.org/accessing.html

It says that the sql.DB object is designed to be long-lived and that we should not Open() and Close() databases frequently. But what should I do if I have 10 different MySQL servers and I have sharded them in a way that I have 511 databases in each server for example the way Pinterest shards their data with MySQL?

https://medium.com/@Pinterest_Engineering/sharding-pinterest-how-we-scaled-our-mysql-fleet-3f341e96ca6f

Then would I not need to constantly access new nodes with new databases all the time? As I understand then I have to Open and Close the database connection all the time depending on which node and database I have to access.

It also says that:

If you don’t treat the sql.DB as a long-lived object, you could
  experience problems such as poor reuse and sharing of connections,
  running out of available network resources, or sporadic failures due
  to a lot of TCP connections remaining in TIME_WAIT status. Such
  problems are signs that you’re not using database/sql as it was
  designed.

Will this be a problem? How should I solve this issue then?

答:
I am also interested in the question. I guess there could be such solution:

Minimize number of idle connection in pool db.SerMaxIdleConns(N)

Make map[serverID]*sql.DB. When you have no such connection - add it to map.

Make Dara more local - so backends usually go to “their” databases. However Pinterest seems not to use it.

Increase number of sockets and files on backend machines so they can keep more open connections.

Provide some reasonable idle timeout so very old unused connections could be closed.


问:
How do I get a list of 802.11 access points and their MAC addresses that's shown in the pull-down?
My Mac says that there are 10 access points nearby. How do I read that list of access points programmatically, getting both the signal strength and the MAC address of the APs?</p>

答: Use the Apple80211 Private framework (/System/Library/PrivateFrameworks/Apple80211.framework).  Since it is private, there is no official documentation, but you can get a lot of information by googling "apple80211". I have found http://code.google.com/p/iphone-wireless/wiki/Apple80211Functions to be the best source. It is specifically for iPhone development, but the frameworks are nearly identical. The two biggest differences: the load location and the fact that it can be linked in on the mac instead of loaded at runtime.</p>


问:
Checksum verification in Hadoop
Do we need to verify checksum after we move files to Hadoop (HDFS) from a Linux server through a Webhdfs ?

I would like to make sure the files on the HDFS have no corruption after they are copied. But is checking checksum necessary?

I read client does checksum before data is written to HDFS

Can somebody help me to understand how can I make sure that source file on Linux system is same as ingested file on Hdfs using webhdfs.

答:
If you are doing this check via API

```<code>import org.apache.hadoop.fs._
import org.apache.hadoop.io._
</code>```

Option 1: for the value b9fdea463b1ce46fabc2958fc5f7644a

```<code>val md5:String = MD5Hash.digest(FileSystem.get(hadoopConfiguration).open(new Path("/project1/file.txt"))).toString
</code>```

Option 2: for the value 3e50be59553b2ddaf401c575f8df6914

```<code>val md5:String = FileSystem.get(hadoopConfiguration).getFileChecksum(new Path("/project1/file.txt"))).toString.split(":")(0)
</code>```

Title: Checksum verification in Hadoop

Body:
If you are doing this check via API

import org.apache.hadoop.fs._
import org.apache.hadoop.io._

Option 1: for the value b9fdea463b1ce46fabc2958fc5f7644a

val md5:String = MD5Hash.digest(FileSystem.get(hadoopConfiguration).open(new Path("/project1/file.txt"))).toString

Option 2: for the value 3e50be59553b2ddaf401c575f8df6914

val md5:String = FileSystem.get(hadoopConfiguration).getFileChecksum(new Path("/project1/file.txt"))).toString.split(":")(0)


问:
Error:Cause: buildToolsVersion is not specified
I create a simple project and then I right-click on the project and then I use the make mudole app option. Now I have two build.gradle folders: 1- build.gradle:project My Application. 2- build.gradle: Mudole app. the first build.gradle is as follows:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply plugin: 'com.android.library'
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

And the second Build.gradle folder is as follows:

```<code> apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"

    defaultConfig {
        applicationId "com.exam.exam.myapplication"
        minSdkVersion 7
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}
</code>```

And now I click on the run option to create aar file from this project But I get the following error:

```<code>Error:Cause: buildToolsVersion is not specified.
</code>```

答:
Check if android studio version in build.gradle is same as the one you are running.

```<code>buildscript {

   repositories {
       google()
       jcenter()
   }
 dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }
}
</code>```

In my case, I opened/imported the project created on android studio 2.3.3 in android studio 3 and i was able to get rid of this issue after updating the build.gradle with 3.0.0

Body:
I create a simple project and then I right-click on the project and then I use the make mudole app option. Now I have two build.gradle folders: 1- build.gradle:project My Application. 2- build.gradle: Mudole app. the first build.gradle is as follows:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply plugin: 'com.android.library'
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

And the second Build.gradle folder is as follows:

 apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"

    defaultConfig {
        applicationId "com.exam.exam.myapplication"
        minSdkVersion 7
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

And now I click on the run option to create aar file from this project But I get the following error:

Error:Cause: buildToolsVersion is not specified.

Body:
Check if android studio version in build.gradle is same as the one you are running.

buildscript {

   repositories {
       google()
       jcenter()
   }
 dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }
}

In my case, I opened/imported the project created on android studio 2.3.3 in android studio 3 and i was able to get rid of this issue after updating the build.gradle with 3.0.0


问:
Query multi tables' columns with join in spring data jpa
Description:

I have two tables, Shop_Employee and Shop_Employee_Type. I wanna display typeName directly when show the employee detail information, but I don't want to config the relationship(OneToMany or ManyToOne) between this two entity.
 Because this will load all Shop_Employee_Type column's value, but these values are useless for me, I just need typeName of Shop_Employee_Type.
Below is my code, but it doesn't work.

ShopEmployeeType:

```<code>@Entity
@Data
//@DynamicUpdate
public class ShopEmployeeType {
    @Id
    private String typeId;
    private String shopId;
    private String typeName;
    private Integer typeStatus;
    private String typeDescription;
}
</code>```

Shop_Employee:

```<code>@Entity
@Data
public class ShopEmployee {

    @Id
    private  String employeeId;
    private String shopId;
    private String typeId;
    private String name;
    private String code;
    private String phone;
    private Integer status;
    private String idcardNumber;
    private String image;
    //@Transient
    private String typeName;

    public ShopEmployee() {
    }
}
</code>```

Repository:

```<code>@Query(value = "select u.*,t.type_name from shop_employee u inner join shop_employee_type t on u.type_id=t.type_id", nativeQuery = true)
List<ShopEmployee> findAllData();
</code>```

This could show typeName as I wished, but there is an error appears when I save a new entity Shop_Employee; If I add a @Transient for 'typeName', It could save successfully, but the value of 'typeName' is null when I query entity Shop_Employee.

答:
Your query should return two Objects Shop_Employee and a String, so the return results should not be List<ShopEmployee> it should be :

```<code>@Query(value = "select u.*, t.type_name from shop_employee ...", nativeQuery = true)
List<Object[]> findAllData();
</code>```

Then you can get the ShopEmployee using :

```<code>List<Object[]> list = findAllData();
for(Object[] obj : list){
   ShopEmployee shopEmployee = (ShopEmployee) obj[0];
   String type_name = (String) obj[1];
}
</code>```

So, in ShopEmployee entity you don't need to use :

```<code>//@Transient
//private String typeName;
</code>```

Body:
Description:

I have two tables, Shop_Employee and Shop_Employee_Type. I wanna display typeName directly when show the employee detail information, but I don't want to config the relationship(OneToMany or ManyToOne) between this two entity.
 Because this will load all Shop_Employee_Type column's value, but these values are useless for me, I just need typeName of Shop_Employee_Type.
Below is my code, but it doesn't work.

ShopEmployeeType:

@Entity
@Data
//@DynamicUpdate
public class ShopEmployeeType {
    @Id
    private String typeId;
    private String shopId;
    private String typeName;
    private Integer typeStatus;
    private String typeDescription;
}

Shop_Employee:

@Entity
@Data
public class ShopEmployee {

    @Id
    private  String employeeId;
    private String shopId;
    private String typeId;
    private String name;
    private String code;
    private String phone;
    private Integer status;
    private String idcardNumber;
    private String image;
    //@Transient
    private String typeName;

    public ShopEmployee() {
    }
}

Repository:

@Query(value = "select u.*,t.type_name from shop_employee u inner join shop_employee_type t on u.type_id=t.type_id", nativeQuery = true)
List<ShopEmployee> findAllData();

This could show typeName as I wished, but there is an error appears when I save a new entity Shop_Employee; If I add a @Transient for 'typeName', It could save successfully, but the value of 'typeName' is null when I query entity Shop_Employee.

Body:
Your query should return two Objects Shop_Employee and a String, so the return results should not be List<ShopEmployee> it should be :

@Query(value = "select u.*, t.type_name from shop_employee ...", nativeQuery = true)
List<Object[]> findAllData();

Then you can get the ShopEmployee using :

List<Object[]> list = findAllData();
for(Object[] obj : list){
   ShopEmployee shopEmployee = (ShopEmployee) obj[0];
   String type_name = (String) obj[1];
}

So, in ShopEmployee entity you don't need to use :

//@Transient
//private String typeName;


问:
Reading particular cell value from excelsheet in python
I want to get particular cell values from excelsheet in my python script.
I came across xlrd, xlwt, xlutils modules for reading/writing to/from excelsheet.

I created myfile.xls with hi, hello, how in first column's 3 cells.

sample code :-

```<code>import xlrd

workbook = xlrd.open_workbook('myfile.xls')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
curr_row = -1
while curr_row < num_rows:
        curr_row += 1
        row = worksheet.row(curr_row)
        print row
</code>```

output :-

```<code>[text:u'hi']
[text:u'hello']
[text:u'how']
</code>```

I want to read specific cell values from excelsheet, can someone suggest me if there is a way to do that?

答:
The code below will help you in solving the problem:

worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
curr_row = 0
while curr_row < num_rows:
        curr_row += 1
        row = worksheet.row(curr_row)
        print row[0].value
```

Body:
I want to get particular cell values from excelsheet in my python script.
I came across xlrd, xlwt, xlutils modules for reading/writing to/from excelsheet.

I created myfile.xls with hi, hello, how in first column's 3 cells.

sample code :-

import xlrd

workbook = xlrd.open_workbook('myfile.xls')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
curr_row = -1
while curr_row < num_rows:
        curr_row += 1
        row = worksheet.row(curr_row)
        print row

output :-

[text:u'hi']
[text:u'hello']
[text:u'how']

I want to read specific cell values from excelsheet, can someone suggest me if there is a way to do that?


问:
Including multiple proto files on to one project causes protobuf_AssignDescriptorsOnce() already has a body
I have got multiple proto files from the server created under the same package. When I add more than one of those proto files on to a project, each proto file is generating its own .pb.cc and .h files and each generated file has the below two methods. I need to include some of the generated .cc files to one of my projects which causes multiple definitions of the below two functions.

auto-generated functions causing "the function already has a body" issues are
1. protobuf_AssignDescriptorsOnce()
2. protobuf_RegisterTypes(const ::std::string&)

Making changes in the package name is obviously solving this issue but the proto file was given by the server and any change on that file could cause huge change in all the other dependant clients.

Any help to address this issue would be much appreciated.

Regards,
Abilash.G

答: The issue was simple and not related to protobuf. I've included all the generated pb.cc files directly on to my 'stdafx.cpp' instead of adding the generated files as a part of projects which was causing the 'already has a body' error for the global functions.</p>


问:
Flaw in the Lunar Lander example (IllegalThreadStateException)
I've been playing around with the lunar lander example and have run into a problem while trying to implement an about screen. I changed one of the menu items (in onCreateOptionsMenu) to an "about" option. When this option is selected, a new Activity starts and displays an about screen.

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case MENU_ABOUT:
            startActivity(new Intent(this, About.class));
            return true;
            //Other cases
    }
    return false;
}
</code>```

This works perfectly and a the focus moves to a new Activity. However, when I press back on the phone to get back to the game, the program crashes. I get this error:

```<code>Thread [<3> main] (Suspended (exception IllegalThreadStateException))
LunarView(SurfaceView).updateWindow(boolean) line: 465
LunarView(SurfaceView).onWindowVisibilityChanged(int) line: 189
LunarView(View).dispatchWindowVisibilityChanged(int) line: 3782
FrameLayout(ViewGroup).dispatchWindowVisibilityChanged(int) line: 704
FrameLayout(ViewGroup).dispatchWindowVisibilityChanged(int) line: 704
PhoneWindow$DecorView(ViewGroup).dispatchWindowVisibilityChanged(int) line: 704
ViewRoot.performTraversals() line: 710
ViewRoot.handleMessage(Message) line: 1650
ViewRoot(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4595
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 860
ZygoteInit.main(String[]) line: 618
NativeStart.main(String[]) line: not available [native method]
</code>```

Can anyone help me figure out whats going on? I run into the same problem anytime I try to come back to the game screen from something else (whether its from a preferences Activity, a help Activity, or from the home screen). Thanks

答:
The link that fiction gave led me to the answer. The problem wasn't in my code, it was due to a flaw in the Lunar Lander example (it doesn't handle its thread properly).

For anyone looking for a stable game loop that doesn't use Lunar Lander's flawed framework, I found this example to work very well: http://blorb.tumblr.com/post/236799414/simple-java-android-game-loop

Thanks for the help

Body:
I've been playing around with the lunar lander example and have run into a problem while trying to implement an about screen. I changed one of the menu items (in onCreateOptionsMenu) to an "about" option. When this option is selected, a new Activity starts and displays an about screen.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case MENU_ABOUT:
            startActivity(new Intent(this, About.class));
            return true;
            //Other cases
    }
    return false;
}

This works perfectly and a the focus moves to a new Activity. However, when I press back on the phone to get back to the game, the program crashes. I get this error:

Thread [<3> main] (Suspended (exception IllegalThreadStateException))
LunarView(SurfaceView).updateWindow(boolean) line: 465
LunarView(SurfaceView).onWindowVisibilityChanged(int) line: 189
LunarView(View).dispatchWindowVisibilityChanged(int) line: 3782
FrameLayout(ViewGroup).dispatchWindowVisibilityChanged(int) line: 704
FrameLayout(ViewGroup).dispatchWindowVisibilityChanged(int) line: 704
PhoneWindow$DecorView(ViewGroup).dispatchWindowVisibilityChanged(int) line: 704
ViewRoot.performTraversals() line: 710
ViewRoot.handleMessage(Message) line: 1650
ViewRoot(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4595
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 860
ZygoteInit.main(String[]) line: 618
NativeStart.main(String[]) line: not available [native method]

Can anyone help me figure out whats going on? I run into the same problem anytime I try to come back to the game screen from something else (whether its from a preferences Activity, a help Activity, or from the home screen). Thanks


问:
XCode 9.1 Command /bin/sh failed with exit code 1
After updating xcode to version 9.1, I can't compile my projects, always have the same error Command /bin/sh failed with exit code 1. I tried to create empty project, install all pods I need, and the result is the same. Here is my podfile

```<code>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target 'xcode9.1' do

pod 'RMStore'
pod 'GoogleMaps'
pod 'RMMapper'
pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'
pod 'VK-ios-sdk'
pod 'TwitterKit'
pod 'GoogleSignIn'
pod 'Flurry-iOS-SDK/FlurrySDK'
pod 'TWSReleaseNotesView'
pod 'GoogleAnalytics'
pod 'GoogleTagManager','~> 3.15.0'
pod 'SBJson'
pod 'Fabric'
pod 'Crashlytics'
pod 'APOfflineReverseGeocoding'
pod 'AFNetworking'
pod 'Realm'

end
</code>```

This problem repeats in all my projects, can anybody explain me how to fix it?

Here is the screen of full error

答: The solution is very simple. In your pods target, Build settings, I changed valid architectures list. Also Build architectures only flag change to No can resolve the problem.

Body:
After updating xcode to version 9.1, I can't compile my projects, always have the same error Command /bin/sh failed with exit code 1. I tried to create empty project, install all pods I need, and the result is the same. Here is my podfile

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target 'xcode9.1' do

pod 'RMStore'
pod 'GoogleMaps'
pod 'RMMapper'
pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'
pod 'VK-ios-sdk'
pod 'TwitterKit'
pod 'GoogleSignIn'
pod 'Flurry-iOS-SDK/FlurrySDK'
pod 'TWSReleaseNotesView'
pod 'GoogleAnalytics'
pod 'GoogleTagManager','~> 3.15.0'
pod 'SBJson'
pod 'Fabric'
pod 'Crashlytics'
pod 'APOfflineReverseGeocoding'
pod 'AFNetworking'
pod 'Realm'

end

This problem repeats in all my projects, can anybody explain me how to fix it?

Here is the screen of full error


问:
Integrating PayU money to Ionic + Cordova Hybrid App
please  help me how to set or render success url to my ionic app.
when i integrating PayU money to Ionic app it requires Success Url and Failure Url after completion of payment it render into success url but it's not back to Ionic App.

```<code><form name="sendParam" method="post"    action="https://test.payu.in/_payment.php">
    <input type="text" name="key" value="P3kHif" />
    <input type="text" name="txnid" value="mdd0123" />
    <input type="text" name="amount" value="100" />
    <input type="text" name="productinfo" value="oxygenconcentrator" />
    <input type="text" name="firstname" value="test" />
    <input type="text" name="email" value="test@gmail.com" />
    <input type="text" name="phone" value="9999999999" />
    <input type="text" name="surl" value="http://example.com" />
    <input type="text" name="Furl" value="http://example.com/about-us/" />
    <input type="text" name="Hash" value="9a4c95b065ae294414e6a5b0b6e8e5d1a2ebf26074228eac6ff7c7d739c9cd4d021a9f70af8860ac369b1ccecfdaa60ba5839ee9dc1fd41e2848a3813677d520"/>
    <input type="submit" value="enter"/>
 </form >
</code>```

and response comes from PayUmoney is only in HTML format it doesn't have any JSON Object format. Just i followed the following Link PayU Money Rest API

答:
Payumoney does't have sdk for Hybrid applications. We need to use Cordova inapp browser to achieve this.

Step 1 : Create Payumoney Account and get sandbox details.

Step 2: Install Cordova inapp browser

Step 3: Create your payment url

Step 4 : Create success and failure url in server and add these urls in your payment page

Step 5: Run your payment url in your inapp browser.

Thats it. It will do a payment process and send a status to given success and failure url.

Here you can find a code for payment gateway integration in ionic.

Body:
please  help me how to set or render success url to my ionic app.
when i integrating PayU money to Ionic app it requires Success Url and Failure Url after completion of payment it render into success url but it's not back to Ionic App.

<form name="sendParam" method="post"    action="https://test.payu.in/_payment.php">
    <input type="text" name="key" value="P3kHif" />
    <input type="text" name="txnid" value="mdd0123" />
    <input type="text" name="amount" value="100" />
    <input type="text" name="productinfo" value="oxygenconcentrator" />
    <input type="text" name="firstname" value="test" />
    <input type="text" name="email" value="test@gmail.com" />
    <input type="text" name="phone" value="9999999999" />
    <input type="text" name="surl" value="http://example.com" />
    <input type="text" name="Furl" value="http://example.com/about-us/" />
    <input type="text" name="Hash" value="9a4c95b065ae294414e6a5b0b6e8e5d1a2ebf26074228eac6ff7c7d739c9cd4d021a9f70af8860ac369b1ccecfdaa60ba5839ee9dc1fd41e2848a3813677d520"/>
    <input type="submit" value="enter"/>
 </form >

and response comes from PayUmoney is only in HTML format it doesn't have any JSON Object format. Just i followed the following Link PayU Money Rest API


问:
Access JSON data through variable .-string interpolation
Trying to access integer stored under id's/keys in json object. Why doesn't this code work on its own?

```<code> var rooms = {
    'kitchen': [7, 40, 36, 16],
    'livingroom': 31,
    'livingroom2': 15,
    'livingroom3': 38,
    'gallery': 35,
    'gallery2': 29,
    'gallery3': 12,
    'office': [22, 32],
    'neekonsbedroom': 18,
    'homeworkroom': 33,
    'diningroom': 13,
    'atrium': 11
}
function switchOne(id) {
    console.log(rooms.id)
}
 switchOne('office')
</code>```

console.log() returns undefined, but simply console.log(rooms.office) returns [ 22, 32 ]
Any and all help is greatly appreciated!
Happy coding!

答:
You're looking for the literal key "id" within your object, not the key at the value of id (i.e. "office"). To get Javascript to treat id as a variable you need to use rooms[id].

The information here explains (towards the bottom) accessing properties of objects: https://www.w3schools.com/js/js_object_definition.asp.

Body:
Trying to access integer stored under id's/keys in json object. Why doesn't this code work on its own?

 var rooms = {
    'kitchen': [7, 40, 36, 16],
    'livingroom': 31,
    'livingroom2': 15,
    'livingroom3': 38,
    'gallery': 35,
    'gallery2': 29,
    'gallery3': 12,
    'office': [22, 32],
    'neekonsbedroom': 18,
    'homeworkroom': 33,
    'diningroom': 13,
    'atrium': 11
}
function switchOne(id) {
    console.log(rooms.id)
}
 switchOne('office')

console.log() returns undefined, but simply console.log(rooms.office) returns [ 22, 32 ]
Any and all help is greatly appreciated!
Happy coding!


问:
maximum recursion depth exceeded in comparison?
Started learning python, this is maximum sum subarray i have tried. Ending up with "maximum recursion depth exceeded in comparison". My algorithm seems ok to me. Please help me if im doing anything wrong. </p>

```<code>import sys
import math
def maxtuple(lss,rss):
    if lss[2] > rss[2]:
        return lss
    else:
        return rss
def crosssubarray(A, start, mid, end):
    ls=rs=-sys.maxsize
    maxleft=0
    maxright=0
    sum = 0;
    for i in reversed(range(start, mid)):
        sum = sum + A[i]
        print(i)
        if sum > ls:
            ls = sum
            maxleft = i
    sum = 0
    for i in range(mid+1, end):
        sum = sum+ A[i]
        if sum > rs:
            rs = sum
            maxright = i
    return (maxleft, maxright, ls+rs)

def maxsubarray(A,start,end):
    if start == end:
        return (start,end,A[start])
    else:
        mid = (start+end)/2
        lss = maxsubarray(A, start, mid)
        rss = maxsubarray(A, mid+1, end)
        css = crosssubarray(A, start, mid, end)
        maxsub = maxtuple(lss,rss)
        maxall = maxtuple(maxsub, css)
        return maxall

A = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(maxsubarray(A,0,15))
</code>```

答:
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

```<code>import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
</code>```

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Body:
Started learning python, this is maximum sum subarray i have tried. Ending up with "maximum recursion depth exceeded in comparison". My algorithm seems ok to me. Please help me if im doing anything wrong.

import sys
import math
def maxtuple(lss,rss):
    if lss[2] > rss[2]:
        return lss
    else:
        return rss
def crosssubarray(A, start, mid, end):
    ls=rs=-sys.maxsize
    maxleft=0
    maxright=0
    sum = 0;
    for i in reversed(range(start, mid)):
        sum = sum + A[i]
        print(i)
        if sum > ls:
            ls = sum
            maxleft = i
    sum = 0
    for i in range(mid+1, end):
        sum = sum+ A[i]
        if sum > rs:
            rs = sum
            maxright = i
    return (maxleft, maxright, ls+rs)

def maxsubarray(A,start,end):
    if start == end:
        return (start,end,A[start])
    else:
        mid = (start+end)/2
        lss = maxsubarray(A, start, mid)
        rss = maxsubarray(A, mid+1, end)
        css = crosssubarray(A, start, mid, end)
        maxsub = maxtuple(lss,rss)
        maxall = maxtuple(maxsub, css)
        return maxall

A = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(maxsubarray(A,0,15))

Body:
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.


问:
How to send a synchronized signal among three processes in C
I have to send signal p1 -> p2 -> p3 ->p1 ... in order to change the value of shared file. however p3 -> p1 is not working(p1 doesn't catch the signal). I put sleep to make time difference between each transition but idk what's wrong. </p>

```<code>#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>
void sig_usr (int signo)
{
        printf("%d\n",getpid());
//      longjmp(jumpbuffer,1);
}

int main(int argc, char **argv)
{
        signal(SIGUSR1, sig_usr);
        jmp_buf jumpbuffer;
        pid_t next,ppid,granmaduh;
        granmaduh = getpid();
        if ((next = fork()) <0 )
        {
                        fprintf(stderr, "fork() error");
                        exit(1);
         }
        else if (next == 0  )
        {

                next = fork();
                if (next >0)
                {

                        sleep(6);
                }
                else
                {
                        next = granmaduh;
                        sleep(10);
                }
        }
        sleep(2);
        printf("%d\n",next);
        //setjmp(jumpbuffer);

        kill(next, SIGUSR1);
        exit(1);
}
</code>```

答:
```<code>#include <signal.h>
#include <stdio.h>
#include <sys/wait.h>
#include <errno.h>

static void signal_handler(int);
int i, pid1, pid2,pid3, status;

int main( int argc, char *argv[], char *env[] )
{
    int exit_status;

    if( signal( SIGUSR1, signal_handler) == SIG_ERR  )
    {
        printf("Pærent: Unable to create handler for SIGUSR1\n");
    }

    // if( signal( SIGUSR2, signal_handler) == SIG_ERR  )
    // {
    //     printf("Pærent: Unable to create handler for SIGUSR2\n");
    // }

    printf( "Parent pid = %d\n", pid1=getpid() );

    if( (pid2 = fork()) == 0 )
    {
        printf( "Child pid = %d\n", getpid() );
        //printf( "Child: %d sending parent SIGUSR1\n", getpid() ); //kill( pid1, SIGUSR1 );

         if( (pid3 = fork()) == 0 )
        {
        printf( "GranChild pid = %d\n", getpid() );
        printf( "Child: %d sending parent SIGUSR1\n", getpid() ); kill( pid2, SIGUSR1 );
        }
        for( ;; ); /* loop forever */

    }
    else
    {
        /*
         * This waits for ANY child to die.  It doesn't matter if the child
         * dies normally or from a signal.  The satus information is then
         * stored in the status integer.
         *
         * If you want to wait on a particular process use waitpid():
         *      waitpid( childPID, &status, 0 );
         * is the common usage.
         *
         * Solaris acts weirdly when a signal is given to the parent process.
         * Therefore we place the wait() inside a while loop so that wait()
         * will not return before the child has died.
         */
         /*   while( (wait( &status ) == -1) && (errno == EINTR) ) {} */

        wait(&status);

        /*
         * The information in status is *NOT* the return code!!  To make use
         * of the information we must macros to extract the needed
         * information.
         */

        /* WIFEXITED() determines if the process exited normally (returned a
         * number).  This can be done through a return or exit()
         */

        if( WIFEXITED( status ) )
        {
            /*
             * Now we know the process exited properly so we can get the
             * return value
             *
             * Note that WEXITSTATUS only retuns the lower 8 bits!  That means
             * that if we ever expect a negative number then we have to count
             * the 8th bit as a sign bit.
             */

            exit_status = WEXITSTATUS( status );

            /*
             * Since we expect negative numbers...
             *
             * If the exit_status is greater than 2^7 (128), thæn the eigth bit
             * is a 1, so we subtract 2^8 (256) from it to make it look like
             * a negative number.
             */
            if( exit_status > 128 )
            {
                exit_status -= 256;
            }

            printf( "Child return - %d\n", WEXITSTATUS( status ) );
        }
        else
        {
            /* Well it didn't exit properly.  Was it a signal? */
            if( WIFSIGNALED( status ) )
            {
                /*
                 * Yes. A signal killed the child process.  Now we can extract
                 * the signal information from status
                 */

                printf( "Child died on signal - %d\n", WTERMSIG( status ));
            }
        }

        /*
         * There are two other macros most UNIXes use.  They are:
         *  WIFSTOPPED() and WSTOPSIG().  See the man pages on the dells for
         *  more information.
         *
         *  To wait on a particular pid - see waitpid()
         */
    }

    return 0;
}

static void signal_handler(int signo)
{

    /* signo contains the signal number that was received */
    switch( signo )
    {
        /* Signal is a SIGUSR1 */
        case SIGUSR1:
            printf( "Process %d: received SIGUSR1 \n", getpid() );
            if(pid1==getpid()) /* it is the parent */
            {
                  printf( "Process %d is passing SIGUSR1 to %d...\n", getpid(),pid2 );
                  kill( pid2, SIGUSR1 );
            }
            else if(pid2==getpid()) /* it is the child */
            {
                    printf( "Process %d is passing SIGUSR2 to itself...\n", getpid());
                    kill(getpid(), SIGUSR2);
            }
            else
            {
              printf( "Process %d is passing SIGUSR2 to itself...\n", getpid());
                    kill(pid3, SIGUSR2);
            }

            break;

        /*  It's a SIGUSR2 */
        case SIGUSR2:
            printf( "Process %d: received SIGUSR2 \n", getpid() );
            if(pid1==getpid())
            {
                  printf( "Process %d is passing SIGUSR2 to %d...\n", getpid(),pid2 );
                  kill( pid2, SIGUSR2 );
            }
            else if(pid2==getpid())/* it is the child */
            {
                     printf( "Process %d is passing SIGUSR2 to %d...\n", getpid(),pid3 );
                    kill(pid3, SIGINT);
            }
            else /* it is the child */
            {
                     printf( "Process %d is passing SIGUSR2 to %d...\n", getpid() );
                    kill(getpid(), SIGINT);
            }
            break;

        default:
                break;
    }

    return;
}
</code>```

Body:
I have to send signal p1 -> p2 -> p3 ->p1 ... in order to change the value of shared file. however p3 -> p1 is not working(p1 doesn't catch the signal). I put sleep to make time difference between each transition but idk what's wrong.

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>
void sig_usr (int signo)
{
        printf("%d\n",getpid());
//      longjmp(jumpbuffer,1);
}

int main(int argc, char **argv)
{
        signal(SIGUSR1, sig_usr);
        jmp_buf jumpbuffer;
        pid_t next,ppid,granmaduh;
        granmaduh = getpid();
        if ((next = fork()) <0 )
        {
                        fprintf(stderr, "fork() error");
                        exit(1);
         }
        else if (next == 0  )
        {

                next = fork();
                if (next >0)
                {

                        sleep(6);
                }
                else
                {
                        next = granmaduh;
                        sleep(10);
                }
        }
        sleep(2);
        printf("%d\n",next);
        //setjmp(jumpbuffer);

        kill(next, SIGUSR1);
        exit(1);
}


问:
Select Distinct Field on Join
I am joining two large tables in MySQL based on a unique identifier they both share. Because there are a large number of fields, I do not want to list out all fields after SELECT. Instead I want to select all fields, but I do not want recurring fields (the shared unique identifier in this case) to be repeated.

With this example query:

```<code>SELECT *
FROM Gr3_PracMath_Jan11_D1 as a, student_list_011811 as b
WHERE a.StudentID = b.StudentID
</code>```

The field StudentID is repeated. Is there a way to prevent this?

答: It is bad practice to not list out all of the columns, even if there are a lot of them. Just bite the bullet and write them out.</p>

Title: Select Distinct Field on Join

Body:
I am joining two large tables in MySQL based on a unique identifier they both share. Because there are a large number of fields, I do not want to list out all fields after SELECT. Instead I want to select all fields, but I do not want recurring fields (the shared unique identifier in this case) to be repeated.

With this example query:

SELECT *
FROM Gr3_PracMath_Jan11_D1 as a, student_list_011811 as b
WHERE a.StudentID = b.StudentID

The field StudentID is repeated. Is there a way to prevent this?


问:
How do I restore administrator account of jenkins
I have recently migrated our Jenkins service from Ubuntu to CentOS 7.
The way I did this is by installing a clean instance of Jenkins (2.89) on CentOS 7 and then move the complete contents of JENKINS_HOME from Ubuntu to CentOS 7.

Obviously, when I try to log in as the administrator it fails on the new instance, since I am having the old instance back instead.
Which means I am dealing with the administrator account of old instance.

I tried to find the administrator account of the old instance in one of the /var/lib/jenkins/users//config.xml files.
But I can't find the definition for the administrator account the config files.

Please help.

答: If you moved this all correctly, there should be no problem with the adminstrator ID. My guess is that you have not set JENKINS_HOME on the new machine before starting Jenkins.</p>


问:
Facebook Messenger Platform API Live Person
Is there a way to delegate the current conversation that a Messenger Platform bot is having to another person through the API? I could not find anything in the documentation.

If no, what's the best way to handle the use case where a person asks the bot to talk to a live person?

答:
You can use the handover protocol to pass thread control to the page inbox, where a live person can respond.

https://developers.facebook.com/docs/messenger-platform/handover-protocol/pass-thread-control


问:
Local Node (Geth) failed to sync from TestNet
Dear all Blockchain experts,

I have created a local node by using Geth, this is the startup command.

geth --testnet  --rpc --rpcaddr "localhost" --rpcport "8545" --rpcapi "web3,eth,net,personal" --rpccorsdomain "*" --datadir "./data" --identity "localnode"  --fast

Upon the local node up and running. Immediately, I created two personal accounts and stored it into the Keystore folder.

Then, I have transfered the ether from my Testnet's account to the local node's account via MetaMasks. Something really odd here is I still can see the local node's account ether value is ZERO.

I even deleted the chaindata folder and re-started the geth client console.

Please advise and much appreciate.

Thank you.

答:
Unfortunately, you had successfully synced your local GEth but with a different network other than the one you checking your Ether at!

This confusion happen because there was an attack on Ropesten network that has been corrected by some nodes but the other nodes still having the old data. And when you run your command:

geth --testnet --rpc --rpcaddr "localhost" --rpcport "8545" --rpcapi "web3,eth,net,personal" --rpccorsdomain "*" --datadir "./data" --identity "localnode" --fast

You are not specifying in the command any specific node to connect to. And by mistake you are connected to node(s) that is still running on the old deprecated obsolete network blockchain data!

And deleting the "chaindata" folder, will not inform GEth to try with other nodes. Because, it will pick the same nodes from the folder "nodes".

To choose new nodes to sync with, you have either to:

Delete the "nodes" folder and also specify an updated nodes to be
used by GEth using "--bootnodes" option.

Or, add the nodes even after sync using the command: "admin.addPeer('enode://ADDRESS@IP:PORT')". this is after you attach to Geth in terminal using "geth attach ipc:/home/developer/.ethereum/testnet/geth.ipc"

However, because there is no clear listing on which nodes had been forked and updated to correct the hack, and because of many other issues like the large size of the full network node, I recommend using Parity to connect to the correct Ropsten nodes' network.

To use parity I recommend following one of those links:

How To Sync Entire Ethereum Client in 2-3 hours for Testnets & Mainnet

Or:
Ethereum Parity fast sync for Ropsten testnet

So, thanks to Parity! You can specify your desired network using "--chain" easily by running: "parity --chain ropsten"


问:
SQL How to restrict parent row from updates once child added?
I use foreign keys to prevent rows from being deleted in some SQL tables once a child uses the key.  However, now I want to be able to restrict any column of the parent table from updates once the child uses the key.

For example if the parent table is
[ID],[First Name],[Last Name]

And the child table is
[ListID],[Emp ID]

The foreign key prevents me from deleting or updating [ID] in the parent table however, it doesn't stop me from modifying [First Name].  Is there a way to set up foreign keys to prevent this?

Thanks.

答:
Try this:

```<code>CREATE TRIGGER trg_name ON parent_table INSTEAD OF UPDATE
AS
BEGIN

    UPDATE parent_table
    SET [FirstName] = I.[firstname]
       ,[LastName] = I.[lastname]
     FROM parent_table A
     INNER JOIN inserted B
        ON A.[ID] = B.[ID]
     LEFT JOIN child_table CT
        ON A.[ID] = CT.[ListID] -- or [EmpID] - am not sure about the relation
     WHERE CT.[LsitID] IS NULL  -- where the element from parent_table does not have element in the child table

END
</code>```

Also, always try to handle the logic in triggers in batches in order not to hurt the performance.

Body:
Try this:

CREATE TRIGGER trg_name ON parent_table INSTEAD OF UPDATE
AS
BEGIN

    UPDATE parent_table
    SET [FirstName] = I.[firstname]
       ,[LastName] = I.[lastname]
     FROM parent_table A
     INNER JOIN inserted B
        ON A.[ID] = B.[ID]
     LEFT JOIN child_table CT
        ON A.[ID] = CT.[ListID] -- or [EmpID] - am not sure about the relation
     WHERE CT.[LsitID] IS NULL  -- where the element from parent_table does not have element in the child table

END

Also, always try to handle the logic in triggers in batches in order not to hurt the performance.


问:
How can I make a label in an iOS renderer wrap around and resize?
I have this code in an iOS Renderer:

```<code>    private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
    {
        public CustomFooterTableViewModelRenderer(TableView model) : base(model)
        {
        }

        public override UIView GetViewForFooter(UITableView tableView, nint section)
        {
                var lbl = new PaddedLabel()
                {

                    // Text = TitleForFooter(tableView, section), // or use some other text here
                    Text = "Select or deselect cards from the list above and they will added or removed from the card deck",
                    TextAlignment = UITextAlignment.Justified,
                    LineBreakMode = UILineBreakMode.WordWrap
                };
                return lbl;
        }

        public sealed class PaddedLabel : UILabel
        {
            private UIEdgeInsets EdgeInsets { get; set; } = new UIEdgeInsets(top: 10, left: 15, bottom: 0, right: 0);

            public override void DrawText(CoreGraphics.CGRect rect)
            {
                var newRect = new CoreGraphics.CGRect(0, 0, rect.Width + 10, rect.Height);
                base.DrawText(EdgeInsets.InsetRect(newRect));
            }
        }

    }
</code>```

The code works but my label does not wrap around and I am guessing it does not resize also  Note that I did try adding WordWrap but that doesn't seem to work. Anyone have any ideas as to how I can fix this and also make it autoresize.

答:
does not wrap around

It is because you forget to set Lines 0.

does not resize

I think It is because  you increase the width when drawing.

Final code :

```<code>public override UIView GetViewForFooter(UITableView tableView, nint section)
{
    var lbl = new PaddedLabel()
    {
         Lines = 0,
        // Text = TitleForFooter(tableView, section), // or use some other text here
        Text = "Select or deselect cards from the list above and they will added or removed from the card deck",
        TextAlignment = UITextAlignment.Justified,
        LineBreakMode = UILineBreakMode.WordWrap
    };
    return lbl;
}

    public sealed class PaddedLabel : UILabel
    {
        private UIEdgeInsets EdgeInsets { get; set; } = new UIEdgeInsets(top: 10, left: 15, bottom: 0, right: 0);

        public override void DrawText(CoreGraphics.CGRect rect)
        {
            var newRect = new CoreGraphics.CGRect(0, 0, rect.Width , rect.Height);
            base.DrawText(EdgeInsets.InsetRect(newRect));
        }
    }
</code>```

Body:
I have this code in an iOS Renderer:

    private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
    {
        public CustomFooterTableViewModelRenderer(TableView model) : base(model)
        {
        }

        public override UIView GetViewForFooter(UITableView tableView, nint section)
        {
                var lbl = new PaddedLabel()
                {

                    // Text = TitleForFooter(tableView, section), // or use some other text here
                    Text = "Select or deselect cards from the list above and they will added or removed from the card deck",
                    TextAlignment = UITextAlignment.Justified,
                    LineBreakMode = UILineBreakMode.WordWrap
                };
                return lbl;
        }

        public sealed class PaddedLabel : UILabel
        {
            private UIEdgeInsets EdgeInsets { get; set; } = new UIEdgeInsets(top: 10, left: 15, bottom: 0, right: 0);

            public override void DrawText(CoreGraphics.CGRect rect)
            {
                var newRect = new CoreGraphics.CGRect(0, 0, rect.Width + 10, rect.Height);
                base.DrawText(EdgeInsets.InsetRect(newRect));
            }
        }

    }

The code works but my label does not wrap around and I am guessing it does not resize also  Note that I did try adding WordWrap but that doesn't seem to work. Anyone have any ideas as to how I can fix this and also make it autoresize.

Body:
does not wrap around

It is because you forget to set Lines 0.

does not resize

I think It is because  you increase the width when drawing.

Final code :

public override UIView GetViewForFooter(UITableView tableView, nint section)
{
    var lbl = new PaddedLabel()
    {
         Lines = 0,
        // Text = TitleForFooter(tableView, section), // or use some other text here
        Text = "Select or deselect cards from the list above and they will added or removed from the card deck",
        TextAlignment = UITextAlignment.Justified,
        LineBreakMode = UILineBreakMode.WordWrap
    };
    return lbl;
}

    public sealed class PaddedLabel : UILabel
    {
        private UIEdgeInsets EdgeInsets { get; set; } = new UIEdgeInsets(top: 10, left: 15, bottom: 0, right: 0);

        public override void DrawText(CoreGraphics.CGRect rect)
        {
            var newRect = new CoreGraphics.CGRect(0, 0, rect.Width , rect.Height);
            base.DrawText(EdgeInsets.InsetRect(newRect));
        }
    }


问:
@Output communication between child and parent. Angular 2(5)
I'm trying to learn angular 2 and am trying to set a variable in a parent component with data from my child components.  Basically I have a subheader in my parent view and I want the title and some HTML to change based on what child is loaded.

Parent component:

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ParentComponent {
  childDetails: {title: String, helperBar: String};

  onChildLoaded(childData: {
    childTitle: string,
    childHelperBar: string
  }) {
    this.childDetails ={
      title: childData.childTitle,
      helperBar: childData.childHelperBar
    };
    console.log (childDetails);
  }
}
</code>```

Child Component :

```<code>import { Component, OnInit, ViewEncapsulation, Output, EventEmitter }
from '@angular/core';

@Component({
  selector: 'app-first-child',
  templateUrl: './first-child.component.html',
  styleUrls: ['./first-child.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class FirstChildComponent implements OnInit {
  @Output() childLoaded = new EventEmitter<{childTitle: string,
childHelperBar: string}>();

  constructor() { }

  ngOnInit() {
    this.childLoaded.emit({
      childTitle: 'Dashboard',
      childHelperBar: '<div class="test"><button>Dash Button</button>
</div>'
    });
  }

}
</code>```

And finally my parent HTML:

```<code><div class="subheader">
  <h1>{{ childDetails.title }}</h1>
  {{ childDetails.helperBar }}
</div>
<nav class="sidebar">

</nav>

<main role="main" class="">
  <router-outlet (childLoaded)="onChildLoaded($event)"></router-outlet>
</main>
</code>```

For the life of me I can't get this approach to work and can't pinpoint where I'm going wrong.  I could always just put the subheader in my children but I dont like the idea of repeating the code so many times and it will make my layout a bit harder to achieve.

答:
The best way is making use of the service and  observable so that whenever the child component changes, the new data will get immediately reflected in the parent component.

in your service.ts,

```<code>import { Subject } from 'rxjs/Subject'
import { Observable } from 'rxjs/Rx';

@Injectable()
export class myService {

  private pageName = new Subject<string>();

  pageNameChange$ = this.pageName.asObservable();
  changedComponentName(option:string){
        this.pageName.next(option);
  }
}
</code>```

In your child components,

child component 1

```<code>public ngOnInit() {
  this.myService.changedComponentName('child1');
}
</code>```

child component 2

```<code>public ngOnInit() {
   this.myService.changedComponentName('child2');
}
</code>```

and so on..

Now, to get the changed Component names in your parent component,

parent component.ts

```<code>import { Subscription } from 'rxjs';

export class parentComponent {

    private subscription:Subscription;

    constructor(private myService:myService){

        this.myService.pageNameChange$.subscribe( /* get called on every child page changes*/
         newPageName => {

        console.log(newPageName); // you get your passed component name ( child1 / child2 /etc.. here in the 'newPageName' variable
    });
  }
}
</code>```

Body:
I'm trying to learn angular 2 and am trying to set a variable in a parent component with data from my child components.  Basically I have a subheader in my parent view and I want the title and some HTML to change based on what child is loaded.

Parent component:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ParentComponent {
  childDetails: {title: String, helperBar: String};

  onChildLoaded(childData: {
    childTitle: string,
    childHelperBar: string
  }) {
    this.childDetails ={
      title: childData.childTitle,
      helperBar: childData.childHelperBar
    };
    console.log (childDetails);
  }
}

Child Component :

import { Component, OnInit, ViewEncapsulation, Output, EventEmitter }
from '@angular/core';

@Component({
  selector: 'app-first-child',
  templateUrl: './first-child.component.html',
  styleUrls: ['./first-child.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class FirstChildComponent implements OnInit {
  @Output() childLoaded = new EventEmitter<{childTitle: string,
childHelperBar: string}>();

  constructor() { }

  ngOnInit() {
    this.childLoaded.emit({
      childTitle: 'Dashboard',
      childHelperBar: '
<button>Dash Button</button>

'
    });
  }

}

And finally my parent HTML:

{{ childDetails.title }}

  {{ childDetails.helperBar }}

  <router-outlet (childLoaded)="onChildLoaded($event)"></router-outlet>

For the life of me I can't get this approach to work and can't pinpoint where I'm going wrong.  I could always just put the subheader in my children but I dont like the idea of repeating the code so many times and it will make my layout a bit harder to achieve.

Body:
The best way is making use of the service and  observable so that whenever the child component changes, the new data will get immediately reflected in the parent component.

in your service.ts,

import { Subject } from 'rxjs/Subject'
import { Observable } from 'rxjs/Rx';

@Injectable()
export class myService {

  private pageName = new Subject<string>();

  pageNameChange$ = this.pageName.asObservable();
  changedComponentName(option:string){
        this.pageName.next(option);
  }
}

In your child components,

child component 1

public ngOnInit() {
  this.myService.changedComponentName('child1');
}

child component 2

public ngOnInit() {
   this.myService.changedComponentName('child2');
}

and so on..

Now, to get the changed Component names in your parent component,

parent component.ts

import { Subscription } from 'rxjs';

export class parentComponent {

    private subscription:Subscription;

    constructor(private myService:myService){

        this.myService.pageNameChange$.subscribe( /* get called on every child page changes*/
         newPageName => {

        console.log(newPageName); // you get your passed component name ( child1 / child2 /etc.. here in the 'newPageName' variable
    });
  }
}


问:
Multiple DomainSite: when one domain site admin login in Umbraco, he can't see other Domain Site user
I have one use case in Umbraco. My project is Multidomain site (India, China, Greece). When I create a USER (India admin and group-adminIndia) from main administrator and in adminIndia group I give permission all along with user.

I did same thing with China and Greece admin. Now when I log in from India admin I can also disable other admin and vice versa.

This is the problem. My requirement is this: when India admin logs in, he shouldn't be able to see admins from others groups. Can anyone help with this issue?. Can I do it with Javascript or Jquery?

Check images: 1) Admin china group screen 2) admin india group 3)Login from indian admin now he can disable china admin. This is the problem. 4)Login from main admin . 5) content in umbraco backoffice

答:
You should not give USER section access  permission to your indian , china etc admin While making group. you should handle by main admin.

Remove User Permission


问:
Should I avoid Alternative Control Syntax?
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

```<code>x = (y == true) ? "foo" : "bar";
</code>```

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

答:
For me this issue is one of readability and maintainability in a multi-programmer environment.

If someone else has to read the code, or if you're going to come back to it later, you need to make it readable.

Unless you keep the cases simple, it's easy for code that uses the ternary operators to become obfuscated and unreadable.

Keep it simple

If it becomes even slightly hard to read, refactor into if { } else { }

OwnerDisplayName: Chris

Body:
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

x = (y == true) ? "foo" : "bar";

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.


问:
Call method on downcasted class
I have a certain SomeInterface and I have a number of classes implementing this interface. All these classes have someMethod() that is not defined by the interface.

Say I have a variable someVariable of type SomeInterface and I want to call someMethod() on it. One way to do it is to downcast SomeInterface to SomeClass that implements SomeInterface and call the someMethod on it like this:

```<code>((SomeClass) someVariable).someMethod()
</code>```

But I do not know which one of the classes that implement SomeInterface is stored in someVariable. What is the alternative clean way to call a method that is implemented by an underlying class but not defined by the interface I am coding against.

答:
The dirtiest solution is to use reflection, using instanceof is a bit less dirty, but still not optimal. Least dirty solution would be to create another interface with someMethod() and make the classes implement that interface as well. Then you can just cast to that interface and call the method.

```<code>((SomeInterface) someVariable).someMethod();
</code>```

This of course requires that you be able to modify the classes in question.

Title: Call method on downcasted class

Body:
I have a certain SomeInterface and I have a number of classes implementing this interface. All these classes have someMethod() that is not defined by the interface.

Say I have a variable someVariable of type SomeInterface and I want to call someMethod() on it. One way to do it is to downcast SomeInterface to SomeClass that implements SomeInterface and call the someMethod on it like this:

((SomeClass) someVariable).someMethod()

But I do not know which one of the classes that implement SomeInterface is stored in someVariable. What is the alternative clean way to call a method that is implemented by an underlying class but not defined by the interface I am coding against.

Body:
The dirtiest solution is to use reflection, using instanceof is a bit less dirty, but still not optimal. Least dirty solution would be to create another interface with someMethod() and make the classes implement that interface as well. Then you can just cast to that interface and call the method.

((SomeInterface) someVariable).someMethod();

This of course requires that you be able to modify the classes in question.