问:
TinyMCE disappears in Blazor page
I want to use TinyMCE in a Blazor server side app, but it shows up on page load for a second and then disappears. I blame it on StatehasChanged() thus I have written an interop function that re-initializes TinyMCE and is called in the OnAfterRender() of the page.

This is the JS interop function:

initTinyMce: function (tinyMceID) {
    tinymce.init({
        selector: 'textarea.tinyMce'
    });
    return "";

    //var editor = tinyMCE.get(tinyMceID);
    //if (editor && editor instanceof tinymce.Editor) {
    //    editor.init();
    //}
}
```

<p>In the <code>OnAfterRender</code> I call it like so:</p>

<pre class="lang-cs prettyprint-override"><code>protected override void OnAfterRender() {

    base.OnAfterRender();
    string a = jsInterop.InitTinyMce("myTinyMce").Result;
}
</code>```

But still it disappears a second after it shows itself. How to fix this problem?

答:
I wasn't able to get it to mimic this behaviour so maybe you were using a different version of tinyMce and Blazor. I'm using TinyMce 5.3.1 and .Net Core 3.1. I see you switched to using SyncFusion but maybe this answer will help anyone else who comes along here looking to try to do this in Blazor like I was yesterday.

I think the main thing is disposing of the element when you navigate away and re-initializing when it comes into view / focus / is loaded / etc...

Here's a component that I put together last night that should take care of all the pieces and make it bind-able like a regular <InputTextArea>

I'm new to Blazor and components. This is the second bind-able form control I've made. If anyone has any comments or suggestions on how this could be better please edit or let me know and I can update. Thanks!

In the JS block in _Host.html (i'm using a local version of TinyMCE)

```<code><script src="/js/tinymce/tinymce.min.js"></script>
</code>```

/Shared/Components/Textarea.razor

```<code><textarea id="@Id" @bind-value="Value" @bind-value:event="onchange" />
</code>```

/Shared/Components/Textarea.razor.cs:

```<code>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.JSInterop;

namespace Application.Shared.Components
{
    public partial class Textarea : ComponentBase, IDisposable
    {
        [Inject] private IJSRuntime JSRuntime { get; set; }

        [Parameter] public RenderFragment ChildContent { get; set; }

        [Parameter] public string Value { get; set; }

        [Parameter] public EventCallback<string> ValueChanged { get; set; }

        [Parameter] public string Id { get; set; } = null;

        private DotNetObjectReference<Textarea> _elementRef;

        [Parameter] public MenuModeEnum MenuMode { get; set; } = MenuModeEnum.standard;

        protected string FieldClass => GivenEditContext?.FieldCssClass(FieldIdentifier) ?? string.Empty;

        protected EditContext GivenEditContext { get; set; }

        protected FieldIdentifier FieldIdentifier { get; set; }

        protected string CurrentValue
        {
            get => Value;
            set
            {
                var hasChanged = !EqualityComparer<string>.Default.Equals(value, Value);
                if (!hasChanged) return;

                _ = value;

                Value = value;
                _ = ValueChanged.InvokeAsync(value);
                GivenEditContext?.NotifyFieldChanged(FieldIdentifier);
            }
        }

        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            this.Id = Id ?? Guid.NewGuid().ToString();
            _elementRef = DotNetObjectReference.Create(this);
        }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                await JSRuntime.InvokeVoidAsync("TinyMce.init", Id, Enum.GetName(typeof(MenuModeEnum), MenuMode), _elementRef);
            }
        }

        [JSInvokable("textArea_OnChange")]
        public void Change(string value)
        {
            CurrentValue = value;
        }

        protected virtual void Dispose(bool disposing)
        {
            JSRuntime.InvokeVoidAsync("TinyMce.dispose", Id, _elementRef);
        }

        void IDisposable.Dispose()
        {
            Dispose(disposing: true);
        }

        internal void DismissInstance()
        {
            JSRuntime.InvokeVoidAsync("TinyMce.dispose", Id, _elementRef);
            StateHasChanged();
        }
    }
}
</code>```

/Shared/Components/Enums/MenuModeEnum.cs:

```<code>namespace Application.Shared.Components.Enums
{
    public enum MenuModeEnum
    {
        standard,
        minimal,
        grouped,
        bloated
    }
}
</code>```

/wwwroot/js/site.js:

```<code>if (!window.TinyMce) {
    window.TinyMce = {};
}

window.TinyMce = {
    params : {
        standard: {
            plugins: 'code codesample link image autolink lists media paste table table spellchecker',
            toolbar1: 'undo redo | paste | removeformat styleselect | bold italic | alignleft aligncenter alignright alignjustify | outdent indent | link image media codesample | table | code | spellchecker',
            menubar: false,
            branding: false,
            toolbar_mode: 'floating'
        },
        minimal: {
            toolbar1: 'bold italic underline',
            menubar: false,
            branding: false,
            toolbar_mode: 'floating'
        },
        grouped: {
            plugins: "emoticons hr image link lists charmap table",
            toolbar: "formatgroup paragraphgroup insertgroup",
            toolbar_groups: {
                formatgroup: {
                    icon: 'format',
                    tooltip: 'Formatting',
                    items: 'bold italic underline strikethrough | forecolor backcolor | superscript subscript | removeformat'
                },
                paragraphgroup: {
                    icon: 'paragraph',
                    tooltip: 'Paragraph format',
                    items: 'h1 h2 h3 | bullist numlist | alignleft aligncenter alignright alignjustify | indent outdent'
                },
                insertgroup: {
                    icon: 'plus',
                    tooltip: 'Insert',
                    items: 'link image emoticons charmap hr'
                }
            },
            menubar: false,
            branding: false
        },
        bloated: {
            plugins: 'code codesample link image autolink lists media paste table table spellchecker',
            toolbar1: 'undo redo | styleselect | forecolor | bold italic underline strikethrough | link image media codesample | table | code | spellchecker',
            toolbar2: 'h1 h2 h3 | bullist numlist | alignleft aligncenter alignright alignjustify | outdent indent | emoticons charmap hr',
            menubar: false,
            branding: false,
            toolbar_mode: 'floating'
        }
    },
    init: function (id, mode, dotnetHelper) {
        var params = window.TinyMce.params[mode];
        params.selector = '#' + id;

        params.setup = function (editor) {
            editor.on('change', function (e) {
                console.log($('#' + id).val());
                $('#' + id).val(editor.getContent());
                $('#' + id).change();
                console.log($('#' + id).val());
                dotnetHelper.invokeMethodAsync("textArea_OnChange", $('#' + id).val());
            });
        }

        tinymce.init(params);
    },
    dispose: function (id, dotnetHelper) {
        tinymce.remove('#' + id);
    }
};
</code>```

Usage:

```<code><Textarea MenuMode="@MenuModeEnum.minimal" @bind-Value="@SomeObject.Comments" />
</code>```

Title: TinyMCE disappears in Blazor page

Body:
I want to use TinyMCE in a Blazor server side app, but it shows up on page load for a second and then disappears. I blame it on StatehasChanged() thus I have written an interop function that re-initializes TinyMCE and is called in the OnAfterRender() of the page.

This is the JS interop function:

initTinyMce: function (tinyMceID) {
    tinymce.init({
        selector: 'textarea.tinyMce'
    });
    return "";

    //var editor = tinyMCE.get(tinyMceID);
    //if (editor && editor instanceof tinymce.Editor) {
    //    editor.init();
    //}
}

In the OnAfterRender I call it like so:

protected override void OnAfterRender() {

    base.OnAfterRender();
    string a = jsInterop.InitTinyMce("myTinyMce").Result;
}

But still it disappears a second after it shows itself. How to fix this problem?

Body:
I wasn't able to get it to mimic this behaviour so maybe you were using a different version of tinyMce and Blazor. I'm using TinyMce 5.3.1 and .Net Core 3.1. I see you switched to using SyncFusion but maybe this answer will help anyone else who comes along here looking to try to do this in Blazor like I was yesterday.

I think the main thing is disposing of the element when you navigate away and re-initializing when it comes into view / focus / is loaded / etc...

Here's a component that I put together last night that should take care of all the pieces and make it bind-able like a regular <InputTextArea>

I'm new to Blazor and components. This is the second bind-able form control I've made. If anyone has any comments or suggestions on how this could be better please edit or let me know and I can update. Thanks!

In the JS block in _Host.html (i'm using a local version of TinyMCE)

<script src="/js/tinymce/tinymce.min.js"></script>

/Shared/Components/Textarea.razor

<textarea id="@Id" @bind-value="Value" @bind-value:event="onchange" />

/Shared/Components/Textarea.razor.cs:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.JSInterop;

namespace Application.Shared.Components
{
    public partial class Textarea : ComponentBase, IDisposable
    {
        [Inject] private IJSRuntime JSRuntime { get; set; }

        [Parameter] public RenderFragment ChildContent { get; set; }

        [Parameter] public string Value { get; set; }

        [Parameter] public EventCallback<string> ValueChanged { get; set; }

        [Parameter] public string Id { get; set; } = null;

        private DotNetObjectReference<Textarea> _elementRef;

        [Parameter] public MenuModeEnum MenuMode { get; set; } = MenuModeEnum.standard;

        protected string FieldClass => GivenEditContext?.FieldCssClass(FieldIdentifier) ?? string.Empty;

        protected EditContext GivenEditContext { get; set; }

        protected FieldIdentifier FieldIdentifier { get; set; }

        protected string CurrentValue
        {
            get => Value;
            set
            {
                var hasChanged = !EqualityComparer<string>.Default.Equals(value, Value);
                if (!hasChanged) return;

                _ = value;

                Value = value;
                _ = ValueChanged.InvokeAsync(value);
                GivenEditContext?.NotifyFieldChanged(FieldIdentifier);
            }
        }

        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            this.Id = Id ?? Guid.NewGuid().ToString();
            _elementRef = DotNetObjectReference.Create(this);
        }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                await JSRuntime.InvokeVoidAsync("TinyMce.init", Id, Enum.GetName(typeof(MenuModeEnum), MenuMode), _elementRef);
            }
        }

        [JSInvokable("textArea_OnChange")]
        public void Change(string value)
        {
            CurrentValue = value;
        }

        protected virtual void Dispose(bool disposing)
        {
            JSRuntime.InvokeVoidAsync("TinyMce.dispose", Id, _elementRef);
        }

        void IDisposable.Dispose()
        {
            Dispose(disposing: true);
        }

        internal void DismissInstance()
        {
            JSRuntime.InvokeVoidAsync("TinyMce.dispose", Id, _elementRef);
            StateHasChanged();
        }
    }
}

