问:
Blazor problem rendering data returned from Web Api
I'm hoping someone can suggest how I might figure out where this underlying problem is. I think it's serialization/deserialization not the grid.

I am trying to render data returned from an ASP.NET Web Api using a Syncfusion Blazor Grid Component. The JliffDocument is from an open source library. Perhaps the fact that the object is made from composite types is a contributory factor but I can successfully serialize and deserialize the object graph within a unit test. E.g. TextElement implements an interface and Segment stores collections of that interface.

This Works (but the jlfDoc is locally created data)

<EjsGrid id="Grid" DataSource="@jlfDoc.Segments" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" AllowPaging="true">
    <GridPageSettings PageSize="5"></GridPageSettings>
    <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"></GridEditSettings>
    <GridColumns>
        <GridColumn Field="SourceText" HeaderText="Source"  IsPrimaryKey="true" TextAlign="@Syncfusion.EJ2.RazorComponents.Grids.TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field="TargetText" HeaderText="Target" Width="150"></GridColumn>
    </GridColumns>
</EjsGrid>

@rawContent

There are @segments Segments

@oneTextString

@functions {
    public object gridData { get; set; }
    public JliffDocument jlfDoc { get; set; }
    public string rawContent { get; set; }
    public int segments { get; set; }
    public string oneTextString { get; set; }
    protected override async Task OnInitAsync()
    {
        jlfDoc = new JliffDocument("en-US",
            "it-IT",
            new File("f1",
                new Unit("u1",
                    new Segment(
                        new TextElement("Hello"),
                        new TextElement("Ciao")),
                    new Segment(
                        new TextElement("Goodnight"),
                        new TextElement("Buonanotte")))));
    }
}
```

<p><strong>This also partially-works</strong> (The <code>rawContent</code>, <code>segments</code> and <code>oneTextString</code> variables <strong>DO</strong> render if the line <code>jlfDoc = jd;</code> is commented out and <code>DataSource="@jlfDoc.Segments"</code> is removed which suggests that the Api call and de-serialization of jd is successful.</p>

<pre class="lang-cs prettyprint-override"><code><EjsGrid id="Grid" DataSource="@gridData" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" AllowPaging="true">
    <GridPageSettings PageSize="5"></GridPageSettings>
    <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"></GridEditSettings>
    <GridColumns>
        <GridColumn Field="SourceText" HeaderText="Source"  IsPrimaryKey="true" TextAlign="@Syncfusion.EJ2.RazorComponents.Grids.TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field="TargetText" HeaderText="Target" Width="150"></GridColumn>
    </GridColumns>
</EjsGrid>

<hr/>
<p>@rawContent</p>

<h1>There are @segments Segments</h1>

<i>@oneTextString</i>

@functions {
    public object gridData { get; set; }
    public JliffDocument jlfDoc { get; set; }
    public string rawContent { get; set; }
    public int segments { get; set; }
    public string oneTextString { get; set; }
    protected override async Task OnInitAsync()
    {
        string serverDoc = String.Empty;

        using (HttpClient client = new HttpClient())
        {
            serverDoc = await client.GetStringAsync("https://localhost:44381/api/document");
        }

        rawContent = serverDoc;

        JliffDocument jd;
        JSON.MakeInto(JSON.Load(serverDoc), out jd);
        segments = jd.Segments.Count;
        oneTextString = jd.Segments[0].TargetText;
        //jlfDoc = jd;
    }
}
</code>```

This two line change fails

====> DataSource reinstated |
                            |
<EjsGrid id="Grid" DataSource="@jlfDoc.Segments" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" AllowPaging="true">
    <GridPageSettings PageSize="5"></GridPageSettings>
    <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"></GridEditSettings>
    <GridColumns>
        <GridColumn Field="SourceText" HeaderText="Source"  IsPrimaryKey="true" TextAlign="@Syncfusion.EJ2.RazorComponents.Grids.TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field="TargetText" HeaderText="Target" Width="150"></GridColumn>
    </GridColumns>
</EjsGrid>

@rawContent

There are @segments Segments

@oneTextString

