问:
jsonpCallback function not working
UPDATE 1:

I've just upgraded from jquery 1.4.4 to 1.6.1.  How does that effect the script in the original question?

ORIGINAL QUESTION:

Just as I test, I did:

```<code>$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }

    function jsonpCallback(data){
        alert("jsonpCallback");
    }
});
</code>```

I was expecting to get 2 alerts, the first showing success and the second showing jsonpCallback.  But I am only getting the first alert success.  Why is the second alert not showing up?

答: George is correct, set the jsonp param to false -- as of jQuery 1.5 (so, how you set this up is jQuery version dependent). I don't believe that your supplied callback name is invoked as a function (rather, it is the name provided in the URL presented to the server). If you are getting success, then you have received the data. Curious: do you have a hosts entry set up for dev, because I tried to do some testing, and http://www.remote_host.co.uk/feed.php does not resolve for me.</p>

Title: jsonpCallback function not working

Body:
UPDATE 1:

I've just upgraded from jquery 1.4.4 to 1.6.1.  How does that effect the script in the original question?

ORIGINAL QUESTION:

Just as I test, I did:

$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }

    function jsonpCallback(data){
        alert("jsonpCallback");
    }
});

I was expecting to get 2 alerts, the first showing success and the second showing jsonpCallback.  But I am only getting the first alert success.  Why is the second alert not showing up?


来源: stackexchange

问:
How to stop the spring MVC controller execution if client close the browser tab?
I'm developing a web app that use a spring websocket connection to send multiple message to a specific user.
I've got a spring mvc controller which when receive a STOMP from the client start sending message to the user. It's something like this:

```<code>@Controller
public class Controller{
     @Autowired
     private SimpMessagingTemplate template;

     @MessageMapping("/")
     @SendToUser("/queue/user")
     public void myMethod(ClientMessage msg, Principal principal){
          Object myObject = new Object();
          //stuff
          while(true){
               //more stuff
               this.template.convertAndSendToUser(principal.getName(), "/queue/user", myObject);
          }
     }
}
</code>```

Now my question is: there's a way to know when the client close (or reload) the browser tab?
I want to exit from the while cycle when the client close the tab to terminate the controller execution.
I was thinking to stop the while cycle by checking something, like: while(!session.isClose())
Can anyone help me out with this problem?

答:
I post my solution if anyone could need it.

I don't really know if i'm doing things correctly but i moved the SessionDisconnectEvent listener from a specific class to my controller. So, now the controller implements the ApplicationListener and override the onApplicationEvent. When the user close the tab a boolean is setted to true and the controller stops its execution.
Now i've got something like this:

```<code>@Controller
public class Controller implements ApplicationListener<SessionDisconnectEvent>{

     @Autowired
     private SimpMessagingTemplate template;

     private boolean disconnected;

     @MessageMapping("/")
     @SendToUser("/queue/user")
     public void myMethod(ClientMessage msg, Principal principal){
          Object myObject = new Object();
          //stuff
          while(!disconnected){
               //more stuff
               this.template.convertAndSendToUser(principal.getName(), "/queue/user", myObject);
          }
     }

     @EventListener
     @Override
     public void onApplicationEvent(SessionDisconnectEvent  applicationEvent) {
          System.out.println("SESSION " + applicationEvent.getSessionId() + " DISCONNECTED");
          this.graphService.setDisconnect(true);
     }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm developing a web app that use a spring websocket connection to send multiple message to a specific user.
I've got a spring mvc controller which when receive a STOMP from the client start sending message to the user. It's something like this:

@Controller
public class Controller{
     @Autowired
     private SimpMessagingTemplate template;

     @MessageMapping("/")
     @SendToUser("/queue/user")
     public void myMethod(ClientMessage msg, Principal principal){
          Object myObject = new Object();
          //stuff
          while(true){
               //more stuff
               this.template.convertAndSendToUser(principal.getName(), "/queue/user", myObject);
          }
     }
}

Now my question is: there's a way to know when the client close (or reload) the browser tab?
I want to exit from the while cycle when the client close the tab to terminate the controller execution.
I was thinking to stop the while cycle by checking something, like: while(!session.isClose())
Can anyone help me out with this problem?

Body:
I post my solution if anyone could need it.

I don't really know if i'm doing things correctly but i moved the SessionDisconnectEvent listener from a specific class to my controller. So, now the controller implements the ApplicationListener and override the onApplicationEvent. When the user close the tab a boolean is setted to true and the controller stops its execution.
Now i've got something like this:

@Controller
public class Controller implements ApplicationListener<SessionDisconnectEvent>{

     @Autowired
     private SimpMessagingTemplate template;

     private boolean disconnected;

     @MessageMapping("/")
     @SendToUser("/queue/user")
     public void myMethod(ClientMessage msg, Principal principal){
          Object myObject = new Object();
          //stuff
          while(!disconnected){
               //more stuff
               this.template.convertAndSendToUser(principal.getName(), "/queue/user", myObject);
          }
     }

     @EventListener
     @Override
     public void onApplicationEvent(SessionDisconnectEvent  applicationEvent) {
          System.out.println("SESSION " + applicationEvent.getSessionId() + " DISCONNECTED");
          this.graphService.setDisconnect(true);
     }
}


问:
Jackson: How to deserialize a list into the value of a field
I am using Jackson as a tool to deserialize a input JSON into a Java POJO. However, I have the need to deserialze a list value into a field of a wrapper class. Here is a sample code:

```<code>class Hello {
    private ListWrapper list;
}

class ListWrapper {
    private List<Item> unnamed;
}

class Item {
    // some fields
}
</code>```

If the user input is as follow, I would like it to be deserialized into a Hello instance with "list" field containing a ListWrapper instance whose "unnamed" field holding the items.

```<code>{
    "list": [
        {
            // item1
        }
        {
            // item2
        }
    ]
}
</code>```

Note that I don't want to customize a deserializer that is used by @JsonDeserialize, because I want Jackson to do the mapping validation on Item for me.

Is it possible? And How?

Thanks.

答:
You can accomplish this using the following Jackson annotations:</p>

```<code>class Hello {
    @JsonUnwrapped
    private ListWrapper list;
}

class ListWrapper {
    @JsonProperty("list")
    private List<Item> unnamed;
}
</code>```

Body:
I am using Jackson as a tool to deserialize a input JSON into a Java POJO. However, I have the need to deserialze a list value into a field of a wrapper class. Here is a sample code:

class Hello {
    private ListWrapper list;
}

class ListWrapper {
    private List<Item> unnamed;
}

class Item {
    // some fields
}

If the user input is as follow, I would like it to be deserialized into a Hello instance with "list" field containing a ListWrapper instance whose "unnamed" field holding the items.

{
    "list": [
        {
            // item1
        }
        {
            // item2
        }
    ]
}

Note that I don't want to customize a deserializer that is used by @JsonDeserialize, because I want Jackson to do the mapping validation on Item for me.

Is it possible? And How?

Thanks.

Body:
You can accomplish this using the following Jackson annotations:

class Hello {
    @JsonUnwrapped
    private ListWrapper list;
}

class ListWrapper {
    @JsonProperty("list")
    private List<Item> unnamed;
}


问:
The name does not exist in the namespace despite being there
I am trying to use data binding to create a list view but get this error. Why does the following error appear even though the affected name is actually in the affected class?

The name "ListItem" does not exist in the namespace "using:My_App.Models".

MainPage.xaml

```<code><Page
    x:Class="My_App.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="using:My_App.Models"
    mc:Ignorable="d">

        <ListView
            ItemsSource="{x:Bind listItems}"
            ItemClick="ListView_ItemClick"
            SelectionChanged="ListView_SelectionChanged">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:ListItem">
                    <StackPanel>
                        <TextBlock Text="{Binding BookTitle}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</Page>
</code>```

MainPage.cs

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using My_App.Models;
using Windows.ApplicationModel.Email;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace My_App
{
    public sealed partial class MainPage : Page
    {
        private List<ListItem> listItems;

        public MainPage()
        {
            this.InitializeComponent();

            listItems = ItemManager.GetListItems();
        }
    }
}
</code>```

ListItem class (inside the 'Models' folder)

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace My_App.Models
{

    public class ListItem
    {
        public string BookTitle { get; set; }
    }

    public class ItemManager
    {
        public static List<ListItem> GetListItems()
        {
            var items = new List<ListItem>
            {
                new ListItem { BookTitle = "The Wizard of Oz" }
            };

            return items;
        }
    }
}
</code>```

答:
That's weird, but changing Binding to x:Bind helped to compile the project.
Also, there was second error with private List<ListItem> listItems;. It has to be public. So:

<StackPanel>
      <TextBlock Text="{x:Bind BookTitle}" />
</StackPanel>
```

<p>and</p>