/Shared/Components/Enums/MenuModeEnum.cs:

namespace Application.Shared.Components.Enums
{
    public enum MenuModeEnum
    {
        standard,
        minimal,
        grouped,
        bloated
    }
}

/wwwroot/js/site.js:

if (!window.TinyMce) {
    window.TinyMce = {};
}

window.TinyMce = {
    params : {
        standard: {
            plugins: 'code codesample link image autolink lists media paste table table spellchecker',
            toolbar1: 'undo redo | paste | removeformat styleselect | bold italic | alignleft aligncenter alignright alignjustify | outdent indent | link image media codesample | table | code | spellchecker',
            menubar: false,
            branding: false,
            toolbar_mode: 'floating'
        },
        minimal: {
            toolbar1: 'bold italic underline',
            menubar: false,
            branding: false,
            toolbar_mode: 'floating'
        },
        grouped: {
            plugins: "emoticons hr image link lists charmap table",
            toolbar: "formatgroup paragraphgroup insertgroup",
            toolbar_groups: {
                formatgroup: {
                    icon: 'format',
                    tooltip: 'Formatting',
                    items: 'bold italic underline strikethrough | forecolor backcolor | superscript subscript | removeformat'
                },
                paragraphgroup: {
                    icon: 'paragraph',
                    tooltip: 'Paragraph format',
                    items: 'h1 h2 h3 | bullist numlist | alignleft aligncenter alignright alignjustify | indent outdent'
                },
                insertgroup: {
                    icon: 'plus',
                    tooltip: 'Insert',
                    items: 'link image emoticons charmap hr'
                }
            },
            menubar: false,
            branding: false
        },
        bloated: {
            plugins: 'code codesample link image autolink lists media paste table table spellchecker',
            toolbar1: 'undo redo | styleselect | forecolor | bold italic underline strikethrough | link image media codesample | table | code | spellchecker',
            toolbar2: 'h1 h2 h3 | bullist numlist | alignleft aligncenter alignright alignjustify | outdent indent | emoticons charmap hr',
            menubar: false,
            branding: false,
            toolbar_mode: 'floating'
        }
    },
    init: function (id, mode, dotnetHelper) {
        var params = window.TinyMce.params[mode];
        params.selector = '#' + id;

        params.setup = function (editor) {
            editor.on('change', function (e) {
                console.log($('#' + id).val());
                $('#' + id).val(editor.getContent());
                $('#' + id).change();
                console.log($('#' + id).val());
                dotnetHelper.invokeMethodAsync("textArea_OnChange", $('#' + id).val());
            });
        }

        tinymce.init(params);
    },
    dispose: function (id, dotnetHelper) {
        tinymce.remove('#' + id);
    }
};

Usage:

<Textarea MenuMode="@MenuModeEnum.minimal" @bind-Value="@SomeObject.Comments" />


来源: stackexchange

问:
Function in getting the less than equal in the list and removing the duplicates
I need to count how many less than or equal numbers in the list and disregarding the duplicates.

```<code>def getVal(prices = [5,5,10], money = 5):
        count = 0
        for i in prices:
            if money >= i and money == i:
                count += 1
        return count
</code>```

the output of this code is:
2

How can I get the output of 1.

答:
Convert your list into a set, and all the duplicate will be removed automatically:

```<code>def getVal(prices = [5,5,10], money = 5):
        count = 0
        for i in set(prices): # Add set() around the list to convert
            if money >= i:
                count += 1
        return count
print(getVal())
</code>```

Output:

```<code>1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to count how many less than or equal numbers in the list and disregarding the duplicates.

def getVal(prices = [5,5,10], money = 5):
        count = 0
        for i in prices:
            if money >= i and money == i:
                count += 1
        return count

the output of this code is:
2

How can I get the output of 1.

Body:
Convert your list into a set, and all the duplicate will be removed automatically:

def getVal(prices = [5,5,10], money = 5):
        count = 0
        for i in set(prices): # Add set() around the list to convert
            if money >= i:
                count += 1
        return count
print(getVal())

Output:

1


问:
What is an elastic network interface (ENI) and when would you use it?
An elastic network interface is defined as a virtual network interface https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ElasticNetworkInterfaces.html.

I was wondering what use cases exist of this. Why would not I simply put directly an instance instead of having to use the eni, and attach it to an instance.

Thks!

答:
Decoupling the ENI from the EC2 instance allows you far more flexibility.

You can connect several ENIs to the same EC2 instance and be attached to different subnets, for example:

ENI A connected to a public-facing subnet

ENI B connected to an internal private subnet

You could, for example, attach an ENI to a running EC2 instance, or you could have it live after the EC2 instance is deleted.

As a form of "cheap" high availability: Attach a ENI to an EC2 instance; if the instance dies launch another one and attach the ENI to it. Traffic flow will only be interrupted for a short period.

There are many scenarios where this flexibility comes in handy.


问:
How to Remove Duplicate Rows in Laravel
I need to delete duplicated rows for specified Mobile Number on a mysql table. How can I do this with an Laravel query?</p>

答:
You could also try to map out all of the phone numbers within the entries and if the number comes up again, you delete it.

For example:

```<code>$allContacts = Contact::all()->map->only(['mobile', 'id']);

$uniqueContacts = [];

foreach ($allContacts as $contact) {
    if (in_array($contact['mobile'], $uniqueContacts)) {
        Contact::where('id', $contact['id'])->delete();
    } else {
        array_push($uniqueContacts, $contact['mobile']);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to Remove Duplicate Rows in Laravel

Body:
You could also try to map out all of the phone numbers within the entries and if the number comes up again, you delete it.

For example:

$allContacts = Contact::all()->map->only(['mobile', 'id']);

$uniqueContacts = [];

foreach ($allContacts as $contact) {
    if (in_array($contact['mobile'], $uniqueContacts)) {
        Contact::where('id', $contact['id'])->delete();
    } else {
        array_push($uniqueContacts, $contact['mobile']);
    }
}


问:
generating and mapping two sets of numbers
I have 2 numbers 25798709 and 25716544 representing the minimum and maximum values of some consecutive numbers with each number differing from the preceeding number by one eg. 25798709,25798710, 25798711................25716544  I want a python code that will convert these figures to 1,2,3,4,5,.............. and map the 1,2,3,4,5 to the original figures in two columns:
Like: </p>

```<code>  1     25798709
  2     25798710
  3     25798711
</code>```

答:
This would work and start from 1:

```<code>for idx, num in enumerate(range(25716544, 25798709), 1):
  print idx, ' ', num
</code>```

To start from 0:

```<code>for idx, num in enumerate(range(25716544, 25798709)):
  print idx, ' ', num
</code>```

Body:
I have 2 numbers 25798709 and 25716544 representing the minimum and maximum values of some consecutive numbers with each number differing from the preceeding number by one eg. 25798709,25798710, 25798711................25716544  I want a python code that will convert these figures to 1,2,3,4,5,.............. and map the 1,2,3,4,5 to the original figures in two columns:
Like:

  1     25798709
  2     25798710
  3     25798711

Body:
This would work and start from 1:

for idx, num in enumerate(range(25716544, 25798709), 1):
  print idx, ' ', num

To start from 0:

for idx, num in enumerate(range(25716544, 25798709)):
  print idx, ' ', num


问:
Regular expression to handle two different file extensions
I am trying to create a regular expression that takes a file of name
"abcd_04-04-2020.txt" or "abcd_04-04-2020.txt.gz"

How can I handle the "OR" condition for the extension. This is what I have so far

```<code>if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3})")){
    Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}
</code>```

This handles only the .txt. How can I handle ".txt.gz"
Thanks

答:
A possible way of doing it:

Pattern pattern = Pattern.compile("^[\\w._-]+_\\d{2}-\\d{2}-\\d{4}(\\.txt(\\.gz)?)$");
```

<p>Then you can run the following test:</p>

<pre class="lang-java prettyprint-override"><code>String[] fileNames = {
        "abcd_04-04-2020.txt",
        "abcd_04-04-2020.tar",
        "abcd_04-04-2020.txt.gz",
        "abcd_04-04-2020.png",
        ".txt",
        ".txt.gz",
        "04-04-2020.txt"
};

Arrays.stream(fileNames)
        .filter(fileName -> pattern.matcher(fileName).find())
        .forEach(System.out::println);

// output
// abcd_04-04-2020.txt
// abcd_04-04-2020.txt.gz
</code>```

Body:
I am trying to create a regular expression that takes a file of name
"abcd_04-04-2020.txt" or "abcd_04-04-2020.txt.gz"

How can I handle the "OR" condition for the extension. This is what I have so far

if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3})")){
    Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}

This handles only the .txt. How can I handle ".txt.gz"
Thanks

Body:
A possible way of doing it:

Pattern pattern = Pattern.compile("^[\\w._-]+_\\d{2}-\\d{2}-\\d{4}(\\.txt(\\.gz)?)$");

Then you can run the following test:

String[] fileNames = {
        "abcd_04-04-2020.txt",
        "abcd_04-04-2020.tar",
        "abcd_04-04-2020.txt.gz",
        "abcd_04-04-2020.png",
        ".txt",
        ".txt.gz",
        "04-04-2020.txt"
};

Arrays.stream(fileNames)
        .filter(fileName -> pattern.matcher(fileName).find())
        .forEach(System.out::println);

// output
// abcd_04-04-2020.txt
// abcd_04-04-2020.txt.gz


问:
Grakn rule that matches on a super-relation failing to find matching instance of its subrelation
I have a Grakn schema fragment for modelling an in-game 'research tree' that looks like this:

```<code># Entities
research-project sub entity,
    has name,
    plays research-task,
    plays required-tech,
    plays research-to-begin;

campaign sub entity,
    has name,
    plays campaign-with-tasks;

# Relations
requirement sub relation,
    abstract,
    relates prerequisite,
    relates outcome,
    plays task;

tech-requirement sub requirement,
    abstract,
    relates required-tech as prerequisite,
    relates outcome;

tech-requirement-to-begin-task sub tech-requirement,
    abstract,
    relates required-tech as prerequisite,
    relates task-to-begin as outcome;

tech-requirement-to-begin-research sub tech-requirement-to-begin-task,
    relates required-tech as prerequisite,
    relates research-to-begin as outcome;

campaign-task sub relation,
    abstract,
    relates campaign-with-tasks,
    relates task,
    has started,
    has progress,
    has can-proceed,
    has completed;

campaign-research-task sub campaign-task,
    relates campaign-with-tasks,
    relates research-task as task;
</code>```

The property can-proceed of campaign-task is governed by a set of rules, one of which is the following:

```<code>when {
    $campaign isa campaign;
    $campaign_task($campaign, task: $task) isa campaign-task, has completed false;
    not {
        (task-to-begin: $task, required-tech: $prerequisite) isa tech-requirement-to-begin-task;
        ($campaign, $prerequisite) isa campaign-task, has completed false;
    };
}, then {
    $campaign_task has can-proceed true;
};
</code>```

Each prerequisite is modelled using a tech-requirement-to-begin-research relation, which is a subrelation of the abstract tech-requirement-to-begin-task.

Expected outcome: it should mark a campaign-task as having can-proceed = true only if it has NO prerequisite campaign-tasks that are not completed.

Actual outcome: it does not detect the tech-requirement-to-begin-research instances, and simply marks all campaign-tasks with can-proceed = true, even if they have unfulfilled prerequisites.

If I change the rule by replacing task-to-begin with research-to-begin, AND tech-requirement-to-begin-task with tech-requirement-to-begin-research, then the rule correctly applies only to tasks that have no unmet prerequisites. However, doing so loses generality, and will require rewriting the rule for every subrelation of tech-requirement-to-begin-task, resulting in a lot of code duplication.

What is the expected behaviour in this case and what is the best way to resolve the issue?

答: I believe that your expected outcome is correct - the rule should apply the negation over tech-requirement-to-begin-task and its subtypes (including tech-requirement-to-begin-research). Therefore, the best way to resolve this is to open an issue on the Grakn repo and have this behaviour fixed in Grakn's reasoner!

Body:
I have a Grakn schema fragment for modelling an in-game 'research tree' that looks like this:

# Entities
research-project sub entity,
    has name,
    plays research-task,
    plays required-tech,
    plays research-to-begin;

campaign sub entity,
    has name,
    plays campaign-with-tasks;

# Relations
requirement sub relation,
    abstract,
    relates prerequisite,
    relates outcome,
    plays task;

tech-requirement sub requirement,
    abstract,
    relates required-tech as prerequisite,
    relates outcome;

tech-requirement-to-begin-task sub tech-requirement,
    abstract,
    relates required-tech as prerequisite,
    relates task-to-begin as outcome;

tech-requirement-to-begin-research sub tech-requirement-to-begin-task,
    relates required-tech as prerequisite,
    relates research-to-begin as outcome;

campaign-task sub relation,
    abstract,
    relates campaign-with-tasks,
    relates task,
    has started,
    has progress,
    has can-proceed,
    has completed;

campaign-research-task sub campaign-task,
    relates campaign-with-tasks,
    relates research-task as task;

The property can-proceed of campaign-task is governed by a set of rules, one of which is the following:

when {
    $campaign isa campaign;
    $campaign_task($campaign, task: $task) isa campaign-task, has completed false;
    not {
        (task-to-begin: $task, required-tech: $prerequisite) isa tech-requirement-to-begin-task;
        ($campaign, $prerequisite) isa campaign-task, has completed false;
    };
}, then {
    $campaign_task has can-proceed true;
};

Each prerequisite is modelled using a tech-requirement-to-begin-research relation, which is a subrelation of the abstract tech-requirement-to-begin-task.

Expected outcome: it should mark a campaign-task as having can-proceed = true only if it has NO prerequisite campaign-tasks that are not completed.

Actual outcome: it does not detect the tech-requirement-to-begin-research instances, and simply marks all campaign-tasks with can-proceed = true, even if they have unfulfilled prerequisites.

If I change the rule by replacing task-to-begin with research-to-begin, AND tech-requirement-to-begin-task with tech-requirement-to-begin-research, then the rule correctly applies only to tasks that have no unmet prerequisites. However, doing so loses generality, and will require rewriting the rule for every subrelation of tech-requirement-to-begin-task, resulting in a lot of code duplication.

What is the expected behaviour in this case and what is the best way to resolve the issue?


问:
Modifying System Theme of AOSP ( Android-Source ) for Automotive
I need to customize the System Theme of Android Automotive, when i check the developer guide i could find that AOSP supports that and as per the developer site it is mentioned like

"OEM's are expected to have a parallel overlay structure to the
  car_product directory in their vendor directory that further extends
  the car_product overlay."

I need to create an overlay structure like the car_product in the vendor directory , Could anybody guide me to create the same . I have tried some methods mentioned in the sites , but these are not the same as mentioned in the developer site.

答:
What you are looking for are static resource overlay (different than Runtime Resource Overlays).
Take a look at the system UI section of the android automotive documentation. It explains more how to use the resource overlay.

This Stack overflow question is also giving some details.


问:
Call async functions in build method flutter
I need to get the text wrote inside a ".txt" file, save it in a variable and give it to a Text, inside a TextField.
The idea is to write the user input in a ".txt" file so he can read what he wrote when needed on the TextField.

All works, when I read the file it takes the right content but when I store it in a variable to use it Text(var_name...) well what I read on the screen is "Instance of 'Future'".

I know this problem comes from a bad handling of async and future but I would like to really understand why this isn't working.

This is my code :

```<code>Future<String> get _localPath async {
 final directory = await getApplicationDocumentsDirectory();
 return directory.path;
}

Future<File> get _localBio async {
 final path = await _localPath;
 print(path);
 return File('$path/bio.txt');
}

Future<File> _write(String text, String filename) async {
final file = await _localBio;

// Write the file.
return file.writeAsString(text);
}

Future<String> _read() async {
  try {
    final file = await _localBio;
     String body = await file.readAsString();
  // Read the file.
    return body;
  } catch (e) {
  // If encountering an error, return 0.
    return "Can't read";
  }
}

Future<String>_MyRead() async {
 String read_ = await _read();
 print(read_);
 return read_;
}
</code>```

Please write a full answer, I tried a lots of video, forums...Don't just tell me to do var str= _MyRead().then((value) => value);
Maybe it can be the answer but please write 2 more lines because I want to understand why this isn't working.
I took the code from dev official documentation.

答:
you should use a FutureBuilder if you wanna render something that takes time (asynchronous)</p>

```<code>FutureBuilder(
 future:_myRead,
 builder: (ctx,snapshot) {
  if(snapshot.connectionState == connectionState.waiting) {
   return // your waiting Widget Ex: CircularLoadingIndicator();
} else if (snapshot.hasData) {
  return Text(snapshot.data.toString()); // toString() is just to be safe
} else { //probably an error occured
  return Text('Something went wrong ...');
}
</code>```

Body:
I need to get the text wrote inside a ".txt" file, save it in a variable and give it to a Text, inside a TextField.
The idea is to write the user input in a ".txt" file so he can read what he wrote when needed on the TextField.

All works, when I read the file it takes the right content but when I store it in a variable to use it Text(var_name...) well what I read on the screen is "Instance of 'Future'".

I know this problem comes from a bad handling of async and future but I would like to really understand why this isn't working.

This is my code :

Future<String> get _localPath async {
 final directory = await getApplicationDocumentsDirectory();
 return directory.path;
}

Future<File> get _localBio async {
 final path = await _localPath;
 print(path);
 return File('$path/bio.txt');
}

Future<File> _write(String text, String filename) async {
final file = await _localBio;

// Write the file.
return file.writeAsString(text);
}

Future<String> _read() async {
  try {
    final file = await _localBio;
     String body = await file.readAsString();
  // Read the file.
    return body;
  } catch (e) {
  // If encountering an error, return 0.
    return "Can't read";
  }
}

Future<String>_MyRead() async {
 String read_ = await _read();
 print(read_);
 return read_;
}

Please write a full answer, I tried a lots of video, forums...Don't just tell me to do var str= _MyRead().then((value) => value);
Maybe it can be the answer but please write 2 more lines because I want to understand why this isn't working.
I took the code from dev official documentation.

Body:
you should use a FutureBuilder if you wanna render something that takes time (asynchronous)

FutureBuilder(
 future:_myRead,
 builder: (ctx,snapshot) {
  if(snapshot.connectionState == connectionState.waiting) {
   return // your waiting Widget Ex: CircularLoadingIndicator();
} else if (snapshot.hasData) {
  return Text(snapshot.data.toString()); // toString() is just to be safe
} else { //probably an error occured
  return Text('Something went wrong ...');
}


问:
Automatic converting loops into streams in Eclipse
Is there a way to refactor a loop over collections into Collection.forEach using refactoring or code inspection (problem severity) using eclipse ?

example :
howto convert this :

```<code>for(Person person : personenListe) {
    System.out.println(person);
}
</code>```

into this :

```<code>personenListe.forEach(System.out::println);
</code>```

using a refactoring action in eclipse ?

答: It doesn't seem to exist yet but there is a bug created for it #431967</p>

Body:
Is there a way to refactor a loop over collections into Collection.forEach using refactoring or code inspection (problem severity) using eclipse ?

example :
howto convert this :

for(Person person : personenListe) {
    System.out.println(person);
}

into this :

personenListe.forEach(System.out::println);

using a refactoring action in eclipse ?


问:
Custom sorting query in KnpPaginatorBundle
I would like to sort items in KnpPaginatorBundle by a custom callback. Is it possible to hook to the Walker somehow?

I mean I want to sort by invoice number which should be something like:

```<code>3/5/2020
2/5/2020
1/5/2020
3/4/2020
2/4/2020
</code>```

instead of

```<code>3/5/2020
3/4/2020
2/5/2020
2/4/2020
1/5/2020
</code>```

答: Don't go this way. Try to make filter before paginate and done result use in pagination</p>

Body:
I would like to sort items in KnpPaginatorBundle by a custom callback. Is it possible to hook to the Walker somehow?

I mean I want to sort by invoice number which should be something like:

3/5/2020
2/5/2020
1/5/2020
3/4/2020
2/4/2020

instead of

3/5/2020
3/4/2020
2/5/2020
2/4/2020
1/5/2020


问:
Alamofire Swift 5 : Throws an error while passing parameter
My parameter value looks like this when it gets printed in the console due to which I get an error :

failure(Alamofire.AFError.responseSerializationFailed(reason:
  Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error:
  Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around
  character 0." UserInfo={NSDebugDescription=Invalid value around
  character 0.})))