@functions {
    public object gridData { get; set; }
    public JliffDocument jlfDoc { get; set; }
    public string rawContent { get; set; }
    public int segments { get; set; }
    public string oneTextString { get; set; }
    protected override async Task OnInitAsync()
    {
        string serverDoc = String.Empty;

        using (HttpClient client = new HttpClient())
        {
            serverDoc = await client.GetStringAsync("https://localhost:44381/api/document");
        }

        rawContent = serverDoc;

        JliffDocument jd;
        JSON.MakeInto(JSON.Load(serverDoc), out jd);
        segments = jd.Segments.Count;
        oneTextString = jd.Segments[0].TargetText;
        jlfDoc = jd;                                  <==== UNCOMMENTED
    }
}
```

<p>The error in browser tools console is:</p>

```WASM: Unhandled exception rendering component:
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: System.NullReferenceException: Object reference not set to an instance of an object.
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Blazorgrid.Pages.Index.BuildRenderTree (Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder builder) [0x00035] in <1cc78bbb60324b879905902bf1175ac2>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__5_0 (Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder builder) <0x20a7d38 + 0x00020> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at (wrapper delegate-invoke) <Module>.invoke_void_RenderTreeBuilder(Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder)
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch (Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, Microsoft.AspNetCore.Components.RenderFragment renderFragment) <0x20a7190 + 0x00092> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.Renderer.RenderInExistingBatch (Microsoft.AspNetCore.Components.Rendering.RenderQueueEntry renderQueueEntry) <0x20a6e48 + 0x00036> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue () <0x20a3eb8 + 0x00056> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Unhandled exception rendering component:
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Microsoft.JSInterop.JSException: No element is currently associated with component 6
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Error: No element is currently associated with component 6
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at e.updateComponent (http://localhost:53239/_framework/blazor.webassembly.js:1:13495)
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at Object.t.renderBatch (http://localhost:53239/_framework/blazor.webassembly.js:1:1686)
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at window.Blazor._internal.renderBatch (http://localhost:53239/_framework/blazor.webassembly.js:1:30422)
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at _mono_wasm_invoke_js_unmarshalled (http://localhost:53239/_framework/wasm/mono.js:1:170240)
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[3762]:35
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[3770]:572
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[3771]:211
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[2977]:241
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[601]:22615
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[601]:21413
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Mono.WebAssembly.Interop.MonoWebAssemblyJSRuntime.InvokeUnmarshalled[T0,T1,T2,TRes] (System.String identifier, T0 arg0, T1 arg1, T2 arg2) <0x236bc00 + 0x00044> in <0544639430f948ad82c54a3effb7ea00>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Mono.WebAssembly.Interop.MonoWebAssemblyJSRuntime.InvokeUnmarshalled[T0,T1,TRes] (System.String identifier, T0 arg0, T1 arg1) <0x236bb28 + 0x00016> in <0544639430f948ad82c54a3effb7ea00>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Blazor.Rendering.WebAssemblyRenderer.UpdateDisplayAsync (Microsoft.AspNetCore.Components.Rendering.RenderBatch& batch) <0x236ba30 + 0x0001e> in <91b564433c704544acd7894656c3aff9>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue () <0x20a3eb8 + 0x000be> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Unhandled exception rendering component:
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: System.NullReferenceException: Object reference not set to an instance of an object.
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame..ctor (System.Int32 sequence, System.Type componentType, System.Int32 subtreeLength, Microsoft.AspNetCore.Components.Rendering.ComponentState componentState) <0x21001d8 + 0x0001c> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame.WithComponent (Microsoft.AspNetCore.Components.Rendering.ComponentState componentState) <0x2100178 + 0x0001c> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.UpdateRetainedChildComponent (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldComponentIndex, System.Int32 newComponentIndex) <0x24c9160 + 0x0004c> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldFrameIndex, System.Int32 newFrameIndex) <0x24b9610 + 0x00368> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldStartIndex, System.Int32 oldEndIndexExcl, System.Int32 newStartIndex, System.Int32 newEndIndexExcl) <0x20a9950 + 0x000ae> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff (Microsoft.AspNetCore.Components.Rendering.Renderer renderer, Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, System.Int32 componentId, Microsoft.AspNetCore.Components.RenderTree.ArrayRange`1[T] oldTree, Microsoft.AspNetCore.Components.RenderTree.ArrayRange`1[T] newTree) <0x20a9558 + 0x0009e> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch (Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, Microsoft.AspNetCore.Components.RenderFragment renderFragment) <0x20a7190 + 0x0013a> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.Renderer.RenderInExistingBatch (Microsoft.AspNetCore.Components.Rendering.RenderQueueEntry renderQueueEntry) <0x20a6e48 + 0x00036> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue () <0x20a3eb8 + 0x00056> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
```

答: We suspect that you are trying to use a reference of an object that is not initialized (“jlfDoc” might be null). So we suggest you to add condition to check whether the object is null before accessing its property  to resolve this issue as mentioned by @HenkHolterman in comment section.</p>

Body:
I'm hoping someone can suggest how I might figure out where this underlying problem is. I think it's serialization/deserialization not the grid.

I am trying to render data returned from an ASP.NET Web Api using a Syncfusion Blazor Grid Component. The JliffDocument is from an open source library. Perhaps the fact that the object is made from composite types is a contributory factor but I can successfully serialize and deserialize the object graph within a unit test. E.g. TextElement implements an interface and Segment stores collections of that interface.

This Works (but the jlfDoc is locally created data)

<EjsGrid id="Grid" DataSource="@jlfDoc.Segments" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" AllowPaging="true">
    <GridPageSettings PageSize="5"></GridPageSettings>
    <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"></GridEditSettings>
    <GridColumns>
        <GridColumn Field="SourceText" HeaderText="Source"  IsPrimaryKey="true" TextAlign="@Syncfusion.EJ2.RazorComponents.Grids.TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field="TargetText" HeaderText="Target" Width="150"></GridColumn>
    </GridColumns>
</EjsGrid>

@rawContent

There are @segments Segments

@oneTextString

@functions {
    public object gridData { get; set; }
    public JliffDocument jlfDoc { get; set; }
    public string rawContent { get; set; }
    public int segments { get; set; }
    public string oneTextString { get; set; }
    protected override async Task OnInitAsync()
    {
        jlfDoc = new JliffDocument("en-US",
            "it-IT",
            new File("f1",
                new Unit("u1",
                    new Segment(
                        new TextElement("Hello"),
                        new TextElement("Ciao")),
                    new Segment(
                        new TextElement("Goodnight"),
                        new TextElement("Buonanotte")))));
    }
}

This also partially-works (The rawContent, segments and oneTextString variables DO render if the line jlfDoc = jd; is commented out and DataSource="@jlfDoc.Segments" is removed which suggests that the Api call and de-serialization of jd is successful.

<EjsGrid id="Grid" DataSource="@gridData" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" AllowPaging="true">
    <GridPageSettings PageSize="5"></GridPageSettings>
    <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"></GridEditSettings>
    <GridColumns>
        <GridColumn Field="SourceText" HeaderText="Source"  IsPrimaryKey="true" TextAlign="@Syncfusion.EJ2.RazorComponents.Grids.TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field="TargetText" HeaderText="Target" Width="150"></GridColumn>
    </GridColumns>
</EjsGrid>

@rawContent

There are @segments Segments

@oneTextString

@functions {
    public object gridData { get; set; }
    public JliffDocument jlfDoc { get; set; }
    public string rawContent { get; set; }
    public int segments { get; set; }
    public string oneTextString { get; set; }
    protected override async Task OnInitAsync()
    {
        string serverDoc = String.Empty;

        using (HttpClient client = new HttpClient())
        {
            serverDoc = await client.GetStringAsync("https://localhost:44381/api/document");
        }

        rawContent = serverDoc;

        JliffDocument jd;
        JSON.MakeInto(JSON.Load(serverDoc), out jd);
        segments = jd.Segments.Count;
        oneTextString = jd.Segments[0].TargetText;
        //jlfDoc = jd;
    }
}

This two line change fails

====> DataSource reinstated |
                            |
<EjsGrid id="Grid" DataSource="@jlfDoc.Segments" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" AllowPaging="true">
    <GridPageSettings PageSize="5"></GridPageSettings>
    <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"></GridEditSettings>
    <GridColumns>
        <GridColumn Field="SourceText" HeaderText="Source"  IsPrimaryKey="true" TextAlign="@Syncfusion.EJ2.RazorComponents.Grids.TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field="TargetText" HeaderText="Target" Width="150"></GridColumn>
    </GridColumns>
</EjsGrid>

@rawContent

There are @segments Segments

@oneTextString

@functions {
    public object gridData { get; set; }
    public JliffDocument jlfDoc { get; set; }
    public string rawContent { get; set; }
    public int segments { get; set; }
    public string oneTextString { get; set; }
    protected override async Task OnInitAsync()
    {
        string serverDoc = String.Empty;

        using (HttpClient client = new HttpClient())
        {
            serverDoc = await client.GetStringAsync("https://localhost:44381/api/document");
        }

        rawContent = serverDoc;

        JliffDocument jd;
        JSON.MakeInto(JSON.Load(serverDoc), out jd);
        segments = jd.Segments.Count;
        oneTextString = jd.Segments[0].TargetText;
        jlfDoc = jd;                                  <==== UNCOMMENTED
    }
}

The error in browser tools console is:

WASM: Unhandled exception rendering component:
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: System.NullReferenceException: Object reference not set to an instance of an object.
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Blazorgrid.Pages.Index.BuildRenderTree (Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder builder) [0x00035] in <1cc78bbb60324b879905902bf1175ac2>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__5_0 (Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder builder) <0x20a7d38 + 0x00020> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at (wrapper delegate-invoke) <Module>.invoke_void_RenderTreeBuilder(Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder)
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch (Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, Microsoft.AspNetCore.Components.RenderFragment renderFragment) <0x20a7190 + 0x00092> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.Renderer.RenderInExistingBatch (Microsoft.AspNetCore.Components.Rendering.RenderQueueEntry renderQueueEntry) <0x20a6e48 + 0x00036> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue () <0x20a3eb8 + 0x00056> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Unhandled exception rendering component:
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Microsoft.JSInterop.JSException: No element is currently associated with component 6
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Error: No element is currently associated with component 6
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at e.updateComponent (http://localhost:53239/_framework/blazor.webassembly.js:1:13495)
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at Object.t.renderBatch (http://localhost:53239/_framework/blazor.webassembly.js:1:1686)
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at window.Blazor._internal.renderBatch (http://localhost:53239/_framework/blazor.webassembly.js:1:30422)
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at _mono_wasm_invoke_js_unmarshalled (http://localhost:53239/_framework/wasm/mono.js:1:170240)
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[3762]:35
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[3770]:572
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[3771]:211
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[2977]:241
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[601]:22615
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:     at wasm-function[601]:21413
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Mono.WebAssembly.Interop.MonoWebAssemblyJSRuntime.InvokeUnmarshalled[T0,T1,T2,TRes] (System.String identifier, T0 arg0, T1 arg1, T2 arg2) <0x236bc00 + 0x00044> in <0544639430f948ad82c54a3effb7ea00>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Mono.WebAssembly.Interop.MonoWebAssemblyJSRuntime.InvokeUnmarshalled[T0,T1,TRes] (System.String identifier, T0 arg0, T1 arg1) <0x236bb28 + 0x00016> in <0544639430f948ad82c54a3effb7ea00>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Blazor.Rendering.WebAssemblyRenderer.UpdateDisplayAsync (Microsoft.AspNetCore.Components.Rendering.RenderBatch& batch) <0x236ba30 + 0x0001e> in <91b564433c704544acd7894656c3aff9>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue () <0x20a3eb8 + 0x000be> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Unhandled exception rendering component:
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: System.NullReferenceException: Object reference not set to an instance of an object.
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame..ctor (System.Int32 sequence, System.Type componentType, System.Int32 subtreeLength, Microsoft.AspNetCore.Components.Rendering.ComponentState componentState) <0x21001d8 + 0x0001c> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame.WithComponent (Microsoft.AspNetCore.Components.Rendering.ComponentState componentState) <0x2100178 + 0x0001c> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.UpdateRetainedChildComponent (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldComponentIndex, System.Int32 newComponentIndex) <0x24c9160 + 0x0004c> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldFrameIndex, System.Int32 newFrameIndex) <0x24b9610 + 0x00368> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldStartIndex, System.Int32 oldEndIndexExcl, System.Int32 newStartIndex, System.Int32 newEndIndexExcl) <0x20a9950 + 0x000ae> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff (Microsoft.AspNetCore.Components.Rendering.Renderer renderer, Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, System.Int32 componentId, Microsoft.AspNetCore.Components.RenderTree.ArrayRange`1[T] oldTree, Microsoft.AspNetCore.Components.RenderTree.ArrayRange`1[T] newTree) <0x20a9558 + 0x0009e> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch (Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, Microsoft.AspNetCore.Components.RenderFragment renderFragment) <0x20a7190 + 0x0013a> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.Renderer.RenderInExistingBatch (Microsoft.AspNetCore.Components.Rendering.RenderQueueEntry renderQueueEntry) <0x20a6e48 + 0x00036> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1
blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue () <0x20a3eb8 + 0x00056> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr @ blazor.webassembly.js:1


来源: stackexchange

问:
Arrow should only appear in cases expressions and anonymous functions
I am trying to check if a given key exist in a dict given the key. I am relatively new to Elm and functional programming, so I am not sure where I am going wrong.

The error I am receiving is:

An arrow should only appear in cases expressions and anonymous functions. Maybe
  you want > or >= instead?

Here's my attempt at returning true or false

```<code>dictExist : comparable -> Dict comparable v -> Bool
dictExist dict key =
    Dict.get key dict
            Just -> True
            Maybe.Maybe -> False
</code>```

On another note I have tried the Dict.member as well, but no success either and would assume instead of the Dict.get I should be using Dict.member for this...

答:
There are four problems with your code:

As the error points out, you're using the arrow outside a case ... of expression.

The Maybe type's Just constructor has an accompanying value, the item from the dict, but you don't bind it to anything. You have to explicitly discard it by assigning it to the wildcard pattern, _.

Maybe.Maybe is not a constructor. This should be Nothing, which is the other constructor of the Maybe type.

You've flipped the argument order of dictExist

Having fixed these problems, this code should work:

```<code>dictExist : comparable -> Dict comparable v -> Bool
dictExist key dict =
    case Dict.get key dict of
        Just _ -> True
        Nothing -> False
</code>```

But this is really just a reimplmentation of Dict.member, which has the exact same type signature. Replacing any usage of dictExist with Dict.member should therefore work exactly the same.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to check if a given key exist in a dict given the key. I am relatively new to Elm and functional programming, so I am not sure where I am going wrong.

The error I am receiving is:

An arrow should only appear in cases expressions and anonymous functions. Maybe
  you want > or >= instead?

Here's my attempt at returning true or false

dictExist : comparable -> Dict comparable v -> Bool
dictExist dict key =
    Dict.get key dict
            Just -> True
            Maybe.Maybe -> False

On another note I have tried the Dict.member as well, but no success either and would assume instead of the Dict.get I should be using Dict.member for this...

Body:
There are four problems with your code:

As the error points out, you're using the arrow outside a case ... of expression.

The Maybe type's Just constructor has an accompanying value, the item from the dict, but you don't bind it to anything. You have to explicitly discard it by assigning it to the wildcard pattern, _.

Maybe.Maybe is not a constructor. This should be Nothing, which is the other constructor of the Maybe type.

You've flipped the argument order of dictExist

Having fixed these problems, this code should work:

dictExist : comparable -> Dict comparable v -> Bool
dictExist key dict =
    case Dict.get key dict of
        Just _ -> True
        Nothing -> False

But this is really just a reimplmentation of Dict.member, which has the exact same type signature. Replacing any usage of dictExist with Dict.member should therefore work exactly the same.


问:
Space key not working in input control when added inside sap.m.ObjectHeader
I have a problem with space key (Space bar) on the keyboard, which doesn't work when I try to type text in FeedInput on Fiori Application. It is possible to add empty space in case I press Shift + Space. This combination works on PC, but not on mobile devices.

I know that the problem happens because I'm embedding the FeedInput inside <headerContainer> or some of the other UI elements. It's actually not relevant only for FeedInput, but also for Input, SmartField in SmartTable, etc.

I can see that SAP provides the following info for class sap.m.HeaderContainer:

The container that provides a horizontal layout. It provides a horizontal scrolling on the mobile devices. On the desktop, it provides scroll left and scroll right buttons. This control supports keyboard navigation. You can use ← and → to navigate through the inner content. The Home key puts focus on the first control and the End key puts focus on the last control. Use Enter or Space key to choose the control. (source)

I found that if I delete event listener in browser debugger for KEYPRESS body#content.sapUiBody, the space bar starts working fine for all type of text fields.

<ObjectHeader id="ohDetails"
  numberState="Success"
  responsive="true"
>
  <headerContainer>
    <IconTabBar id="itb1"
      select=".onIconTabBarSelect"
      expandable="false"
    >
      <items>

        <IconTabFilter id="iftLog"
          key="logKey"
          icon="sap-icon://notes"
        >
          <VBox alignContent="End">
            <FeedInput id="fiComment"
              class="sapUiSmallMarginTopBottom"
              post=".onSubmitComment"
              icon="sap-icon://comment"
              placeholder="{i18n>plhFeedInput}"
            />

          </VBox>
        </IconTabFilter>
      </items>
    </IconTabBar>
  </headerContainer>
</ObjectHeader>
```

答:
There is nothing wrong with putting <IconTabBar> as the header container of <ObjectHeader>. In fact, the <headerContainer> aggregation awaits <IconTabBar> as one of the controls that implements "sap.m.ObjectHeaderContainer".

The reason why it didn't work was because of the regression introduced with commit:d05437d while trying to prevent scrolling when the space bar was pressed. With commit:38f5481, it's all fixed now.

Preventing all pressing of SPACE when inside ObjectHeader caused that, in case there is Input field inside HeaderContainer, the user couldn't enter space in it.

On the other hand, SPACE is still prevented on all interactive elements of the ObjectHeader.

Demo: https://jsbin.com/takequm/edit?js,output

Update: the fix is now distributed with 1.67+. After updating the UI5 resource bootstrap to, for example, src="https://ui5.sap.com/1.70.0/resources/sap-ui-core.js", we can see that the spacebar works again.


问:
Ignore duplicate servlet mappings in web.xml
We are getting an error with duplicate servlet mappings in web.xml for tomcat. We want to allow duplicate servlet mappings without tomcat to falling all over its self

We removed the duplicate entry and did not have a problem anymore. However we have no way currently to tell if a developer checked in a web.xml with duplicate entries so we don't want to break production.

答:
I think that the OP would still want the warning in catalina.out, but would still want Tomcat to continue to load the servlets successfully.

I've seen Tomcat systems with dozens of .war files deployed to them, and you wouldn't want the entire server to go down because just one of those .war files was deployed incorrectly.


问:
I can't get wanted parameters through the json response (web-scraping)
I'm trying to extract data through the json response of this link : https://www.bienici.com/recherche/achat/france?page=2

I have 2 problems:
- first, I want scrape a house's parametrs like (price, area, city, zip code) but I don't know how ?
- Secondly, I want to make a loop that goes all the pages up to page 100

This is the program :

```<code> import requests
 from pandas.io.json import json_normalize
 import csv

 payload = {'filters': '{"size":24,"from":0,"filterType":"buy","newProperty":false,"page":2,"resultsPerPage":24,"maxAuthorizedResults":2400,"sortBy":"relevance","sortOrder":"desc","onTheMarket":[true],"limit":"ih{eIzjhZ?q}qrAzaf}AlrD?rvfrA","showAllModels":false,"blurInfoType":["disk","exact"]}'}

 url = 'https://www.bienici.com/realEstateAds.json'
 response = requests.get(url, params = payload).json()
 with open("selog.csv", "w", newline="") as f:
     writer = csv.writer(f)

     for prop in response['realEstateAds']:
         title = prop['title']
         city = prop['city']
         desc = prop['description']
         price = prop['price']

         df = json_normalize(response['realEstateAds'])
         df.to_csv('selog.csv', index=False)
         writer.writerow([price,title,city,desc])
</code>```

答:
Hi first thing I notice is you're writing the csv twice. Once with writer and once with .to_csv(). Depending what you are trying to do, you don't need both, but ultimately either would work. It just depends then how you iterated through the data.

Personally, I like working with pandas. I’ve had people tell me it’s a little overkill to store temp dataframes and append to a “final” dataframe, but it’s just what I’m comfortable doing and haven’t had issues with it, so I just used that.

To get other data parts, you'll need to investigate what’s all there and work your way through the json format to pull that out of the json response (if you’re going the route of using csv writer).

The pages are part of the payload parameters. To go through pages, just iterate that. The weird thing is, when I tried that, not only do you have to iterate through pages, but also the from parameter. Ie. since I have it doing 60 per page, page 1 is from 0, page 2 is from 60, page 3 is from 120, etc. So had it iterate through those multiples of 60 (it seems to get it). Sometimes it’s possible to see how many pages you’ll iterate through, but I couldn’t find it, so simply left it as a try/except, so when it reaches the end, it’ll break the loop. The only downside, is it could draw an error unexpected before, causing it to stop pre-maturely. I didn’t look too much into that, but just as a side note.

so it would look something like this (might take a while to go through all the pages, so I just did pages 1-10$:

You can also before saving to csv, manipulte the dataframe to keep only the columns you want:

```<code>import requests
import pandas as pd
from pandas.io.json import json_normalize

tot_pages = 10

url = 'https://www.bienici.com/realEstateAds.json'

results_df = pd.DataFrame()

for page in range(1, tot_pages+1):

    try:
        payload = {'filters': '{"size":60,"from":%s,"filterType":"buy","newProperty":false,"page":%s,"resultsPerPage":60,"maxAuthorizedResults":2400,"sortBy":"relevance","sortOrder":"desc","onTheMarket":[true],"limit":"ih{eIzjhZ?q}qrAzaf}AlrD?rvfrA","showAllModels":false,"blurInfoType":["disk","exact"]}' %((60 * (page-1)), page)}
        response = requests.get(url, params = payload).json()

        print ('Processing Page: %s' %page)
        temp_df = json_normalize(response['realEstateAds'])

        results_df = results_df.append(temp_df).reset_index(drop=True)
    except:
        print ('No more pages.')
        break

# To Filter out to certain columns, un-comment below
#results_df = results_df[['city','district.name','postalCode','price','propertyType','surfaceArea','bedroomsQuantity','bathroomsQuantity']]

results_df.to_csv('selog.csv', index=False)
</code>```

Output:

```<code>    print(results_df.head(5).to_string())
             city                    district.name postalCode   price propertyType  surfaceArea  bedroomsQuantity  bathroomsQuantity
0        Colombes   Colombes - Fossés Jean Bouvier      92700  469000         flat        92.00               3.0                1.0
1            Nice   Nice - Parc Impérial - Le Piol      06000  215000         flat        49.05               1.0                NaN
2            Nice                  Nice - Gambetta      06000  145000         flat        21.57               0.0                NaN
3  Cagnes-sur-Mer  Cagnes-sur-Mer - Les Bréguières      06800  770000        house       117.00               3.0                3.0
4             Pau                  Pau - Le Hameau      64000  310000        house       110.00               3.0                2.0
</code>```

Body:
I'm trying to extract data through the json response of this link : https://www.bienici.com/recherche/achat/france?page=2

I have 2 problems:
- first, I want scrape a house's parametrs like (price, area, city, zip code) but I don't know how ?
- Secondly, I want to make a loop that goes all the pages up to page 100

This is the program :

 import requests
 from pandas.io.json import json_normalize
 import csv

 payload = {'filters': '{"size":24,"from":0,"filterType":"buy","newProperty":false,"page":2,"resultsPerPage":24,"maxAuthorizedResults":2400,"sortBy":"relevance","sortOrder":"desc","onTheMarket":[true],"limit":"ih{eIzjhZ?q}qrAzaf}AlrD?rvfrA","showAllModels":false,"blurInfoType":["disk","exact"]}'}

 url = 'https://www.bienici.com/realEstateAds.json'
 response = requests.get(url, params = payload).json()
 with open("selog.csv", "w", newline="") as f:
     writer = csv.writer(f)

     for prop in response['realEstateAds']:
         title = prop['title']
         city = prop['city']
         desc = prop['description']
         price = prop['price']

         df = json_normalize(response['realEstateAds'])
         df.to_csv('selog.csv', index=False)
         writer.writerow([price,title,city,desc])

Body:
Hi first thing I notice is you're writing the csv twice. Once with writer and once with .to_csv(). Depending what you are trying to do, you don't need both, but ultimately either would work. It just depends then how you iterated through the data.

Personally, I like working with pandas. I’ve had people tell me it’s a little overkill to store temp dataframes and append to a “final” dataframe, but it’s just what I’m comfortable doing and haven’t had issues with it, so I just used that.

To get other data parts, you'll need to investigate what’s all there and work your way through the json format to pull that out of the json response (if you’re going the route of using csv writer).

The pages are part of the payload parameters. To go through pages, just iterate that. The weird thing is, when I tried that, not only do you have to iterate through pages, but also the from parameter. Ie. since I have it doing 60 per page, page 1 is from 0, page 2 is from 60, page 3 is from 120, etc. So had it iterate through those multiples of 60 (it seems to get it). Sometimes it’s possible to see how many pages you’ll iterate through, but I couldn’t find it, so simply left it as a try/except, so when it reaches the end, it’ll break the loop. The only downside, is it could draw an error unexpected before, causing it to stop pre-maturely. I didn’t look too much into that, but just as a side note.

so it would look something like this (might take a while to go through all the pages, so I just did pages 1-10$:

You can also before saving to csv, manipulte the dataframe to keep only the columns you want:

import requests
import pandas as pd
from pandas.io.json import json_normalize

tot_pages = 10

url = 'https://www.bienici.com/realEstateAds.json'

results_df = pd.DataFrame()

for page in range(1, tot_pages+1):

    try:
        payload = {'filters': '{"size":60,"from":%s,"filterType":"buy","newProperty":false,"page":%s,"resultsPerPage":60,"maxAuthorizedResults":2400,"sortBy":"relevance","sortOrder":"desc","onTheMarket":[true],"limit":"ih{eIzjhZ?q}qrAzaf}AlrD?rvfrA","showAllModels":false,"blurInfoType":["disk","exact"]}' %((60 * (page-1)), page)}
        response = requests.get(url, params = payload).json()

        print ('Processing Page: %s' %page)
        temp_df = json_normalize(response['realEstateAds'])

        results_df = results_df.append(temp_df).reset_index(drop=True)
    except:
        print ('No more pages.')
        break

# To Filter out to certain columns, un-comment below
#results_df = results_df[['city','district.name','postalCode','price','propertyType','surfaceArea','bedroomsQuantity','bathroomsQuantity']]

results_df.to_csv('selog.csv', index=False)

Output:

    print(results_df.head(5).to_string())
             city                    district.name postalCode   price propertyType  surfaceArea  bedroomsQuantity  bathroomsQuantity
0        Colombes   Colombes - Fossés Jean Bouvier      92700  469000         flat        92.00               3.0                1.0
1            Nice   Nice - Parc Impérial - Le Piol      06000  215000         flat        49.05               1.0                NaN
2            Nice                  Nice - Gambetta      06000  145000         flat        21.57               0.0                NaN
3  Cagnes-sur-Mer  Cagnes-sur-Mer - Les Bréguières      06800  770000        house       117.00               3.0                3.0
4             Pau                  Pau - Le Hameau      64000  310000        house       110.00               3.0                2.0


问:
How can I schedule a cron job but not execute it?
I wanted to create a crontab file with schedule but do not want it to run.
How can I achieve this?

I created a crontab file using crontab -e, added the job. This has started running. I do not want this to run as the job should be scheduled ad hoc.

I wanted to prepare and keep and use the schedule on ad hoc.

答:
You can comment your schedule line out with a leading #, and remove the comment marker again when you want it to run.

http://man7.org/linux/man-pages/man5/crontab.5.html


问:
Is there a library for "linear quadratic regulator" function in C++
Is there a library in control, similar to  MATLAB's control toolbox, for C++? Where I could run functions such as linear quadratic regulator (lqr)?</p>

答:
Although this question is old, I would like to point to the following open-source library, which holds a C++ implementation of LQR, iLQR, and others:

https://github.com/ethz-adrl/control-toolbox


问:
Window xp and java 8
I am making a project by java 8 but I'm confusing about can window xp run java 8 project as well, and I don't know if I use new resources of java 8, will it work in window xp like work in window 10? =)), Thanks!</p>

答:
Oracle Java is not free for commercial usage anymore.

These days with OpenJDK you have these options (free even for commercial usage):

https://aws.amazon.com/corretto - sponsored by Amazon

https://github.com/ojdkbuild/ojdkbuild - sponsored by Red Hat

https://www.azul.com/downloads/zulu - sponsored by Azul Systems

and more... https://github.com/akullpp/awesome-java#jvm-and-jdk

ContentLicense: CC BY-SA 3.0

Title: Window xp and java 8


问:
Create a new column in a dataframe out of previous rows from a factor variable
Given a dataframe like this:

```<code>game     team
zap.che  zap
zap.che  che
zap.che  zap
zap.che  zap
zap.che  che
bar.var  bar
bar.var  var
bar.var  var
bar.var  bar
bar.var  bar
</code>```

I'd like to add another new column, being my desired outcome something like this:

```<code>game     team    poss
zap.che  zap     1
zap.che  che     1
zap.che  zap     2
zap.che  zap     2
zap.che  che     2
bar.var  bar     1
bar.var  var     1
bar.var  var     1
bar.var  bar     2
bar.var  bar     2
</code>```

My purposes are:
a) assign the same value to all the consecutive occurrences of the same value in "team" column
b) count all the wrapped "team" values in "poss" column (1,2,3 and so on)
c) once in "game" column the value changes, restart the same process

