问:
Django datetimefield not showing datetimepicker widget for new inline form rows
In regards to the image below, when I click "add entry", the new entry row no longer has the datetimepicker widget. Which is odd because it has the right class. The +1 field represents the django form auto-added additional field. Which seems to work fine. It's only the fields that are added after the page has rendered which may be a key to the solution.

I am using the flatpickr package as my datetimepicker widget.

trade_form.html

```<code>{% extends 'dashboard/base.html' %}
{% load static %}

{% block content %}

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'js/formset/jquery.formset.js' %}"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-3">
    <h2>New Trade</h2>
</div>

<div class="row">
    <div class="col">
        <form action="" method="post">{% csrf_token %}
            {{ form.media }}
            {{ form.as_p }}

            <table class="table">
                {{ entries.management_form }}

                {% for form in entries.forms %}
                {% if forloop.first %}
                <thead>
                <tr>
                    {% for field in form.visible_fields %}
                    <th>{{ field.label|capfirst }}</th>
                    {% endfor %}
                </tr>
                </thead>
                {% endif %}
                <tr class="{% cycle row1 row2 %} formset_row">
                    {% for field in form.visible_fields %}
                    <td>
                        {# Include the hidden fields in the form #}
                        {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                        {{ hidden }}
                        {% endfor %}
                        {% endif %}
                        {{ field.errors.as_ul }}
                        {{ field }}
                    </td>
                    {% endfor %}
                </tr>
                {% endfor %}
            </table>
            <input type="submit" value="Save"/> <a href="{% url 'trade-list' %}">back to the list</a>
        </form>
    </div>

</div>

<script type="text/javascript">
    $('.formset_row').formset({
        addText: 'add entry',
        deleteText: 'remove',
        prefix: 'entry_set'
    });

</script>

<!-- Makes DateTimeFields Show Picker-->
<script>
    // This code activates flatpickr on fields with the 'datetimefield' class when the document has loaded
    window.addEventListener("DOMContentLoaded", function () {
        flatpickr(".datetimefield", {
            enableTime: true,
            enableSeconds: true,
            dateFormat: "Y-m-d H:i:S",
        });
    });
</script>

{% endblock content %}
</code>```

forms.py

```<code>class EntriesForm(ModelForm):
    class Meta:
        model = Entry
        exclude = ()
        widgets = {
            'date': forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S', attrs={'class': 'datetimefield'}),
        }

    # Adding default class to every visible field

    def __init__(self, *args, **kwargs):
        super(EntriesForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if field.widget.attrs.get('class'):
                field.widget.attrs['class'] += ' form-control'
            else:
                field.widget.attrs['class'] = 'form-control'

EntriesFormSet = inlineformset_factory(Trade, Entry, form=EntriesForm, extra=1)
</code>```

Updated trade_form.html scripts but with still no luck.
So far this code just removed the datetimepicker widget on the fields that were already working. So it may just be a format issue.

```<code><!-- Makes DateTimeFields Show Picker-->
<script>
    // This code activates flatpickr on fields with the 'datetimefield' class when the document has loaded
    window.addEventListener(

        "DOMContentLoaded", function () {
            flatpickr(".datetimefield", {
                enableTime: true,
                enableSeconds: true,
                dateFormat: "Y-m-d H:i:S",
            });
        }

        "added", function() {
            flatpickr(".datetimefield", {
                enableTime: true,
                enableSeconds: true,
                dateFormat: "Y-m-d H:i:S",
            });

        }

    );
</script>
</code>```

答:
The place where the added needs to be put is in the django-dynamic-formset call, rather than in the addEventListener code, as the call is done by django-dynamic-formset itself.

That is: (note: I haven't tested this myself because I'm on phone at the moment)

```<code><script type="text/javascript">

    function applyFlatpickr(parent) {
     flatpickr(parent.find(".datetimefield"), {
                enableTime: true,
                enableSeconds: true,
                dateFormat: "Y-m-d H:i:S",
            });
    }
    <!-- Makes DateTimeFields Show Picker-->
        // This code activates flatpickr on fields with the 'datetimefield' class when the document has loaded
        window.addEventListener("DOMContentLoaded", function(){applyFlatpickr($(document))});

        $('.formset_row').formset({
            addText: 'add entry',
            deleteText: 'remove',
            prefix: 'entry_set',
            added: applyFlatpickr
        });
    </script>
</script>
</code>```

django-dynamic-formset passes the newly created row to the added function as a jQuery object, so by using .find on the argument we can match only the newly added row and apply flatpickr only to that new row.

From the django-dynamic-formset docs:

added
      If you set this to a function, that function will be called each
      time a new form is added. The function should take a single argument,
      row; it will be passed a jQuery object, wrapping the form that
      was just added.)

Body:
In regards to the image below, when I click "add entry", the new entry row no longer has the datetimepicker widget. Which is odd because it has the right class. The +1 field represents the django form auto-added additional field. Which seems to work fine. It's only the fields that are added after the page has rendered which may be a key to the solution.

I am using the flatpickr package as my datetimepicker widget.

trade_form.html

{% extends 'dashboard/base.html' %}
{% load static %}

{% block content %}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

New Trade

        <form action="" method="post">{% csrf_token %}
            {{ form.media }}
            {{ form.as_p }}

                {{ entries.management_form }}

                {% for form in entries.forms %}
                {% if forloop.first %}

                    {% for field in form.visible_fields %}
                    {{ field.label|capfirst }}
                    {% endfor %}

                {% endif %}

                    {% for field in form.visible_fields %}

                        {# Include the hidden fields in the form #}
                        {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                        {{ hidden }}
                        {% endfor %}
                        {% endif %}
                        {{ field.errors.as_ul }}
                        {{ field }}

                    {% endfor %}

                {% endfor %}

            <input type="submit" value="Save"/> back to the list
        </form>

{% endblock content %}

forms.py

class EntriesForm(ModelForm):
    class Meta:
        model = Entry
        exclude = ()
        widgets = {
            'date': forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S', attrs={'class': 'datetimefield'}),
        }

    # Adding default class to every visible field

    def __init__(self, *args, **kwargs):
        super(EntriesForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if field.widget.attrs.get('class'):
                field.widget.attrs['class'] += ' form-control'
            else:
                field.widget.attrs['class'] = 'form-control'

EntriesFormSet = inlineformset_factory(Trade, Entry, form=EntriesForm, extra=1)

Updated trade_form.html scripts but with still no luck.
So far this code just removed the datetimepicker widget on the fields that were already working. So it may just be a format issue.

Body:
The place where the added needs to be put is in the django-dynamic-formset call, rather than in the addEventListener code, as the call is done by django-dynamic-formset itself.

That is: (note: I haven't tested this myself because I'm on phone at the moment)

<script type="text/javascript">

    function applyFlatpickr(parent) {
     flatpickr(parent.find(".datetimefield"), {
                enableTime: true,
                enableSeconds: true,
                dateFormat: "Y-m-d H:i:S",
            });
    }
    <!-- Makes DateTimeFields Show Picker-->
        // This code activates flatpickr on fields with the 'datetimefield' class when the document has loaded
        window.addEventListener("DOMContentLoaded", function(){applyFlatpickr($(document))});

        $('.formset_row').formset({
            addText: 'add entry',
            deleteText: 'remove',
            prefix: 'entry_set',
            added: applyFlatpickr
        });
    </script>
</script>

django-dynamic-formset passes the newly created row to the added function as a jQuery object, so by using .find on the argument we can match only the newly added row and apply flatpickr only to that new row.

From the django-dynamic-formset docs:

added
      If you set this to a function, that function will be called each
      time a new form is added. The function should take a single argument,
      row; it will be passed a jQuery object, wrapping the form that
      was just added.)


来源: stackexchange

问:
AWS Lambda using Asynchronous code returns NULL
This question is a follow up question, the link to the other question is --
aws lambda function async connection query

I am developing server code using AWS Lambda and to test the asynchronous connection I am using the same code provided by Trung with improvement by giankotarola and the output of the Lambda Function comes only if I replace  --

1. return callback(null, {body: JSON.stringify(result),statusCode:200});

with --

2. return result;

Also, at the following line --

3. pool.getConnection((err, connection) => {

It gives a warning:  Expected Error to be handled

I cannot understand why the code at Line 1. mentioned above doesn't work ? And how to handle the warning at 3.

答:
The first issue is because the function is using async. With async functions you just return the result. The callback is used when you are not using async.

I believe the second issue is because the err on that call isn't handled. There is a handler for the second err, but not this one. Basically that code should look like this:

let getOrder = async (sql, params) => {
    return new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
            if (err){
                reject(err);
            }
            else {
                connection.query(sql, params, (err, results) => {
                    if (err){
                        reject(err);
                    }
                    else {
                        console.log("-----Query Done!");
                        connection.release();
                        console.log("-----Data: ", results);
                        resolve(results);
                    }
                }
            });
        });
    });
};
```

ContentLicense: CC BY-SA 4.0


问:
R saving new column names for dataframe
I am new to R, coming from mostly Python, and still in the testing phase of whether I need both or just Python.

I imported the iris dataset from the UCI repo and changed the column names but then when I save it and load it again, it does not have the new column names.

```<code># read in csv and change col names
iris = read.csv(file="/home/n/Desktop/stat3990/data/iris.data")
plot(iris[,3:4])