<pre class="lang-cs prettyprint-override"><code>public List<ListItem> listItems;
</code>```

Body:
I am trying to use data binding to create a list view but get this error. Why does the following error appear even though the affected name is actually in the affected class?

The name "ListItem" does not exist in the namespace "using:My_App.Models".

MainPage.xaml

<Page
    x:Class="My_App.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="using:My_App.Models"
    mc:Ignorable="d">

        <ListView
            ItemsSource="{x:Bind listItems}"
            ItemClick="ListView_ItemClick"
            SelectionChanged="ListView_SelectionChanged">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:ListItem">
                    <StackPanel>
                        <TextBlock Text="{Binding BookTitle}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</Page>

MainPage.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using My_App.Models;
using Windows.ApplicationModel.Email;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace My_App
{
    public sealed partial class MainPage : Page
    {
        private List<ListItem> listItems;

        public MainPage()
        {
            this.InitializeComponent();

            listItems = ItemManager.GetListItems();
        }
    }
}

ListItem class (inside the 'Models' folder)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace My_App.Models
{

    public class ListItem
    {
        public string BookTitle { get; set; }
    }

    public class ItemManager
    {
        public static List<ListItem> GetListItems()
        {
            var items = new List<ListItem>
            {
                new ListItem { BookTitle = "The Wizard of Oz" }
            };

            return items;
        }
    }
}

Body:
That's weird, but changing Binding to x:Bind helped to compile the project.
Also, there was second error with private List<ListItem> listItems;. It has to be public. So:

<StackPanel>
      <TextBlock Text="{x:Bind BookTitle}" />
</StackPanel>

and

public List<ListItem> listItems;


问:
Silverlight, Path.Width and Path.Height is NaN
I'm begginer in Silverlight and
I have next code:

```<code>private void btnAdd_Click_2(object sender, RoutedEventArgs e)
{
    string xmlns = "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"";
    string xmlnsx = "xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"";
    string pathXaml =
        String.Format("<Path {0} {1} Data=\"{2}\" />", xmlns, xmlnsx,this.Resources[txt.Text].ToString());
    Path p1 = (Path)System.Windows.Markup.XamlReader.Load(pathXaml);

    //p1.Width == NaN ??????
}
</code>```

Can somebody explain to me why p1.Width is NaN?

Thanks,
Viktor

答:
Path inherits from FrameworkElement and there the default value is set to Double.NaN (http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.width(v=vs.95).aspx). If you want to get the current width, use the ActualWidth Property of the path. This is the width of the currently rendered Path.

BR,

TJ

ContentLicense: CC BY-SA 3.0

Body:
I'm begginer in Silverlight and
I have next code:

private void btnAdd_Click_2(object sender, RoutedEventArgs e)
{
    string xmlns = "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"";
    string xmlnsx = "xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"";
    string pathXaml =
        String.Format("<Path {0} {1} Data=\"{2}\" />", xmlns, xmlnsx,this.Resources[txt.Text].ToString());
    Path p1 = (Path)System.Windows.Markup.XamlReader.Load(pathXaml);

    //p1.Width == NaN ??????
}

Can somebody explain to me why p1.Width is NaN?

Thanks,
Viktor


问:
Asymptotic analysis of algorithms problem
Well, I came across a question that I could not solve can anyone tell how I can solve this problem. Not the definition but the mathematical problem.

答:
express each time in microseconds, for example 1 sec = 10^6 microsec, let it be t (unclear for Month, perhaps it is considered 30 days?)

find inverse function, i.e. n in f(n)=t equation, for example if sqrt(n)=t , then n = t^2

substitute t (round down if not integer - all functions are increasing)

for n! there is no simple inverse function, you can compute it numerically or partially help yourself using inverse Stirling's approximation.


问:
DOM not updating in Jasmine
I have a simple component with a button that toggles the visibility of a paragraph on and off. The button toggles the visibility correctly in the app, but it does not toggle properly in my Jasmine unit test (the content does not toggle properly). It also does not work properly if I manually click the toggle button in the test browser.

Interestingly, I also have a passing test that tests my toggle method that sets my hideContent to false. However, even with hideContent: false, my content does not show up.

Relevant parts of my code:

alert-button-component.ts:

```<code>export class AlertButtonComponent implements OnInit {

  hideContent = true;

  constructor() { }

  ngOnInit(): void {
  }

  toggle() {
    this.hideContent = !this.hideContent;
  }
}
</code>```

alert-button.component.html:

```<code><div class="content">
    <p id="content" *ngIf="hideContent">My Content</p>
    <button (click) = "toggle()" class="button">Toggle Visibility</button>
</div>
</code>```

alert-button.component.spec.ts:

```<code>describe('AlertButtonComponent', () => {
  let component: AlertButtonComponent;
  let fixture: ComponentFixture<AlertButtonComponent>;
  let de: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AlertButtonComponent ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AlertButtonComponent);
    component = fixture.componentInstance;
    de = fixture.debugElement;
    fixture.detectChanges();
  });

 // Interestingly enough, this test works, but the content does not show up either
 it('should toggle', () => {
    expect(component.hideContent).toBeTruthy();
    component.toggle();
    expect(component.hideContent).toBeFalsy();
  });

  // returns TypeError: Cannot read property 'nativeElement' of null
  it('should show content after clicking button', () => {
    spyOn(component, 'toggle');
    const el = de.nativeElement;
    el.querySelector('button').dispatchEvent(new Event('click'));
    expect(component.toggle).toHaveBeenCalled();
    expect(de.query(By.css('#content')).nativeElement).toBeTruthy();
  });
});
</code>```

Any help would greatly be appreciated!

答:
I have explained in the comments, it seems like you only need one line for both tests.

```<code>// Interestingly enough, this test works, but the content does not show up either
 it('should toggle', () => {
    expect(component.hideContent).toBeTruthy();
    component.toggle();
    fixture.detectChanges(); // to show the content, you have to call fixture.detectChanges()
// for change detection to kick in to see the content. This is optional, like you said the test
// already passses.
    expect(component.hideContent).toBeFalsy();
  });

  // returns TypeError: Cannot read property 'nativeElement' of null
  it('should show content after clicking button', () => {
    spyOn(component, 'toggle');
    const el = de.nativeElement;
    el.querySelector('button').dispatchEvent(new Event('click'));
    expect(component.toggle).toHaveBeenCalled();
    fixture.detectChanges(); // again, call fixture.detectChanges for reason stated above.
    // this time it is not optional
    expect(de.query(By.css('#content')).nativeElement).toBeTruthy();
  });
</code>```

Edit

To debug your tests, I assume a browser opens when you're running npm run test.

When the browser opens, quickly press F12 (or inspect the dom) and it should trip on the debugger points. Press play to release the debuggers I think there is even a debug button as well depending on what version of Karma you're running.

```<code>  it('should show content after clicking button', () => {
    spyOn(component, 'toggle');
    const el = de.nativeElement;
    el.querySelector('button').dispatchEvent(new Event('click'));
    expect(component.toggle).toHaveBeenCalled();
    debugger; // you shouldn't see the p tag
    fixture.detectChanges(); // again, call fixture.detectChanges for reason stated above.
    // this time it is not optional
    expect(de.query(By.css('#content')).nativeElement).toBeTruthy();
    debugger; // you should see the p tag, maybe even go through the DOM tree to see it
  });
</code>```

Another side note is that the first fixture.detectChanges in the first beforeEach calls ngOnInit so it is needed. The other fixture.detectChanges later on are what will change the view according to the change in state.

Title: DOM not updating in Jasmine

Body:
I have a simple component with a button that toggles the visibility of a paragraph on and off. The button toggles the visibility correctly in the app, but it does not toggle properly in my Jasmine unit test (the content does not toggle properly). It also does not work properly if I manually click the toggle button in the test browser.

Interestingly, I also have a passing test that tests my toggle method that sets my hideContent to false. However, even with hideContent: false, my content does not show up.

Relevant parts of my code:

alert-button-component.ts:

export class AlertButtonComponent implements OnInit {

  hideContent = true;

  constructor() { }

  ngOnInit(): void {
  }

  toggle() {
    this.hideContent = !this.hideContent;
  }
}

alert-button.component.html:

My Content

    <button (click) = "toggle()" class="button">Toggle Visibility</button>

alert-button.component.spec.ts:

describe('AlertButtonComponent', () => {
  let component: AlertButtonComponent;
  let fixture: ComponentFixture<AlertButtonComponent>;
  let de: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AlertButtonComponent ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AlertButtonComponent);
    component = fixture.componentInstance;
    de = fixture.debugElement;
    fixture.detectChanges();
  });

 // Interestingly enough, this test works, but the content does not show up either
 it('should toggle', () => {
    expect(component.hideContent).toBeTruthy();
    component.toggle();
    expect(component.hideContent).toBeFalsy();
  });

  // returns TypeError: Cannot read property 'nativeElement' of null
  it('should show content after clicking button', () => {
    spyOn(component, 'toggle');
    const el = de.nativeElement;
    el.querySelector('button').dispatchEvent(new Event('click'));
    expect(component.toggle).toHaveBeenCalled();
    expect(de.query(By.css('#content')).nativeElement).toBeTruthy();
  });
});

Any help would greatly be appreciated!

Body:
I have explained in the comments, it seems like you only need one line for both tests.

// Interestingly enough, this test works, but the content does not show up either
 it('should toggle', () => {
    expect(component.hideContent).toBeTruthy();
    component.toggle();
    fixture.detectChanges(); // to show the content, you have to call fixture.detectChanges()
// for change detection to kick in to see the content. This is optional, like you said the test
// already passses.
    expect(component.hideContent).toBeFalsy();
  });

  // returns TypeError: Cannot read property 'nativeElement' of null
  it('should show content after clicking button', () => {
    spyOn(component, 'toggle');
    const el = de.nativeElement;
    el.querySelector('button').dispatchEvent(new Event('click'));
    expect(component.toggle).toHaveBeenCalled();
    fixture.detectChanges(); // again, call fixture.detectChanges for reason stated above.
    // this time it is not optional
    expect(de.query(By.css('#content')).nativeElement).toBeTruthy();
  });

Edit

To debug your tests, I assume a browser opens when you're running npm run test.

When the browser opens, quickly press F12 (or inspect the dom) and it should trip on the debugger points. Press play to release the debuggers I think there is even a debug button as well depending on what version of Karma you're running.

  it('should show content after clicking button', () => {
    spyOn(component, 'toggle');
    const el = de.nativeElement;
    el.querySelector('button').dispatchEvent(new Event('click'));
    expect(component.toggle).toHaveBeenCalled();
    debugger; // you shouldn't see the p tag
    fixture.detectChanges(); // again, call fixture.detectChanges for reason stated above.
    // this time it is not optional
    expect(de.query(By.css('#content')).nativeElement).toBeTruthy();
    debugger; // you should see the p tag, maybe even go through the DOM tree to see it
  });

Another side note is that the first fixture.detectChanges in the first beforeEach calls ngOnInit so it is needed. The other fixture.detectChanges later on are what will change the view according to the change in state.


问:
Can someone help me with this problem of finding indices of the pairs of elements of an array that sum to k?
```<code>#include <vector>
#include <iostream>
#include <unordered_map>