答:
We can create a new column representing row_number() of the dataframe,  group_by game and team and increment the count when difference between consecutive row is more than 1.

```<code>library(dplyr)

df %>%
  mutate(row = row_number()) %>%
  group_by(game, team) %>%
  mutate(poss = cumsum(c(TRUE, diff(row) > 1)))%>%
  select(-row)

#   game    team   poss
#   <fct>   <fct> <int>
# 1 zap.che zap       1
# 2 zap.che che       1
# 3 zap.che zap       2
# 4 zap.che zap       2
# 5 zap.che che       2
# 6 bar.var bar       1
# 7 bar.var var       1
# 8 bar.var var       1
# 9 bar.var bar       2
#10 bar.var bar       2
</code>```

Body:
Given a dataframe like this:

game     team
zap.che  zap
zap.che  che
zap.che  zap
zap.che  zap
zap.che  che
bar.var  bar
bar.var  var
bar.var  var
bar.var  bar
bar.var  bar

I'd like to add another new column, being my desired outcome something like this:

game     team    poss
zap.che  zap     1
zap.che  che     1
zap.che  zap     2
zap.che  zap     2
zap.che  che     2
bar.var  bar     1
bar.var  var     1
bar.var  var     1
bar.var  bar     2
bar.var  bar     2

My purposes are:
a) assign the same value to all the consecutive occurrences of the same value in "team" column
b) count all the wrapped "team" values in "poss" column (1,2,3 and so on)
c) once in "game" column the value changes, restart the same process