#install.packages("plyr")
library("plyr")
rename(iris, c("X5.1"="sepal.len", "X3.5"="sepal.wid", "X1.4"="petal.len", "X0.2"="petal.wid", "Iris.setosa"="class"))
save(iris, file="iris.rda")
load("iris.rda")
</code>```

I have tried saving the data as Rdata, .csv but none seem to save the new columnn names.

Also this is such a famous dataset that it is weird for the column names to be so confusing in the first place but this is another issue.

答:
May be the issue is that the OP didn't assign

```<code>iris <- plyr::rename(iris, c("X5.1"="sepal.len", "X3.5"="sepal.wid",
        "X1.4"="petal.len", "X0.2"="petal.wid", "Iris.setosa"="class"))
</code>```

With the assignment, the column names are changed in the original object

With a reproducible example

```<code>data(iris)
iris1 <- plyr::rename(iris, c("Sepal.Length" = "X5.1", "Sepal.Width" = "X3.5"));
save(iris1, file = "iris.rda")
load("iris.rda")
</code>```

Title: R saving new column names for dataframe

Body:
I am new to R, coming from mostly Python, and still in the testing phase of whether I need both or just Python.

I imported the iris dataset from the UCI repo and changed the column names but then when I save it and load it again, it does not have the new column names.

# read in csv and change col names
iris = read.csv(file="/home/n/Desktop/stat3990/data/iris.data")
plot(iris[,3:4])

#install.packages("plyr")
library("plyr")
rename(iris, c("X5.1"="sepal.len", "X3.5"="sepal.wid", "X1.4"="petal.len", "X0.2"="petal.wid", "Iris.setosa"="class"))
save(iris, file="iris.rda")
load("iris.rda")

I have tried saving the data as Rdata, .csv but none seem to save the new columnn names.

Also this is such a famous dataset that it is weird for the column names to be so confusing in the first place but this is another issue.

Body:
May be the issue is that the OP didn't assign

iris <- plyr::rename(iris, c("X5.1"="sepal.len", "X3.5"="sepal.wid",
        "X1.4"="petal.len", "X0.2"="petal.wid", "Iris.setosa"="class"))

With the assignment, the column names are changed in the original object

With a reproducible example

data(iris)
iris1 <- plyr::rename(iris, c("Sepal.Length" = "X5.1", "Sepal.Width" = "X3.5"));
save(iris1, file = "iris.rda")
load("iris.rda")


问:
Pasting multiple images in a word doc
I need assistance in building a macro that would take the image that is stored in the clipboard and paste it in the word doc. There will be multiple images so sequential images must be pasted at the end of the document.

Here is my current code so far

' Create word document and paste to word

```<code>Set wordobj = CreateObject("Word.Application")
Set objdoc = wordobj.Documents.Add
wordobj.Visible = True
Set objSelection = wordobj.Selection
objSelection.Paste
</code>```

' Paste in the active end of the word document
'??? tried multiple lines but it gives "object" error

```<code>objdoc.ActiveDocument.Content
objdoc.Collapse Direction:=wdCollapseEnd
objSelection.Paste.Paste
</code>```

Any assistance will be helpful

答:
Since your code creates a new document each time it's run, the only way there'd be anything to paste over is if that new document already has some content. But since you don't even specify a template to load from, that can only mean Word's 'Normal' template, which should never have any content. Regardless, it's as simple as:</p>

```<code>Sub Demo()
Dim wordobj As Object, objdoc As Object
Set wordobj = CreateObject("Word.Application")
Set objdoc = wordobj.Documents.Add
With objdoc.Range
  .InsertAfter vbCr
  .Characters.Last.Paste
End With
End Sub
</code>```

Title: Pasting multiple images in a word doc

Body:
I need assistance in building a macro that would take the image that is stored in the clipboard and paste it in the word doc. There will be multiple images so sequential images must be pasted at the end of the document.

Here is my current code so far

' Create word document and paste to word

Set wordobj = CreateObject("Word.Application")
Set objdoc = wordobj.Documents.Add
wordobj.Visible = True
Set objSelection = wordobj.Selection
objSelection.Paste

' Paste in the active end of the word document
'??? tried multiple lines but it gives "object" error

objdoc.ActiveDocument.Content
objdoc.Collapse Direction:=wdCollapseEnd
objSelection.Paste.Paste

Any assistance will be helpful

Body:
Since your code creates a new document each time it's run, the only way there'd be anything to paste over is if that new document already has some content. But since you don't even specify a template to load from, that can only mean Word's 'Normal' template, which should never have any content. Regardless, it's as simple as:

Sub Demo()
Dim wordobj As Object, objdoc As Object
Set wordobj = CreateObject("Word.Application")
Set objdoc = wordobj.Documents.Add
With objdoc.Range
  .InsertAfter vbCr
  .Characters.Last.Paste
End With
End Sub


问:
what is difference between rtmp and rtsp protocol?
i just want to know what is the difference between rtsp and rtmp protocol and if  there are mp3s on my server and i am playing it in my android using http,how these differs in work.

In android if i want to implement rtmp or rtsp ,which is the best?
what are the limitation of rtmp & rtsp in android?

can anybody give me brief answer for above?

答:
The Real Time Streaming Protocol (RTSP) is a network control protocol designed for use in entertainment and communications systems to control streaming media servers. The protocol is used for establishing and controlling media sessions between end points. Clients of media servers issue VCR-like commands, such as play and pause, to facilitate real-time control of playback of media files from the server.

Real Time Messaging Protocol (RTMP) was initially a proprietary protocol developed by Macromedia for streaming audio, video and data over the Internet, between a Flash player and a server.

I would use HTTP to stream MP3.

ContentLicense: CC BY-SA 3.0


问:
Could not get to a route in asp.net core
Why can't I get to the controller in my asp.net core application. Please see code below.

```<code>using System;
using System.Threading.Tasks;
using HashingApplication;
using Microsoft.AspNetCore.Mvc;
using NgWithJwt.Models;