int main() {

    std::unordered_map<int, int> nMap;

    int a[] = {3,4,5,6,5,7,4};
    int k = 10;
    for(int i = 0; i < 7; i++) {
        int rem = k - a[i];
        if(nMap.find(rem) != nMap.end()){
            printf("(%d,%d)\n",nMap[rem], i);
        }

        nMap.insert(std::pair<int,int>(a[i],i));
    }
    return 0;
}
</code>```

In the above program I have used a hash-map to find the indices of the pairs of the elements giving the sum equal to the k. And it's working fine for the above code and gives me the required pairs

```<code>(1,3)
(2,4)
(0,5)
(3,6)
</code>```

Note: These are the indices of the elements that actually add up to k.

But, this does work correctly for the input int a[] = {1,1,1,1,1,1,1}; int k = 2 the output given is:

```<code>(0,1)
(0,2)
(0,3)
(0,4)
(0,5)
(0,6)
</code>```

However according to me I guess the output must have all pairs namely (1,2),(1,3)...(5,6).
What is the correct program for the above problem?

答:
The input 1,1,1,1,1,1,1 produces 6+5+4+3+2+1 = 21 = N * (N-1) / 2 = N²/2 - N/2 outputs:

(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(0, 6)
(1, 2)
(1, 3)
(1, 4)
(1, 5)
(1, 6)
(2, 3)
(2, 4)
(2, 5)
(2, 6)
(3, 4)
(3, 5)
(3, 6)
(4, 5)
(4, 6)
(5, 6)

You need an algorithm with complexity O(N²) to produce such output. Your code doesn't work because a code with complexity O(N) can't produce this much output.

Here is a more performant solution using unordered map:

```<code>#include <array>
#include <vector>
#include <iostream>
#include <unordered_map>

int main() {
    std::array<int, 7> a{3,4,5,6,5,7,4};
    std::unordered_map<int, std::vector<std::size_t>> nMap;
    for (std::size_t i = 0; i < a.size(); ++i) {
        nMap[a[i]].push_back(i);
    }
    int k = 10;
    for (const auto &el : nMap) {
        if (nMap.find(k - el.first) == nMap.end()) continue;
        for (const auto &left : el.second) {
            for (const auto &right : nMap.at(k - el.first)) {
                if (left < right) std::cout << '(' << left << ',' << right << ")\n";
            }
        }
    }
    return 0;
}
</code>```

I filled a map with all indices for one value. Now I can access all indices in O(1) for a target value. I iterate all values in the map and print all pairs of values.

Body:
#include <vector>
#include <iostream>
#include <unordered_map>

int main() {

    std::unordered_map<int, int> nMap;

    int a[] = {3,4,5,6,5,7,4};
    int k = 10;
    for(int i = 0; i < 7; i++) {
        int rem = k - a[i];
        if(nMap.find(rem) != nMap.end()){
            printf("(%d,%d)\n",nMap[rem], i);
        }

        nMap.insert(std::pair<int,int>(a[i],i));
    }
    return 0;
}

In the above program I have used a hash-map to find the indices of the pairs of the elements giving the sum equal to the k. And it's working fine for the above code and gives me the required pairs

(1,3)
(2,4)
(0,5)
(3,6)

Note: These are the indices of the elements that actually add up to k.

But, this does work correctly for the input int a[] = {1,1,1,1,1,1,1}; int k = 2 the output given is:

(0,1)
(0,2)
(0,3)
(0,4)
(0,5)
(0,6)

However according to me I guess the output must have all pairs namely (1,2),(1,3)...(5,6).
What is the correct program for the above problem?

Body:
The input 1,1,1,1,1,1,1 produces 6+5+4+3+2+1 = 21 = N * (N-1) / 2 = N²/2 - N/2 outputs:

(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(0, 6)
(1, 2)
(1, 3)
(1, 4)
(1, 5)
(1, 6)
(2, 3)
(2, 4)
(2, 5)
(2, 6)
(3, 4)
(3, 5)
(3, 6)
(4, 5)
(4, 6)
(5, 6)

You need an algorithm with complexity O(N²) to produce such output. Your code doesn't work because a code with complexity O(N) can't produce this much output.

Here is a more performant solution using unordered map:

#include <array>
#include <vector>
#include <iostream>
#include <unordered_map>

int main() {
    std::array<int, 7> a{3,4,5,6,5,7,4};
    std::unordered_map<int, std::vector<std::size_t>> nMap;
    for (std::size_t i = 0; i < a.size(); ++i) {
        nMap[a[i]].push_back(i);
    }
    int k = 10;
    for (const auto &el : nMap) {
        if (nMap.find(k - el.first) == nMap.end()) continue;
        for (const auto &left : el.second) {
            for (const auto &right : nMap.at(k - el.first)) {
                if (left < right) std::cout << '(' << left << ',' << right << ")\n";
            }
        }
    }
    return 0;
}

I filled a map with all indices for one value. Now I can access all indices in O(1) for a target value. I iterate all values in the map and print all pairs of values.


问:
Using MSTest unit framework I get the below error
MSTest Unit Framework

The type 'TestClassAttribute' exists in both Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a and Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

答:
You have two possible solutions:

Decide, which assembly need to reference and remove second one.
When you're creating a UnitTest-Project from the Wizard, there is Microsoft.VisualStudio.QualityTools.UnitTestFramework referenced, so i'd try to remove Microsoft.VisualStudio.TestPlatform.TestFramework

If the second Assembly (Microsoft.VisualStudio.TestPlatform.TestFramework) can't be removed, you can use alias:

```<code>using mstest = Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject1
{
  [mstest.TestClass]
  public class UnitTest1
  {
    [mstest.TestMethod]
    public void TestMethod1()
    {
    }
  }
}
</code>```

Body:
You have two possible solutions:

Decide, which assembly need to reference and remove second one.
When you're creating a UnitTest-Project from the Wizard, there is Microsoft.VisualStudio.QualityTools.UnitTestFramework referenced, so i'd try to remove Microsoft.VisualStudio.TestPlatform.TestFramework

If the second Assembly (Microsoft.VisualStudio.TestPlatform.TestFramework) can't be removed, you can use alias:

using mstest = Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject1
{
  [mstest.TestClass]
  public class UnitTest1
  {
    [mstest.TestMethod]
    public void TestMethod1()
    {
    }
  }
}


问:
PHPWord HTML to Word design issue
I am using PHPWord library to convert my HTML template to Word.

Library link

My code to convert HTML to Word file is as below:

```<code>$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
\PhpOffice\PhpWord\Shared\Html::addHtml($section, $htmlTemplate);
$targetFile = __DIR__ . "/1.docx";
$phpWord->save($targetFile, 'HTML');
</code>```

I am facing below issues:

I am applying background color and font color using inline style but font color is only working and background color is not working.

```<code> <p style="background-color:#FFFF00;color:#FF0000;">Some text</p>
</code>```

I am using below HTML code to allow Page break within sections of HTML templates. but it does not work in exported Word file.

```<code><div style="page-break-after:always"><span style="display:none"> </span></div>
</code>```

I am using span tag to mark some word in bold or change the color of word in paragraph. but when i export to Word file, content after span tag, moves to new line below the word. I tried with display:inline css property in span tag. but it doesn't work.

```<code><p>some text before span tag <span style="color:#FF0000;display:inline">XXXXX</span> Text after span tag.</p>
</code>```

Edit:

Please recommend any other library which i can use to convert HTML with inline css to Word if above mentioned issues can't be resolved with PHPWord!

答:
I just performed a very simple test and it is working correctly. My code is pretty much exactly the same as yours except that I'm telling the system to write it as a Word document, not HTML.

use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\Html;

require_once __DIR__ . '/vendor/autoload.php';

$htmlTemplate = '
Some text
';

$phpWord = new PhpWord();
$section = $phpWord->addSection();
Html::addHtml($section, $htmlTemplate);
$targetFile = __DIR__ . "/1.docx";
$phpWord->save($targetFile, 'Word2007');
```

<p>Which produces:</p>

<p><img src="https://i.stack.imgur.com/NRbh4.png" alt="Screenshot showing requested background and foreground text correctly applied in Word document"></p>

<p>If you change the save mode to <code>HTML</code>, the background color does disappear, however it isn't a Word document anymore anyways, just raw HTML, so I don't think that matters.</p>

<pre class="lang-php prettyprint-override"><code>$targetFile = __DIR__ . "/1.html";
$phpWord->save($targetFile, 'HTML');
</code>```

Title: PHPWord HTML to Word design issue

Body:
I am using PHPWord library to convert my HTML template to Word.

Library link

My code to convert HTML to Word file is as below:

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
\PhpOffice\PhpWord\Shared\Html::addHtml($section, $htmlTemplate);
$targetFile = __DIR__ . "/1.docx";
$phpWord->save($targetFile, 'HTML');

I am facing below issues:

I am applying background color and font color using inline style but font color is only working and background color is not working.

Some text

I am using below HTML code to allow Page break within sections of HTML templates. but it does not work in exported Word file.

I am using span tag to mark some word in bold or change the color of word in paragraph. but when i export to Word file, content after span tag, moves to new line below the word. I tried with display:inline css property in span tag. but it doesn't work.

some text before span tag XXXXX Text after span tag.

Edit:

Please recommend any other library which i can use to convert HTML with inline css to Word if above mentioned issues can't be resolved with PHPWord!

Body:
I just performed a very simple test and it is working correctly. My code is pretty much exactly the same as yours except that I'm telling the system to write it as a Word document, not HTML.

use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\Html;

require_once __DIR__ . '/vendor/autoload.php';

$htmlTemplate = ' <p style="background-color:#FFFF00;color:#FF0000;">Some text</p>';

$phpWord = new PhpWord();
$section = $phpWord->addSection();
Html::addHtml($section, $htmlTemplate);
$targetFile = __DIR__ . "/1.docx";
$phpWord->save($targetFile, 'Word2007');

Which produces:

If you change the save mode to HTML, the background color does disappear, however it isn't a Word document anymore anyways, just raw HTML, so I don't think that matters.

$targetFile = __DIR__ . "/1.html";
$phpWord->save($targetFile, 'HTML');


问:
Which mechanism is a better way to extend Dictionary to deal with missing keys and why?
There is a minor annoyance I find myself with a lot - I have a Dictionary<TKey, TValue> that contains values that may or may not be there.

So normal behaviour would be to use the indexer, like this:

```<code>object result = myDictionary["key"];
</code>```

However, if "key" is not in the dictionary this throws a KeyNotFoundException, so you do this instead:

```<code>object val;
if (!myDictionary.TryGetValue("key", out val))
{
    val = ifNotFound;
}
</code>```

Which is fine, except that I can have a load of these in a row - TryGetValue starts to feel awful clunky.

So option 1 is an extension method:

```<code>public static TValue TryGet<TKey, TValue>(
    this Dictionary<TKey, TValue> input,
    TKey key,
    TValue ifNotFound = default(TValue))
{
    TValue val;
    if (input.TryGetValue(key, out val))
    {
        return val;
    }

    return ifNotFound;
}
</code>```

Which lets me do:

```<code>object result = myDictionary.TryGet("key1") ?? ifNotFound;