Body:
We can create a new column representing row_number() of the dataframe,  group_by game and team and increment the count when difference between consecutive row is more than 1.

library(dplyr)

df %>%
  mutate(row = row_number()) %>%
  group_by(game, team) %>%
  mutate(poss = cumsum(c(TRUE, diff(row) > 1)))%>%
  select(-row)

#   game    team   poss
#   <fct>   <fct> <int>
# 1 zap.che zap       1
# 2 zap.che che       1
# 3 zap.che zap       2
# 4 zap.che zap       2
# 5 zap.che che       2
# 6 bar.var bar       1
# 7 bar.var var       1
# 8 bar.var var       1
# 9 bar.var bar       2
#10 bar.var bar       2


问:
Make String input an object instance
```<code>user1.subscribe();
</code>```

user1 is under a User class, I'm looking at how to use Scanner to get the user input. So when asking username using Scanner, like user2, that can be used to call user2.subscribe();

Used Scanner String input but can't convert to object

```<code>User userID;
Scanner input = new Scanner(System.in);
userID = input.next();
</code>```

Type mismatch: cannot convert from String to User

So the user has been added as follow

```<code>User user1 = new User("user1", "James Smith", "915661829");
</code>```

In main method I can call user1.subscribe() to subscribe the user. I'm trying to ask for an input, like "user2" which will call user2.subscribe().

The Scanner would ask for the username of the user that wants to subscribe.

答:
You have to make field to accept input from command line. Something like this.

```<code>class User {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                '}';
    }
}
</code>```

And then accept input in the field, and you need to instantiate object before populating it.

```<code>User userID = new User();
Scanner input = new Scanner(System.in);
userID.setId(input.next());
System.out.println("User object : " + userID);
</code>```

Title: Make String input an object instance

Body:
user1.subscribe();

user1 is under a User class, I'm looking at how to use Scanner to get the user input. So when asking username using Scanner, like user2, that can be used to call user2.subscribe();

Used Scanner String input but can't convert to object

User userID;
Scanner input = new Scanner(System.in);
userID = input.next();

Type mismatch: cannot convert from String to User

So the user has been added as follow

User user1 = new User("user1", "James Smith", "915661829");

In main method I can call user1.subscribe() to subscribe the user. I'm trying to ask for an input, like "user2" which will call user2.subscribe().

The Scanner would ask for the username of the user that wants to subscribe.

Body:
You have to make field to accept input from command line. Something like this.

class User {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                '}';
    }
}

And then accept input in the field, and you need to instantiate object before populating it.

User userID = new User();
Scanner input = new Scanner(System.in);
userID.setId(input.next());
System.out.println("User object : " + userID);


问:
Upsert parent and children with EntityFramework
I find myself frequently wanting "Upsert" functionality in EntityFramework - I've got a disconnected graph of parent + children entities and I want to "upsert" the parent (and its children). By that I mean

When the parent doesn't have an ID assigned (id = 0) I'd like to simply insert the parent and the children (auto assign IDs in both cases)