namespace NgWithJwt.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ApplicationDbContext context;

        public UserController(ApplicationDbContext context)
        {
            this.context = context;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("add-user")]
        public async Task<IActionResult> AddUser(AppUser model)
        {
            if (ModelState.IsValid)
            {
                var saltValue = Guid.NewGuid().ToString() + model.Password;
                var password = Encryption.Encrypt(model.Password, saltValue);

                model.SaltValue = saltValue;
                model.Password = password;
                model.CreatedDate = DateTime.Now;

                context.Add(model);
                var response = await context.SaveChangesAsync();
                if(response > 0)
                {
                    return Ok(model);
                }
            }
            return BadRequest();
        }
    }
}
</code>```

This is my class for model

```<code> public partial class AppUser
    {
        [Key]
        public int Id { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Username is required.")]
        [DisplayName("Username")]
        public string UserName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "First Name is required")]
        [DisplayName("First Name")]
        public string FirstName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [DisplayName("Middle Name")]
        public string MiddleName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Last Name is required")]
        [DisplayName("Last Name")]
        public string LastName { get; set; }

        [Column(TypeName = "nvarchar(max)")]
        public string SaltValue { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Password is required")]
        [DisplayName("Password")]
        public string Password { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string UserType { get; set; }
        public DateTime CreatedDate { get; set; }
    }
</code>```

My server is running so I try accessing it with postman like so:

```<code>{
    "Username": "juan",
    "FirstName": "Juan",
    "MiddleName": "A.",
    "LastName": "Dela Cruz",
    "Password": "password",
    "UserType": "User"
}
</code>```

Server is running at

"https://localhost:44366/"

I use this url to post data

http://localhost:44366/api/user/add-user

This is the error I get on postman. I am using the debug mode to get to my controller break point.

答: @Jason answer could be solve your problem but I have this problem sometimes when using postman because I forgot to turn off the SSL certificate verification

Body:
Why can't I get to the controller in my asp.net core application. Please see code below.

using System;
using System.Threading.Tasks;
using HashingApplication;
using Microsoft.AspNetCore.Mvc;
using NgWithJwt.Models;

namespace NgWithJwt.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ApplicationDbContext context;

        public UserController(ApplicationDbContext context)
        {
            this.context = context;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("add-user")]
        public async Task<IActionResult> AddUser(AppUser model)
        {
            if (ModelState.IsValid)
            {
                var saltValue = Guid.NewGuid().ToString() + model.Password;
                var password = Encryption.Encrypt(model.Password, saltValue);

                model.SaltValue = saltValue;
                model.Password = password;
                model.CreatedDate = DateTime.Now;

                context.Add(model);
                var response = await context.SaveChangesAsync();
                if(response > 0)
                {
                    return Ok(model);
                }
            }
            return BadRequest();
        }
    }
}

This is my class for model

 public partial class AppUser
    {
        [Key]
        public int Id { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Username is required.")]
        [DisplayName("Username")]
        public string UserName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "First Name is required")]
        [DisplayName("First Name")]
        public string FirstName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [DisplayName("Middle Name")]
        public string MiddleName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Last Name is required")]
        [DisplayName("Last Name")]
        public string LastName { get; set; }

        [Column(TypeName = "nvarchar(max)")]
        public string SaltValue { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Password is required")]
        [DisplayName("Password")]
        public string Password { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string UserType { get; set; }
        public DateTime CreatedDate { get; set; }
    }

My server is running so I try accessing it with postman like so:

{
    "Username": "juan",
    "FirstName": "Juan",
    "MiddleName": "A.",
    "LastName": "Dela Cruz",
    "Password": "password",
    "UserType": "User"
}

Server is running at

"https://localhost:44366/"

I use this url to post data

http://localhost:44366/api/user/add-user

This is the error I get on postman. I am using the debug mode to get to my controller break point.


问:
how to fill missing values in a vector with the mean of value before and after the missing one
Currently I am trying to impute values in a vector in R. The conditions
of the imputation are.

Find all NA values

Then check if they have an existing value before and after them

Also check if the value which follows the NA is larger than
the value before the NA

If the conditions are met, calculate a mean taking the values before
and after.

Replace the NA value with the imputed one

```<code># example one
input_one = c(1,NA,3,4,NA,6,NA,NA)

# example two
input_two = c(NA,NA,3,4,5,6,NA,NA)

# example three
input_three = c(NA,NA,3,4,NA,6,NA,NA)

</code>```

I started out to write code to detect the values which can
be imputed. But I got stuck with the following.

```<code># incomplete function to detect the values
sapply(split(!is.na(input[c(rbind(which(is.na(c(input)))-1, which(is.na(c(input)))+1))]),
             rep(1:(length(!is.na(input[c(which(is.na(c(input)))-1, which(is.na(c(input)))+1)]))/2), each = 2)), all)
</code>```

This however only detects the NAs which might be
imputable and it only works with example one. It is incomplete and
unfortunately super hard to read and understand.

Any help with this would be highly appreciated.

答:
There is also the na_ma function in the imputeTS package for imputing moving averages.

In your case this would be with the following settings:

na_ma(x, k = 1, weighting = "simple")

k = 1 (meaning 1 value before and 1 after the NA are taken into account)

weighting = "simple" (the mean of these two values is calculated)

This can be applied quite easy with basically 1 line of code:

```<code>library(imputeTS)
na_ma(yourData, k = 1, weighting = "simple")
</code>```

You could also choose to take more values before and after the NA into account e.g. k=3. Interesting feature if you take more than 1 value to each side into account is the possibility to choose a different weighting e.g. with weighting = "linear" weights decrease in arithmetical progression (a Linear Weighted Moving Average) - meaning the further they values are away from the NA the less impact they have.

Body:
Currently I am trying to impute values in a vector in R. The conditions
of the imputation are.

Find all NA values

Then check if they have an existing value before and after them

Also check if the value which follows the NA is larger than
the value before the NA

If the conditions are met, calculate a mean taking the values before
and after.

Replace the NA value with the imputed one

# example one
input_one = c(1,NA,3,4,NA,6,NA,NA)

# example two
input_two = c(NA,NA,3,4,5,6,NA,NA)

# example three
input_three = c(NA,NA,3,4,NA,6,NA,NA)

I started out to write code to detect the values which can
be imputed. But I got stuck with the following.

# incomplete function to detect the values
sapply(split(!is.na(input[c(rbind(which(is.na(c(input)))-1, which(is.na(c(input)))+1))]),
             rep(1:(length(!is.na(input[c(which(is.na(c(input)))-1, which(is.na(c(input)))+1)]))/2), each = 2)), all)

This however only detects the NAs which might be
imputable and it only works with example one. It is incomplete and
unfortunately super hard to read and understand.

Any help with this would be highly appreciated.

Body:
There is also the na_ma function in the imputeTS package for imputing moving averages.

In your case this would be with the following settings:

na_ma(x, k = 1, weighting = "simple")

k = 1 (meaning 1 value before and 1 after the NA are taken into account)

weighting = "simple" (the mean of these two values is calculated)

This can be applied quite easy with basically 1 line of code:

library(imputeTS)
na_ma(yourData, k = 1, weighting = "simple")

You could also choose to take more values before and after the NA into account e.g. k=3. Interesting feature if you take more than 1 value to each side into account is the possibility to choose a different weighting e.g. with weighting = "linear" weights decrease in arithmetical progression (a Linear Weighted Moving Average) - meaning the further they values are away from the NA the less impact they have.


问:
how to post XML to URL in Javascript
how can i post this xml to url htttp://191.165.0.51:1024/LaunchRemoteXml.ashx in Javascript

```<code>           <Pipeline Name="MyTest">

                          <Task Name="EmailReport" Timeout="0" Enabled="true" OnFail="Abort" NotifyOnError="true" CodeBase="phynn.Workflow.TaskSmtp@workflow.base.dll">

                          <Smtp>

                                         <Message From="NoOne@directmailers.com" To="xyz@we.com" Subject="TestLaunch" IsHtml="false" Priority="Normal">

                                                        <Body>Hi</Body>

                                         </Message>

                          </Smtp>

                          </Task>

           </Pipeline>
</code>```

答:
If you limit Vanilla.js only, you can use XMLHttpRequest

You can see how to use it from the link

If the xml is a file, you can refer to the link

Or use Jquery ajax

```<code>$.ajax({
  url: ajaxurl,
  data: "<test></test>",
  type: 'POST',
  contentType: "text/xml",
  dataType: "text",
  success : function(data, textStatus, qXHR){
    //do something
  },
  error : function (xhr, ajaxOptions, thrownError){
    //do something
  }
});
</code>```

For more usage of ajax, please refer to the link

Title: how to post XML to URL in Javascript

Body:
how can i post this xml to url htttp://191.165.0.51:1024/LaunchRemoteXml.ashx in Javascript

           <Pipeline Name="MyTest">

                          <Task Name="EmailReport" Timeout="0" Enabled="true" OnFail="Abort" NotifyOnError="true" CodeBase="phynn.Workflow.TaskSmtp@workflow.base.dll">

                          <Smtp>

                                         <Message From="NoOne@directmailers.com" To="xyz@we.com" Subject="TestLaunch" IsHtml="false" Priority="Normal">

                                                        Hi

                                         </Message>

                          </Smtp>

                          </Task>

           </Pipeline>

Body:
If you limit Vanilla.js only, you can use XMLHttpRequest

You can see how to use it from the link

If the xml is a file, you can refer to the link

Or use Jquery ajax

$.ajax({
  url: ajaxurl,
  data: "<test></test>",
  type: 'POST',
  contentType: "text/xml",
  dataType: "text",
  success : function(data, textStatus, qXHR){
    //do something
  },
  error : function (xhr, ajaxOptions, thrownError){
    //do something
  }
});

For more usage of ajax, please refer to the link


问:
Swift- Using Delegation to append data to TableView within CollectionView
I have a CollectionViewController named yearOnethat looks something like this:

When you click the add button for each quarter cell it leads you to SearchPage:

I used delegation to append the data clicked on SearchPage to yearOne
The delegation seems to work and data seems to append as I tried the print(vc.data) but it doesn't seem to show up on the tableView when backed into yearOne viewcontroller through navigationController?.popViewController(animated: true) Am I doing something wrong?

```<code>import UIKit

class yearOne: UICollectionViewController, coursesDelegate {

    let customCellIdentifier = "cellID"
    let customCellIdentifier2 = "cellID2"
    let customCellIdentifier3 = "cellID3"
    let customCellIdentifier4 = "cellID4"

    let quarters = [
        customLabel (title: "Fall Quarter"),
        customLabel (title: "Winter Quarter"),
        customLabel (title: "Spring Quarter"),
        customLabel (title: "Summer Quarter")
    ]

    let vc = fallQuarterCell()
    let vc2 = winterQuarterCell()
    let vc3 = springQuarterCell()
    let vc4 = summerQuarterCell()

    func sendDataBackFall(data: String) {
        vc.data.append(data)
        print(vc.data)
        //UserDefaults.standard.set(vc.data, forKey: "SavedArray")

    }
    func sendDataBackWinter(data2: String) {
        vc2.data.append(data2)
    }
    func sendDataBackSpring(data3: String) {
        vc3.data.append(data3)
    }
    func sendDataBackSummer(data4: String) {
        vc4.data.append(data4)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        vc.tableView.reloadData()
        collectionView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.dataSource = self
        collectionView.delegate = self

        self.collectionView!.register(fallQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier)//
        self.collectionView!.register(winterQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier2)
        self.collectionView!.register(springQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier3)
        self.collectionView!.register(summerQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier4)

        navigationItem.title = "Year One"
        navigationController?.navigationBar.prefersLargeTitles = true
        collectionView?.backgroundColor = .lightGray

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return quarters.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if (indexPath.row == 0){
            let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as! fallQuarterCell
            cell1.layer.borderColor = UIColor.orange.cgColor
            cell1.layer.borderWidth = 2
            cell1.layer.cornerRadius = 5
            cell1.quarters = self.quarters[0]
            return cell1
        }
        else if (indexPath.row == 1){
            let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier2, for: indexPath) as! winterQuarterCell
            cell2.layer.borderColor = UIColor.blue.cgColor
            cell2.layer.borderWidth = 2
            cell2.layer.cornerRadius = 5
            cell2.quarters = self.quarters[1]
            return cell2
        }
        else if (indexPath.row == 2){
            let cell3 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier3, for: indexPath) as! springQuarterCell
            cell3.layer.borderColor = UIColor.green.cgColor
            cell3.layer.borderWidth = 2
            cell3.layer.cornerRadius = 5
            cell3.quarters = self.quarters[2]
            return cell3
        }
        else if (indexPath.row == 3){
            let cell4 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier4, for: indexPath) as! summerQuarterCell
            cell4.layer.borderColor = UIColor.red.cgColor
            cell4.layer.cornerRadius = 5
            cell4.quarters = self.quarters[3]
            return cell4
        }
        else{
            return UICollectionViewCell()
        }
    }

    @objc func buttonAction(sender: UIButton!) {
        switch sender.tag {
        case 0:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 1:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 2:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 3:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        default:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        }

    }
}

extension yearOne : UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (view.frame.width - 30)
        return CGSize(width: width, height: 200)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        UIEdgeInsets(top: 30, left: 10, bottom: 30, right: 10)
    }

}

class fallQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {

    //var data = UserDefaults.standard.object(forKey: "SavedArray") as? [String] ?? [String]()