int i = anotherDictionary.TryGet("key2", -1);
</code>```

Which is simple enough, but an additional extension method with a name similar to existing instance methods potentially adds confusion and reduces maintainability. It's also not consistent with the dictionary's indexer set - that will handle missing keys.

So option 2 is a new implementation of IDictionary<TKey, TValue> with a implicit cast from Dictionary<TKey, TValue> but an indexer that returns default(TValue) instead of throwing a KeyNotFoundException.

That let's me do:

```<code>ForgivingDictionary<string, object> dict = myDictionary;

object val = dict["key"] ?? ifNotFound;

// do stuff to val, then...
dict["key"] = val;
</code>```

So now the get and set values are consistent, but value types are messier and ForgivingDictionary involves a lot more code.

Both methods seem 'messy' - is there a better way to do this already in .Net?

Both methods make compromises that could cause confusion, but is one more obvious/clear than the other? And why?

答:
I'm unable to infer from your question what should be done when a key is not found. I can imagine nothing should be done in that case, but I can also imagine the opposite.
Anyway, an elegant alternative for a series of these TryGetValue-statements you describe, is using one of the following extension methods. I have provided two options, depending on whether something should be done or not when the dictionary does not contain the key:

```<code>/// <summary> Iterates over all values corresponding to the specified keys,
///for which the key is found in the dictionary. </summary>
public static IEnumerable<TValue> TryGetValues<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, IEnumerable<TKey> keys)
{
    TValue value;
    foreach (TKey key in keys)
        if (dictionary.TryGetValue(key, out value))
            yield return value;
}

/// <summary> Iterates over all values corresponding to the specified keys,
///for which the key is found in the dictionary. A function can be specified to handle not finding a key. </summary>
public static IEnumerable<TValue> TryGetValues<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, IEnumerable<TKey> keys, Action<TKey> notFoundHandler)
{
    TValue value;
    foreach (TKey key in keys)
        if (dictionary.TryGetValue(key, out value))
            yield return value;
        else
            notFoundHandler(key);
}
</code>```

Example code on how to use this is:

```<code>TKey[] keys = new TKey{...};
foreach(TValue value in dictionary.TryGetValues(keys))
{
    //some action on all values here
}
</code>```

Body:
There is a minor annoyance I find myself with a lot - I have a Dictionary<TKey, TValue> that contains values that may or may not be there.

So normal behaviour would be to use the indexer, like this:

object result = myDictionary["key"];

However, if "key" is not in the dictionary this throws a KeyNotFoundException, so you do this instead:

object val;
if (!myDictionary.TryGetValue("key", out val))
{
    val = ifNotFound;
}

Which is fine, except that I can have a load of these in a row - TryGetValue starts to feel awful clunky.

So option 1 is an extension method:

public static TValue TryGet<TKey, TValue>(
    this Dictionary<TKey, TValue> input,
    TKey key,
    TValue ifNotFound = default(TValue))
{
    TValue val;
    if (input.TryGetValue(key, out val))
    {
        return val;
    }

    return ifNotFound;
}

Which lets me do:

object result = myDictionary.TryGet("key1") ?? ifNotFound;

int i = anotherDictionary.TryGet("key2", -1);

Which is simple enough, but an additional extension method with a name similar to existing instance methods potentially adds confusion and reduces maintainability. It's also not consistent with the dictionary's indexer set - that will handle missing keys.

So option 2 is a new implementation of IDictionary<TKey, TValue> with a implicit cast from Dictionary<TKey, TValue> but an indexer that returns default(TValue) instead of throwing a KeyNotFoundException.

That let's me do:

ForgivingDictionary<string, object> dict = myDictionary;

object val = dict["key"] ?? ifNotFound;

// do stuff to val, then...
dict["key"] = val;

So now the get and set values are consistent, but value types are messier and ForgivingDictionary involves a lot more code.

Both methods seem 'messy' - is there a better way to do this already in .Net?

Both methods make compromises that could cause confusion, but is one more obvious/clear than the other? And why?

Body:
I'm unable to infer from your question what should be done when a key is not found. I can imagine nothing should be done in that case, but I can also imagine the opposite.
Anyway, an elegant alternative for a series of these TryGetValue-statements you describe, is using one of the following extension methods. I have provided two options, depending on whether something should be done or not when the dictionary does not contain the key:

/// <summary> Iterates over all values corresponding to the specified keys,
///for which the key is found in the dictionary. </summary>
public static IEnumerable<TValue> TryGetValues<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, IEnumerable<TKey> keys)
{
    TValue value;
    foreach (TKey key in keys)
        if (dictionary.TryGetValue(key, out value))
            yield return value;
}

/// <summary> Iterates over all values corresponding to the specified keys,
///for which the key is found in the dictionary. A function can be specified to handle not finding a key. </summary>
public static IEnumerable<TValue> TryGetValues<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, IEnumerable<TKey> keys, Action<TKey> notFoundHandler)
{
    TValue value;
    foreach (TKey key in keys)
        if (dictionary.TryGetValue(key, out value))
            yield return value;
        else
            notFoundHandler(key);
}

Example code on how to use this is:

TKey[] keys = new TKey{...};
foreach(TValue value in dictionary.TryGetValues(keys))
{
    //some action on all values here
}


问:
iOS UIButton near screen edge not respond to tap normally
As shown in below image, part in the red rectangle in buttons near the screen edge  cannot respond to tap normally. I've heard some mechanism in iOS that can disable touched near the edge for user experience consideration. So how to disable this mechanism? Or how to make buttons near the edge work normally.

I tried UIButton: Making the hit area larger than the default hit area. It works for "Center" button in the image but not for "Edge" button.

Thank you!

答:
Add this in viewDidAppear</p>

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if let window = view.window,
        let recognizers = window.gestureRecognizers {
        recognizers.forEach { r in
            r.delaysTouchesBegan = false
            r.cancelsTouchesInView = false
            r.isEnabled = false
        }
    }
}
</code>```

Body:
Add this in viewDidAppear

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if let window = view.window,
        let recognizers = window.gestureRecognizers {
        recognizers.forEach { r in
            r.delaysTouchesBegan = false
            r.cancelsTouchesInView = false
            r.isEnabled = false
        }
    }
}


问:
Not properly executed overridden code using an INET extended module
I have to extend the UdpBasicApp module from INET4 in OMNeT++ 5.6.1 (Ubuntu 18.04.4) and execute two overridden methods (initialize and handleMessageWhenUp).
It seems an easy task, and looked like it was all fine when I built the project (momentarily stored inside the "examples" folder in inet4) with no errors but, after starting the simulation the code isn't successfully overridden. The original code (the one from UdpBasicApp) is executed instead.
In fact, after inspecting the code in the editor, the methods' name isn't bold (as should be) and the keywords aren't colored as they normally should be.
My C++ skill is not high (nor my OMNeT one) hence I'm not sure what is really happening.
The extended simple module is called "PriorityApp" (I added just an integer field more).

This is the .ned code (not sure if you need it)

```<code>package inet.examples.MyProject.src;

import inet.applications.udpapp.UdpBasicApp;

// The module extends UdpBasicApp adding a priority parameter
simple PriorityApp extends UdpBasicApp
{
    parameters:
        int priority = default(0);  // priority 0 = higher priority
}
</code>```

This is the .h code

```<code>#ifndef __INET4_PRIORITYAPP_H_
#define __INET4_PRIORITYAPP_H_

#include "inet/applications/udpapp/UdpBasicApp.h"

namespace inet {

class PriorityApp : public UdpBasicApp
{
  protected:
    int priority;

    virtual void initialize(int stage) override;
    virtual void handleMessageWhenUp(cMessage *msg) override;
};

} // namespace inet

#endif  // ifndef __INET_PRIORITYAPP_H
</code>```

This is the .cc code

```<code>#include "PriorityApp.h"

namespace inet {

Define_Module(PriorityApp);

void PriorityApp::initialize(int stage)
{
    msg = new cMessage("priority");
    EV << "Example Message" << endl;
}

void PriorityApp::handleMessageWhenUp(cMessage *msg)
{

}

} //namespace inet
</code>```

This is the .ini file

```<code>[General]

[Config SwitchedNet1G]
description = "1Gbps Switched Network"
network = SwitchedNet

**.dataRate = 1Gbps                                         # 1 Gbps channel datarate

# Priority stuff
**.host[0].app[0].priority = 1

# Dst Params
**.sink.app[*].typename = "UdpSink"                         # Destination host (it receives messages)
**.sink.app[*].localPort = 2500

# Src Params
**.host[0].app[0].packetName = "Host0-Data"
**.host[*].app[0].typename = "PriorityApp"                  # Source host (they send messages)
**.host[*].app[0].destPort = 2500
**.host[*].app[0].destAddresses = "sink"
**.host[0].app[0].sendInterval = 3s
**.host[*].app[0].startTime = uniform (0s, 3s)

# EthInterface Setup
**.eth[*].qEncap.typename = "Ieee8021qEncap"                # 8021Q Encapsulation
**.etherSwitch.numEthInterfaces = 2                         # Switch ethInterfaces total number (2)
**.numEthInterfaces = 1

# Global Params
**.messageLength = 100B
**.numHosts = 1
**.numApps = 1                                  # every host has 1 app (UdpBasicApp or UdpSink)
</code>```