When the parent does have a ID assigned, I'd like to replace the existing parent entity in the database (having the same ID) with the new one. In addition, any children associated with that parent should be removed (parent 'owns' the children). The children on the new parent should be inserted in their place (keeping the assigned ids).

This "mostly" works in that it retains the ID of the parent, but does not retain the IDs of the children (the children are assigned new IDs on each "upsert").

public void Upsert(ParentEntity parentEntity) {
    ParentEntity existing = DB.Parents.Find(parentEntity.Id);

    if (existing == null) {
        DB.Parents.Add(parentEntity);
    } else {
        var existingChildren = DB.Children.Where(m => m.ParentId == parentEntity.Id).ToArray();

        foreach (var child in parentEntity.Children) {
            child.ParentId = parentEntity.Id;
        }

        DB.Children.RemoveRange(existingChildren);
        DB.Children.AddRange(parentEntity.Children);

        DB.Entry(existing).State = EntityState.Detached;
        DB.Parents.Attach(parentEntity);
        DB.Entry(parentEntity).State = EntityState.Modified;
    }

    SaveChanges();
}
```

答:
This is something I use to get what I want. For my purpose it works great:

```<code>foreach (var metric in metrics)
{
    var added = context.Set(metric.GetType()).Add(metric);

    foreach (var dbEntityEntry in context.ChangeTracker.Entries())
    {
        //If these entities exist, don't add them.
        var metricContext = dbEntityEntry.Entity as MetricContext;
        if (metricContext != null)
        {
            var found = context.MetricContext.FirstOrDefault(c => c.Context == metricContext.Context);
            if (found != default(MetricContext))
            {
                dbEntityEntry.State = EntityState.Detached;
            }
        }
    }
}
</code>```

This detaches any entities that already live in the db, meaning they will not be processed.

Body:
This is something I use to get what I want. For my purpose it works great:

foreach (var metric in metrics)
{
    var added = context.Set(metric.GetType()).Add(metric);

    foreach (var dbEntityEntry in context.ChangeTracker.Entries())
    {
        //If these entities exist, don't add them.
        var metricContext = dbEntityEntry.Entity as MetricContext;
        if (metricContext != null)
        {
            var found = context.MetricContext.FirstOrDefault(c => c.Context == metricContext.Context);
            if (found != default(MetricContext))
            {
                dbEntityEntry.State = EntityState.Detached;
            }
        }
    }
}

This detaches any entities that already live in the db, meaning they will not be processed.


问:
Issue: Violation of Permissions policy After reviewing your app while uploading Android app on Store
While uploading my Android app , I receive a rejected mail from Google says that

Issue: Violation of Permissions policy After reviewing your app, we found that it doesn’t qualify to use the requested permissions for the following reason(s):
  Based on our review, we found your app’s expressed user experience did not match your declared core functionality { Default SMS handler (and any other core functionality usage while default handler), Cross-device synchronization or transfer of SMS or calls, SMS-based financial transactions (e.g., 5 digit messages), and related activity including OTP account verification for financial transactions and fraud detection, Track, budget, manage SMS-based financial transactions (e.g., 5 digit messages) and related account verification }. Please remove these permissions from your app.
  Your app seems to be a {Violation Monitoring app} and does not meet any of the allowed use cases. Hence, we cannot provide SMS/Call Log permissions.

I tried to search on it and I didn't find a real solution for my problem

Here is my Permissions

```<code>  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.RECEIVE_SMS" />
  <uses-permission android:name="android.permission.READ_SMS" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
     />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    />
  <uses-permission android:name="android.permission.CAMERA" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
     />
   <uses-permission android:name="android.permission.ACCESS_GPS" />
  <uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
  <uses-permission android:name="android.permission.ACCESS_LOCATION" /> ```
```

答:
My app used read sms permission which allowed my app read otp sms send to user mobile device to verify user mobile number.

So i too received this violation policy permission mail stating i am using read sms permission in my app.
Using that permission i was able toread OTP automatically from the sms.

But according to new google guidelines,we cant use read sms permission for above mentioned account verification.
So right now i have removed sms read permission and made user to enter the otp received in sms manually.

If you are using read sms permission ,there are certain requirements to be met.

For apps requesting access to the SMS or Call Log permissions, the intended and permitted uses include default SMS handling, default
  phone handling, or Assistant handling capability.
 Apps must be
  actively registered as the default SMS, Phone, or Assistant handler
  before prompting users to accept any of the above permissions and must
  immediately stop the use of the permission when they no longer are the
  default handler.

I got information from this link.

https://support.google.com/googleplay/android-developer/answer/9047303

Hope this helps you.

Body:
While uploading my Android app , I receive a rejected mail from Google says that

Issue: Violation of Permissions policy After reviewing your app, we found that it doesn’t qualify to use the requested permissions for the following reason(s):
  Based on our review, we found your app’s expressed user experience did not match your declared core functionality { Default SMS handler (and any other core functionality usage while default handler), Cross-device synchronization or transfer of SMS or calls, SMS-based financial transactions (e.g., 5 digit messages), and related activity including OTP account verification for financial transactions and fraud detection, Track, budget, manage SMS-based financial transactions (e.g., 5 digit messages) and related account verification }. Please remove these permissions from your app.
  Your app seems to be a {Violation Monitoring app} and does not meet any of the allowed use cases. Hence, we cannot provide SMS/Call Log permissions.

I tried to search on it and I didn't find a real solution for my problem

Here is my Permissions

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.RECEIVE_SMS" />
  <uses-permission android:name="android.permission.READ_SMS" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
     />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    />
  <uses-permission android:name="android.permission.CAMERA" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
     />
   <uses-permission android:name="android.permission.ACCESS_GPS" />
  <uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
  <uses-permission android:name="android.permission.ACCESS_LOCATION" /> ```


问:
IAR assembler BKPT immediate as input operand
I am writing a flashloader for a Cortex M4 device and I'd like to "return" a value for the driving PC application using the breakpoint instruction's immediate value.

While hardcoding an immediate works fine:

```<code>__asm("bkpt 0x70");
__asm("bkpt %0" : : "i" (0x70));
</code>```

as soon as I want to "return" something run-time dependent like

```<code>uint8_t status = Flash_EraseAll();
__asm("bkpt %0" : : "i" (status));
</code>```

The compilation fails with

Error[Ta090]: Immediate operand is not constant

I tried using preprocessor macros with different concatenate setups, but to no avail.

Has anybody got an idea of how I could input the run-time dependent status flags to the __asm() block in IAR as an immediate? Based on what I read here, this is not exactly possible, but there might be a clever hacky way to do it.

P.S.: Yes, as a workaround I could use a switch statement where I list and hardcode every possible state, but that's just ugly and long.

答:
I would push the value on the stack, and then use the bkpt instruction with a defined number, so the debugger can look at the stack for this state.

Something like this (pseudocode):

```<code>__asm("push %0" : : "i" (status));
__asm("bkpt %0" : : "i" (0x70));
</code>```

Of course you shouldn't forget to cleanup the stack afterwards.

Since bkpt is encoded with an immediate only, you can obviously not change that at runtime, as you would have to modify the code.

Body:
I am writing a flashloader for a Cortex M4 device and I'd like to "return" a value for the driving PC application using the breakpoint instruction's immediate value.

While hardcoding an immediate works fine:

__asm("bkpt 0x70");
__asm("bkpt %0" : : "i" (0x70));

as soon as I want to "return" something run-time dependent like

uint8_t status = Flash_EraseAll();
__asm("bkpt %0" : : "i" (status));

The compilation fails with

Error[Ta090]: Immediate operand is not constant

I tried using preprocessor macros with different concatenate setups, but to no avail.

Has anybody got an idea of how I could input the run-time dependent status flags to the __asm() block in IAR as an immediate? Based on what I read here, this is not exactly possible, but there might be a clever hacky way to do it.

P.S.: Yes, as a workaround I could use a switch statement where I list and hardcode every possible state, but that's just ugly and long.

Body:
I would push the value on the stack, and then use the bkpt instruction with a defined number, so the debugger can look at the stack for this state.

Something like this (pseudocode):

__asm("push %0" : : "i" (status));
__asm("bkpt %0" : : "i" (0x70));

Of course you shouldn't forget to cleanup the stack afterwards.

Since bkpt is encoded with an immediate only, you can obviously not change that at runtime, as you would have to modify the code.


问:
How will I know the Controler’s Table in Database (Laravel)
I’m beginner in Laravel Framework. I want to know how the Controller Identifies what table it belongs to? </p>

答: Model, View, and Controller are there different components of MVC Patterns. You need to understand this first. The controller does not identify tables. Business logic is supposed to be held by models/services. Controllers hold the specification for endpoints, which will act as per the requests. Views, of course, contains markup and logics depending on use cases.</p>


问:
Merging two Collection<T>
I got a Function that returns a Collection<string>, and that calls itself recursively to eventually return one big Collection<string>.

Now, i just wonder what the best approach to merge the lists? Collection.CopyTo() only copies to string[], and using a foreach() loop feels like being inefficient. However, since I also want to filter out duplicates, I feel like i'll end up with a foreach that calls Contains() on the Collection.

I wonder, is there a more efficient way to have a recursive function that returns a list of strings without duplicates? I don't have to use a Collection, it can be pretty much any suitable data type.

Only exclusion, I'm bound to Visual Studio 2005 and .net 3.0, so no LINQ.

Edit: To clarify: The Function takes a user out of Active Directory, looks at the Direct Reports of the user, and then recursively looks at the direct reports of every user. So the end result is a List of all users that are in the "command chain" of a given user.Since this is executed quite often and at the moment takes 20 Seconds for some users, i'm looking for ways to improve it. Caching the result for 24 Hours is also on my list btw., but I want to see how to improve it before applying caching.

答:
As far as merging goes:

I wonder, is there a more efficient
  way to have a recursive function that
  returns a list of strings without
  duplicates? I don't have to use a
  Collection, it can be pretty much any
  suitable data type.

Your function assembles a return value, right? You're splitting the supplied list in half, invoking self again (twice) and then merging those results.

During the merge step, why not just check before you add each string to the result? If it's already there, skip it.

Assuming you're working with sorted lists of course.

OwnerDisplayName: Michael Stum

Title: Merging two Collection<T>

LastEditorDisplayName: Michael Stum

ContentLicense: CC BY-SA 2.5


问:
What are the often misunderstood concepts in C++?
What are the often misunderstood concepts in c++?</p>

答:
Why is A[b] the same thing as b[A]?

Ok, not really a COMMON question, but it came up in a class I was teaching once...

OwnerDisplayName: rajKumar

LastEditorDisplayName: starblue

OwnerDisplayName: Brian Postow


问:
Facebook PHP SDK Curl over proxy
Im trying to setup php sdk. SDK is using Curl to make request. But i have to do this by proxy.

My OPTS:

```<code>  public static $CURL_OPTS = array(
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_USERAGENT      => 'facebook-php-2.0',
    CURLOPT_PROXYPORT      => '8080',
    CURLOPT_PROXY          => 'proxy',

  );