```<code>["preparation_method[]": "[{\"method_stage\":\"0\",\"method_description\":\"This is test methof1\"}]", "recipe_id": "10454", "ingredients[]": "[{\"ingredient_unit_id\":\"Cup\",\"ingredient_item_id\":\"1\",\"ingredient_item\":\"Rice\",\"ingredient_remark\":\"\",\"ingredient_qty\":\"1\"},{\"ingredient_unit_id\":\"\",\"ingredient_item_id\":\"2\",\"ingredient_item\":\"\",\"ingredient_remark\":\"\",\"ingredient_qty\":\"\"},{\"ingredient_unit_id\":\"\",\"ingredient_item_id\":\"3\",\"ingredient_item\":\"\",\"ingredient_remark\":\"\",\"ingredient_qty\":\"\"}]"]
</code>```

the format in which the parameter should look like is given below:

```<code>["recipe_id" : "10454",
ingredients[]: [{"ingredient_unit_id":"Cup","ingredient_item_id":"1","ingredient_item":"Rice","ingredient_remark":"","ingredient_qty":"1"},
{"ingredient_unit_id":"","ingredient_item_id":"2","ingredient_item":"","ingredient_remark":"","ingredient_qty":""},
{"ingredient_unit_id":"","ingredient_item_id":"3","ingredient_item":"","ingredient_remark":"","ingredient_qty":""}],
 preparation_method[] :
[{"method_stage":"0","method_description":"This is test methof1"}] ]
</code>```

The code I have used is

```<code>let arr = ingredient.map({ Model(ingredient_item: $0,
                                  ingredient_item_id: $1,
                                  ingredient_qty: $2,
                                  ingredient_unit_id: $3,
                                  ingredient_remark: $4)})

        let jsonData = try! JSONEncoder().encode(arr)
        let jsonString = String(data: jsonData, encoding: .utf8)
        let ingredientstring = jsonString?.replacingOccurrences(of: "'\'" , with: "")
        let ingredientarrayvalue = "\(ingredientstring!)"
        print(ingredientarrayvalue)
        let ingredient_array = String(ingredientarrayvalue)

        let arr1 = prepatation.map({ Model1(method_stage: $0,
                                  method_description: $1)})

        let jsonData1 = try! JSONEncoder().encode(arr1)
        let jsonString1 = String(data: jsonData1, encoding: .utf8)
        let preparationstring = jsonString1?.replacingOccurrences(of: "'\'" , with: "")
        let preparationarrayvalue = "\(preparationstring!)"
        print(preparationarrayvalue)
        let preparation_array = String(preparationarrayvalue)

        let parameter = ["recipe_id" : recipevalue, "ingredients[]" : ingredient_array, "preparation_method[]" : preparationarrayvalue]
        print(parameter)

 let url = RECIPE.recipeSAVEURL
  AF.request(url, method: .post, parameters: parameter).responseJSON(completionHandler: {response in

            print(response)
            if let response_data = response.value as? NSDictionary{

                let responsestatus = response_data.value(forKey: "response") as! String
                print(responsestatus)

                if responsestatus == "success"{
                }
            }
        })
</code>```

How can I pass the parameter without "\" in the parameter?Can anyone help me with this?

答:
After tiring hours of searching for a solution to my above question, I came across the following github link : https://gist.github.com/cprovatas/5c9f51813bc784ef1d7fcbfb89de74fe

Where they uses an extension for data and I applied it as following in my code :

```<code>let preparation_array = jsonString1!.data(using: .utf8)!.prettyPrintedJSONString!
let ingredient_array = jsonString!.data(using: .utf8)!.prettyPrintedJSONString!
</code>```

the copy of the extension code used in the link mentioned above is given below for reference, if any:

```<code>extension Data {
    var prettyPrintedJSONString: NSString? { /// NSString gives us a nice sanitized debugDescription
        guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
              let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
              let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }

        return prettyPrintedString
    }
}

let str = "{\"foo\": \"bar\"}".data(using: .utf8)!.prettyPrintedJSONString!
debugPrint(str)
</code>```