答:
There are two independent faults here:

1.) You should NOT add C++ code into INET's examples folder. That folder is NOT designated as a source folder, so the build system will not pick up, build and link to the executable, meaning that your code is not present in the model. That's one reason why you are not getting your new behavior.

2.) Even if you place your source code in the src folder along with the UdpBasicApp and the build system would properly link it in, you still have to properly set up the NED part. Specifically you have to specify the @class property to tell NED which C++ class you intend to use to specify behavior: @class(PriorityApp) Otherwise your PriorityApp module would inherit the value of @class property from UdpBasicApp and would use the CdpBasicApp C++ class.

```<code>import inet.applications.udpapp.UdpBasicApp;

// The module extends UdpBasicApp adding a priority parameter
simple PriorityApp extends UdpBasicApp
{
    @class(PriorityApp)
    parameters:
        int priority = default(0);  // priority 0 = higher priority
}
</code>```

Body:
I have to extend the UdpBasicApp module from INET4 in OMNeT++ 5.6.1 (Ubuntu 18.04.4) and execute two overridden methods (initialize and handleMessageWhenUp).
It seems an easy task, and looked like it was all fine when I built the project (momentarily stored inside the "examples" folder in inet4) with no errors but, after starting the simulation the code isn't successfully overridden. The original code (the one from UdpBasicApp) is executed instead.
In fact, after inspecting the code in the editor, the methods' name isn't bold (as should be) and the keywords aren't colored as they normally should be.
My C++ skill is not high (nor my OMNeT one) hence I'm not sure what is really happening.
The extended simple module is called "PriorityApp" (I added just an integer field more).

This is the .ned code (not sure if you need it)

package inet.examples.MyProject.src;

import inet.applications.udpapp.UdpBasicApp;

// The module extends UdpBasicApp adding a priority parameter
simple PriorityApp extends UdpBasicApp
{
    parameters:
        int priority = default(0);  // priority 0 = higher priority
}

This is the .h code

#ifndef __INET4_PRIORITYAPP_H_
#define __INET4_PRIORITYAPP_H_

#include "inet/applications/udpapp/UdpBasicApp.h"

namespace inet {

class PriorityApp : public UdpBasicApp
{
  protected:
    int priority;

    virtual void initialize(int stage) override;
    virtual void handleMessageWhenUp(cMessage *msg) override;
};

} // namespace inet

#endif  // ifndef __INET_PRIORITYAPP_H

This is the .cc code

#include "PriorityApp.h"

namespace inet {

Define_Module(PriorityApp);

void PriorityApp::initialize(int stage)
{
    msg = new cMessage("priority");
    EV << "Example Message" << endl;
}

void PriorityApp::handleMessageWhenUp(cMessage *msg)
{

}

} //namespace inet

This is the .ini file

[General]

[Config SwitchedNet1G]
description = "1Gbps Switched Network"
network = SwitchedNet

**.dataRate = 1Gbps                                         # 1 Gbps channel datarate

# Priority stuff
**.host[0].app[0].priority = 1

# Dst Params
**.sink.app[*].typename = "UdpSink"                         # Destination host (it receives messages)
**.sink.app[*].localPort = 2500

# Src Params
**.host[0].app[0].packetName = "Host0-Data"
**.host[*].app[0].typename = "PriorityApp"                  # Source host (they send messages)
**.host[*].app[0].destPort = 2500
**.host[*].app[0].destAddresses = "sink"
**.host[0].app[0].sendInterval = 3s
**.host[*].app[0].startTime = uniform (0s, 3s)

# EthInterface Setup
**.eth[*].qEncap.typename = "Ieee8021qEncap"                # 8021Q Encapsulation
**.etherSwitch.numEthInterfaces = 2                         # Switch ethInterfaces total number (2)
**.numEthInterfaces = 1

# Global Params
**.messageLength = 100B
**.numHosts = 1
**.numApps = 1                                  # every host has 1 app (UdpBasicApp or UdpSink)

Body:
There are two independent faults here:

1.) You should NOT add C++ code into INET's examples folder. That folder is NOT designated as a source folder, so the build system will not pick up, build and link to the executable, meaning that your code is not present in the model. That's one reason why you are not getting your new behavior.

2.) Even if you place your source code in the src folder along with the UdpBasicApp and the build system would properly link it in, you still have to properly set up the NED part. Specifically you have to specify the @class property to tell NED which C++ class you intend to use to specify behavior: @class(PriorityApp) Otherwise your PriorityApp module would inherit the value of @class property from UdpBasicApp and would use the CdpBasicApp C++ class.

import inet.applications.udpapp.UdpBasicApp;

// The module extends UdpBasicApp adding a priority parameter
simple PriorityApp extends UdpBasicApp
{
    @class(PriorityApp)
    parameters:
        int priority = default(0);  // priority 0 = higher priority
}


问:
objcopy prepends directory pathname to symbol name
I am tying to use objcopy to include a binary form of a text file into an executable. (At runtime I need the file as a string). This works fine until the linker needs to find the references from the symbol names. The problem is that objcopy prepends the symbol names with the pathname to the file. Since I am using GNU Autotools to ship the package this prepended pathname changes and I don't know what external linker symbol to use in the C/C++ program.

```<code>nm libtest.a |grep textfile
textfile.o:
00001d21 D _binary__home_git_textfile_end
00001d21 A _binary__home_git_textfile_size
00000000 D _binary__home_git_textfile_start
</code>```

libtest.a was produced with (extract from Makefile.am):

```<code>SUFFIXES = .txt
.txt.$(OBJEXT):
    objcopy --input binary --output elf32-i386 --binary-architecture i386 $< $@
</code>```

How can I tell objcopy to only us the stem of the filename as linker symbols? Or is there another way around the problem?

答:
I had to do this with cmake, and I ended up using /dev/stdin as input to get consistent symbols name, then redefining the symbols thanks to
   string(MAKE_C_IDENTIFIER ...)
And then use objcopy --redefine-sym on the resulting object file.

The resulting function is then :

```<code>function(make_binary_object __file)
    get_filename_component(__file_name ${__file} NAME)
    set(__object ${CMAKE_CURRENT_BINARY_DIR}/${__file_name}.obj)
    string(MAKE_C_IDENTIFIER ${__file_name} __file_c_identifier)
    add_custom_command(OUTPUT ${__object}
        COMMAND ${CMAKE_OBJCOPY}
            --input-format binary
            --output-format elf64-x86-64
            --binary-architecture i386:x86-64
            /dev/stdin
            ${__object} < ${__file}
        COMMAND ${CMAKE_OBJCOPY}
            --redefine-sym _binary__dev_stdin_start=_binary_${__file_c_identifier}_start
            --redefine-sym _binary__dev_stdin_end=_binary_${__file_c_identifier}_end
            --redefine-sym _binary__dev_stdin_size=_binary_${__file_c_identifier}_size
            ${__object}
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
        DEPENDS ${__file})
    set_source_files_properties(${__object} PROPERTIES EXTERNAL_OBJECT TRUE)
endfunction()
</code>```

And you can use it like this:

```<code>make_binary_object(index.html)

add_executable(my_server
    server.c
    ${CMAKE_CURRENT_BINARY_DIR}/index.html.obj)
</code>```

Body:
I am tying to use objcopy to include a binary form of a text file into an executable. (At runtime I need the file as a string). This works fine until the linker needs to find the references from the symbol names. The problem is that objcopy prepends the symbol names with the pathname to the file. Since I am using GNU Autotools to ship the package this prepended pathname changes and I don't know what external linker symbol to use in the C/C++ program.

nm libtest.a |grep textfile
textfile.o:
00001d21 D _binary__home_git_textfile_end
00001d21 A _binary__home_git_textfile_size
00000000 D _binary__home_git_textfile_start

libtest.a was produced with (extract from Makefile.am):

SUFFIXES = .txt
.txt.$(OBJEXT):
    objcopy --input binary --output elf32-i386 --binary-architecture i386 $< $@

How can I tell objcopy to only us the stem of the filename as linker symbols? Or is there another way around the problem?

Body:
I had to do this with cmake, and I ended up using /dev/stdin as input to get consistent symbols name, then redefining the symbols thanks to
   string(MAKE_C_IDENTIFIER ...)
And then use objcopy --redefine-sym on the resulting object file.

The resulting function is then :

function(make_binary_object __file)
    get_filename_component(__file_name ${__file} NAME)
    set(__object ${CMAKE_CURRENT_BINARY_DIR}/${__file_name}.obj)
    string(MAKE_C_IDENTIFIER ${__file_name} __file_c_identifier)
    add_custom_command(OUTPUT ${__object}
        COMMAND ${CMAKE_OBJCOPY}
            --input-format binary
            --output-format elf64-x86-64
            --binary-architecture i386:x86-64
            /dev/stdin
            ${__object} < ${__file}
        COMMAND ${CMAKE_OBJCOPY}
            --redefine-sym _binary__dev_stdin_start=_binary_${__file_c_identifier}_start
            --redefine-sym _binary__dev_stdin_end=_binary_${__file_c_identifier}_end
            --redefine-sym _binary__dev_stdin_size=_binary_${__file_c_identifier}_size
            ${__object}
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
        DEPENDS ${__file})
    set_source_files_properties(${__object} PROPERTIES EXTERNAL_OBJECT TRUE)
endfunction()

And you can use it like this:

make_binary_object(index.html)

add_executable(my_server
    server.c
    ${CMAKE_CURRENT_BINARY_DIR}/index.html.obj)


问:
Full range of options for respond_to format.*
I'm looking into rendering more complex responses.

Specifically, I am searching for options for formatting yaml and json responses with multiple levels, but right now I cannot locate any api information on options.