curl_setopt_array($ch, $opts);
print "```"; print_r($opts);    print "```";
</code>```

this is printing:

```<code>Array
(
    [78] => 10
    [19913] => 1
    [13] => 60
    [10018] => facebook-php-2.0
    [59] => 8080
    [10004] => proxy
    [10015] => method=GET&access_token=xxxxxxxxxxxxxxxxxx
    [10002] => https://graph.facebook.com/naitik
    [10023] => Array
        (
            [0] => Expect:
        )

)
</code>```

and print print_r(curl_error($ch)); returning:

```<code>Received HTTP code 403 from proxy after CONNECT
</code>```

What opptions should be used, to get it work?

答:
In case it is a problem with CURLE_SSL_CACERT, this line:

```<code>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
</code>```

added to

```<code>if (curl_errno($ch) == 60) {
.
.
</code>```

should solve the problem.

Title: Facebook PHP SDK Curl over proxy

Body:
Im trying to setup php sdk. SDK is using Curl to make request. But i have to do this by proxy.

My OPTS:

  public static $CURL_OPTS = array(
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_USERAGENT      => 'facebook-php-2.0',
    CURLOPT_PROXYPORT      => '8080',
    CURLOPT_PROXY          => 'proxy',

  );

curl_setopt_array($ch, $opts);
print "
"; print_r($opts);    print "
";

this is printing:

Array
(
    [78] => 10
    [19913] => 1
    [13] => 60
    [10018] => facebook-php-2.0
    [59] => 8080
    [10004] => proxy
    [10015] => method=GET&access_token=xxxxxxxxxxxxxxxxxx
    [10002] => https://graph.facebook.com/naitik
    [10023] => Array
        (
            [0] => Expect:
        )

)

and print print_r(curl_error($ch)); returning:

Received HTTP code 403 from proxy after CONNECT

What opptions should be used, to get it work?

Body:
In case it is a problem with CURLE_SSL_CACERT, this line:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

added to

if (curl_errno($ch) == 60) {
.
.

should solve the problem.


问:
How to find text in mongodb like LIKE in mySQL?
I find text in mongodb as the same LIKE in MySQL, but the result is not as expected

I have 6 docs in collection posts:

(1) David Beckham's Kids Cheer Him on During Charity Soccer Game

(2) David Beckham is casual in sweater and jeans as he attends Copa

(3) David Beckham spoke out in view of his 55.6 million Instagram followers, saying

(4) David Beckham's family were out in force to support him at the

(5) Handsome: David Beckham looked dapper in a shirt and olive-green jacket before another day of shooting for his eyewear collection in Venice

(6) But on Wednesday, David Beckham was spotted going back to his roots as he caught up with Tottenham ace Harry Kane on the football pitch

SQL's like query:

SELECT * FROM posts  WHERE content LIKE '%David%Tottenham%'

=> (6) But on Wednesday, David Beckham was spotted going back to his roots as he caught up with Tottenham ace Harry Kane on the football pitch

Mongo's find query:

db.posts.find({"content": /.*David.Tottenham./})

=> error

I expect the output of Mongo's find query is (6), but the actual output is error

Can Anyone Help Me to find query in mongodb? Thank you!

答:
you can use mongodb $regex operator.
I think this query might work for you:</p>

```<code>db.posts.find({"content": {$regex: ".*David.*Tottenham .*"}})
</code>```

Body:
you can use mongodb $regex operator.
I think this query might work for you:

db.posts.find({"content": {$regex: ".*David.*Tottenham .*"}})


问:
Why my 'for' loop function doesn't work in sass?
I am trying to call @for loop in my style file but it doesn't work.
here is what I tried

```<code>@for $i from 1 to 50{
.point-#{i}{
  background-color: red;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  -webkit-animation: movee 5s infinite;
  animation: movee 10s infinite;
  margin-left: #{i};
  margin-top: #{i} + 1;
}
  @keyframes movee {
    0% {
      margin-left: 0px;
    }
    50% {
      margin-left: 200px;
    }
    100% {
      margin-left: 0px;
    }
  }

}
</code>```

and nothing styles are shown on my points class.

in HTML I wrote with typescript like this

```<code>  ngOnInit() {
    for (let i = 1; i <= 50; i++) {
      this.point += '<div class="point-' + i + '"></div>';
    }
  }
</code>```

here is my template

```<code><div class="move" [innerHtml]="point">
</div>
</code>```

答:
I think you need to use #{$i} instead of #{i} for the class name accessor in your sass code and $i for values.
You can see some examples here: https://sass-lang.com/documentation/interpolation

I also found a good example here:
http://thesassway.com/intermediate/if-for-each-while

Body:
I am trying to call @for loop in my style file but it doesn't work.
here is what I tried

@for $i from 1 to 50{
.point-#{i}{
  background-color: red;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  -webkit-animation: movee 5s infinite;
  animation: movee 10s infinite;
  margin-left: #{i};
  margin-top: #{i} + 1;
}
  @keyframes movee {
    0% {
      margin-left: 0px;
    }
    50% {
      margin-left: 200px;
    }
    100% {
      margin-left: 0px;
    }
  }

}

and nothing styles are shown on my points class.

in HTML I wrote with typescript like this

  ngOnInit() {
    for (let i = 1; i <= 50; i++) {
      this.point += '

';
    }
  }

here is my template


问:
how to make my LSTM model predict after training
I'm a begginer at ML and I'm using an LSTM model to forcast a future value of a column I think i succeded in training my model but I'm strugling to make my model predict the future values
my dataset is like this:
   c0            c1         c2        c3          c4          c5
 0.953202     0.998825   0.943329   0.762738    0.046798      0.0
....
I trained my model to predict the values of c5 based on the the other columns

# split into train and test sets
values = reframed.values
n_train_hours = 24*24
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]

# split into input and outputs
train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape, try1.shape)

# design network
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=50, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False)

# make a prediction
      ???

```

答:
To see predictions:

```<code>model.predict(test_X)
</code>```

To calculate acurracy and loss for test data:

```<code>model.evaluate(test_X,test_Y)
</code>```

You can find everythin about model methods in https://keras.io/models/model/

Body:
To see predictions:

model.predict(test_X)

To calculate acurracy and loss for test data:

model.evaluate(test_X,test_Y)

You can find everythin about model methods in https://keras.io/models/model/


问:
How to change committed User name in bitbucket?
How to change commit username in bitbucket account ? To change in git I have used this command </p>

```<code> git filter-branch -f --env-filter " GIT_AUTHOR_NAME='newUser' GIT_AUTHOR_EMAIL='newuser@email.com' " HEAD
</code>```

<p>It only change username in local machine but not in my bitbucket account. How to change committed username in bitbucket ? </p>

答:
Also to change authors in Git for a particular project, one may run:</p>

```<code>git config user.name "Author Name"
git config user.email "author@email.com"
</code>```

Body:
How to change commit username in bitbucket account ? To change in git I have used this command

 git filter-branch -f --env-filter " GIT_AUTHOR_NAME='newUser' GIT_AUTHOR_EMAIL='newuser@email.com' " HEAD

It only change username in local machine but not in my bitbucket account. How to change committed username in bitbucket ?

Body:
Also to change authors in Git for a particular project, one may run:

git config user.name "Author Name"
git config user.email "author@email.com"


问:
Ionic3: Cannot declare InAppBrowser
I want to use InAppBrowser to open all target blank links. I follow the documentation and I always get an error when I declare the plugin on constructor:

Can't resolve all parameters for MyApp: (?, ?, ?).

This error appears to me when I put private iab: InAppBrowser on constructor.

My code:

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { Platform } from 'ionic-angular';

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

export class HomePage {