    var data : [String] = []

//    func load(){
//        if let loadeddata: [String] = UserDefaults.standard.object(forKey: "SavedArray") as? [String] {
//            data = loadeddata
//            tableView.reloadData()
//        }
//    }

    let cellId = "coursesName"

    let tableView:UITableView = {
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.backgroundColor = UIColor.white
        return tableView
    }()

    override init(frame: CGRect){
        super.init(frame: frame)
        addSubview(tableView)
        setupView()
    }

    func setupView(){

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.backgroundColor = UIColor.white
        contentView.addSubview(quarterLabel)
        contentView.addSubview(addButton)

        quarterLabel.translatesAutoresizingMaskIntoConstraints = false
        quarterLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
        quarterLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true

        addButton.translatesAutoresizingMaskIntoConstraints = false
        addButton.topAnchor.constraint(equalTo: quarterLabel.topAnchor, constant: -5).isActive = true
        addButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        addButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
        addButton.widthAnchor.constraint(equalToConstant: 25).isActive = true

        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 35).isActive = true
        tableView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5).isActive = true
        tableView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5).isActive = true
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        cell.textLabel?.text = data[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == .delete) {
            if (indexPath.row == 0){
                data.remove(at: 0)
                //UserDefaults.standard.set(data, forKey: "SavedArray")
                self.tableView.reloadData()
            }
            else if (indexPath.row == 1){
                data.remove(at: 1)
                //UserDefaults.standard.set(data, forKey: "SavedArray")
                self.tableView.reloadData()
            }
            else if (indexPath.row == 2){
                data.remove(at: 2)
                //UserDefaults.standard.set(data, forKey: "SavedArray")
                self.tableView.reloadData()
            }
            else if (indexPath.row == 3){
                data.remove(at: 3)
                //UserDefaults.standard.set(data, forKey: "SavedArray")
                self.tableView.reloadData()
            }
            else if (indexPath.row == 4){
                data.remove(at: 4)
                //UserDefaults.standard.set(data, forKey: "SavedArray")
                self.tableView.reloadData()
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //add class information???
    }

    var quarters: customLabel? {
        didSet {
            guard let quarters = quarters else {return}
            quarterLabel.text = quarters.title
        }
    }

    let quarterLabel : UILabel = {
        let label = UILabel()//frame: CGRect(x: 15, y: -75, width: 300, height: 50))
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.black
        label.font = UIFont.boldSystemFont(ofSize: 16)
        //label.textAlignment = .center
        return label
    }()

    let addButton : UIButton = {
        let button = UIButton()//frame: CGRect(x: 345, y: 10, width: 30, height: 30))
        button.setImage(UIImage(named: "addicon"), for: .normal)
        button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        button.tag = 0
        button.addTarget(self, action: #selector(yearOne.buttonAction), for: .touchUpInside)
        return button
    }()

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
</code>```

I also have the

class winterQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class springQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class summerQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

similar to fallQuarterCell but excluded it.

```<code>import UIKit

protocol coursesDelegate {
    func sendDataBackFall(data: String)
    func sendDataBackWinter(data2: String)
    func sendDataBackSpring(data3: String)
    func sendDataBackSummer(data4: String)
}

class SearchPage: UITableViewController {

    var delegate: coursesDelegate?

    let cellId = "course"

    var allCourses : NSArray = NSArray()
    var filteredCourses = [String]()
    var resultSearchController = UISearchController()

    var tag: Int?
    let vc = fallQuarterCell()
    let vc2 = winterQuarterCell()
    let vc3 = springQuarterCell()
    let vc4 = summerQuarterCell()

    override func viewDidLoad() {
        super.viewDidLoad()

        let courses : CourseList = CourseList()
        allCourses = courses.coursesList

        navigationItem.title = "Select Courses"
        navigationController?.navigationBar.prefersLargeTitles = true

        //let button1 = UIBarButtonItem(title: "Add Course", style: .plain, target: self, action: #selector(addTapped))
        //self.navigationItem.rightBarButtonItem = button1

        self.view.backgroundColor = .systemBackground

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.tableView.tableFooterView = UIView()

        resultSearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.obscuresBackgroundDuringPresentation = false
            controller.searchBar.placeholder = "Search Courses"
            controller.searchBar.sizeToFit()

            tableView.tableHeaderView = controller.searchBar

            return controller
        })()

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if  (resultSearchController.isActive) {
            return filteredCourses.count
        }
        else{
            return allCourses.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        if (resultSearchController.isActive) {
            cell.textLabel?.text = filteredCourses[indexPath.row]
            return cell
         }
         else {
            let courses = self.allCourses[indexPath.row]
            cell.textLabel?.text = courses as? String
            return cell
         }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)

        if (tag == 0){
            if (resultSearchController.isActive){
//                vc.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(vc.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = filteredCourses[indexPath.row]
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
            else{
//                vc.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(vc.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = allCourses[indexPath.row] as! String
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
        }

        else if (tag == 1){
            if (resultSearchController.isActive){
//                vc2.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(vc2.data, forKey: "SavedArray2")
//                self.navigationController?.popViewController(animated: true)
                let data = filteredCourses[indexPath.row]
                delegate?.sendDataBackWinter(data2: data)
                self.navigationController?.popViewController(animated: true)
            }
            else{
//                vc2.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(vc2.data, forKey: "SavedArray2")
//                self.navigationController?.popViewController(animated: true)
                let data = allCourses[indexPath.row] as! String
                delegate?.sendDataBackWinter(data2: data)
                self.navigationController?.popViewController(animated: true)
            }
        }

        else if (tag == 2){
            if (resultSearchController.isActive){
//                vc3.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(vc3.data, forKey: "SavedArray3")
//                self.navigationController?.popViewController(animated: true)

            }
            else{
//                vc3.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(vc3.data, forKey: "SavedArray3")
//                self.navigationController?.popViewController(animated: true)
            }
        }

        else if (tag == 3){
            if (resultSearchController.isActive){
//                vc4.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(vc4.data, forKey: "SavedArray4")
//                self.navigationController?.popViewController(animated: true)

            }
            else{
//                vc4.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(vc4.data, forKey: "SavedArray4")
//                self.navigationController?.popViewController(animated: true)
            }
        }

    }

    var isSearchBarEmpty: Bool {
      return resultSearchController.searchBar.text?.isEmpty ?? true
    }
}

extension SearchPage: UISearchResultsUpdating {

  func updateSearchResults(for searchController: UISearchController) {
      filteredCourses.removeAll(keepingCapacity: false)

      let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
      let array = (allCourses as NSArray).filtered(using: searchPredicate)
      filteredCourses = array as! [String]

      self.tableView.reloadData()
  }

}
</code>```

I commented out the UsersDefault.standard.set.... because the data itself doesn't seem to refresh and display in the tableView atm

答: Check at your cellForRow method. I don't believe you set the text anywhere.</p>

Body:
I have a CollectionViewController named yearOnethat looks something like this:

When you click the add button for each quarter cell it leads you to SearchPage:

I used delegation to append the data clicked on SearchPage to yearOne
The delegation seems to work and data seems to append as I tried the print(vc.data) but it doesn't seem to show up on the tableView when backed into yearOne viewcontroller through navigationController?.popViewController(animated: true) Am I doing something wrong?

import UIKit

class yearOne: UICollectionViewController, coursesDelegate {

    let customCellIdentifier = "cellID"
    let customCellIdentifier2 = "cellID2"
    let customCellIdentifier3 = "cellID3"
    let customCellIdentifier4 = "cellID4"

    let quarters = [
        customLabel (title: "Fall Quarter"),
        customLabel (title: "Winter Quarter"),
        customLabel (title: "Spring Quarter"),
        customLabel (title: "Summer Quarter")
    ]

    let vc = fallQuarterCell()
    let vc2 = winterQuarterCell()
    let vc3 = springQuarterCell()
    let vc4 = summerQuarterCell()

    func sendDataBackFall(data: String) {
        vc.data.append(data)
        print(vc.data)
        //UserDefaults.standard.set(vc.data, forKey: "SavedArray")

    }
    func sendDataBackWinter(data2: String) {
        vc2.data.append(data2)
    }
    func sendDataBackSpring(data3: String) {
        vc3.data.append(data3)
    }
    func sendDataBackSummer(data4: String) {
        vc4.data.append(data4)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        vc.tableView.reloadData()
        collectionView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.dataSource = self
        collectionView.delegate = self

        self.collectionView!.register(fallQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier)//
        self.collectionView!.register(winterQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier2)
        self.collectionView!.register(springQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier3)
        self.collectionView!.register(summerQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier4)

        navigationItem.title = "Year One"
        navigationController?.navigationBar.prefersLargeTitles = true
        collectionView?.backgroundColor = .lightGray

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return quarters.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if (indexPath.row == 0){
            let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as! fallQuarterCell
            cell1.layer.borderColor = UIColor.orange.cgColor
            cell1.layer.borderWidth = 2
            cell1.layer.cornerRadius = 5
            cell1.quarters = self.quarters[0]
            return cell1
        }
        else if (indexPath.row == 1){
            let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier2, for: indexPath) as! winterQuarterCell
            cell2.layer.borderColor = UIColor.blue.cgColor
            cell2.layer.borderWidth = 2
            cell2.layer.cornerRadius = 5
            cell2.quarters = self.quarters[1]
            return cell2
        }
        else if (indexPath.row == 2){
            let cell3 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier3, for: indexPath) as! springQuarterCell
            cell3.layer.borderColor = UIColor.green.cgColor
            cell3.layer.borderWidth = 2
            cell3.layer.cornerRadius = 5
            cell3.quarters = self.quarters[2]
            return cell3
        }
        else if (indexPath.row == 3){
            let cell4 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier4, for: indexPath) as! summerQuarterCell
            cell4.layer.borderColor = UIColor.red.cgColor
            cell4.layer.cornerRadius = 5
            cell4.quarters = self.quarters[3]
            return cell4
        }
        else{
            return UICollectionViewCell()
        }
    }

    @objc func buttonAction(sender: UIButton!) {
        switch sender.tag {
        case 0:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 1:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 2:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 3:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        default:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        }

    }
}

extension yearOne : UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (view.frame.width - 30)
        return CGSize(width: width, height: 200)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        UIEdgeInsets(top: 30, left: 10, bottom: 30, right: 10)
    }

}

class fallQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {

    //var data = UserDefaults.standard.object(forKey: "SavedArray") as? [String] ?? [String]()

    var data : [String] = []

//    func load(){
//        if let loadeddata: [String] = UserDefaults.standard.object(forKey: "SavedArray") as? [String] {
//            data = loadeddata
//            tableView.reloadData()
//        }
//    }

    let cellId = "coursesName"

    let tableView:UITableView = {
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.backgroundColor = UIColor.white
        return tableView
    }()

    override init(frame: CGRect){
        super.init(frame: frame)
        addSubview(tableView)
        setupView()
    }

    func setupView(){

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.backgroundColor = UIColor.white
        contentView.addSubview(quarterLabel)
        contentView.addSubview(addButton)

        quarterLabel.translatesAutoresizingMaskIntoConstraints = false
        quarterLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
        quarterLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true

        addButton.translatesAutoresizingMaskIntoConstraints = false
        addButton.topAnchor.constraint(equalTo: quarterLabel.topAnchor, constant: -5).isActive = true
        addButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        addButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
        addButton.widthAnchor.constraint(equalToConstant: 25).isActive = true

        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 35).isActive = true
        tableView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5).isActive = true
        tableView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5).isActive = true
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        cell.textLabel?.text = data[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == .delete) {
            if (indexPath.row == 0){
                data.remove(at: 0)
                //UserDefaults.standard.set(data, forKey: "SavedArray")
                self.tableView.reloadData()
            }
            else if (indexPath.row == 1){
                data.remove(at: 1)
                //UserDefaults.standard.set(data, forKey: "SavedArray")
                self.tableView.reloadData()
            }
            else if (indexPath.row == 2){
                data.remove(at: 2)
                //UserDefaults.standard.set(data, forKey: "SavedArray")
                self.tableView.reloadData()
            }
            else if (indexPath.row == 3){
                data.remove(at: 3)
                //UserDefaults.standard.set(data, forKey: "SavedArray")
                self.tableView.reloadData()
            }
            else if (indexPath.row == 4){
                data.remove(at: 4)
                //UserDefaults.standard.set(data, forKey: "SavedArray")
                self.tableView.reloadData()
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //add class information???
    }

    var quarters: customLabel? {
        didSet {
            guard let quarters = quarters else {return}
            quarterLabel.text = quarters.title
        }
    }

    let quarterLabel : UILabel = {
        let label = UILabel()//frame: CGRect(x: 15, y: -75, width: 300, height: 50))
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.black
        label.font = UIFont.boldSystemFont(ofSize: 16)
        //label.textAlignment = .center
        return label
    }()

    let addButton : UIButton = {
        let button = UIButton()//frame: CGRect(x: 345, y: 10, width: 30, height: 30))
        button.setImage(UIImage(named: "addicon"), for: .normal)
        button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        button.tag = 0
        button.addTarget(self, action: #selector(yearOne.buttonAction), for: .touchUpInside)
        return button
    }()

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

I also have the

class winterQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class springQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class summerQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

similar to fallQuarterCell but excluded it.

import UIKit

protocol coursesDelegate {
    func sendDataBackFall(data: String)
    func sendDataBackWinter(data2: String)
    func sendDataBackSpring(data3: String)
    func sendDataBackSummer(data4: String)
}

class SearchPage: UITableViewController {

    var delegate: coursesDelegate?

    let cellId = "course"

    var allCourses : NSArray = NSArray()
    var filteredCourses = [String]()
    var resultSearchController = UISearchController()

    var tag: Int?
    let vc = fallQuarterCell()
    let vc2 = winterQuarterCell()
    let vc3 = springQuarterCell()
    let vc4 = summerQuarterCell()

    override func viewDidLoad() {
        super.viewDidLoad()

        let courses : CourseList = CourseList()
        allCourses = courses.coursesList

        navigationItem.title = "Select Courses"
        navigationController?.navigationBar.prefersLargeTitles = true

        //let button1 = UIBarButtonItem(title: "Add Course", style: .plain, target: self, action: #selector(addTapped))
        //self.navigationItem.rightBarButtonItem = button1

        self.view.backgroundColor = .systemBackground

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.tableView.tableFooterView = UIView()

        resultSearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.obscuresBackgroundDuringPresentation = false
            controller.searchBar.placeholder = "Search Courses"
            controller.searchBar.sizeToFit()

            tableView.tableHeaderView = controller.searchBar

            return controller
        })()

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if  (resultSearchController.isActive) {
            return filteredCourses.count
        }
        else{
            return allCourses.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        if (resultSearchController.isActive) {
            cell.textLabel?.text = filteredCourses[indexPath.row]
            return cell
         }
         else {
            let courses = self.allCourses[indexPath.row]
            cell.textLabel?.text = courses as? String
            return cell
         }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)

        if (tag == 0){
            if (resultSearchController.isActive){
//                vc.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(vc.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = filteredCourses[indexPath.row]
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
            else{
//                vc.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(vc.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = allCourses[indexPath.row] as! String
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
        }

        else if (tag == 1){
            if (resultSearchController.isActive){
//                vc2.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(vc2.data, forKey: "SavedArray2")
//                self.navigationController?.popViewController(animated: true)
                let data = filteredCourses[indexPath.row]
                delegate?.sendDataBackWinter(data2: data)
                self.navigationController?.popViewController(animated: true)
            }
            else{
//                vc2.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(vc2.data, forKey: "SavedArray2")
//                self.navigationController?.popViewController(animated: true)
                let data = allCourses[indexPath.row] as! String
                delegate?.sendDataBackWinter(data2: data)
                self.navigationController?.popViewController(animated: true)
            }
        }

        else if (tag == 2){
            if (resultSearchController.isActive){
//                vc3.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(vc3.data, forKey: "SavedArray3")
//                self.navigationController?.popViewController(animated: true)

            }
            else{
//                vc3.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(vc3.data, forKey: "SavedArray3")
//                self.navigationController?.popViewController(animated: true)
            }
        }

        else if (tag == 3){
            if (resultSearchController.isActive){
//                vc4.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(vc4.data, forKey: "SavedArray4")
//                self.navigationController?.popViewController(animated: true)

            }
            else{
//                vc4.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(vc4.data, forKey: "SavedArray4")
//                self.navigationController?.popViewController(animated: true)
            }
        }

    }

    var isSearchBarEmpty: Bool {
      return resultSearchController.searchBar.text?.isEmpty ?? true
    }
}

extension SearchPage: UISearchResultsUpdating {

  func updateSearchResults(for searchController: UISearchController) {
      filteredCourses.removeAll(keepingCapacity: false)

      let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
      let array = (allCourses as NSArray).filtered(using: searchPredicate)
      filteredCourses = array as! [String]

      self.tableView.reloadData()
  }

}

I commented out the UsersDefault.standard.set.... because the data itself doesn't seem to refresh and display in the tableView atm


Title: Sort list of strings numerically and filter duplicates?

Body:
Given a list of strings in the following format:

[
    "464782,-100,4,3,1,100,0,0"
    "465042,-166.666666666667,4,3,1,100,0,0",
    "465825,-250.000000000001,4,3,1,100,0,0",
    "466868,-166.666666666667,4,3,1,100,0,0",
    "467390,-200.000000000001,4,3,1,100,0,0",
    "469999,-100,4,3,1,100,0,0",
    "470260,-166.666666666667,4,3,1,100,0,0",
    "474173,-100,4,3,1,100,0,0",
    "474434,-166.666666666667,4,3,1,100,0,0",
    "481477,-100,4,3,1,100,0,1",
    "531564,259.011439671919,4,3,1,60,1,0",
    "24369,-333.333333333335,4,3,1,100,0,0",
    "21082,410.958904109589,4,3,1,60,1,0",
    "21082,-250,4,3,1,100,0,0",
    "22725,-142.857142857143,4,3,1,100,0,0",
    "23547,-166.666666666667,4,3,1,100,0,0",
    "24369,-333.333333333335,4,3,1,100,0,0",
    "27657,-200.000000000001,4,3,1,100,0,0",
    "29301,-142.857142857143,4,3,1,100,0,0",
    "30123,-166.666666666667,4,3,1,100,0,0",
    "30945,-250,4,3,1,100,0,0",
    "32588,-166.666666666667,4,3,1,100,0,0",
    "34232,-250,4,3,1,100,0,0",
    "35876,-142.857142857143,4,3,1,100,0,0",
    "36698,-166.666666666667,4,3,1,100,0,0",
    "37520,-250,4,3,1,100,0,0",
    "42451,-142.857142857143,4,3,1,100,0,0",
    "43273,-166.666666666667,4,3,1,100,0,0",
]

How can I sort the list based on the first number in each line with python?
And then, once sorted, remove all duplicates, if any are there?

The sorting criteria for the list is the number before the first comma in each line, which is always an integer.

I tried using list.sort() , however, this sorts the items in lexical order, not numerically.

Body:
You could use a dictionary for this. The key will be number before the first comma and the value the entire string. Duplicates will be eliminated, but only the last occurrence of a particular number's string is stored.

l = ['464782,-100,4,3,1,100,0,0',
'465042,-166.666666666667,4,3,1,100,0,0',
'465825,-250.000000000001,4,3,1,100,0,0',
'466868,-166.666666666667,4,3,1,100,0,0',
'467390,-200.000000000001,4,3,1,100,0,0',
...]

d = {int(s.split(',')[0]) : s for s in l}
result = [d[key] for key in sorted(d.keys())]


问:
Can Azure Functions be deployed to a Vnet?
Can Azure Functions be deployed inside a VNet?

If I created an App Service environment in a VNet and then picked that App Service Plan when creating the Function, Would that mean that the Azure Function is deployed inside the VNet and have the same restrictions etc. as defined by the VNet?

答:
Yes, you can host an Azure function on Azure App Service Environment which provides a fully isolated and dedicated environment for securely running App Service apps or your functions. You will have fine-grained control over inbound and outbound application network traffic. So it could be restricted by network security groups.

ASEs are isolated to running only a single customer's applications and
  are always deployed into a virtual network. Customers have
  fine-grained control over inbound and outbound application network
  traffic. Applications can establish high-speed secure connections over
  VPNs to on-premises corporate resources.

VNet Integration with Azure function is a feature to use Azure Functions to connect to resources in an Azure virtual network. VNet Integration is only for making outbound calls from your app into your VNet.

In this case, you just need to deploy your Azure function in a VNet with ASE instead of VNet integration. Read Services that can be deployed into a virtual network


Body:
You can try this.

First we need to remove the duplicates inside the list using set()

removed_duplicates_list = list(set(listr))

Then we convert the list of strings in to a list of tuples

list_of_tuples = [tuple(i.split(",")) for i in removed_duplicates_list]

Then we sort it using the sort()

list_of_tuples.sort()

The complete code sample below:

listr = [
    "464782,-100,4,3,1,100,0,0"
    "465042,-166.666666666667,4,3,1,100,0,0",
    "465825,-250.000000000001,4,3,1,100,0,0",
    "466868,-166.666666666667,4,3,1,100,0,0",
    "467390,-200.000000000001,4,3,1,100,0,0",
    "469999,-100,4,3,1,100,0,0",
    "470260,-166.666666666667,4,3,1,100,0,0",
    "474173,-100,4,3,1,100,0,0",
    "474434,-166.666666666667,4,3,1,100,0,0",
    "481477,-100,4,3,1,100,0,1",
    "531564,259.011439671919,4,3,1,60,1,0",
    "24369,-333.333333333335,4,3,1,100,0,0",
    "21082,410.958904109589,4,3,1,60,1,0",
    "21082,-250,4,3,1,100,0,0",
    "22725,-142.857142857143,4,3,1,100,0,0",
    "23547,-166.666666666667,4,3,1,100,0,0",
    "24369,-333.333333333335,4,3,1,100,0,0",
    "27657,-200.000000000001,4,3,1,100,0,0",
    "29301,-142.857142857143,4,3,1,100,0,0",
    "30123,-166.666666666667,4,3,1,100,0,0",
    "30945,-250,4,3,1,100,0,0",
    "32588,-166.666666666667,4,3,1,100,0,0",
    "34232,-250,4,3,1,100,0,0",
    "35876,-142.857142857143,4,3,1,100,0,0",
    "36698,-166.666666666667,4,3,1,100,0,0",
    "37520,-250,4,3,1,100,0,0",
    "42451,-142.857142857143,4,3,1,100,0,0",
    "43273,-166.666666666667,4,3,1,100,0,0",
]

removed_duplicates_list = list(set(listr))
list_of_tuples = [tuple(i.split(",")) for i in removed_duplicates_list]
list_of_tuples.sort()
print(list_of_tuples) # the output is a list of tuples

OUTPUT:

    [('21082', '-250', '4', '3', '1', '100', '0', '0'),
    ('21082', '410.958904109589', '4', '3', '1', '60', '1', '0'),
    ('22725', '-142.857142857143', '4', '3', '1', '100', '0', '0'),
    ('23547', '-166.666666666667', '4', '3', '1', '100', '0', '0'),
    ('24369', '-333.333333333335', '4', '3', '1', '100', '0', '0'),
    ('27657', '-200.000000000001', '4', '3', '1', '100', '0', '0'),
    ('29301', '-142.857142857143', '4', '3', '1', '100', '0', '0'),
    ('30123', '-166.666666666667', '4', '3', '1', '100', '0', '0'),
    ('30945', '-250', '4', '3', '1', '100', '0', '0'),
    ('32588', '-166.666666666667', '4', '3', '1', '100', '0', '0'),
    ('34232', '-250', '4', '3', '1', '100', '0', '0'),
    ('35876', '-142.857142857143', '4', '3', '1', '100', '0', '0'),
    ('36698', '-166.666666666667', '4', '3', '1', '100', '0', '0'),
    ('37520', '-250', '4', '3', '1', '100', '0', '0'),
    ('42451', '-142.857142857143', '4', '3', '1', '100', '0', '0'),
    ('43273', '-166.666666666667', '4', '3', '1', '100', '0', '0'),
    ('464782','-100','4','3','1','100','0'),
    ('465042','-166.666666666667','4','3','1','100','0','0'),
    ('465825', '-250.000000000001', '4', '3', '1', '100', '0', '0'),
    ('466868', '-166.666666666667', '4', '3', '1', '100', '0', '0'),
    ('467390', '-200.000000000001', '4', '3', '1', '100', '0', '0'),
    ('469999', '-100', '4', '3', '1', '100', '0', '0'),
    ('470260', '-166.666666666667', '4', '3', '1', '100', '0', '0'),
    ('474173', '-100', '4', '3', '1', '100', '0', '0'),
    ('474434', '-166.666666666667', '4', '3', '1', '100', '0', '0'),
    ('481477', '-100', '4', '3', '1', '100', '0', '1'),
    ('531564', '259.011439671919', '4', '3', '1', '60', '1', '0')]


问:
How to create Toast in Flutter
Can I create something similar to Toasts in Flutter?

Just a tiny notification window that is not directly in the face of the user and does not lock or fade the view behind it.

答:
For this, there are different versions.

First of all, you can use SnackBar which is a widget in Flutter.

You can use libraries like toast - flutter_toast from pub.dev.

The third version is creating your custom widget. It can be created using Overlay widget and Animation in Flutter.

You can this this tutorial to learn more about it. Here is a link.

Title: How to create Toast in Flutter


问:
XDocument xml parsed but fails to save attributes. Xml.Linq
I am looping over the controls and setting the textbox values in the xml like so:

```<code>using System.Xml.Linq;

/* code */

XDocument _xml = XDocument.Load(_DialogOpen);

foreach (Control t in tableLayoutPanel.Controls)
{
    if (t is TextBox)
    {
        //setting the value
        _xml.Root.SetAttributeValue("isPreview", t.Text);
        //log
        textBox.AppendText("n=" + t.Name + " t=" + t.Text + Environment.NewLine);
    }
}

_xml.Save(_DialogOpen);
</code>```

My problem is that the _xml.Save(_DialogOpen); does save but none of the attributes are changed and there is no exception. If anyone has any suggestions it will be greatly appreciated.

xml example:

```<code><?xml version="1.0" encoding="utf-8"?>
<config id="1">
  <parmVer __id="0" version="V1234" />
    <RecordSetChNo __id="0" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="1" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="2" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="3" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="4" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="5" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="6" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="7" isPreview="1" AIVolume="15" />
</config>
</code>```

答:
Take a look at the following line from OP

```<code>_xml.Root.SetAttributeValue("isPreview", t.Text);
</code>```

The above code is attempting to set the attribute in Root element, when it looks like you want to set it for the Element RecordSetChNo.

Also, believe you want to set the attribute based on each of the textboxes, ie, each textbox has a corresponding attribute in the xml. In such a scenario, you would need to filter the right XElement (since there are more than one RecordSetChNo) before setting the attribute.

```<code>    foreach (Control t in tableLayoutPanel.Controls)
    {
        if (t is TextBox)
        {
            //filter the xelement, only a sample here.
            // Should change according to your requirement
            var filteredXElement = _xml.Root
                                      .Descendants("RecordSetChNo")
                                      .First(x=>x.Attribute("__id").Value==idToFilter);
            // Now set the attribute for the filtered Element
            filteredXElement.SetAttributeValue("isPreview", t.Text);
            //log
            textBox.AppendText("n=" + t.Name + " t=" + t.Text + Environment.NewLine);
        }
    }
</code>```

Body:
I am looping over the controls and setting the textbox values in the xml like so:

using System.Xml.Linq;

/* code */

XDocument _xml = XDocument.Load(_DialogOpen);

foreach (Control t in tableLayoutPanel.Controls)
{
    if (t is TextBox)
    {
        //setting the value
        _xml.Root.SetAttributeValue("isPreview", t.Text);
        //log
        textBox.AppendText("n=" + t.Name + " t=" + t.Text + Environment.NewLine);
    }
}

_xml.Save(_DialogOpen);

My problem is that the _xml.Save(_DialogOpen); does save but none of the attributes are changed and there is no exception. If anyone has any suggestions it will be greatly appreciated.

xml example:

<?xml version="1.0" encoding="utf-8"?>
<config id="1">
  <parmVer __id="0" version="V1234" />
    <RecordSetChNo __id="0" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="1" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="2" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="3" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="4" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="5" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="6" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="7" isPreview="1" AIVolume="15" />
</config>

Body:
Take a look at the following line from OP

_xml.Root.SetAttributeValue("isPreview", t.Text);

The above code is attempting to set the attribute in Root element, when it looks like you want to set it for the Element RecordSetChNo.

Also, believe you want to set the attribute based on each of the textboxes, ie, each textbox has a corresponding attribute in the xml. In such a scenario, you would need to filter the right XElement (since there are more than one RecordSetChNo) before setting the attribute.

    foreach (Control t in tableLayoutPanel.Controls)
    {
        if (t is TextBox)
        {
            //filter the xelement, only a sample here.
            // Should change according to your requirement
            var filteredXElement = _xml.Root
                                      .Descendants("RecordSetChNo")
                                      .First(x=>x.Attribute("__id").Value==idToFilter);
            // Now set the attribute for the filtered Element
            filteredXElement.SetAttributeValue("isPreview", t.Text);
            //log
            textBox.AppendText("n=" + t.Name + " t=" + t.Text + Environment.NewLine);
        }
    }


问:
SignalR list of object undefined
I am trying to display on the console a list of object But it doesn't show the objects...

Here is the javascript I use to display the object received from the server :

```<code>connection.on("ReceiveLog", function (chatMessages) {

console.log(chatMessages);

for (var item in chatMessages) {

    // work with key and value
    var encodedMsg = item.User + " says " + item.Message;
        var li = document.createElement("li");
        li.textContent = encodedMsg;
        document.getElementById("messagesList").appendChild(li);
} });
</code>```

The server is sending a list of ChatMessage. Here is the ChatMessage class :

```<code>public class ChatMessage
{
    string User { get; set; }
    string Message { get; set; }

    public ChatMessage(string user, string message)
    {
        this.User = user;
        this.Message = message;
    }
}
</code>```

Why are my objects completely broken ? When I break the code on the server side, it really sends the list correctly. The problem seems to be from the javascript or maybe I need to serialize from the server side ?

答:
I needed to set all the property of the object Public like so :

```<code>public class ChatMessage
{
    public string User { get; set; }
    public string Message { get; set; }

    public ChatMessage(string user, string message)
    {
        this.User = user;
        this.Message = message;
    }
}
</code>```

It works now.

Title: SignalR list of object undefined

Body:
I am trying to display on the console a list of object But it doesn't show the objects...

Here is the javascript I use to display the object received from the server :

connection.on("ReceiveLog", function (chatMessages) {

console.log(chatMessages);

for (var item in chatMessages) {

    // work with key and value
    var encodedMsg = item.User + " says " + item.Message;
        var li = document.createElement("li");
        li.textContent = encodedMsg;
        document.getElementById("messagesList").appendChild(li);
} });

The server is sending a list of ChatMessage. Here is the ChatMessage class :

public class ChatMessage
{
    string User { get; set; }
    string Message { get; set; }

    public ChatMessage(string user, string message)
    {
        this.User = user;
        this.Message = message;
    }
}

Why are my objects completely broken ? When I break the code on the server side, it really sends the list correctly. The problem seems to be from the javascript or maybe I need to serialize from the server side ?

Body:
I needed to set all the property of the object Public like so :

public class ChatMessage
{
    public string User { get; set; }
    public string Message { get; set; }

    public ChatMessage(string user, string message)
    {
        this.User = user;
        this.Message = message;
    }
}

It works now.


问:
"Module not found: Error: Can't resolve 'electron-is-dev'" in electron & typescript & webpack project
I'm using Electron and Typescript with webpack.
And I'm gonna add react.js.

But I typed "npx webpack", I got an error.

It says "electron-is-dev module is not found", but I already installed it.

```<code> ERROR in ./src/main/window.ts
    Module not found: Error: Can't resolve 'electron-is-dev' in 'project-path/src/main'
     @ ./src/main/window.ts 2:0-36 12:35-40
     @ ./src/main/app.ts
</code>```

I can't find how to solve this error.

window.ts

```<code>import { app, BrowserWindow } from 'electron';
import isDev from 'electron-is-dev';

(...)
</code>```

webpack.config.js

```<code>const path = require('path');

module.exports = [
    {
        target: 'electron-main',
        entry: path.join(__dirname, 'src/main/app.ts'),
        mode: 'development',
        module: {
            rules: [
                {
                    test: /\.ts$/,
                    include: path.join(__dirname, 'src/main'),
                    use: 'ts-loader',
                    exclude: [
                        /node_modules/,
                        path.join(__dirname, 'src/renderer')
                    ]
                }
            ]
        },
        output: {
            path: path.join(__dirname, 'build'),
            filename: 'electron.js'
        },
        resolve: {
            extensions: ['.tsx', '.ts', 'js']
        },
        node: {
            __dirname: false
        }
    }
];
</code>```

And package.json:

```<code>{
    "name": "electron-react-typescript",
    "version": "0.0.1",
    "description": "",
    "main": "build/electron.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "@types/electron-devtools-installer": "^2.2.0",
        "@types/react": "^16.9.19",
        "@types/react-dom": "^16.9.5",
        "@typescript-eslint/eslint-plugin": "2.x",
        "@typescript-eslint/parser": "2.x",
        "babel-eslint": "10.x",
        "concurrently": "^5.1.0",
        "electron": "^8.0.0",
        "electron-builder": "^22.3.2",
        "eslint": "6.x",
        "eslint-config-prettier": "^6.10.0",
        "eslint-config-react-app": "^5.2.0",
        "eslint-plugin-flowtype": "3.x",
        "eslint-plugin-import": "2.x",
        "eslint-plugin-jsx-a11y": "6.x",
        "eslint-plugin-react": "7.x",
        "eslint-plugin-react-hooks": "1.x",
        "html-webpack-plugin": "^3.2.0",
        "prettier": "^1.19.1",
        "source-map-loader": "^0.2.4",
        "ts-loader": "^6.2.1",
        "typescript": "^3.7.5",
        "webpack": "^4.41.5",
        "webpack-cli": "^3.3.10",
        "webpack-dev-server": "^3.10.3"
    },
    "dependencies": {
        "electron-devtools-installer": "^2.2.4",
        "electron-is-dev": "^1.1.0",
        "react": "^16.12.0",
        "react-dom": "^16.12.0"
    }
}
</code>```

And I'm using eslint and prettier.

答:
I have webpack.config.js file that I used in another project, so I copy it and edit a little. And It worked! I compared them and found a very very tiny mistake.

```<code>(...)
resolve: {
    extensions: ['.ts', 'js', '.tsx']
},
(...)
</code>```

I wrote ['.ts', 'js', '.tsx'] not ['.ts', '.js', 'tsx'].
This error occurred because I didn't just write a dot.

Body:
I'm using Electron and Typescript with webpack.
And I'm gonna add react.js.

But I typed "npx webpack", I got an error.

It says "electron-is-dev module is not found", but I already installed it.

 ERROR in ./src/main/window.ts
    Module not found: Error: Can't resolve 'electron-is-dev' in 'project-path/src/main'
     @ ./src/main/window.ts 2:0-36 12:35-40
     @ ./src/main/app.ts

I can't find how to solve this error.

window.ts

import { app, BrowserWindow } from 'electron';
import isDev from 'electron-is-dev';

(...)

webpack.config.js

const path = require('path');

module.exports = [
    {
        target: 'electron-main',
        entry: path.join(__dirname, 'src/main/app.ts'),
        mode: 'development',
        module: {
            rules: [
                {
                    test: /\.ts$/,
                    include: path.join(__dirname, 'src/main'),
                    use: 'ts-loader',
                    exclude: [
                        /node_modules/,
                        path.join(__dirname, 'src/renderer')
                    ]
                }
            ]
        },
        output: {
            path: path.join(__dirname, 'build'),
            filename: 'electron.js'
        },
        resolve: {
            extensions: ['.tsx', '.ts', 'js']
        },
        node: {
            __dirname: false
        }
    }
];

And package.json:

{
    "name": "electron-react-typescript",
    "version": "0.0.1",
    "description": "",
    "main": "build/electron.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "@types/electron-devtools-installer": "^2.2.0",
        "@types/react": "^16.9.19",
        "@types/react-dom": "^16.9.5",
        "@typescript-eslint/eslint-plugin": "2.x",
        "@typescript-eslint/parser": "2.x",
        "babel-eslint": "10.x",
        "concurrently": "^5.1.0",
        "electron": "^8.0.0",
        "electron-builder": "^22.3.2",
        "eslint": "6.x",
        "eslint-config-prettier": "^6.10.0",
        "eslint-config-react-app": "^5.2.0",
        "eslint-plugin-flowtype": "3.x",
        "eslint-plugin-import": "2.x",
        "eslint-plugin-jsx-a11y": "6.x",
        "eslint-plugin-react": "7.x",
        "eslint-plugin-react-hooks": "1.x",
        "html-webpack-plugin": "^3.2.0",
        "prettier": "^1.19.1",
        "source-map-loader": "^0.2.4",
        "ts-loader": "^6.2.1",
        "typescript": "^3.7.5",
        "webpack": "^4.41.5",
        "webpack-cli": "^3.3.10",
        "webpack-dev-server": "^3.10.3"
    },
    "dependencies": {
        "electron-devtools-installer": "^2.2.4",
        "electron-is-dev": "^1.1.0",
        "react": "^16.12.0",
        "react-dom": "^16.12.0"
    }
}

And I'm using eslint and prettier.

Body:
I have webpack.config.js file that I used in another project, so I copy it and edit a little. And It worked! I compared them and found a very very tiny mistake.

(...)
resolve: {
    extensions: ['.ts', 'js', '.tsx']
},
(...)

I wrote ['.ts', 'js', '.tsx'] not ['.ts', '.js', 'tsx'].
This error occurred because I didn't just write a dot.


问:
Parsing lat and long from JSON
I have a JSON file with lat and long in the incorrect format to call position {lat, lng} for map markers.

I'm trying to do a getJSON and for each incorrect lat and long, send it to a function that parses it into the correct format and add a marker to my map.

I'm not having any luck though. It comes in like
"latLang": "27.8247427:-82.75040159999999"

Here's a link to the JSON for reference. JSON

Here's my code.

```<code>$(document).ready(function() {
    $.getJSON("http://cs1.utm.edu/~bbradley/map1/customers1.json", function(data) {
      const markers = data.map(({
        latLang
      }) => new google.maps.Marker({
        map: myMap,
        position: new google.maps.LatLng(parseGeo(latLang))
      }));
    });
  });

  const parseGeo = str => { // this is to parse it into the right format
    const [lat, lng] = str.split(':').map(value => parseFloat(value, 10));
    return {
      lat,
      lng
    };
  }
</code>```

Exert from JSON

```<code>[{
        "name": "Carole McKenzie",
        "address": "5720 80TH ST NORTH UNIT 310",
        "cityStateZip": "ST PETERSBURG, Florida 33709",
        "latLang": "27.8247427:-82.75040159999999",
        "image": "./people/MTI4MTYuanBn.jpg"
    },
    {
        "name": "Matt Russell",
        "address": "1211 Miller Place Dr",
        "cityStateZip": "Bryant, Arkansas 72022-2389",
        "latLang": "34.606806:-92.5042948",
        "image": "./people/MTQ3OTUuanBn.jpg"
    },
    {
        "name": "George Thrapp",
        "address": "2906 Haddington Court",
        "cityStateZip": "North Chesterfield, Virginia 23224-5716",
        "latLang": "37.466937:-77.5075449",
        "image": "./people/MTk3NTkuanBn.jpg"
    },
</code>```

答:
At a glance I think the problem you're running into might be that you're passing in two strings instead of an object with numeric lat and lng properties.

I think you can simplify it. Here's how I might go about such a thing:

const data = [{
    "name": "Carole McKenzie",
    "address": "5720 80TH ST NORTH UNIT 310",
    "cityStateZip": "ST PETERSBURG, Florida 33709",
    "latLang": "27.8247427:-82.75040159999999",
    "image": "./people/MTI4MTYuanBn.jpg"
  },
  {
    "name": "Matt Russell",
    "address": "1211 Miller Place Dr",
    "cityStateZip": "Bryant, Arkansas 72022-2389",
    "latLang": "34.606806:-92.5042948",
    "image": "./people/MTQ3OTUuanBn.jpg"
  },
  {
    "name": "George Thrapp",
    "address": "2906 Haddington Court",
    "cityStateZip": "North Chesterfield, Virginia 23224-5716",
    "latLang": "37.466937:-77.5075449",
    "image": "./people/MTk3NTkuanBn.jpg"
  },
  {
    "name": "Trina Anderson",
    "address": "112 South Niles Avenue",
    "cityStateZip": "South Bend, Indiana 46617",
    "latLang": "41.6759656:-86.24418419999999",
    "image": "./people/NDExMTAuanBn.jpg"
  }
];

// utility function for turning the latLang string into an object with lat and lng properties, e.g.
// "41.6759656:-86.24418419999999" => {lat: 41.6759656, lng: -86.24418419999999}
const parseGeo = str => {
  const [lat, lng] = str.split(':').map(value => parseFloat(value, 10));
  return {
    lat,
    lng
  };
}

// convert all of the input items to lat/lng numeric props instead of latLang string
const parsed = data.map(({latLang, ...other}) => ({
  ...other,
  ...parseGeo(latLang)
}));

console.log(parsed);```
</div>
</div>
</p>

<p>From there you could iterate the parsed values and construct the markers:</p>

<pre class="lang-js prettyprint-override"><code>const markers = parsed.map(({lat, lng}) => (
  new google.maps.Marker({
    map: myMap,
    position: new google.maps.LatLng({lat, lng})
  })
);
</code>```

Or you could skip the pre-parsing and do the parseGeo conversion inline when creating the markers:

const parseGeo = str => {
  const [lat, lng] = str.split(':').map(value => parseFloat(value, 10));
  return {
    lat,
    lng
  };
}

const markers = data.map(({latLang}) => (
  new google.maps.Marker({
    map: myMap,
    position: new google.maps.LatLng(parseGeo(latLang))
  })
);
```

Title: Parsing lat and long from JSON

Body:
I have a JSON file with lat and long in the incorrect format to call position {lat, lng} for map markers.

I'm trying to do a getJSON and for each incorrect lat and long, send it to a function that parses it into the correct format and add a marker to my map.

I'm not having any luck though. It comes in like
"latLang": "27.8247427:-82.75040159999999"

Here's a link to the JSON for reference. JSON

Here's my code.

$(document).ready(function() {
    $.getJSON("http://cs1.utm.edu/~bbradley/map1/customers1.json", function(data) {
      const markers = data.map(({
        latLang
      }) => new google.maps.Marker({
        map: myMap,
        position: new google.maps.LatLng(parseGeo(latLang))
      }));
    });
  });

  const parseGeo = str => { // this is to parse it into the right format
    const [lat, lng] = str.split(':').map(value => parseFloat(value, 10));
    return {
      lat,
      lng
    };
  }

Exert from JSON

[{
        "name": "Carole McKenzie",
        "address": "5720 80TH ST NORTH UNIT 310",
        "cityStateZip": "ST PETERSBURG, Florida 33709",
        "latLang": "27.8247427:-82.75040159999999",
        "image": "./people/MTI4MTYuanBn.jpg"
    },
    {
        "name": "Matt Russell",
        "address": "1211 Miller Place Dr",
        "cityStateZip": "Bryant, Arkansas 72022-2389",
        "latLang": "34.606806:-92.5042948",
        "image": "./people/MTQ3OTUuanBn.jpg"
    },
    {
        "name": "George Thrapp",
        "address": "2906 Haddington Court",
        "cityStateZip": "North Chesterfield, Virginia 23224-5716",
        "latLang": "37.466937:-77.5075449",
        "image": "./people/MTk3NTkuanBn.jpg"
    },

Body:
At a glance I think the problem you're running into might be that you're passing in two strings instead of an object with numeric lat and lng properties.

I think you can simplify it. Here's how I might go about such a thing:

const data = [{
    "name": "Carole McKenzie",
    "address": "5720 80TH ST NORTH UNIT 310",
    "cityStateZip": "ST PETERSBURG, Florida 33709",
    "latLang": "27.8247427:-82.75040159999999",
    "image": "./people/MTI4MTYuanBn.jpg"
  },
  {
    "name": "Matt Russell",
    "address": "1211 Miller Place Dr",
    "cityStateZip": "Bryant, Arkansas 72022-2389",
    "latLang": "34.606806:-92.5042948",
    "image": "./people/MTQ3OTUuanBn.jpg"
  },
  {
    "name": "George Thrapp",
    "address": "2906 Haddington Court",
    "cityStateZip": "North Chesterfield, Virginia 23224-5716",
    "latLang": "37.466937:-77.5075449",
    "image": "./people/MTk3NTkuanBn.jpg"
  },
  {
    "name": "Trina Anderson",
    "address": "112 South Niles Avenue",
    "cityStateZip": "South Bend, Indiana 46617",
    "latLang": "41.6759656:-86.24418419999999",
    "image": "./people/NDExMTAuanBn.jpg"
  }
];

// utility function for turning the latLang string into an object with lat and lng properties, e.g.
// "41.6759656:-86.24418419999999" => {lat: 41.6759656, lng: -86.24418419999999}
const parseGeo = str => {
  const [lat, lng] = str.split(':').map(value => parseFloat(value, 10));
  return {
    lat,
    lng
  };
}

// convert all of the input items to lat/lng numeric props instead of latLang string
const parsed = data.map(({latLang, ...other}) => ({
  ...other,
  ...parseGeo(latLang)
}));

console.log(parsed);

From there you could iterate the parsed values and construct the markers:

const markers = parsed.map(({lat, lng}) => (
  new google.maps.Marker({
    map: myMap,
    position: new google.maps.LatLng({lat, lng})
  })
);

Or you could skip the pre-parsing and do the parseGeo conversion inline when creating the markers:

const parseGeo = str => {
  const [lat, lng] = str.split(':').map(value => parseFloat(value, 10));
  return {
    lat,
    lng
  };
}

const markers = data.map(({latLang}) => (
  new google.maps.Marker({
    map: myMap,
    position: new google.maps.LatLng(parseGeo(latLang))
  })
);


问:
How do I start and reference my WebApplication so Watin can access it using Visual Studio UnitTesting?
I've easily setup the simple search with google example for WatiN and would like to now hook it up to my own Web Application.

I've got an MVC 3 Web Application that I'd like to test from within Visual Studio. Meaning I'd like to test my development version not a true external published website.

How do I tell the VisualStudio UnitTesting platform to startup my MVC project so its accessible to my TestMethods?

Thanks

答:
What I do is just start the application in Cassini (Visual Studio embedded web server).
Then when it's working my Watin tests visit that app. You probably know that You can instruct web app to always use same port in Cassini? Same would work with IIS Express.

Other way is to create virtual directory under IIS and point it to your web app source folder. Then your Watin tests visit http://localhost/YourApp.