I've seen something about :include and :only in other sample controllers. I'm wondering what the full range of options are for more complex rendering of documents (specifically yaml, but I'd like to learn for all)

For example:

```<code> def index
    @people = Person.find(:all)

    respond_to do |format|
      format.*  ?????????????????????
    end
  end
</code>```

background: trying to assemble what is for me more complex yaml ouput and seeing what and how I can from the controller as opposed to having to build a specific view.

答:
A standard set of MIME types is supported:
:html, :xhtml, :text, :txt, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :url_encoded_form, :multipart_form, :json.

To create new ones, register them in the mime_types.rb initializer

```<code># Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
</code>```

I hope this helps.

Body:
I'm looking into rendering more complex responses.

Specifically, I am searching for options for formatting yaml and json responses with multiple levels, but right now I cannot locate any api information on options.

I've seen something about :include and :only in other sample controllers. I'm wondering what the full range of options are for more complex rendering of documents (specifically yaml, but I'd like to learn for all)

For example:

 def index
    @people = Person.find(:all)

    respond_to do |format|
      format.*  ?????????????????????
    end
  end

background: trying to assemble what is for me more complex yaml ouput and seeing what and how I can from the controller as opposed to having to build a specific view.

Body:
A standard set of MIME types is supported:
:html, :xhtml, :text, :txt, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :url_encoded_form, :multipart_form, :json.

To create new ones, register them in the mime_types.rb initializer

# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone

I hope this helps.


问:
Single Expression in the SELECT clause is supported with UDTF's
This is the below query I am using and every time I get the below semantic analysis error.

```<code>hive> select explode(test2.purchased_item.product_id) AS prodID,
explode(test2.purchased_item.timestamps) AS time from testingtable2 test2;

FAILED: Error in semantic analysis: Only a single expression in the SELECT clause
is supported with UDTF's
</code>```

Is there any restriction with the hive I cannot use two explode in a single select statement?

答:
Use LATERAL VIEW. I took this from the "Programming Hive"

Hive offers a LATERAL VIEW feature to allow this kind of query:

```<code>hive> SELECT name, sub
> FROM employees
> LATERAL VIEW explode(subordinates) subView AS sub;
</code>```

Body:
This is the below query I am using and every time I get the below semantic analysis error.

hive> select explode(test2.purchased_item.product_id) AS prodID,
explode(test2.purchased_item.timestamps) AS time from testingtable2 test2;

FAILED: Error in semantic analysis: Only a single expression in the SELECT clause
is supported with UDTF's

Is there any restriction with the hive I cannot use two explode in a single select statement?

Body:
Use LATERAL VIEW. I took this from the "Programming Hive"

Hive offers a LATERAL VIEW feature to allow this kind of query:

hive> SELECT name, sub
> FROM employees
> LATERAL VIEW explode(subordinates) subView AS sub;


问:
A Game of Hand Cricket - Javascript
I am trying to make a simple game, in the below function handCricketBat(), the if conditional statement is getting skipped even when the condition batsMan = bowlerMan is satisfied. It always moves on to the else statement. Can someone tell me why this is happening.</p>

```<code>function handCricketBat(){
        var total = 0;
        for (x = 1; x <=6; x++){
            var batsMan = prompt("Ball " + x + " \nEnter Between 1-6");
            var bowlerMan = randomBall();
            console.log("The bowler - "+ bowlerMan);
            if (batsMan === bowlerMan) {
                console.log("Howzattt");
                break;

            }
            else if (batsMan !== bowlerMan) {
                console.log("That's good batiing, scoring a " + batsMan);
                continue;

            }
            total += +batsMan;

        }
        console.log(total);
    }

    function randomBall(){
        return Math.floor(Math.random()*7);
    }
</code>```

答:
Your batsMan is a string.

Use var batsMan = parseInt(prompt("Ball " + x + " \nEnter Between 1-6")); instead and it should work.

Title: A Game of Hand Cricket - Javascript

Body:
I am trying to make a simple game, in the below function handCricketBat(), the if conditional statement is getting skipped even when the condition batsMan = bowlerMan is satisfied. It always moves on to the else statement. Can someone tell me why this is happening.

function handCricketBat(){
        var total = 0;
        for (x = 1; x <=6; x++){
            var batsMan = prompt("Ball " + x + " \nEnter Between 1-6");
            var bowlerMan = randomBall();
            console.log("The bowler - "+ bowlerMan);
            if (batsMan === bowlerMan) {
                console.log("Howzattt");
                break;

            }
            else if (batsMan !== bowlerMan) {
                console.log("That's good batiing, scoring a " + batsMan);
                continue;

            }
            total += +batsMan;

        }
        console.log(total);
    }

    function randomBall(){
        return Math.floor(Math.random()*7);
    }


问:
Persistence solutions for C++ (with a SQL database)?
I'm wondering what kind of persistence solutions are there for C++ with a SQL database? In addition to doing things with custom SQL (and encapsulating the data access to DAOs or something similar), are there some other (more general) solutions?

Like some general libraries or frameworks (something like Hibernate & co for Java and .NET) or something else? (Something that I haven't even thought of can also be welcome to be suggested)

EDIT: Yep, I was searching more for an ORM solution or something similar to handle sql queries and the relationships between tables and objects than for the db engine itself. Thanks for all the answers anyway!

答:
MySQL Connector/C++ is a C++ implementation of JDBC 4.0

The reference customers who use MySQL Connector/C++ are:
- OpenOffice - MySQL Workbench

Learn more: http://forums.mysql.com/read.php?167,221298

OwnerDisplayName: Touko

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Touko

OwnerDisplayName: MySQL Workbench


问:
What's the proper terminology for 32- vs 64- "bits"
I'm crystal clear on different architectures providing 32-bit or 64-bit registers and how that all works out at a low level.  However, one thing has always eluded me.. specific terminology for whether you're 32- or 64- bit.  For example:

```
string XXX;</p>

<p>if(architecture == i386)
  XXX = "32";
else if(architecture == x86_64)
  XXX = "64";</p>

<p>... go on to use variable XXX ...
</code>```

So, what would I name my variable?  Not architecture.  Not "bits".  Not "bus width" or "register width" (that would seem quite out of place I think)

So what would this variable be named and what would someone say in conversation?

答:
I thought of "pointer size", since the first relevant thing about 32-bit vs 64-bit is how much memory the application/OS can address.

But pretty much any such terminology is going to diverge from what you would say in conversation, since everybody mostly says "32-bit" and "64-bit" (and sometimes "x86" and "x64").

How about just architectureBitLength?

Body:
I'm crystal clear on different architectures providing 32-bit or 64-bit registers and how that all works out at a low level.  However, one thing has always eluded me.. specific terminology for whether you're 32- or 64- bit.  For example:

string XXX;

if(architecture == i386)
  XXX = "32";
else if(architecture == x86_64)
  XXX = "64";

... go on to use variable XXX ...

So, what would I name my variable?  Not architecture.  Not "bits".  Not "bus width" or "register width" (that would seem quite out of place I think)

So what would this variable be named and what would someone say in conversation?


问:
Add turf.js script tag
I am trying to add turf.js script tag to my asp.net MVC view but the @ symbol in the url is causing the view to fail. Does anyone know how to fix this?

Here is script tag:

I receive a compilation error because of the /@turf/ section in the URL.

Line 22: https://npmcdn.com/@turf/turf/turf.min.js'>

答:
Add two @ symbols to solve your problem:</p>

```<code><script src='https://unpkg.com/@@turf/turf/turf.min.js'></script>
</code>```

Title: Add turf.js script tag

Body:
Add two @ symbols to solve your problem:

<script src='https://unpkg.com/@@turf/turf/turf.min.js'></script>


问:
Card drop-down on react native
Is it possible to achieve a component drop on react native?

Something like this. Sorry for the paint skills. Thank you in advance .

答:
You can create a custom component like below, You can change the render label to support the view you want.

This sample needs the data to be like the below object but you can create your own object.

```<code>const dataArray = [{value: 'Car', id: 1,},{value: 'Van',id: 2},{ value: 'Bus',id: 3}];

   //Usage
    <CustomDropDown data={dataArray} />

const CustomDropDown = (props) => {
  const [open, setOpen] = React.useState(false);
  const [selected, setSelected] = React.useState(-1);

  const renderLabel = (item) => {
    return (
      <View
        style={{
          width: 200,
          height: 60,
          borderWidth: 1,
          borderRadius: 10,
          padding: 5,
          marginVertical: 3,
        }}>
        <Text style={{ fontSize: 20 }}>{item.value}</Text>
        <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
          <Text>{item.value}</Text>
          <Text style={{ fontSize: 15 }}>{item.value}</Text>
        </View>
      </View>
    );
  };

  const renderItem = (item) => {
    return (
      <TouchableOpacity
        onPress={() => {
          setSelected(item.id);
          setOpen(!open);
          //Call back to external state
        }}>
        {renderLabel(item)}
      </TouchableOpacity>
    );
  };

  return (
    <View>
      <TouchableOpacity style={{}} onPress={() => setOpen(!open)}>
        {selected === -1 && <Text>Place holder text</Text>}
        {selected !== -1 &&
          renderLabel(props.data.find((x) => x.id === selected))}
      </TouchableOpacity>
      {open && (
        <View
          style={{
            position: 'absolute',
            top: 70,
          }}>
          {props.data.map((item) => renderItem(item))}
        </View>
      )}
    </View>
  );
};
</code>```

Title: Card drop-down on react native

Body:
You can create a custom component like below, You can change the render label to support the view you want.

This sample needs the data to be like the below object but you can create your own object.

const dataArray = [{value: 'Car', id: 1,},{value: 'Van',id: 2},{ value: 'Bus',id: 3}];

   //Usage
    <CustomDropDown data={dataArray} />

const CustomDropDown = (props) => {
  const [open, setOpen] = React.useState(false);
  const [selected, setSelected] = React.useState(-1);

  const renderLabel = (item) => {
    return (
      <View
        style={{
          width: 200,
          height: 60,
          borderWidth: 1,
          borderRadius: 10,
          padding: 5,
          marginVertical: 3,
        }}>
        <Text style={{ fontSize: 20 }}>{item.value}</Text>
        <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
          <Text>{item.value}</Text>
          <Text style={{ fontSize: 15 }}>{item.value}</Text>
        </View>
      </View>
    );
  };

  const renderItem = (item) => {
    return (
      <TouchableOpacity
        onPress={() => {
          setSelected(item.id);
          setOpen(!open);
          //Call back to external state
        }}>
        {renderLabel(item)}
      </TouchableOpacity>
    );
  };

  return (
    <View>
      <TouchableOpacity style={{}} onPress={() => setOpen(!open)}>
        {selected === -1 && <Text>Place holder text</Text>}
        {selected !== -1 &&
          renderLabel(props.data.find((x) => x.id === selected))}
      </TouchableOpacity>
      {open && (
        <View
          style={{
            position: 'absolute',
            top: 70,
          }}>
          {props.data.map((item) => renderItem(item))}
        </View>
      )}
    </View>
  );
};


问:
PHP variable in Javascript
Consider this simple example;

```<code><?php $text = test; ?>

<script type="text/javascript" defer="defer">

var test;

test = "<?php echo $text; ?>"

$(document).ready(function(){
alert(test);
});

</script>
</code>```

This works fine. Creating the alert with the text from the php var. However, if I place;

```<code><?php $text = test; ?>
</code>```

below the script - it does not work. I've tried the defer function. What am I doing wrong?

Cheers

答: There are two computers involved, the web server (which processes php) and the user's browser (which processes javascript).  So no, you cannot transfer a javascript variable back to php without sending the value of that variable from the user's browser to the web server (normally done by posting a form or ajax).</p>

Title: PHP variable in Javascript

Body:
Consider this simple example;

<?php $text = test; ?>

This works fine. Creating the alert with the text from the php var. However, if I place;

<?php $text = test; ?>

below the script - it does not work. I've tried the defer function. What am I doing wrong?

Cheers


问:
How to count the strings in a vector?
I have a data set as I've shown below:

```<code>df_A <- tribble(
      ~shop_name,      ~id,
        "A",         "1, 4, 3",
        "B",         "4, 6",
        "C",         "3, 5",
        "D",         "6, 2, 3",
)
</code>```

Now, I want to group the data by each unique id which in the vector, and then count them accordingly. Do you think it is doable? How can I manipulate the data to get my desired data?

```<code>desired <- tribble(
  ~id,   ~counted_id,
  "1",      1,
  "2",      1,
  "3",      3,
  "4",      2,
  "5",      1,
  "6",      2,
)
</code>```

答:
Minimalist tidyverse solution:

```<code>library(tidyverse)
df_A %>%
  separate_rows(id) %>%
  count(id, name = "counted_id")

# A tibble: 6 x 2
  id    counted_id
  <chr>      <int>
1 1              1
2 2              1
3 3              3
4 4              2
5 5              1
6 6              2
</code>```

Title: How to count the strings in a vector?

Body:
I have a data set as I've shown below:

df_A <- tribble(
      ~shop_name,      ~id,
        "A",         "1, 4, 3",
        "B",         "4, 6",
        "C",         "3, 5",
        "D",         "6, 2, 3",
)

Now, I want to group the data by each unique id which in the vector, and then count them accordingly. Do you think it is doable? How can I manipulate the data to get my desired data?

desired <- tribble(
  ~id,   ~counted_id,
  "1",      1,
  "2",      1,
  "3",      3,
  "4",      2,
  "5",      1,
  "6",      2,
)

Body:
Minimalist tidyverse solution:

library(tidyverse)
df_A %>%
  separate_rows(id) %>%
  count(id, name = "counted_id")

# A tibble: 6 x 2
  id    counted_id
  <chr>      <int>
1 1              1
2 2              1
3 3              3
4 4              2
5 5              1
6 6              2


问:
How to convert wordpress page to regular html page?
I am trying to make a one page landing page. I want the website to be html based and not wordpress based to make managing it easier. There is a wordpress theme that I really like. Can I do this: 1) install the theme in wordpress 2) view page source 3) copy all code 4) open notepad++ and paste all code 5) save as .html 6) upload html page to the same domain </p>