 constructor(public navCtrl: NavController, public plt: Platform, private iab: InAppBrowser) {

    this.plt.ready().then((readySource) => {
        console.log("Ready!");
        window.open = this.iab.open;
    });
  }
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { InAppBrowser } from '@ionic-native/in-app-browser';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    InAppBrowser,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
</code>```

Someone knows whats it can be?

Thanks!

答:
Your code looks good, so the problem seems to be because of the @ionic-native/core version that your project uses.

As you can see in the docs the Ionic team has updated the Ionic Native commands in order to avoid this error:

Installation

To add Ionic Native to your app, run following command to install the core package:
  npm install @ionic-native/core@4 --save

And...

Usage

Install the Needed Plugins
  Install the Ionic Native package for each plugin you want to add.
  For example, if you want to install the Camera plugin, you will need to run the following command:

npm install @ionic-native/camera@4 --save

Then install the plugin using Cordova or Ionic CLI. For example:

ionic cordova plugin add cordova-plugin-camera

Notice the @4 in both commands. That allows you to install the right version of the Ionic Native dependencies even if you're using the new CLI.

TLDR; So if you installed the plugin using the @4 you can import it like this: import { InAppBrowser } from '@ionic-native/in-app-browser';

If not, you may be using a newer version of Ionic Native so you need to import it like this: import { InAppBrowser } from '@ionic-native/in-app-browser/ngx'

Title: Ionic3: Cannot declare InAppBrowser

Body:
I want to use InAppBrowser to open all target blank links. I follow the documentation and I always get an error when I declare the plugin on constructor:

Can't resolve all parameters for MyApp: (?, ?, ?).

This error appears to me when I put private iab: InAppBrowser on constructor.

My code:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { Platform } from 'ionic-angular';

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

export class HomePage {

 constructor(public navCtrl: NavController, public plt: Platform, private iab: InAppBrowser) {

    this.plt.ready().then((readySource) => {
        console.log("Ready!");
        window.open = this.iab.open;
    });
  }

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { InAppBrowser } from '@ionic-native/in-app-browser';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    InAppBrowser,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

Someone knows whats it can be?

Thanks!


问:
Ruby on Rails Devise encrypted password read from C# .NET
We have a Ruby on Rails app that uses the Devise gem for user handling, including creating and authenticating user passwords. The passwords are encrypted in the MySQL database obviously. We are using Devise defaults for how it encrypts the password. Now we have another small same-LAN side app that (a C# ASP.NET app) needs to authenticate with a user/password directly with the database to do some read-only operations.

How can we best mimic what Devise does for user/password authentication in the C# ASP.NET app against the very same data in the MySQL database?

Essentially, I need to figure out how to recreate Devise's valid_password? method in C# .NET

http://www.rubydoc.info/github/plataformatec/devise/Devise/Models/DatabaseAuthenticatable#valid_password%3F-instance_method

```<code># File 'lib/devise/models/database_authenticatable.rb', line 46

def valid_password?(password)
  return false if encrypted_password.blank?
  bcrypt   = ::BCrypt::Password.new(encrypted_password)
  password = ::BCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", bcrypt.salt)
  Devise.secure_compare(password, encrypted_password)
end
</code>```

答:
Devise uses BCrypt for password storage, and so thankfully the verification process is fairly simple. Install the BCrypt.Net NuGet package (or any other BCrypt implementation), and then do this:

public static bool ValidPassword(string userSuppliedPassword, string hashedAndSaltedPassFromDatabase)
{
    return BCrypt.Net.BCrypt.Verify(userSuppliedPassword, hashedAndSaltedPassFromDatabase);
}
```

Body:
We have a Ruby on Rails app that uses the Devise gem for user handling, including creating and authenticating user passwords. The passwords are encrypted in the MySQL database obviously. We are using Devise defaults for how it encrypts the password. Now we have another small same-LAN side app that (a C# ASP.NET app) needs to authenticate with a user/password directly with the database to do some read-only operations.

How can we best mimic what Devise does for user/password authentication in the C# ASP.NET app against the very same data in the MySQL database?

Essentially, I need to figure out how to recreate Devise's valid_password? method in C# .NET

http://www.rubydoc.info/github/plataformatec/devise/Devise/Models/DatabaseAuthenticatable#valid_password%3F-instance_method

# File 'lib/devise/models/database_authenticatable.rb', line 46

def valid_password?(password)
  return false if encrypted_password.blank?
  bcrypt   = ::BCrypt::Password.new(encrypted_password)
  password = ::BCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", bcrypt.salt)
  Devise.secure_compare(password, encrypted_password)
end


问:
MS Access AcDialog hiding the form
I had a button click event in my access form which has

```<code>DoCmd.OpenForm "frmStudentsAll", acNormal, , , , acDialog
</code>```

Clicking this button opened the frmStudentAll in dialog view but all of a sudden today clicking this button did not open the form. I thought Access was crashing everytime I clicked this button but I can still edit the VBA but I cannot press any of the buttons in GUI. My thought is that the acDialog is opening a really small form somewhere that I cannot see and I cannot press anything without closing it. I am having to close Access using task manager.

```<code> DoCmd.OpenForm "frmStudentsAll", acNormal
</code>```

Opening the form in just normal view works fine but this is not really what I want. I did not do any new Access updates recently. Not sure why this is happening.

答:
The problem is that the form does open, but is positioned off-screen.

This is a common issue when you have a multi-monitor setup or have different users with different resolutions using the database.

By default, Access stores the location of the form relative to the database window. If a specific user has two screens, or a very large screen, he can easily position it where others can't reach it. And even a single user can position it where he himself can't see it, by first positioning it on the first screen while Access is open on the second screen, and then opening Access on the first screen.

To avoid it, set Auto Center to Yes in the property pane for the form. That makes sure the form is always centered with respect to the Access application window, so always is on-screen as long as Access is on-screen.

Alternatively, when you're locked out of the database because of this issue so can't adjust the form, you can use Forms!frmStudentsAll.Move 0,0 in the VBA Immediate window to reposition it. That way, you don't have to close the database when this occurs.

Title: MS Access AcDialog hiding the form

Body:
I had a button click event in my access form which has

DoCmd.OpenForm "frmStudentsAll", acNormal, , , , acDialog

Clicking this button opened the frmStudentAll in dialog view but all of a sudden today clicking this button did not open the form. I thought Access was crashing everytime I clicked this button but I can still edit the VBA but I cannot press any of the buttons in GUI. My thought is that the acDialog is opening a really small form somewhere that I cannot see and I cannot press anything without closing it. I am having to close Access using task manager.

 DoCmd.OpenForm "frmStudentsAll", acNormal

Opening the form in just normal view works fine but this is not really what I want. I did not do any new Access updates recently. Not sure why this is happening.


问:
Calculate the area of a polygon drawn on google maps in an Android application
I would like to calculate the are of a polygon drawn in a map fragment for a college project.

This is how I draw my polygon.

```<code>@Override
    public void onMapClick(LatLng point) {
        //tvLocInfo.setText("New marker added@" + point.toString());
        map.addMarker(new MarkerOptions().position(point).draggable(true).title(point.toString()));

        markerClicked = false;
    }

    @Override
    public void onMapLongClick(LatLng point) {
        //tvLocInfo.setText("New marker added@" + point.toString());
        map.clear();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {

        if(markerClicked){

            if(polygon != null){
                polygon.remove();
                polygon = null;
            }

            polygonOptions.add(marker.getPosition());
            polygonOptions.strokeColor(Color.RED);
            polygonOptions.fillColor(Color.BLUE);
            polygon = map.addPolygon(polygonOptions);
            //Area = google.maps.geometry.spherical.computeArea(polygon.getPath().getArray());
        }else{
            if(polygon != null){
                polygon.remove();
                polygon = null;
            }

            polygonOptions = new PolygonOptions().add(marker.getPosition());
            markerClicked = true;
        }
</code>```

I have seen this code on how to calculate the area but I am unsure how to implement it in my application and calculate the area of my polygon.

I use this code to calculate an area of a GPS with Android:

```<code>  private static final double EARTH_RADIUS = 6371000;// meters

  public static double calculateAreaOfGPSPolygonOnEarthInSquareMeters(final List<Location> locations) {
    return calculateAreaOfGPSPolygonOnSphereInSquareMeters(locations, EARTH_RADIUS);
  }

  private static double calculateAreaOfGPSPolygonOnSphereInSquareMeters(final List<Location> locations, final double radius) {
    if (locations.size() < 3) {
      return 0;
    }

    final double diameter = radius * 2;
    final double circumference = diameter * Math.PI;
    final List<Double> listY = new ArrayList<Double>();
    final List<Double> listX = new ArrayList<Double>();
    final List<Double> listArea = new ArrayList<Double>();
    // calculate segment x and y in degrees for each point
    final double latitudeRef = locations.get(0).getLatitude();
    final double longitudeRef = locations.get(0).getLongitude();
    for (int i = 1; i < locations.size(); i++) {
      final double latitude = locations.get(i).getLatitude();
      final double longitude = locations.get(i).getLongitude();
      listY.add(calculateYSegment(latitudeRef, latitude, circumference));
      Log.d(LOG_TAG, String.format("Y %s: %s", listY.size() - 1, listY.get(listY.size() - 1)));
      listX.add(calculateXSegment(longitudeRef, longitude, latitude, circumference));
      Log.d(LOG_TAG, String.format("X %s: %s", listX.size() - 1, listX.get(listX.size() - 1)));
    }

    // calculate areas for each triangle segment
    for (int i = 1; i < listX.size(); i++) {
      final double x1 = listX.get(i - 1);
      final double y1 = listY.get(i - 1);
      final double x2 = listX.get(i);
      final double y2 = listY.get(i);
      listArea.add(calculateAreaInSquareMeters(x1, x2, y1, y2));
      Log.d(LOG_TAG, String.format("area %s: %s", listArea.size() - 1, listArea.get(listArea.size() - 1)));
    }

    // sum areas of all triangle segments
    double areasSum = 0;
    for (final Double area : listArea) {
      areasSum = areasSum + area;
    }

    // get abolute value of area, it can't be negative
    return Math.abs(areasSum);// Math.sqrt(areasSum * areasSum);
  }

  private static Double calculateAreaInSquareMeters(final double x1, final double x2, final double y1, final double y2) {
    return (y1 * x2 - x1 * y2) / 2;
  }

  private static double calculateYSegment(final double latitudeRef, final double latitude, final double circumference) {
    return (latitude - latitudeRef) * circumference / 360.0;
  }

  private static double calculateXSegment(final double longitudeRef, final double longitude, final double latitude,
      final double circumference) {
    return (longitude - longitudeRef) * circumference * Math.cos(Math.toRadians(latitude)) / 360.0;
  }
</code>```

I could also use the following polygon which is static if calculating the area of the drawn polygon is not possible.

```<code>Polygon UCCpolygon = map.addPolygon(new PolygonOptions()
    .add(new LatLng(51.893728, -8.491865),
         new LatLng(51.893550, -8.492479),
         new LatLng(51.893216, -8.492224),
         new LatLng(51.893404, -8.491598))
 .strokeColor(Color.RED)
 .fillColor(Color.BLUE));
</code>```

Thanks for the help!

Sean

答:
If you want to use SphericalUtils code without any library, you can use following code. it's taken from opensource code from SphericalUtils.java and other class. I have taken this code and used it as i was using MapBox and MapBox does not have implemented the calculateArea function in Turf.</p>

```<code>import java.util.List;

import pojo.LatLng;

import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.tan;
import static java.lang.Math.toRadians;

public class PolygonUtils {

    /**
     * The earth's radius, in meters.
     * Mean radius as defined by IUGG.
     */
    static final double EARTH_RADIUS = 6371009;

    /**
     * Returns the area of a closed path on Earth.
     * @param path A closed path.
     * @return The path's area in square meters.
     */
    public static double computeArea(List<LatLng> path) {
        return abs(computeSignedArea(path,EARTH_RADIUS));
    }

    /**
     * Returns the signed area of a closed path on a sphere of given radius.
     * The computed area uses the same units as the radius squared.
     * Used by SphericalUtilTest.
     */
    static double computeSignedArea(List<LatLng> path, double radius) {
        int size = path.size();
        if (size < 3) { return 0; }
        double total = 0;
        LatLng prev = path.get(size - 1);
        double prevTanLat = tan((PI / 2 - toRadians(prev.getLatitude())) / 2);
        double prevLng = toRadians(prev.getLongitude());
        // For each edge, accumulate the signed area of the triangle formed by the North Pole
        // and that edge ("polar triangle").
        for (LatLng point : path) {
            double tanLat = tan((PI / 2 - toRadians(point.getLatitude())) / 2);
            double lng = toRadians(point.getLongitude());
            total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
            prevTanLat = tanLat;
            prevLng = lng;
        }
        return total * (radius * radius);
    }

    /**
     * Returns the signed area of a triangle which has North Pole as a vertex.
     * Formula derived from "Area of a spherical triangle given two edges and the included angle"
     * as per "Spherical Trigonometry" by Todhunter, page 71, section 103, point 2.
     * See http://books.google.com/books?id=3uBHAAAAIAAJ&pg=PA71
     * The arguments named "tan" are tan((pi/2 - latitude)/2).
     */
    private static double polarTriangleArea(double tan1, double lng1, double tan2, double lng2) {
        double deltaLng = lng1 - lng2;
        double t = tan1 * tan2;
        return 2 * atan2(t * sin(deltaLng), 1 + t * cos(deltaLng));
    }
}
</code>```

Body:
I would like to calculate the are of a polygon drawn in a map fragment for a college project.

This is how I draw my polygon.

@Override
    public void onMapClick(LatLng point) {
        //tvLocInfo.setText("New marker added@" + point.toString());
        map.addMarker(new MarkerOptions().position(point).draggable(true).title(point.toString()));

        markerClicked = false;
    }

    @Override
    public void onMapLongClick(LatLng point) {
        //tvLocInfo.setText("New marker added@" + point.toString());
        map.clear();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {

        if(markerClicked){

            if(polygon != null){
                polygon.remove();
                polygon = null;
            }

            polygonOptions.add(marker.getPosition());
            polygonOptions.strokeColor(Color.RED);
            polygonOptions.fillColor(Color.BLUE);
            polygon = map.addPolygon(polygonOptions);
            //Area = google.maps.geometry.spherical.computeArea(polygon.getPath().getArray());
        }else{
            if(polygon != null){
                polygon.remove();
                polygon = null;
            }

            polygonOptions = new PolygonOptions().add(marker.getPosition());
            markerClicked = true;
        }

I have seen this code on how to calculate the area but I am unsure how to implement it in my application and calculate the area of my polygon.

I use this code to calculate an area of a GPS with Android:

  private static final double EARTH_RADIUS = 6371000;// meters

  public static double calculateAreaOfGPSPolygonOnEarthInSquareMeters(final List<Location> locations) {
    return calculateAreaOfGPSPolygonOnSphereInSquareMeters(locations, EARTH_RADIUS);
  }

  private static double calculateAreaOfGPSPolygonOnSphereInSquareMeters(final List<Location> locations, final double radius) {
    if (locations.size() < 3) {
      return 0;
    }

    final double diameter = radius * 2;
    final double circumference = diameter * Math.PI;
    final List<Double> listY = new ArrayList<Double>();
    final List<Double> listX = new ArrayList<Double>();
    final List<Double> listArea = new ArrayList<Double>();
    // calculate segment x and y in degrees for each point
    final double latitudeRef = locations.get(0).getLatitude();
    final double longitudeRef = locations.get(0).getLongitude();
    for (int i = 1; i < locations.size(); i++) {
      final double latitude = locations.get(i).getLatitude();
      final double longitude = locations.get(i).getLongitude();
      listY.add(calculateYSegment(latitudeRef, latitude, circumference));
      Log.d(LOG_TAG, String.format("Y %s: %s", listY.size() - 1, listY.get(listY.size() - 1)));
      listX.add(calculateXSegment(longitudeRef, longitude, latitude, circumference));
      Log.d(LOG_TAG, String.format("X %s: %s", listX.size() - 1, listX.get(listX.size() - 1)));
    }

    // calculate areas for each triangle segment
    for (int i = 1; i < listX.size(); i++) {
      final double x1 = listX.get(i - 1);
      final double y1 = listY.get(i - 1);
      final double x2 = listX.get(i);
      final double y2 = listY.get(i);
      listArea.add(calculateAreaInSquareMeters(x1, x2, y1, y2));
      Log.d(LOG_TAG, String.format("area %s: %s", listArea.size() - 1, listArea.get(listArea.size() - 1)));
    }

    // sum areas of all triangle segments
    double areasSum = 0;
    for (final Double area : listArea) {
      areasSum = areasSum + area;
    }

    // get abolute value of area, it can't be negative
    return Math.abs(areasSum);// Math.sqrt(areasSum * areasSum);
  }

  private static Double calculateAreaInSquareMeters(final double x1, final double x2, final double y1, final double y2) {
    return (y1 * x2 - x1 * y2) / 2;
  }

  private static double calculateYSegment(final double latitudeRef, final double latitude, final double circumference) {
    return (latitude - latitudeRef) * circumference / 360.0;
  }

  private static double calculateXSegment(final double longitudeRef, final double longitude, final double latitude,
      final double circumference) {
    return (longitude - longitudeRef) * circumference * Math.cos(Math.toRadians(latitude)) / 360.0;
  }

I could also use the following polygon which is static if calculating the area of the drawn polygon is not possible.

Polygon UCCpolygon = map.addPolygon(new PolygonOptions()
    .add(new LatLng(51.893728, -8.491865),
         new LatLng(51.893550, -8.492479),
         new LatLng(51.893216, -8.492224),
         new LatLng(51.893404, -8.491598))
 .strokeColor(Color.RED)
 .fillColor(Color.BLUE));

Thanks for the help!

Sean

Body:
If you want to use SphericalUtils code without any library, you can use following code. it's taken from opensource code from SphericalUtils.java and other class. I have taken this code and used it as i was using MapBox and MapBox does not have implemented the calculateArea function in Turf.

import java.util.List;

import pojo.LatLng;

import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.tan;
import static java.lang.Math.toRadians;

public class PolygonUtils {

    /**
     * The earth's radius, in meters.
     * Mean radius as defined by IUGG.
     */
    static final double EARTH_RADIUS = 6371009;

    /**
     * Returns the area of a closed path on Earth.
     * @param path A closed path.
     * @return The path's area in square meters.
     */
    public static double computeArea(List<LatLng> path) {
        return abs(computeSignedArea(path,EARTH_RADIUS));
    }

    /**
     * Returns the signed area of a closed path on a sphere of given radius.
     * The computed area uses the same units as the radius squared.
     * Used by SphericalUtilTest.
     */
    static double computeSignedArea(List<LatLng> path, double radius) {
        int size = path.size();
        if (size < 3) { return 0; }
        double total = 0;
        LatLng prev = path.get(size - 1);
        double prevTanLat = tan((PI / 2 - toRadians(prev.getLatitude())) / 2);
        double prevLng = toRadians(prev.getLongitude());
        // For each edge, accumulate the signed area of the triangle formed by the North Pole
        // and that edge ("polar triangle").
        for (LatLng point : path) {
            double tanLat = tan((PI / 2 - toRadians(point.getLatitude())) / 2);
            double lng = toRadians(point.getLongitude());
            total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
            prevTanLat = tanLat;
            prevLng = lng;
        }
        return total * (radius * radius);
    }

    /**
     * Returns the signed area of a triangle which has North Pole as a vertex.
     * Formula derived from "Area of a spherical triangle given two edges and the included angle"
     * as per "Spherical Trigonometry" by Todhunter, page 71, section 103, point 2.
     * See http://books.google.com/books?id=3uBHAAAAIAAJ&pg=PA71
     * The arguments named "tan" are tan((pi/2 - latitude)/2).
     */
    private static double polarTriangleArea(double tan1, double lng1, double tan2, double lng2) {
        double deltaLng = lng1 - lng2;
        double t = tan1 * tan2;
        return 2 * atan2(t * sin(deltaLng), 1 + t * cos(deltaLng));
    }
}