/* prints:
     {
        "foo" : "bar"
     }

Body:
My parameter value looks like this when it gets printed in the console due to which I get an error :

failure(Alamofire.AFError.responseSerializationFailed(reason:
  Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error:
  Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around
  character 0." UserInfo={NSDebugDescription=Invalid value around
  character 0.})))

["preparation_method[]": "[{\"method_stage\":\"0\",\"method_description\":\"This is test methof1\"}]", "recipe_id": "10454", "ingredients[]": "[{\"ingredient_unit_id\":\"Cup\",\"ingredient_item_id\":\"1\",\"ingredient_item\":\"Rice\",\"ingredient_remark\":\"\",\"ingredient_qty\":\"1\"},{\"ingredient_unit_id\":\"\",\"ingredient_item_id\":\"2\",\"ingredient_item\":\"\",\"ingredient_remark\":\"\",\"ingredient_qty\":\"\"},{\"ingredient_unit_id\":\"\",\"ingredient_item_id\":\"3\",\"ingredient_item\":\"\",\"ingredient_remark\":\"\",\"ingredient_qty\":\"\"}]"]

the format in which the parameter should look like is given below:

["recipe_id" : "10454",
ingredients[]: [{"ingredient_unit_id":"Cup","ingredient_item_id":"1","ingredient_item":"Rice","ingredient_remark":"","ingredient_qty":"1"},
{"ingredient_unit_id":"","ingredient_item_id":"2","ingredient_item":"","ingredient_remark":"","ingredient_qty":""},
{"ingredient_unit_id":"","ingredient_item_id":"3","ingredient_item":"","ingredient_remark":"","ingredient_qty":""}],
 preparation_method[] :
[{"method_stage":"0","method_description":"This is test methof1"}] ]

The code I have used is

let arr = ingredient.map({ Model(ingredient_item: $0,
                                  ingredient_item_id: $1,
                                  ingredient_qty: $2,
                                  ingredient_unit_id: $3,
                                  ingredient_remark: $4)})

        let jsonData = try! JSONEncoder().encode(arr)
        let jsonString = String(data: jsonData, encoding: .utf8)
        let ingredientstring = jsonString?.replacingOccurrences(of: "'\'" , with: "")
        let ingredientarrayvalue = "\(ingredientstring!)"
        print(ingredientarrayvalue)
        let ingredient_array = String(ingredientarrayvalue)

        let arr1 = prepatation.map({ Model1(method_stage: $0,
                                  method_description: $1)})

        let jsonData1 = try! JSONEncoder().encode(arr1)
        let jsonString1 = String(data: jsonData1, encoding: .utf8)
        let preparationstring = jsonString1?.replacingOccurrences(of: "'\'" , with: "")
        let preparationarrayvalue = "\(preparationstring!)"
        print(preparationarrayvalue)
        let preparation_array = String(preparationarrayvalue)

        let parameter = ["recipe_id" : recipevalue, "ingredients[]" : ingredient_array, "preparation_method[]" : preparationarrayvalue]
        print(parameter)

 let url = RECIPE.recipeSAVEURL
  AF.request(url, method: .post, parameters: parameter).responseJSON(completionHandler: {response in

            print(response)
            if let response_data = response.value as? NSDictionary{

                let responsestatus = response_data.value(forKey: "response") as! String
                print(responsestatus)

                if responsestatus == "success"{
                }
            }
        })

How can I pass the parameter without "\" in the parameter?Can anyone help me with this?

Body:
After tiring hours of searching for a solution to my above question, I came across the following github link : https://gist.github.com/cprovatas/5c9f51813bc784ef1d7fcbfb89de74fe

Where they uses an extension for data and I applied it as following in my code :

let preparation_array = jsonString1!.data(using: .utf8)!.prettyPrintedJSONString!
let ingredient_array = jsonString!.data(using: .utf8)!.prettyPrintedJSONString!

the copy of the extension code used in the link mentioned above is given below for reference, if any:

extension Data {
    var prettyPrintedJSONString: NSString? { /// NSString gives us a nice sanitized debugDescription
        guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
              let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
              let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }

        return prettyPrintedString
    }
}

let str = "{\"foo\": \"bar\"}".data(using: .utf8)!.prettyPrintedJSONString!
debugPrint(str)

/* prints:
     {
        "foo" : "bar"
     }


问:
insert new field in mongodb database
I'm a beginner in mongodb and pymongo and I'm working on a project where I have a students mongodb collection . What I want is to add a new field and specifically an adrress of a student to each element in my collection (the field is obviously added everywhere as null and will be filled by me later).

However when I try using this specific example to add a new field I get a the following syntax error:

```<code> client = MongoClient('mongodb://localhost:27017/') #connect to local mongodb

 db = client['InfoSys']   #choose infosys database
 students = db['Students']

 students.update(  {  $set : {"address":1} }  ) #set address field to every column (error happens here)
</code>```

How can I fix this error?

答:
I solved my problem by iterating through every element in my collection and inserting the address field to each one.</p>

```<code> cursor = students.find({})
 for student in cursor :
      students.update_one(student, {'$set': {'address': '1'}})
</code>```

Title: insert new field in mongodb database

Body:
I'm a beginner in mongodb and pymongo and I'm working on a project where I have a students mongodb collection . What I want is to add a new field and specifically an adrress of a student to each element in my collection (the field is obviously added everywhere as null and will be filled by me later).

However when I try using this specific example to add a new field I get a the following syntax error:

 client = MongoClient('mongodb://localhost:27017/') #connect to local mongodb

 db = client['InfoSys']   #choose infosys database
 students = db['Students']

 students.update(  {  $set : {"address":1} }  ) #set address field to every column (error happens here)

How can I fix this error?

Body:
I solved my problem by iterating through every element in my collection and inserting the address field to each one.

 cursor = students.find({})
 for student in cursor :
      students.update_one(student, {'$set': {'address': '1'}})


问:
How do you check if a record pointer has no value in Object Pascal / Delphi?
I am trying to create a linked list implementation in Delphi, but can't create a node because I need to check if  the head pointer is empty or not. The code I'm using right now looks like this:

```<code>procedure LinkedList.addNode(newNode: Node);
var lastNode: Node;
begin
if pHead = nil then
  pHead := @newNode
else
   lastNode := peekLastNode(pHead^);
   lastNode.pNext := @newNode;
end;
</code>```

The program freezes up after just adding one element, so the nil part is the issue indefinitely.

Here is the entire program:

```<code>program LinkedListImplementation;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;
type
  Node = record
    data: string;
    pNext: ^Node;
  end;
type
  LinkedList = class
    pHead: ^Node;
    function peekLastNode (currentNode: Node) : Node;
    function listToString(currentNode: Node) : String;
    procedure addNode (newNode: Node);
  end;

//the initial parameter for this function is LinkedList.pHead^
function LinkedList.peekLastNode (currentNode: Node) : Node;
begin
  if currentNode.pNext = nil then
    result := currentNode
  else
    result := peekLastNode(currentNode.pNext^);
end;

//produces string in form 'abc -> def -> ghi' from linked list
function LinkedList.listToString(currentNode: Node) : String;
begin
  if currentNode.pNext = nil then
    result := currentNode.data
  else
    result := currentNode.data + ' -> ' + listToString(currentNode.pNext^)
end;

//this uses helper method 'peekLastNode'
procedure LinkedList.addNode(newNode: Node);
var lastNode: Node;
begin
if pHead = nil then
  pHead := @newNode
else
   lastNode := peekLastNode(pHead^);
   lastNode.pNext := @newNode;
end;

var
  Strings: LinkedList;
  String1: Node;
  String2: Node;
begin
  try
    String1.data := 'abc';
    String2.data := 'def';
    Strings.Create();
    Strings.addNode(String1);
    Strings.addNode(String2);

    WriteLn(Strings.listToString(Strings.pHead^));
    ReadLn;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
</code>```

答:
In addNode(), if pHead is nil then you are setting it to point at a local variable, and if it is not nil then you set lastNode.pNext instead to point at another local variable.  Those local variables go out of scope when addNode() exits, thus leaving pHead/pNext dangling so they are pointing at invalid memory for the next time you try to use them.

You need to use heap allocation when adding Node instances to your list, and you need to pass ^Node pointers around rather than Node instances directly.

Also, addNode() has a logic error in that it sets lastNode.pNext unconditionally whether pHead is nil or not.  If pHead is nil then lastNode is not assigned anything. The else block is missing begin..end statements around its operations.

Also, you are not even constructing the LinkedList object correctly.  Strings.Create(); needs to be Strings := LinkedList.Create(); instead.

With that said, try something more like this:

program LinkedListImplementation;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  PNode = ^Node;
  Node = record
    data: string;
    pNext: PNode;
  end;

type
  LinkedList = class
  private
    pHead: PNode;
  public
    destructor Destroy; override;
    function peekLastNode(currentNode: PNode = nil): PNode;
    function listToString(currentNode: PNode = nil): String;
    function addNode(const data: String): PNode;
    procedure clear;
  end;

destructor LinkedList.Destroy;
begin
  clear;
end;

//the initial parameter for this function is LinkedList.pHead
function LinkedList.peekLastNode(currentNode: PNode) : PNode;
begin
  if currentNode = nil then currentNode := pHead;
  if (currentNode = nil) or (currentNode.pNext = nil) then
    Result := currentNode
  else
    Result := peekLastNode(currentNode.pNext);
end;

{ Alternatively:

function LinkedList.peekLastNode(currentNode: PNode): PNode;
begin
  if currentNode = nil then currentNode := pHead;
  Result := currentNode;
  if Result <> nil then
  begin
    while Result.pNext <> nil do
      Result := Result.pNext;
  end;
end;
}

//produces string in form 'abc -> def -> ghi' from linked list
function LinkedList.listToString(currentNode: PNode): String;
begin
  if currentNode = nil then currentNode := pHead;
  if currentNode = nil then
    Result := ''
  else if currentNode.pNext = nil then
    Result := currentNode.data
  else
    Result := currentNode.data + ' -> ' + listToString(currentNode.pNext);
end;

{ Alternatively:

function LinkedList.listToString(currentNode: PNode): String;
begin
  Result := '';
  if currentNode = nil then currentNode := pHead;
  if currentNode <> nil then
  begin
    Result := currentNode.data;
    while currentNode.pNext <> nil do
    begin
      currentNode := currentNode.pNext;
      Result := Result + ' -> ' + currentNode.data;
    end;
  end;
end;
}

//this uses helper method 'peekLastNode'
function LinkedList.addNode(const data: String): PNode;
begin
  New(Result);
  Result.data := data;
  Result.pNext := nil;
  if pHead = nil then
    pHead := Result
  else
    peekLastNode(pHead).pNext := Result;
end;

{ Alternatively:

function LinkedList.addNode(const data: String): PNode;
var
  currentNode: ^PNode;
begin
  currentNode := @pHead;
  while currentNode^ <> nil do
    currentNode := @((currentNode^).pNext);
  New(currentNode^);
  (currentNode^).data := data;
  (currentNode^).pNext := nil;
  Result := currentNode^;
end;
}

procedure LinkedList.clear;
var
  currentNode, nextNode: PNode;
begin
  currentNode := pHead;
  while currentNode <> nil do
  begin
    nextNode := currentNode.pNext;
    Dispose(currentNode);
    currentNode := nextNode;
  end;
end;

var
  Strings: LinkedList;
begin
  try
    Strings := LinkedList.Create();
    try
      Strings.addNode('abc');
      Strings.addNode('def');

      WriteLn(Strings.listToString());
    finally
      Strings.Free();
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  ReadLn;
end.
```

Body:
I am trying to create a linked list implementation in Delphi, but can't create a node because I need to check if  the head pointer is empty or not. The code I'm using right now looks like this:

procedure LinkedList.addNode(newNode: Node);
var lastNode: Node;
begin
if pHead = nil then
  pHead := @newNode
else
   lastNode := peekLastNode(pHead^);
   lastNode.pNext := @newNode;
end;

The program freezes up after just adding one element, so the nil part is the issue indefinitely.

Here is the entire program:

program LinkedListImplementation;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;
type
  Node = record
    data: string;
    pNext: ^Node;
  end;
type
  LinkedList = class
    pHead: ^Node;
    function peekLastNode (currentNode: Node) : Node;
    function listToString(currentNode: Node) : String;
    procedure addNode (newNode: Node);
  end;

//the initial parameter for this function is LinkedList.pHead^
function LinkedList.peekLastNode (currentNode: Node) : Node;
begin
  if currentNode.pNext = nil then
    result := currentNode
  else
    result := peekLastNode(currentNode.pNext^);
end;

//produces string in form 'abc -> def -> ghi' from linked list
function LinkedList.listToString(currentNode: Node) : String;
begin
  if currentNode.pNext = nil then
    result := currentNode.data
  else
    result := currentNode.data + ' -> ' + listToString(currentNode.pNext^)
end;

//this uses helper method 'peekLastNode'
procedure LinkedList.addNode(newNode: Node);
var lastNode: Node;
begin
if pHead = nil then
  pHead := @newNode
else
   lastNode := peekLastNode(pHead^);
   lastNode.pNext := @newNode;
end;

var
  Strings: LinkedList;
  String1: Node;
  String2: Node;
begin
  try
    String1.data := 'abc';
    String2.data := 'def';
    Strings.Create();
    Strings.addNode(String1);
    Strings.addNode(String2);

    WriteLn(Strings.listToString(Strings.pHead^));
    ReadLn;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.


问:
Why is the main purpose of ResNet if the vanishing gradient problem is solved using RELU activation function?
I read that ResNet solves the problem of vanishing gradient problem by using skip functions. But are they not already solved using RELU? Is there some other important thing I'm missing about ResNet or does Vanishing gradient problem occur even after using RELU? </p>

答: The main purpose of ResNet is to create more deeper models. In theory deeper models (speaking about VGG models) must show better accuracy, but in the real life they usually do not. But if we add short-connection to the model, we can increase the number of layers and accuracy as well


问:
Progress bar and text are not aligned
I am trying to align the text to the side of the progress bar. but the text and the progress bar in the container are not being aligned. How do I align them side by side? I have provided the html code and the screenshot of the problem below.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Operating Systems

Ubuntu

75%

```

Progress bar and their label are not aligned

答:
@Md. Shajedul Hasan

Here is the answer

User md instead of xs

.someSpace{
  padding:10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
              integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
              integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <div class="container" style="height: 250px;">
                    <h3>Operating Systems</h3>
      <div class="someSpace"></div>
                    <div class="row">
                        <div class="col-md-1">Ubuntu</div>
                        <div class="col-md-6">
                            <div class="progress" style="height: max-content;">
                                <div class="progress-bar progress-bar-animated progress-bar-striped" role="progressbar" style="width: 75%"
                                    aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"><strong>75%</strong></div>
                            </div>
                        </div>
                    </div>
      <div class="row">
                        <div class="col-md-1">Ubuntu Fedora</div>
                        <div class="col-md-6">
                            <div class="progress" style="height: max-content;">
                                <div class="progress-bar progress-bar-animated progress-bar-striped" role="progressbar" style="width: 75%"
                                    aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"><strong>75%</strong></div>
                            </div>
                        </div>
                    </div>
                    </div></code>```

Title: Progress bar and text are not aligned

Body:
I am trying to align the text to the side of the progress bar. but the text and the progress bar in the container are not being aligned. How do I align them side by side? I have provided the html code and the screenshot of the problem below.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Operating Systems

Ubuntu

75%

Progress bar and their label are not aligned

Body:
@Md. Shajedul Hasan

Here is the answer

User md instead of xs

.someSpace{
  padding:10px;
}

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
              integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
              integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <div class="container" style="height: 250px;">
                    <h3>Operating Systems</h3>
      <div class="someSpace"></div>
                    <div class="row">
                        <div class="col-md-1">Ubuntu</div>
                        <div class="col-md-6">
                            <div class="progress" style="height: max-content;">
                                <div class="progress-bar progress-bar-animated progress-bar-striped" role="progressbar" style="width: 75%"
                                    aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"><strong>75%</strong></div>
                            </div>
                        </div>
                    </div>
      <div class="row">
                        <div class="col-md-1">Ubuntu Fedora</div>
                        <div class="col-md-6">
                            <div class="progress" style="height: max-content;">
                                <div class="progress-bar progress-bar-animated progress-bar-striped" role="progressbar" style="width: 75%"
                                    aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"><strong>75%</strong></div>
                            </div>
                        </div>
                    </div>
                    </div>


问:
Flutter : Cannot display image from image url firestore
I try display data from firestore using image url. i use FutureBuilder for get my image url value from firestore. but i have problem because my image cannot display and show red screen. i got messages in my debug console like :

Another exception was thrown: A build function returned null.

I/flutter (13506): Another exception was thrown: NoSuchMethodError:
  The method '[]' was called on null.

I/flutter (13506): Another exception was thrown: NoSuchMethodError:
  Class 'QuerySnapshot' has no instance method '[]'

and this my code :

```<code>ListTile(
  leading: new FutureBuilder(
    future: Firestore.instance.collection('users').where('uid', isEqualTo: _post['imgurl']).getDocuments(),
    builder: (BuildContext context, AsyncSnapshot snapshot){
      if(snapshot.hasData){
        if(snapshot.data != null){
          print(snapshot.data['imgurl']);
          return CircleAvatar(
            backgroundImage: NetworkImage(snapshot.data['imgurl']),
          );
        }
      }
    },
  ),
  title: Text('Richard');
)
</code>```

can you tell me where is my fault?

答:
```<code>FadeInImage.assetNetwork(
width: 50.0,
height: 50.0,
fit: BoxFit.cover,
image:ContentThumbnail.thumbnails[index],
placeholder: 'images/placeholder.jpg',),),
</code>```

Body:
I try display data from firestore using image url. i use FutureBuilder for get my image url value from firestore. but i have problem because my image cannot display and show red screen. i got messages in my debug console like :

Another exception was thrown: A build function returned null.

I/flutter (13506): Another exception was thrown: NoSuchMethodError:
  The method '[]' was called on null.

I/flutter (13506): Another exception was thrown: NoSuchMethodError:
  Class 'QuerySnapshot' has no instance method '[]'

and this my code :

ListTile(
  leading: new FutureBuilder(
    future: Firestore.instance.collection('users').where('uid', isEqualTo: _post['imgurl']).getDocuments(),
    builder: (BuildContext context, AsyncSnapshot snapshot){
      if(snapshot.hasData){
        if(snapshot.data != null){
          print(snapshot.data['imgurl']);
          return CircleAvatar(
            backgroundImage: NetworkImage(snapshot.data['imgurl']),
          );
        }
      }
    },
  ),
  title: Text('Richard');
)

can you tell me where is my fault?


问:
Parse routes in cakephp to load specific model (is it possible to use .htaccess for this?)
First part of this question will look trivial, but the point is in second part.

So, let's say that I have next few links on my app:

```<code>http://myapp.com/cars-audi
http://myapp.com/cars-opel
http://myapp.com/cars-fiat
http://myapp.com/cars-vw
</code>```

In these cases, model car is used. So, in this case, I want to escape using slash in URL.

Then I will have more pages, and URLs, where roads will be involved, like:

```<code>http://myapp.com/roads/germany
http://myapp.com/roads/austria
http://myapp.com/roads/hungary
http://myapp.com/roads/poland
</code>```

So, if it starts with cars-, in that case model cars should be used, and if it starts with roads/, model roads will be in the game.

Is it possible to do with some regular expressions in routes.php, or is it better to load (use) one same model in both cases, and to work with them like that?

Also, is it possible to help  parsing URL using .htaccess file?

答:
This is a simple case of routing a URL to a controller action, it doesn't involve models at all.

```<code>Router::connect('/:carlink',
                array('controller' => 'cars', 'action' => 'view'),
                array('carlink' => 'cars-\w+', 'pass' => array('carlink')));
</code>```

This route says any URL that matches /:carlink should be routed to the given controller and action. In the last part you're clarifying what :carlink can be with the regular expression cars-\w+ ("cars-" followed by any word). You also pass that value to your called action.

```<code>class CarsController extends AppController {
    public function view($car) {
        if (!preg_match('/cars-(\w+)/', $car, $matches)) {
            // action was accessed with invalid URL, bail out
            $this->cakeError('error404');
        }

        // use $matches[1], which will be 'audi', for example
        …
    }
}
</code>```

Your road URLs would be routed to the RoadsController as usual like this:

```<code>Router::connect('/roads/*', array('controller' => 'roads', 'action' => 'view'));
</code>```

Body:
First part of this question will look trivial, but the point is in second part.

So, let's say that I have next few links on my app:

http://myapp.com/cars-audi
http://myapp.com/cars-opel
http://myapp.com/cars-fiat
http://myapp.com/cars-vw

In these cases, model car is used. So, in this case, I want to escape using slash in URL.

Then I will have more pages, and URLs, where roads will be involved, like:

http://myapp.com/roads/germany
http://myapp.com/roads/austria
http://myapp.com/roads/hungary
http://myapp.com/roads/poland

So, if it starts with cars-, in that case model cars should be used, and if it starts with roads/, model roads will be in the game.

Is it possible to do with some regular expressions in routes.php, or is it better to load (use) one same model in both cases, and to work with them like that?

Also, is it possible to help  parsing URL using .htaccess file?

Body:
This is a simple case of routing a URL to a controller action, it doesn't involve models at all.

Router::connect('/:carlink',
                array('controller' => 'cars', 'action' => 'view'),
                array('carlink' => 'cars-\w+', 'pass' => array('carlink')));

This route says any URL that matches /:carlink should be routed to the given controller and action. In the last part you're clarifying what :carlink can be with the regular expression cars-\w+ ("cars-" followed by any word). You also pass that value to your called action.

class CarsController extends AppController {
    public function view($car) {
        if (!preg_match('/cars-(\w+)/', $car, $matches)) {
            // action was accessed with invalid URL, bail out
            $this->cakeError('error404');
        }

        // use $matches[1], which will be 'audi', for example
        …
    }
}

Your road URLs would be routed to the RoadsController as usual like this:

Router::connect('/roads/*', array('controller' => 'roads', 'action' => 'view'));


问:
Cypress - Visit a URL obtained from a 3rd party(email)
In my test, I want to visit a URL that is sent in an email. I can successfully save the URL in a variable, but am unable to get cypress to go to that URL. I keep getting the below error. I don't fully understand cypress being "promise-like", so I'm not sure how to resolve the issue

Uncaught (in promise) CypressError: Cypress detected that you returned
  a promise from a command while also invoking one or more cy commands
  in that promise.

The command that returned the promise was:

cy.get()

The cy command you invoked inside the promise was:

cy.request()

Because Cypress commands are already promise-like, you don't need to
  wrap them or return your own promise.

Cypress will resolve your command with whatever the final Cypress
  command yields.

```<code>Cypress.Commands.add("clickForgotPwdLink", (emailaddress) => {
    const MailosaurClient = require('mailosaur');
    const client = new MailosaurClient('1234');
    let latestEmail;
    var emailLower = emailaddress.toLowerCase();
    client.messages.search('abc', {
        sentTo: emailLower
    }).then((results) => {
        latestEmail = results.items[0];
        let email = latestEmail.id;
        client.messages.get(email)
            .then((newlink) => {
                var forgotpwd = newlink.html.links[0].href;
                console.log(forgotpwd)
                cy.request(''+forgotpwd+'');
            })
    })
});
</code>```

答:
I have to face this today.
If you are getting a raw body response (string) you have to get the link in this way:</p>

```<code>            const links = body.split("href=http://my.url.com");
            var activation_link = links[0].match(/\bhttp?:\/\/\S+/);
            activation_link= activation_link[0].replace('"','')
            cy.visit(activation_link)
</code>```

Body:
In my test, I want to visit a URL that is sent in an email. I can successfully save the URL in a variable, but am unable to get cypress to go to that URL. I keep getting the below error. I don't fully understand cypress being "promise-like", so I'm not sure how to resolve the issue

Uncaught (in promise) CypressError: Cypress detected that you returned
  a promise from a command while also invoking one or more cy commands
  in that promise.

The command that returned the promise was:

cy.get()

The cy command you invoked inside the promise was:

cy.request()

Because Cypress commands are already promise-like, you don't need to
  wrap them or return your own promise.

Cypress will resolve your command with whatever the final Cypress
  command yields.

Cypress.Commands.add("clickForgotPwdLink", (emailaddress) => {
    const MailosaurClient = require('mailosaur');
    const client = new MailosaurClient('1234');
    let latestEmail;
    var emailLower = emailaddress.toLowerCase();
    client.messages.search('abc', {
        sentTo: emailLower
    }).then((results) => {
        latestEmail = results.items[0];
        let email = latestEmail.id;
        client.messages.get(email)
            .then((newlink) => {
                var forgotpwd = newlink.html.links[0].href;
                console.log(forgotpwd)
                cy.request(''+forgotpwd+'');
            })
    })
});

Body:
I have to face this today.
If you are getting a raw body response (string) you have to get the link in this way:

            const links = body.split("href=http://my.url.com");
            var activation_link = links[0].match(/\bhttp?:\/\/\S+/);
            activation_link= activation_link[0].replace('"','')
            cy.visit(activation_link)


问:
When specifying a 0 value in CSS, should I explicitly mark the units or omit?
This is more of a 'philosophy' argument, but I'd like to know what the recommended practice here. I'm not setting it up as a Wiki yet in case there is an 'official' answer.

Obviously, there is no difference between 0px and 0em or whatever, so one could simply specify 0 and the units are redundant (see CSS difference between 0 and 0em). Some of the folks who answered that question argued that one should always omit the units.

However, it seems to me that omitting the unit is more error-prone, since a later change may accidentally omit the unit. It is also less consistent with non-zero elements elsewhere in the document.

答:
I'm gradually starting to believe in zeros with units.

I follow a style guide that says to use unitless zeros. I also think they look better. I agree with all the pro-unitless arguments on here. But twice in my career a bug has been caused by unitless zeros. (one having to do with calc and one having to do with a transition from 0 to something - but I can't remember the details.)

With "causes bugs" on one side of the equation can any pro-unitless argument compete no matter how aesthetically pleasing or logical?

BTW, I originally attributed the unitless zero style to Airbnb's guide, but after rereading it, it doesn't actually say that explicity, but comes close: https://stackoverflow.com/a/55391061/2836695


问:
How to aggregate 2D documents in Forge viewer?
I would like to aggregate multiple 2D sheets within same scene of Forge viewer. Testing with the legendary "Office" model so it's easy for you to reproduce. When loading sheet1 everything is ok, when loading a second sheet the sheet itself completely overlap the sheet1 so none of the entities on sheet1 are visible any more. Any workaround for that?

Yes, I am using the keepCurrentModels: true:

```<code>const loadOptions = {
  keepCurrentModels: true,
  preserveView: true
}

viewer.loadDocumentNode(doc, viewable, loadOptions)
</code>```

答:
Did you try modelSpace:true in the options ?

let options = {
      placementTransform: new window.THREE.Matrix4(),
      modelSpace: true,
      globalOffset: { x: 0, y: 0, z: 0 },
      applyRefPoint: true,
      isAEC: true, // to align the models,
    }

More details here:

Autodesk forge viewer api v7.* align multiple 2d dwg models

Body:
I would like to aggregate multiple 2D sheets within same scene of Forge viewer. Testing with the legendary "Office" model so it's easy for you to reproduce. When loading sheet1 everything is ok, when loading a second sheet the sheet itself completely overlap the sheet1 so none of the entities on sheet1 are visible any more. Any workaround for that?

Yes, I am using the keepCurrentModels: true:

const loadOptions = {
  keepCurrentModels: true,
  preserveView: true
}

viewer.loadDocumentNode(doc, viewable, loadOptions)


问:
Using WTForms' populate_obj( ) method with Flask micro framework
I have a template which allows the user to edit their user information.

```<code><form method="post">
    <table>
        <tr>
            <td>Username:</td>
            <td>{{user['username']}}</td>
        </tr>
        <tr>
            <td>New Password:</td>
            <td> <input type="password" name="password"></td>
            <td>{% if form.password.errors %} {{form.password.errors}} {% endif %}<td>
        </tr>
        <tr>
            <td>Re-enter Password:</td>
            <td> <input type="password" name="confirm_password">
            </td>
        </tr>
        <input type='hidden' name='username' value="{{user['username']}}">
        <tr>
            <td><input type="submit" value="Submit"></td>
        </tr>
    </table>
</form>
</code>```

I also have a view function for handling such edits by the user. The database I am currently using is MongoDB with the MongoKit module. I have only been able to do up to this so far in the view function, yet with no luck.

```<code>def edit():
    username = request.args.get('user')
    user = User.find_one({'username':username}) # Is this a correct way of doing it?
    form = UserForm(**what should be placed here?**, obj=user)

    if request.method == 'POST' and form.validate():
        form.populate_obj(user)
        user.save()
        return 'updated'
    return render_template('edituser.html', form=form, user=user)
</code>```

I am going through populate_obj(obj) for this purpose. I couldn't find much help in this matter. What should I do in order to get populate_obj() working?

答:
UserForm should have request.form passed into it to populate it with the values available in the POST request (if any).

```<code>form = UserForm(request.form, obj=user)
</code>```

Body:
I have a template which allows the user to edit their user information.

<form method="post">

            Username:
            {{user['username']}}

            New Password:
             <input type="password" name="password">
            {% if form.password.errors %} {{form.password.errors}} {% endif %}

            Re-enter Password:
             <input type="password" name="confirm_password">

        <input type='hidden' name='username' value="{{user['username']}}">

            <input type="submit" value="Submit">

</form>

I also have a view function for handling such edits by the user. The database I am currently using is MongoDB with the MongoKit module. I have only been able to do up to this so far in the view function, yet with no luck.

def edit():
    username = request.args.get('user')
    user = User.find_one({'username':username}) # Is this a correct way of doing it?
    form = UserForm(**what should be placed here?**, obj=user)

    if request.method == 'POST' and form.validate():
        form.populate_obj(user)
        user.save()
        return 'updated'
    return render_template('edituser.html', form=form, user=user)

I am going through populate_obj(obj) for this purpose. I couldn't find much help in this matter. What should I do in order to get populate_obj() working?

Body:
UserForm should have request.form passed into it to populate it with the values available in the POST request (if any).

form = UserForm(request.form, obj=user)


问:
Align Text with padding SwiftUI
I am creating a view that looks like this -

I am struggling to align the summary text with the text inside the image overlay.

I would like the leading edge of Research to align with the leading edge of My experience.

At the moment my view is rendering as

As you can see text view is too close to the leading edge.

I have tried adding .padding() but the view changes to

How can I properly inset the text so these 2 components line up?

import SwiftUI

struct ContentView: View {
  var body: some View {
    ZStack {
      FeaturedContentCard()
        .frame(minHeight: 100)
    }.padding()
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

struct FeaturedContentCard: View {
  var body: some View {
    VStack {
      ImageWithTextOverlayView(image: "featured_image", text: "My experience with EAP and Income Protection")
      ContentCardSummary(text: "Research shows that our social enviroment significantly impacts our biology")
        .padding(.all)
      ContentCardMetaView(readTime: "10 min read", name: "Jessica Bell")
    }
    .padding(.bottom, 16)
    .background(Color.white)
    .feedItemContainer()
  }
}

struct ImageWithTextOverlayView: View {

  private(set) var image: String
  private(set) var text: String

  var body: some View {
    Image(image)
      .resizable()
      .aspectRatio(contentMode: .fit)
      .frame(minWidth: 0, maxWidth: .infinity)
      .overlay(LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.6536279966)), Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 0))]), startPoint: .bottom, endPoint: .top))
      .overlay(
        Text(text)
          .foregroundColor(Color.white)
          .font(.title)
          .padding(),
        alignment: .bottomLeading
    )
  }
}

struct ContentCardSummary: View {
  private(set) var text: String
  var body: some View {
    Text(text)
      .frame(alignment: .leading)
      .foregroundColor(Color(#colorLiteral(red: 0.2901960784, green: 0.2901960784, blue: 0.2901960784, alpha: 1)))
  }
}

struct FeedItemContainer: ViewModifier {
  func body(content: Content) -> some View {
    content
      .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
      .customShadow()
  }
}

struct BenefexShadow: ViewModifier {
  func body(content: Content) -> some View {
    content
      .shadow(color: Color(.init(red: 0.18, green: 0.18, blue: 0.18, alpha: 0.16)).opacity(1), radius: 4, x: 0, y: 1)
      .shadow(color: Color(.init(red: 0.18, green: 0.18, blue: 0.18, alpha: 0.1)).opacity(1), radius: 60, x: 0, y: 4)
      .shadow(color: Color(.init(red: 0.18, green: 0.18, blue: 0.18, alpha: 0.16)).opacity(1), radius: 4, x: 0, y: 1)
  }
}

extension View {

  func customShadow() -> some View {
    self.modifier(BenefexShadow())
  }

  func feedItemContainer() -> some View {
    self.modifier(FeedItemContainer())
  }
}

struct AvatarView: View {
  var body: some View {
    Image("profile_pic")
      .resizable()
      .aspectRatio(contentMode: .fill)
      .frame(width: 40, height: 40)
      .clipShape(Circle())
      .overlay(
        Circle()
          .stroke(Color.white, lineWidth: 2)
    )
      .customShadow()
  }
}

struct ContentCardMetaView: View {
  private(set) var readTime: String
  private(set) var name: String
  var body: some View {
    HStack(spacing: 8) {
      AvatarView()
      VStack(alignment: .leading) {
        Text(readTime)
          .font(.subheadline)
          .foregroundColor(Color(#colorLiteral(red: 0.2901960784, green: 0.2901960784, blue: 0.2901960784, alpha: 1)))
        Text(name)
          .fontWeight(.medium)
          .foregroundColor(Color(#colorLiteral(red: 0.2980392157, green: 0.1843137255, blue: 0.737254902, alpha: 1)))
      }
      Spacer()
      Button(action: { }) {
        Image(systemName: "ellipsis")
          .font(.system(size: 24))
          .foregroundColor(Color(#colorLiteral(red: 0.7803921569, green: 0.7803921569, blue: 0.7803921569, alpha: 1)))
          .rotationEffect(.degrees(-90))
      }

    }
  }
}

```

答:
Here is fix. Tested with Xcode 11.4 / iOS 13.4

1) Remove padding at top layer, so

```<code>  ImageWithTextOverlayView(image: "large_image", text: "My experience with EAP and Income Protection")
  ContentCardSummary(text: "Research shows that our social enviroment significantly impacts our biology")
  ContentCardMetaView(readTime: "10 min read", name: "Jessica Bell")
</code>```

2) Correct alignment of summary, as

```<code>struct ContentCardSummary: View {
  private(set) var text: String
  var body: some View {
    Text(text)
      .frame(maxWidth: .infinity, alignment: .leading) // << full width
      .padding() // << same padding as above text
      .foregroundColor(Color(#colorLiteral(red: 0.2901960784, green: 0.2901960784, blue: 0.2901960784, alpha: 1)))
  }
}
</code>```

Title: Align Text with padding SwiftUI

Body:
Here is fix. Tested with Xcode 11.4 / iOS 13.4

1) Remove padding at top layer, so

  ImageWithTextOverlayView(image: "large_image", text: "My experience with EAP and Income Protection")
  ContentCardSummary(text: "Research shows that our social enviroment significantly impacts our biology")
  ContentCardMetaView(readTime: "10 min read", name: "Jessica Bell")

2) Correct alignment of summary, as

struct ContentCardSummary: View {
  private(set) var text: String
  var body: some View {
    Text(text)
      .frame(maxWidth: .infinity, alignment: .leading) // << full width
      .padding() // << same padding as above text
      .foregroundColor(Color(#colorLiteral(red: 0.2901960784, green: 0.2901960784, blue: 0.2901960784, alpha: 1)))
  }
}


问:
How to find two same items in a python list
So I want to be able to check if a list in a python program contains a particular value written twice.

```<code>list_one = [a, b, c, d, e, f, g]
</code>```

Here I want to check if two different items have the same value, for instance a == d

答:
Iterate through your list to see how many times each value appears. If count() evaluates to more than 1, you know there are duplicates of the current value.

```<code>for i in list_one:
    if i.count() > 1:
        print("Duplicate: " + i)
</code>```

If you want to compare two values directly, you can use their indices. For example, in the case of a == d:

```<code>if list_one[0] == list_one[3]:
    print("a and d are equal.")
</code>```

You can also use a function, like follows, to find all of the indexes that there are duplicates:

```<code>def getIndexPositions(listOfElements, element): #pass it the list and element to check for duplicates of
    ''' Returns the indexes of all occurrences of give element in
    the list- listOfElements '''
    indexPosList = []
    indexPos = 0
    while True:
        try:
            # Search for item in list from indexPos to the end of list
            indexPos = listOfElements.index(element, indexPos)
            # Add the index position in list
            indexPosList.append(indexPos)
            indexPos += 1
        except ValueError as e:
            break

    return indexPosLis
</code>```

Body:
So I want to be able to check if a list in a python program contains a particular value written twice.

list_one = [a, b, c, d, e, f, g]

Here I want to check if two different items have the same value, for instance a == d

Body:
Iterate through your list to see how many times each value appears. If count() evaluates to more than 1, you know there are duplicates of the current value.

for i in list_one:
    if i.count() > 1:
        print("Duplicate: " + i)

If you want to compare two values directly, you can use their indices. For example, in the case of a == d:

if list_one[0] == list_one[3]:
    print("a and d are equal.")

You can also use a function, like follows, to find all of the indexes that there are duplicates:

def getIndexPositions(listOfElements, element): #pass it the list and element to check for duplicates of
    ''' Returns the indexes of all occurrences of give element in
    the list- listOfElements '''
    indexPosList = []
    indexPos = 0
    while True:
        try:
            # Search for item in list from indexPos to the end of list
            indexPos = listOfElements.index(element, indexPos)
            # Add the index position in list
            indexPosList.append(indexPos)
            indexPos += 1
        except ValueError as e:
            break

    return indexPosLis


问:
how to pass initial state value using immutable js
I am using immutable js and in my reducer I am initializing the state like this:

```<code>     export default function reducer(state = new Map(), action = {}) {
      switch (action.type) {
        case actionType.SET_YEARS:
          return handlers.setYears(state, fromJS(action.Years));

       default:
       return state;
   }
 }
</code>```

And then in my action I have created the action creator like this:

```<code>    function setYears(Years) {
     return {
       type: types.SET_YEARS,
       Years,
    };
  }
</code>```

And in Action Handlers I am declaring the state this:

```<code>  export const setYears = (state, Years) => state.set('Years',Years);
</code>```

From my component I am accessing the years like this:

```<code>years: state.app.get('Years') where app is the reducer name:
</code>```

So, in the whole scenario,I am getting the years from an endpoint.I want to pass some initial value to my state so that I can get some initial values. I could do it easily without using the immutable js but not sure how to set the initial values in immutable state property.Any help would be highly appreciated.Thanks in Advance.

reducer:

```<code>import { Map } from 'immutable';
import * as handlers from './actionHandlers';
import * as actionType from './actionTypes';

const initialState = new Map({
  Years: [{ year: 2017 }, { year: 2016 }],
});
export default function reducer(state = new Map(), action = {}) {
  switch (action.type) {

    case actionType.SET_YEARS:
      return handlers.setYears(state, fromJS(action.Years));

    default:
      return state;
  }
</code>```

}
combineReducer:

```<code>  const reducer = combineReducers({
    app: appReducer,
  });
</code>```

sandbox link: https://codesandbox.io/s/youthful-williams-hnrg1?file=/src/YearsView.js

答:
You just have to pass an object to the initial state.

you can do

```<code>const initialState = Map({Years:1});
</code>```

I'll update the full code as per the comments for the answer provided

```<code>//Actions.js
export const updateYears = Years => {
    return {
        type: 'UpdateYears',
         Years
    };
};
</code>```

//Reducer.js combine reducer is placed in same file as well

```<code>const setYears = (state, Years) => state.set('Years', Years);
const initialState = new Map({
    Years: [{ year: 2017 }, { year: 2016 }],
});
const commonReducer = (state = initialState, action = {}) => {
    switch (action.type) {

        case 'UpdateYears':
            return setYears(state, [...state.get('Years'),fromJS(action.Years)]);

        default:
            return state;
    }
};

export default combineReducers({
    common: commonReducer
});

//Years View
const YearsView = props => {
    useEffect(() => {
        console.log(JSON.stringify(props.years));
        setTimeout(()=>{
            props.dateActions.updateYears([{ years: 333 }]);
        },2000);
    }, []);

    return (
        <div>
            {
                JSON.stringify(props.years)
            }
        </div>
    );
}

export default connect(state => ({
    years: state.common.get('Years')
}), dispatch => {
    return {
        dateActions: bindActionCreators(actions, dispatch)
    }
})(YearsView);
</code>```

When years view is mounted the useeffect will fire the action after 2 seconds

```<code>const YearsView = props => {
    useEffect(() => {
        console.log(JSON.stringify(props.years));
        setTimeout(()=>{
            props.dateActions.updateYears([{ years: 333 }]);
        },2000);
    }, []);

    return (
        <div>
            {
                JSON.stringify(props.years)
            }
        </div>
    );
}

export default connect(state => ({
    years: state.common.get('Years')
}), dispatch => {
    return {
        dateActions: bindActionCreators(actions, dispatch)
    }
})(YearsView);
</code>```

Hope this helps.

Body:
I am using immutable js and in my reducer I am initializing the state like this:

     export default function reducer(state = new Map(), action = {}) {
      switch (action.type) {
        case actionType.SET_YEARS:
          return handlers.setYears(state, fromJS(action.Years));

       default:
       return state;
   }
 }

And then in my action I have created the action creator like this:

    function setYears(Years) {
     return {
       type: types.SET_YEARS,
       Years,
    };
  }

And in Action Handlers I am declaring the state this:

  export const setYears = (state, Years) => state.set('Years',Years);

From my component I am accessing the years like this:

years: state.app.get('Years') where app is the reducer name:

So, in the whole scenario,I am getting the years from an endpoint.I want to pass some initial value to my state so that I can get some initial values. I could do it easily without using the immutable js but not sure how to set the initial values in immutable state property.Any help would be highly appreciated.Thanks in Advance.

reducer:

import { Map } from 'immutable';
import * as handlers from './actionHandlers';
import * as actionType from './actionTypes';

const initialState = new Map({
  Years: [{ year: 2017 }, { year: 2016 }],
});
export default function reducer(state = new Map(), action = {}) {
  switch (action.type) {

    case actionType.SET_YEARS:
      return handlers.setYears(state, fromJS(action.Years));

    default:
      return state;
  }

}
combineReducer:

  const reducer = combineReducers({
    app: appReducer,
  });

sandbox link: https://codesandbox.io/s/youthful-williams-hnrg1?file=/src/YearsView.js

Body:
You just have to pass an object to the initial state.

you can do

const initialState = Map({Years:1});

I'll update the full code as per the comments for the answer provided

//Actions.js
export const updateYears = Years => {
    return {
        type: 'UpdateYears',
         Years
    };
};

//Reducer.js combine reducer is placed in same file as well

const setYears = (state, Years) => state.set('Years', Years);
const initialState = new Map({
    Years: [{ year: 2017 }, { year: 2016 }],
});
const commonReducer = (state = initialState, action = {}) => {
    switch (action.type) {

        case 'UpdateYears':
            return setYears(state, [...state.get('Years'),fromJS(action.Years)]);

        default:
            return state;
    }
};

export default combineReducers({
    common: commonReducer
});

//Years View
const YearsView = props => {
    useEffect(() => {
        console.log(JSON.stringify(props.years));
        setTimeout(()=>{
            props.dateActions.updateYears([{ years: 333 }]);
        },2000);
    }, []);

    return (
        <div>
            {
                JSON.stringify(props.years)
            }
        </div>
    );
}

export default connect(state => ({
    years: state.common.get('Years')
}), dispatch => {
    return {
        dateActions: bindActionCreators(actions, dispatch)
    }
})(YearsView);

When years view is mounted the useeffect will fire the action after 2 seconds

const YearsView = props => {
    useEffect(() => {
        console.log(JSON.stringify(props.years));
        setTimeout(()=>{
            props.dateActions.updateYears([{ years: 333 }]);
        },2000);
    }, []);

    return (
        <div>
            {
                JSON.stringify(props.years)
            }
        </div>
    );
}

export default connect(state => ({
    years: state.common.get('Years')
}), dispatch => {
    return {
        dateActions: bindActionCreators(actions, dispatch)
    }
})(YearsView);

Hope this helps.


问:
Firebase crashlytics upload dsym automatically
I'm using React Native Firebase. At firebase crashlytics I have missing DSYM's.

What's the right way to add dSYMs automatically on every build? I guess it should be added to run script? If so, how can I get the path to /path/to/pods/directory/FirebaseCrashlytics/upload-symbols and /path/to/dSYMs.

Thanks!

答:
This question has been answered in previous posts, but I'll provide a quick summary. The paths below will automatically find your dSYMs and upload them.

Here is what goes into your runscript:

```<code>"${PODS_ROOT}/FirebaseCrashlytics/run"
</code>```

This is what goes into your input file:

```<code>${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME}
</code>```

You can use this terminal command to find the correct paths to your dSYMs:

```<code>mdfind "com_apple_xcode_dsym_uuids == UUID"
</code>```

You can use the below post as a reference:

Firebase Crashlytics DSYM file.

Body:
This question has been answered in previous posts, but I'll provide a quick summary. The paths below will automatically find your dSYMs and upload them.

Here is what goes into your runscript:

"${PODS_ROOT}/FirebaseCrashlytics/run"

This is what goes into your input file:

${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME}

You can use this terminal command to find the correct paths to your dSYMs:

mdfind "com_apple_xcode_dsym_uuids == UUID"

You can use the below post as a reference:

Firebase Crashlytics DSYM file.