<p>would this result in a functional website? do you foresee any problems? </p>

答:
I found Your post cause same as You I'm total newb to web page building and developing. In the past I've used wordpress theme's to "build and put online" few simple website's - but decided to learn more to be able to create something by myself and have better control of it.

Same as You I thought about using bits of wordpress theme I really like and convert it to html5 - but unfortunately it's not as easy as you described it above.

The way I understand it (someone correct me if I'm wrong please) the main difference is wordpress themes are "dynamic" and html is static kind of web site , and wordpress themes involve different technology (php not html etc) so simply changing changing *.php to *.html will not work:)

there are few ways of doing it though, please find some resources below:

Using HTTrack to convert WordPress to a static website

Tools to Migrate from WordPress to HTML

hope it helps!

Body:
I am trying to make a one page landing page. I want the website to be html based and not wordpress based to make managing it easier. There is a wordpress theme that I really like. Can I do this: 1) install the theme in wordpress 2) view page source 3) copy all code 4) open notepad++ and paste all code 5) save as .html 6) upload html page to the same domain

would this result in a functional website? do you foresee any problems?


问:
Generate all possible correct sentences from a set of words
I have a set of 276 different words, I want to generate all possible correct sentences from them. It can be composed of two words only or more.

I used NLTK tagger to give every word a class. For instance, ('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN') but this technique has drowbacks when the words are independent from each other (An array of 276 words in my case).

If anyone has an idea of how I could do it, it would really help me. Thanks!

答:
You would need a grammar to describe valid combinations of word classes or words. For example:

```<code>S -> NP VP
NP -> det adj* noun
VP -> verb NP
VP -> verb NP conj NP
</code>```

and so on. This is a fairly old and simple mechanism, but should be easy enough to implement. You simply generate expansions of the rules until you hit word class categories, and then substitute the respective words for them. The meaning is, of course, a different issue, as your sentences will be grammatically correct, but semantically weird.

Body:
You would need a grammar to describe valid combinations of word classes or words. For example:

S -> NP VP
NP -> det adj* noun
VP -> verb NP
VP -> verb NP conj NP

and so on. This is a fairly old and simple mechanism, but should be easy enough to implement. You simply generate expansions of the rules until you hit word class categories, and then substitute the respective words for them. The meaning is, of course, a different issue, as your sentences will be grammatically correct, but semantically weird.


问:
How to use Linq to Xml to get tree data with recursive querying?
I have following kind of xml data from restful service:

```<code><nodeData>
  <nodeObject>
    <nodeName>Node 1</nodeName>
    <nodeChildren>
      <nodeObject>
        <nodeName>Node 1-1</nodeName>
        <nodeChildren>
          <nodeObject>
            <nodeName>Leaf 1-1-1</nodeName>
          </nodeObject>
          <nodeObject>
            <nodeName>Leaf 1-1-2</nodeName>
          </nodeObject>
          <nodeObject>
            <nodeName>Leaf 1-1-3</nodeName>
          </nodeObject>
          <nodeObject>
            <nodeName>schedule 4.pdf</nodeName>
          </nodeObject>
        </nodeChildren>
      </nodeObject>
      <nodeObject>
        <nodeName>Node 1-2</nodeName>
        <nodeChildren>
          <nodeObject>
            <nodeName>Leaf 1-2-1</nodeName>
          </nodeObject>
        </nodeChildren>
      </nodeObject>
    </nodeChildren>
  </nodeObject>
  <nodeObject>
    <nodeName>Node 2</nodeName>
    <nodeChildren>
      <nodeObject>
        <nodeName>Node 2-1</nodeName>
        <nodeChildren>
          <nodeObject>
            <nodeName>Leaf 2-1-1</nodeName>
          </nodeObject>
        </nodeChildren>
      </nodeObject>
    </nodeChildren>
  </nodeObject>
......
</nodeData>
</code>```

So I want to get the tree data to fill a treeview in sliverlight. What I did as below:

Create a internal class:

```<code>public class nodeObject
    {
        public string nodeName { get; set; }
        public IEnumerable<nodeObject> nodeChildren { get; set; }
    }
</code>```

Write Linq as:

```<code>void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                XDocument xml = XDocument.Parse(e.Result);
                var dataSource = (from results in xml.Descendants("nodeObject")
                                  select new nodeObject
                                  {
                                    nodeName = results.Element("nodeName").Value.ToString(),
                                    nodeChildren = this.GetChilden(results)
                                  });

                this.dataTree.ItemsSource = dataSource.ToList();
            }
        }

        private IEnumerable<nodeObject> GetChilden(XElement parent)
        {
            return (from results in parent.Descendants("nodeObject")
                    select new nodeObject
                    {
                        nodeName = results.Element("nodeName").Value.ToString(),
                    }).ToList<nodeObject>();
        }
</code>```

then run the silverlight app.  the data display in the treevew as(only 2 levels with many duplication):

```<code>Node 1
  Node 1-1
  Leaf 1-1-1
  Leaf 1-1-2
  Leaf 1-1-3
  Node 1-2
  Leaf 2-1-1
Node 1-1
  Leaf 1-1-1
  Leaf 1-1-2
  Leaf 1-1-3
  Node 1-2
  Leaf 2-1-1
Node 1-2
  Leaf 2-1-1
Node 2
  Node 2-1
  Leaf 2-1-1
Node 2-1
  Leaf 2-1-1
</code>```

But the expected display should be like (without leaf):

```<code>Node 1
  Node 1-1
  Node 1-2
Node 2
  Node 2-1
</code>```

Or like (include leaf):

```<code>Node 1
  Node 1-1
    Leaf 1-1-1
    Leaf 1-1-2
    Leaf 1-1-3
  Node 1-2
    Leaf 2-1-1
Node 2
  Node 2-1
    Leaf 2-1-1
</code>```

How to resolve this problem?

答: Figured it out: it is because of binding issue in xaml. Linq query is fine. </p>

Body:
I have following kind of xml data from restful service:

<nodeData>
  <nodeObject>
    <nodeName>Node 1</nodeName>
    <nodeChildren>
      <nodeObject>
        <nodeName>Node 1-1</nodeName>
        <nodeChildren>
          <nodeObject>
            <nodeName>Leaf 1-1-1</nodeName>
          </nodeObject>
          <nodeObject>
            <nodeName>Leaf 1-1-2</nodeName>
          </nodeObject>
          <nodeObject>
            <nodeName>Leaf 1-1-3</nodeName>
          </nodeObject>
          <nodeObject>
            <nodeName>schedule 4.pdf</nodeName>
          </nodeObject>
        </nodeChildren>
      </nodeObject>
      <nodeObject>
        <nodeName>Node 1-2</nodeName>
        <nodeChildren>
          <nodeObject>
            <nodeName>Leaf 1-2-1</nodeName>
          </nodeObject>
        </nodeChildren>
      </nodeObject>
    </nodeChildren>
  </nodeObject>
  <nodeObject>
    <nodeName>Node 2</nodeName>
    <nodeChildren>
      <nodeObject>
        <nodeName>Node 2-1</nodeName>
        <nodeChildren>
          <nodeObject>
            <nodeName>Leaf 2-1-1</nodeName>
          </nodeObject>
        </nodeChildren>
      </nodeObject>
    </nodeChildren>
  </nodeObject>
......
</nodeData>

So I want to get the tree data to fill a treeview in sliverlight. What I did as below:

Create a internal class:

public class nodeObject
    {
        public string nodeName { get; set; }
        public IEnumerable<nodeObject> nodeChildren { get; set; }
    }

Write Linq as:

void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                XDocument xml = XDocument.Parse(e.Result);
                var dataSource = (from results in xml.Descendants("nodeObject")
                                  select new nodeObject
                                  {
                                    nodeName = results.Element("nodeName").Value.ToString(),
                                    nodeChildren = this.GetChilden(results)
                                  });

                this.dataTree.ItemsSource = dataSource.ToList();
            }
        }

        private IEnumerable<nodeObject> GetChilden(XElement parent)
        {
            return (from results in parent.Descendants("nodeObject")
                    select new nodeObject
                    {
                        nodeName = results.Element("nodeName").Value.ToString(),
                    }).ToList<nodeObject>();
        }

then run the silverlight app.  the data display in the treevew as(only 2 levels with many duplication):

Node 1
  Node 1-1
  Leaf 1-1-1
  Leaf 1-1-2
  Leaf 1-1-3
  Node 1-2
  Leaf 2-1-1
Node 1-1
  Leaf 1-1-1
  Leaf 1-1-2
  Leaf 1-1-3
  Node 1-2
  Leaf 2-1-1
Node 1-2
  Leaf 2-1-1
Node 2
  Node 2-1
  Leaf 2-1-1
Node 2-1
  Leaf 2-1-1

But the expected display should be like (without leaf):

Node 1
  Node 1-1
  Node 1-2
Node 2
  Node 2-1

Or like (include leaf):

Node 1
  Node 1-1
    Leaf 1-1-1
    Leaf 1-1-2
    Leaf 1-1-3
  Node 1-2
    Leaf 2-1-1
Node 2
  Node 2-1
    Leaf 2-1-1

How to resolve this problem?


问:
Getting wrong data when extracting details from contact in Android
I am trying to get the details from a selected contact and feed it back to my Fragment in an Observable. I get some data but it's not correct, for example i get just a "1" or a "3" as given name and date of birth as url/website. And some data isn't retrieved at all, such as anything post address related (street, postcode, city etc.)

Where have I gone wrong?

```<code>public Observable<Contact> getContact(ContentResolver contentResolver, Uri uri) {
        return Observable.create(emitter -> {
            Cursor contactCursor = null;
            Cursor detailedCursor = null;
            String firstName = "",
                    lastName  = "",
                    organization = "",
                    email = "",
                    phone = "",
                    cell = "",
                    street = "",
                    postcode = "",
                    city = "",
                    region = "",
                    country = "",
                    url = "";
            try {
                contactCursor = contentResolver.query(
                        uri,
                        new String[] { ContactsContract.Data.LOOKUP_KEY },
                        null,
                        null,
                        null);
                if (contactCursor != null && contactCursor.getCount() > 0 && contactCursor.moveToNext()) {
                    String lookupKey = contactCursor.getString(contactCursor.getColumnIndex(
                            ContactsContract.Data.LOOKUP_KEY));
                    final String[] projection =
                            {
                                    StructuredName.GIVEN_NAME,
                                    StructuredName.FAMILY_NAME,
                                    Organization.COMPANY,
                                    Email.ADDRESS,
                                    Phone.NUMBER,
                                    StructuredPostal.STREET,
                                    StructuredPostal.POSTCODE,
                                    StructuredPostal.CITY,
                                    StructuredPostal.REGION,
                                    StructuredPostal.COUNTRY,
                                    Website.URL
                            };
                    String selection = ContactsContract.Data.LOOKUP_KEY + " = ?";
                    String sortOrder = ContactsContract.Data.MIMETYPE;
                    detailedCursor = contentResolver.query(
                            ContactsContract.Data.CONTENT_URI,
                            projection,
                            selection,
                            new String[] { lookupKey },
                            sortOrder);
                    if(detailedCursor != null && detailedCursor.getCount() > 0 && detailedCursor.moveToNext()) {
                        Log.d(TAG, "detailedCursor Columns: " + Arrays.toString(detailedCursor.getColumnNames()));

                        firstName = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredName.GIVEN_NAME));
                        lastName = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredName.FAMILY_NAME));
                        organization = detailedCursor.getString(detailedCursor.getColumnIndex(
                                Organization.COMPANY));
                        email = detailedCursor.getString(detailedCursor.getColumnIndex(
                                Email.ADDRESS));
                        street = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredPostal.STREET));
                        postcode = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredPostal.POSTCODE));
                        city = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredPostal.CITY));
                        region = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredPostal.REGION));
                        country = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredPostal.COUNTRY));
                        url = detailedCursor.getString(detailedCursor.getColumnIndex(
                                Website.URL));
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Couldn't retrieve columns", e);
            } finally {
                if (contactCursor != null) {
                    contactCursor.close();
                }
                if (detailedCursor != null) {
                    detailedCursor.close();
                }
                emitter.onNext(new Contact(firstName, lastName, organization, email, phone,
                        cell, street, postcode, city, region, country, url));
                emitter.onComplete();
            }
        });
    }
</code>```

答:
Each row of the ContactsContract.Data contains a MIMETYPE which means what "type" of data does this entire row contains, so if the Data.MIMETYPE = Phone.CONTENT_ITEM_TYPE that means the entire row stores a single phone number.

You're trying to extract StructuredName, Organization, Email, StructuredPostal, etc. from a single row, which explains the junk you're getting back.

See here for code example on how to use the MIMETYPE value to extract contact information from a cursor running on ContactsContract.Data:
https://stackoverflow.com/a/46594049/819355

Body:
I am trying to get the details from a selected contact and feed it back to my Fragment in an Observable. I get some data but it's not correct, for example i get just a "1" or a "3" as given name and date of birth as url/website. And some data isn't retrieved at all, such as anything post address related (street, postcode, city etc.)

Where have I gone wrong?

public Observable<Contact> getContact(ContentResolver contentResolver, Uri uri) {
        return Observable.create(emitter -> {
            Cursor contactCursor = null;
            Cursor detailedCursor = null;
            String firstName = "",
                    lastName  = "",
                    organization = "",
                    email = "",
                    phone = "",
                    cell = "",
                    street = "",
                    postcode = "",
                    city = "",
                    region = "",
                    country = "",
                    url = "";
            try {
                contactCursor = contentResolver.query(
                        uri,
                        new String[] { ContactsContract.Data.LOOKUP_KEY },
                        null,
                        null,
                        null);
                if (contactCursor != null && contactCursor.getCount() > 0 && contactCursor.moveToNext()) {
                    String lookupKey = contactCursor.getString(contactCursor.getColumnIndex(
                            ContactsContract.Data.LOOKUP_KEY));
                    final String[] projection =
                            {
                                    StructuredName.GIVEN_NAME,
                                    StructuredName.FAMILY_NAME,
                                    Organization.COMPANY,
                                    Email.ADDRESS,
                                    Phone.NUMBER,
                                    StructuredPostal.STREET,
                                    StructuredPostal.POSTCODE,
                                    StructuredPostal.CITY,
                                    StructuredPostal.REGION,
                                    StructuredPostal.COUNTRY,
                                    Website.URL
                            };
                    String selection = ContactsContract.Data.LOOKUP_KEY + " = ?";
                    String sortOrder = ContactsContract.Data.MIMETYPE;
                    detailedCursor = contentResolver.query(
                            ContactsContract.Data.CONTENT_URI,
                            projection,
                            selection,
                            new String[] { lookupKey },
                            sortOrder);
                    if(detailedCursor != null && detailedCursor.getCount() > 0 && detailedCursor.moveToNext()) {
                        Log.d(TAG, "detailedCursor Columns: " + Arrays.toString(detailedCursor.getColumnNames()));

                        firstName = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredName.GIVEN_NAME));
                        lastName = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredName.FAMILY_NAME));
                        organization = detailedCursor.getString(detailedCursor.getColumnIndex(
                                Organization.COMPANY));
                        email = detailedCursor.getString(detailedCursor.getColumnIndex(
                                Email.ADDRESS));
                        street = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredPostal.STREET));
                        postcode = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredPostal.POSTCODE));
                        city = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredPostal.CITY));
                        region = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredPostal.REGION));
                        country = detailedCursor.getString(detailedCursor.getColumnIndex(
                                StructuredPostal.COUNTRY));
                        url = detailedCursor.getString(detailedCursor.getColumnIndex(
                                Website.URL));
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Couldn't retrieve columns", e);
            } finally {
                if (contactCursor != null) {
                    contactCursor.close();
                }
                if (detailedCursor != null) {
                    detailedCursor.close();
                }
                emitter.onNext(new Contact(firstName, lastName, organization, email, phone,
                        cell, street, postcode, city, region, country, url));
                emitter.onComplete();
            }
        });
    }