问:
SWIFTUI: Invalid conversion from 'async' function of type '(IndexSet) async
I am learning SWIFTUI and trying to do some app to test my knowledge without actually following a tutorial, as I like to wrap my head around why things work certain way. It's how I learn :)

So, I am trying to call a function to post some data through an API. The method is inside of the ViewModel. The view is a List, and I need to be able to trigger .OnDelete modifier to trigger the API call through the viewmodel.

but I am always faced with the error:

Invalid conversion from 'async' function of type '(IndexSet) async -> Void' to synchronous function type '(IndexSet) -> Void'

here's the code.

in ContentView.swift:

```<code>        // there is a @State var res = PostsViewModel() above the body!
    List {
        ForEach(res.posts, id:\.self){ item in
            VStack {
                Text(item.title)
                    .font(.headline)
                Text("\(item.content) <> \(item._id)")
            }

        }
        .onDelete{ IndexSet in
                var index: Int = -1
                for idx in IndexSet {
                    index = idx
                }
                print("index ix \(index)")

                 await res.updateData(at: index)

        }

    }
</code>```

In PostViewModel.swift:

```<code>    func updateData(at index: Int) async {
        let item = posts[index]
        print(item._id)
        guard let url = URL(string: "{URL HERE HIDDEN}/api/posts/\(item._id)") else {
            print("Error: cannot create URL")
            return
        }
        struct UploadData: Codable {
            let title: String
            let content: String
        }

        // Add data to the model
        let uploadDataModel = UploadData(title: "Hello", content: "World!!")

        // Convert model to JSON data
        guard let jsonData = try? JSONEncoder().encode(uploadDataModel) else {
            print("Error: Trying to convert model to JSON data")
            return
        }
        // Create the request
        var request = URLRequest(url: url)
        request.httpMethod = "PUT"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        do {
            guard let (data, _) = try? await URLSession.shared.upload(for: request, from: jsonData) else {
                 print("failed to connect")
                return
            }

            guard let decodedOrder = try JSONDecoder().decode(PostsModel?.self, from: data) else {
                 print("failed to decode")
                return
            }
                print(decodedOrder.content)

            } catch {
                print("Checkout failed.")
                return
            }
}
</code>```

what am I doing wrong here?

答:
Wrap the asynchronous function in a Task

```<code>Task {
    await res.updateData(at: index)
}
</code>```

And if PostsViewModel is a class declare a @StateObject

```<code>@StateObject var res = PostsViewModel()
</code>```

Body:
I am learning SWIFTUI and trying to do some app to test my knowledge without actually following a tutorial, as I like to wrap my head around why things work certain way. It's how I learn :)

So, I am trying to call a function to post some data through an API. The method is inside of the ViewModel. The view is a List, and I need to be able to trigger .OnDelete modifier to trigger the API call through the viewmodel.

but I am always faced with the error:

Invalid conversion from 'async' function of type '(IndexSet) async -> Void' to synchronous function type '(IndexSet) -> Void'

here's the code.

in ContentView.swift:

        // there is a @State var res = PostsViewModel() above the body!
    List {
        ForEach(res.posts, id:\.self){ item in
            VStack {
                Text(item.title)
                    .font(.headline)
                Text("\(item.content) <> \(item._id)")
            }

        }
        .onDelete{ IndexSet in
                var index: Int = -1
                for idx in IndexSet {
                    index = idx
                }
                print("index ix \(index)")

                 await res.updateData(at: index)

        }

    }

In PostViewModel.swift:

    func updateData(at index: Int) async {
        let item = posts[index]
        print(item._id)
        guard let url = URL(string: "{URL HERE HIDDEN}/api/posts/\(item._id)") else {
            print("Error: cannot create URL")
            return
        }
        struct UploadData: Codable {
            let title: String
            let content: String
        }

        // Add data to the model
        let uploadDataModel = UploadData(title: "Hello", content: "World!!")

        // Convert model to JSON data
        guard let jsonData = try? JSONEncoder().encode(uploadDataModel) else {
            print("Error: Trying to convert model to JSON data")
            return
        }
        // Create the request
        var request = URLRequest(url: url)
        request.httpMethod = "PUT"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        do {
            guard let (data, _) = try? await URLSession.shared.upload(for: request, from: jsonData) else {
                 print("failed to connect")
                return
            }

            guard let decodedOrder = try JSONDecoder().decode(PostsModel?.self, from: data) else {
                 print("failed to decode")
                return
            }
                print(decodedOrder.content)

            } catch {
                print("Checkout failed.")
                return
            }
}

what am I doing wrong here?

Body:
Wrap the asynchronous function in a Task

Task {
    await res.updateData(at: index)
}

And if PostsViewModel is a class declare a @StateObject

@StateObject var res = PostsViewModel()


来源: stackexchange

问:
PlatformException(VideoError, Video player had error com.google.android.exoplayer2.ExoPlaybackException: Source error, null, null)
**HI I am trying to play a live news video in my flutter app it is .m3u8 format but get above error. Using all of the updated dependencies. I want to play live news in my flutter app. I have the url you can also try it.
URL: http://161.97.162.167:1936/live/tnnnews/playlist.m3u8
When I use another url with .m3u8 it plays on flutter app but when I paste the live url code it throws me the above error.
**

Code

```<code>import 'package:video_player/video_player.dart';
import 'package:flutter/material.dart';

class VideoApp extends StatefulWidget {
  @override
  _VideoAppState createState() => _VideoAppState();
}

class _VideoAppState extends State<VideoApp> {
  VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(
        'http://161.97.162.167:1936/live/tnnnews/playlist.m3u8')
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
        setState(() {});
      });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Video Demo',
      home: Scaffold(
        body: Center(
          child: _controller.value.isInitialized
              ? AspectRatio(
            aspectRatio: _controller.value.aspectRatio,
            child: VideoPlayer(_controller),
          )
              : Container(),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              _controller.value.isPlaying
                  ? _controller.pause()
                  : _controller.play();
            });
          },
          child: Icon(
            _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }
}
</code>```

答:
Put this in your AndroidManifest.xml</p>
```<code><application ...
android:usesCleartextTraffic="true"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
**HI I am trying to play a live news video in my flutter app it is .m3u8 format but get above error. Using all of the updated dependencies. I want to play live news in my flutter app. I have the url you can also try it.
URL: http://161.97.162.167:1936/live/tnnnews/playlist.m3u8
When I use another url with .m3u8 it plays on flutter app but when I paste the live url code it throws me the above error.
**

Code

import 'package:video_player/video_player.dart';
import 'package:flutter/material.dart';

class VideoApp extends StatefulWidget {
  @override
  _VideoAppState createState() => _VideoAppState();
}

class _VideoAppState extends State<VideoApp> {
  VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(
        'http://161.97.162.167:1936/live/tnnnews/playlist.m3u8')
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
        setState(() {});
      });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Video Demo',
      home: Scaffold(
        body: Center(
          child: _controller.value.isInitialized
              ? AspectRatio(
            aspectRatio: _controller.value.aspectRatio,
            child: VideoPlayer(_controller),
          )
              : Container(),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              _controller.value.isPlaying
                  ? _controller.pause()
                  : _controller.play();
            });
          },
          child: Icon(
            _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }
}

Body:
Put this in your AndroidManifest.xml

<application ...
android:usesCleartextTraffic="true"


问:
I have an error in plyer.facades.Notification.notify() that is TypeError: Notification.notify() missing 1 required positional argument: 'self'
<pre class="lang-py prettyprint-override"><code># import Notification Method from plyer module
from plyer.facades import Notification
# notify function declaration
def notifyMe(title,text):
    Notification.notify(
        title=title,
        message=text,
        app_icon=None,
        timeout=5
    )

# main function declaration
if __name__ == '__main__':
    notifyMe("Notification","Just Click here to see what it is")
</code>```

答:
You are trying to call an instance method as a class method.
You should create an object from the Notification class first, and then use it to call this method. Or use a Singleton "notification" provided for you by the package developer.

Maybe this documentation will be helpful: https://github.com/kivy/plyer/blob/master/plyer/facades/notification.py

```<code># To send notification::
from plyer import notification
title = 'plyer'
message = 'This is an example.'
notification.notify(title=title, message=message)
</code>```

Body:
You are trying to call an instance method as a class method.
You should create an object from the Notification class first, and then use it to call this method. Or use a Singleton "notification" provided for you by the package developer.

Maybe this documentation will be helpful: https://github.com/kivy/plyer/blob/master/plyer/facades/notification.py

# To send notification::
from plyer import notification
title = 'plyer'
message = 'This is an example.'
notification.notify(title=title, message=message)


问:
Flutter Countdown Timer
How can I do to put the value passed in the construction, to make a timer that rounds to the first decimal and shows at the child text of my RaisedButton? I've tried but without luck. I manage to make work the callback function with a simple Timer but no periodic and with no update of value in real time in the text...</p>

```<code>import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:async';

class TimerButton extends StatefulWidget {
  final Duration timerTastoPremuto;

  TimerButton(this.timerTastoPremuto);

  @override
  _TimerButtonState createState() => _TimerButtonState();
}

class _TimerButtonState extends State<TimerButton> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(5.0),
      height: 135.0,
      width: 135.0,
      child: new RaisedButton(
        elevation: 100.0,
        color: Colors.white.withOpacity(.8),
        highlightElevation: 0.0,
        onPressed: () {
          int _start = widget.timerTastoPremuto.inMilliseconds;

          const oneDecimal = const Duration(milliseconds: 100);
          Timer _timer = new Timer.periodic(
              oneDecimal,
                  (Timer timer) =>
                  setState(() {
                    if (_start < 100) {
                      _timer.cancel();
                    } else {
                      _start = _start - 100;
                    }
                  }));

        },
        splashColor: Colors.red,
        highlightColor: Colors.red,
        //shape: RoundedRectangleBorder e tutto il resto uguale
        shape: BeveledRectangleBorder(
            side: BorderSide(color: Colors.black, width: 2.5),
            borderRadius: new BorderRadius.circular(15.0)),
        child: new Text(
          "$_start",
          style: new TextStyle(fontFamily: "Minim", fontSize: 50.0),
        ),
      ),
    );
  }
}
</code>```

答:
```<code>import 'package:rxdart/rxdart.dart';

final BehaviorSubject<int> resendTimeController = BehaviorSubject<int>();
static const timerDuration = 90;
int resendTimer = 0;
Timer? timer;

void startTimer() {
  timer?.cancel();
  resendTimer = timerDuration;

  timer = Timer.periodic(const Duration(seconds: 1), (timer) {
    if (resendTimer > 0) {
      resendTimer--;
      resendTimeController.add(resendTimer);

      if (resendTimer == 0) {
        timer.cancel();
      }
    }
  });
}
and use intl this

StreamBuilder<int>(
  stream: _bloc.resendTimeController,
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return Container();
    }

    final DateTime date = DateTime.fromMillisecondsSinceEpoch(snapshot.data! * 1000);

    return GestureDetector(
      onTap: () {
        if (snapshot.data == 0) {
          _bloc.resendCode();
        }
      },
      child: Text(
        snapshot.data! > 0 ? 'Resend code ${DateFormat('mm:ss').format(date)}' : 'Resend SMS',
      ),
    );
  },
),
</code>```

Title: Flutter Countdown Timer

Body:
How can I do to put the value passed in the construction, to make a timer that rounds to the first decimal and shows at the child text of my RaisedButton? I've tried but without luck. I manage to make work the callback function with a simple Timer but no periodic and with no update of value in real time in the text...

import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:async';

class TimerButton extends StatefulWidget {
  final Duration timerTastoPremuto;

  TimerButton(this.timerTastoPremuto);

  @override
  _TimerButtonState createState() => _TimerButtonState();
}

class _TimerButtonState extends State<TimerButton> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(5.0),
      height: 135.0,
      width: 135.0,
      child: new RaisedButton(
        elevation: 100.0,
        color: Colors.white.withOpacity(.8),
        highlightElevation: 0.0,
        onPressed: () {
          int _start = widget.timerTastoPremuto.inMilliseconds;

          const oneDecimal = const Duration(milliseconds: 100);
          Timer _timer = new Timer.periodic(
              oneDecimal,
                  (Timer timer) =>
                  setState(() {
                    if (_start < 100) {
                      _timer.cancel();
                    } else {
                      _start = _start - 100;
                    }
                  }));

        },
        splashColor: Colors.red,
        highlightColor: Colors.red,
        //shape: RoundedRectangleBorder e tutto il resto uguale
        shape: BeveledRectangleBorder(
            side: BorderSide(color: Colors.black, width: 2.5),
            borderRadius: new BorderRadius.circular(15.0)),
        child: new Text(
          "$_start",
          style: new TextStyle(fontFamily: "Minim", fontSize: 50.0),
        ),
      ),
    );
  }
}


问:
How do I check if a value is of, or promotable to, a column type in pandas?
For example, suppose I have the following DataFrame.

```<code>import pandas as pd

df = pd.DataFrame([['a', 1.3, 10], ['b', 2, 20]], columns=['id', 'v1', 'v2'])
df = df.astype({col: 'category' for col in df.columns[df.dtypes == object]})

print(df)
print()
print(df.dtypes)

  id   v1  v2
0  a  1.3  10
1  b  2.0  20

id    category
v1     float64
v2       int64
</code>```

Given a value and a column identifier, I need to know whether the type of the value is compatible with the column.  (Of the same type or promotable.)

For category fields, I'd like to know if a value is in the category.  I can do something like

```<code>'x' in df['id'].unique()
</code>```

but there may be a more efficient way.

Thanks.

答:
I think 'x' in df['id'].unique() will check if the value 'x' is in the column—which is not the same as checking if it is one of the categories.

Based on this answer it looks like you check if a value is in the categorical as follows:

```<code>'x' in df["id"].cat.categories
</code>```

Test:

```<code>ids = pd.Categorical(["a", "b"], categories=["a", "b", "c"])
assert(("c" in ids) is False)
assert(("c" in ids.categories) is True)
</code>```

UPDATE:

Is this what you wanted?

```<code>def check_type(x, df, name):
    try:
        return x in df[name].cat.categories
    except AttributeError:
        return type(x) == df[name].dtype
</code>```

Test:

```<code>assert(check_type('a', df, "ids") is True)
assert(check_type('c', df, "ids") is True)
assert(check_type(3.4, df, "ids") is False)
assert(check_type(3.4, df, "v1") is True)
assert(check_type(3.4, df, "v2") is False)
assert(check_type(3, df, "v1") is False)
assert(check_type(3, df, "v2") is True)
</code>```

Body:
For example, suppose I have the following DataFrame.

import pandas as pd

df = pd.DataFrame([['a', 1.3, 10], ['b', 2, 20]], columns=['id', 'v1', 'v2'])
df = df.astype({col: 'category' for col in df.columns[df.dtypes == object]})

print(df)
print()
print(df.dtypes)

  id   v1  v2
0  a  1.3  10
1  b  2.0  20

id    category
v1     float64
v2       int64

Given a value and a column identifier, I need to know whether the type of the value is compatible with the column.  (Of the same type or promotable.)

For category fields, I'd like to know if a value is in the category.  I can do something like

'x' in df['id'].unique()

but there may be a more efficient way.

Thanks.

Body:
I think 'x' in df['id'].unique() will check if the value 'x' is in the column—which is not the same as checking if it is one of the categories.

Based on this answer it looks like you check if a value is in the categorical as follows:

'x' in df["id"].cat.categories

Test:

ids = pd.Categorical(["a", "b"], categories=["a", "b", "c"])
assert(("c" in ids) is False)
assert(("c" in ids.categories) is True)

UPDATE:

Is this what you wanted?

def check_type(x, df, name):
    try:
        return x in df[name].cat.categories
    except AttributeError:
        return type(x) == df[name].dtype

Test:

assert(check_type('a', df, "ids") is True)
assert(check_type('c', df, "ids") is True)
assert(check_type(3.4, df, "ids") is False)
assert(check_type(3.4, df, "v1") is True)
assert(check_type(3.4, df, "v2") is False)
assert(check_type(3, df, "v1") is False)
assert(check_type(3, df, "v2") is True)


问:
Elements in the table that are part of section (i.e: A) should be placed at the bottom of the table
I have a set of elements. Some of these are part of section A, others of section B and still others of section C. There is a special column that defines this Section.

The elements in the table that are part of section A must be placed at the bottom of the table.

To be able to put the elements at the bottom of the table I know that you have to use the command:

var row = table.insertRow(-1);

Since my table is dynamic, how can I set what I want?

Items.forEach(function (item) {
                    let child = document.createElement("tr");
                    child.innerHTML = `
                    ${item.id}
                    ${item.title}
                    ${item.image}
                    ${item.section}
                    ${item.date}	`;
                    table.appendChild(child);
                })```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <table id="my-table" width="90%">
            <tr>
                <th>Id</th>
                <th>Title</th>
                <th>Image</th>
                <th>Section</th>
                <th>Date</th>
            </tr>

        </table></code>```

Example to understand

let itemarr = [{
  id: 1,
  title: "image 1",
  image: "url 1",
  section: "Film",
  date: "date 1",
}, {
  id: 2,
  title: "image 2",
  image: "url 2",
  section: "Video",
  date: "date 2",
},
{
  id: 3,
  title: "image 3",
  image: "url 2",
  section: "Film",
  date: "date 2",
},
{
  id: 4,
  title: "image 4",
  image: "url 2",
  section: "Video",
  date: "date 2",
}]
itemarr.forEach(function(item) {
  let child = document.querySelector('table').insertRow(-1)
  child.innerHTML = `
                    ${item.id}
                    ${item.title}
                    ${item.image}
                    ${item.section}
                    ${item.date}	`

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="my-table" width="90%">
  <tr>
    <th>Id</th>
    <th>Title</th>
    <th>Image</th>
    <th>Section</th>
    <th>Date</th>
  </tr>

</table></code>```

答:
You are on the right track by using insertRow(-1).

Try this one will work, a small notice that Items is currently undefined but I believe you define it

let itemarr = [{
  id: 1,
  title: "image 1",
  image: "url 1",
  section: "section 1",
  date: "date 1",
}, {
  id: 2,
  title: "image 2",
  image: "url 2",
  section: "section 2",
  date: "date 2",
}]
itemarr.forEach(function(item) {
  let child = document.querySelector('table').insertRow(-1)
  child.innerHTML = `
                    ${item.id}
                    ${item.title}
                    ${item.image}
                    ${item.section}
                    ${item.date}	`

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  text-align: center
}</code>```

    Id
    Title
    Image
    Section
    Date

    id
    title
    image
    section
    date

```

Body:
I have a set of elements. Some of these are part of section A, others of section B and still others of section C. There is a special column that defines this Section.

The elements in the table that are part of section A must be placed at the bottom of the table.

To be able to put the elements at the bottom of the table I know that you have to use the command:

var row = table.insertRow(-1);

Since my table is dynamic, how can I set what I want?

Items.forEach(function (item) {
                    let child = document.createElement("tr");
                    child.innerHTML = `
                    ${item.id}
                    ${item.title}
                    ${item.image}
                    ${item.section}
                    ${item.date}	`;
                    table.appendChild(child);
                })

                Id
                Title
                Image
                Section
                Date

Example to understand

let itemarr = [{
  id: 1,
  title: "image 1",
  image: "url 1",
  section: "Film",
  date: "date 1",
}, {
  id: 2,
  title: "image 2",
  image: "url 2",
  section: "Video",
  date: "date 2",
},
{
  id: 3,
  title: "image 3",
  image: "url 2",
  section: "Film",
  date: "date 2",
},
{
  id: 4,
  title: "image 4",
  image: "url 2",
  section: "Video",
  date: "date 2",
}]
itemarr.forEach(function(item) {
  let child = document.querySelector('table').insertRow(-1)
  child.innerHTML = `
                    ${item.id}
                    ${item.title}
                    ${item.image}
                    ${item.section}
                    ${item.date}	`

})

    Id
    Title
    Image
    Section
    Date

Body:
You are on the right track by using insertRow(-1).

Try this one will work, a small notice that Items is currently undefined but I believe you define it

let itemarr = [{
  id: 1,
  title: "image 1",
  image: "url 1",
  section: "section 1",
  date: "date 1",
}, {
  id: 2,
  title: "image 2",
  image: "url 2",
  section: "section 2",
  date: "date 2",
}]
itemarr.forEach(function(item) {
  let child = document.querySelector('table').insertRow(-1)
  child.innerHTML = `
                    <td>${item.id}</td>
                    <td>${item.title}</td>
                    <td>${item.image}</td>
                    <td>${item.section}</td>
                    <td>${item.date}</td>`

})

table {
  text-align: center
}

<table id="my-table" width="90%">
  <tr>
    <th>Id</th>
    <th>Title</th>
    <th>Image</th>
    <th>Section</th>
    <th>Date</th>
  </tr>
  <tr>
    <td>id</td>
    <td>title</td>
    <td>image</td>
    <td>section</td>
    <td>date</td>
  </tr>

</table>


问:
Can you redirect Tee-Object to standard out?
I am writing a script and I want to pass the values but also see them displayed

```<code>Get-Content data.txt | Tee-Object | data_processor.exe
</code>```

But Tee-Object always requests a file and I just want to see it on the screen.

答:
To complement zett42's helpful answer:

If you're running PowerShell (Core) 7+, you can pass the file path that represents the terminal (console) to the (positionally implied) -FilePath parameter (in Windows PowerShell, this causes an error, unfortunately - see bottom section):

# PowerShell 7+ only

# Windows
Get-Content data.txt | Tee-Object \\.\CON | data_processor.exe

# Unix-like platforms (Linux, macOS)
Get-Content data.txt | Tee-Object /dev/tty | data_processor.exe

# Platform-agnostic
Get-Content data.txt | Tee-Object ($IsWindows ? '\\.\CON': '/dev/tty') | data_processor.exe
```
<p>This <strong>passes all data through while also printing it to the terminal (console), richly formatted, as usual, <em>as it becomes available</em></strong> - unlike with the <code>Tee-Object -Variable</code> approach, which requires collecting all output in memory first (which is a concern both in terms of output timing and memory consumption).</p>
<hr />
<p><strong><em>Windows PowerShell</em> solution</strong>: Custom proxy (wrapper) function <strong><code>Tee-Host</code></strong> wraps <code>Out-Host</code> while also passing its input through; use it <em>instead</em> of <code>Tee-Object</code>:</p>
<pre class="lang-bash prettyprint-override"><code>function Tee-Host {
  [CmdletBinding()]
  param(
    [Parameter(ValueFromPipeline)] $InputObject
  )

  begin
  {
    $scriptCmd = { Out-Host }
    $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
    $steppablePipeline.Begin($PSCmdlet)
  }

  process
  {
    # Pass to Out-Host, and therefore to the host (terminal)
    $steppablePipeline.Process($InputObject)
    # Pass through (to the success stream)
    $InputObject
  }

  end
  {
    $steppablePipeline.End()
  }

}
</code>```

In effect, Tee-Host behaves like Tee-Object \\.\CON / Tee-Object /dev/tty in PowerShell 7+, where Tee-Host works too.

Even in PowerShell 7+ Tee-Host may be preferable, because it uses colored output unconditionally, whereas the coloring behavior of Tee-Object \\.\CON / Tee-Object /dev/tty depends on the value of $PSStyle.OutputRendering

It is the use of a proxy function with a steppable pipeline wrapping Out-Host that ensures that the to-host formatted output looks the same as when the input is directly sent to the host.

Body:
I am writing a script and I want to pass the values but also see them displayed

Get-Content data.txt | Tee-Object | data_processor.exe

But Tee-Object always requests a file and I just want to see it on the screen.

Body:
To complement zett42's helpful answer:

If you're running PowerShell (Core) 7+, you can pass the file path that represents the terminal (console) to the (positionally implied) -FilePath parameter (in Windows PowerShell, this causes an error, unfortunately - see bottom section):

# PowerShell 7+ only

# Windows
Get-Content data.txt | Tee-Object \\.\CON | data_processor.exe

# Unix-like platforms (Linux, macOS)
Get-Content data.txt | Tee-Object /dev/tty | data_processor.exe

# Platform-agnostic
Get-Content data.txt | Tee-Object ($IsWindows ? '\\.\CON': '/dev/tty') | data_processor.exe

This passes all data through while also printing it to the terminal (console), richly formatted, as usual, as it becomes available - unlike with the Tee-Object -Variable approach, which requires collecting all output in memory first (which is a concern both in terms of output timing and memory consumption).

Windows PowerShell solution: Custom proxy (wrapper) function Tee-Host wraps Out-Host while also passing its input through; use it instead of Tee-Object:

function Tee-Host {
  [CmdletBinding()]
  param(
    [Parameter(ValueFromPipeline)] $InputObject
  )

  begin
  {
    $scriptCmd = { Out-Host }
    $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
    $steppablePipeline.Begin($PSCmdlet)
  }

  process
  {
    # Pass to Out-Host, and therefore to the host (terminal)
    $steppablePipeline.Process($InputObject)
    # Pass through (to the success stream)
    $InputObject
  }

  end
  {
    $steppablePipeline.End()
  }

}

In effect, Tee-Host behaves like Tee-Object \\.\CON / Tee-Object /dev/tty in PowerShell 7+, where Tee-Host works too.

Even in PowerShell 7+ Tee-Host may be preferable, because it uses colored output unconditionally, whereas the coloring behavior of Tee-Object \\.\CON / Tee-Object /dev/tty depends on the value of $PSStyle.OutputRendering

It is the use of a proxy function with a steppable pipeline wrapping Out-Host that ensures that the to-host formatted output looks the same as when the input is directly sent to the host.


问:
How do I send UpperCase Headers in HTTP
The standard says headers are case insensitive.

Ruby and node both force lower case headers.

We are using an outside server program that expects headers 'AuthToken' to be case sensitive, using .NET framework, and apparently both don't follow standards. We need headers to be up case in this instance.

答:
By looking at the source of NodeJS library on github, you do not need to override the OutgoingMessage.prototype.setHeader

Instead of passing the headers as an Object, you should send them as an Array. Here is a working example :

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

const postData = JSON.stringify({
  'msg': 'Hello World!'
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',

// use an Array instead of Object to avoid lowercase transformation
  headers: [
    ['Host' ,'localhost' ],
    ['X-CustomHeaderFancy' , 'valueForFancyHeader'],
    ['Content-Type', 'application/json'],
    ['Content-Length', Buffer.byteLength(postData)]

  }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();
</code>```

inside the source code of https://github.com/nodejs/node/blob/v16.x/lib/_http_client.js#L249 there is a test to know if the headers are an array, if it is the case, then it bypass the lowercase transformation.
I do not know why it is not documented ? It's a very useful feature.

ContentLicense: CC BY-SA 3.0

Title: How do I send UpperCase Headers in HTTP

Body:
By looking at the source of NodeJS library on github, you do not need to override the OutgoingMessage.prototype.setHeader

Instead of passing the headers as an Object, you should send them as an Array. Here is a working example :

const http = require('http');

const postData = JSON.stringify({
  'msg': 'Hello World!'
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',

// use an Array instead of Object to avoid lowercase transformation
  headers: [
    ['Host' ,'localhost' ],
    ['X-CustomHeaderFancy' , 'valueForFancyHeader'],
    ['Content-Type', 'application/json'],
    ['Content-Length', Buffer.byteLength(postData)]

  }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();

inside the source code of https://github.com/nodejs/node/blob/v16.x/lib/_http_client.js#L249 there is a test to know if the headers are an array, if it is the case, then it bypass the lowercase transformation.
I do not know why it is not documented ? It's a very useful feature.


问:
How do I get a particular InnerText in this XML file?
I need to parse out the Amount node inside the first TotalNetChargeWithDutiesAndTaxes parent node in the sample XML below. How do I do this? I've tried a bunch of stuff but I can't figure out a way to specifically get the value by name of nodes.

The code below is what I have so far, but this is a really hacky way of doing this. I don't know if I can rely on the Amount node always being the second element of the TotalNetChargeWithDutiesAndTaxes node, so I need a way to search this XML doc specifically by the names of the nodes.

```<code>Dim elemList as XmlNodeList = Doc.GetElementsByTagName("TotalNetChargeWithDutiesAndTaxes")

MsgBox(elemList(0).ChildNodes(1).InnerText)
</code>```

The full XML:

```<code><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <RateReply xmlns="http://fedex.com/ws/rate/v31">
         <HighestSeverity>SUCCESS</HighestSeverity>
         <Notifications>
            <Severity>SUCCESS</Severity>
            <Source>crs</Source>
            <Code>0</Code>
            <Message>Request was successfully processed. </Message>
            <LocalizedMessage>Request was successfully processed. </LocalizedMessage>
         </Notifications>
         <TransactionDetail>
            <CustomerTransactionId>94c345b5-55d6-4a44-9c97-d5809179eaa4</CustomerTransactionId>
         </TransactionDetail>
         <Version>
            <ServiceId>crs</ServiceId>
            <Major>31</Major>
            <Intermediate>0</Intermediate>
            <Minor>0</Minor>
         </Version>
         <RateReplyDetails>
            <ServiceType>FEDEX_GROUND</ServiceType>
            <ServiceDescription>
               <ServiceType>FEDEX_GROUND</ServiceType>
               <Code>92</Code>
               <Names>
                  <Type>long</Type>
                  <Encoding>utf-8</Encoding>
                  <Value>FedEx GroundÂ®</Value>
               </Names>
               <Names>
                  <Type>long</Type>
                  <Encoding>ascii</Encoding>
                  <Value>FedEx Ground</Value>
               </Names>
               <Names>
                  <Type>medium</Type>
                  <Encoding>utf-8</Encoding>
                  <Value>GroundÂ®</Value>
               </Names>
               <Names>
                  <Type>medium</Type>
                  <Encoding>ascii</Encoding>
                  <Value>Ground</Value>
               </Names>
               <Names>
                  <Type>short</Type>
                  <Encoding>utf-8</Encoding>
                  <Value>FG</Value>
               </Names>
               <Names>
                  <Type>short</Type>
                  <Encoding>ascii</Encoding>
                  <Value>FG</Value>
               </Names>
               <Names>
                  <Type>abbrv</Type>
                  <Encoding>ascii</Encoding>
                  <Value>SG</Value>
               </Names>
               <Description>FedEx Ground</Description>
               <AstraDescription>FXG</AstraDescription>
            </ServiceDescription>
            <PackagingType>YOUR_PACKAGING</PackagingType>
            <DestinationAirportId>ORD</DestinationAirportId>
            <IneligibleForMoneyBackGuarantee>false</IneligibleForMoneyBackGuarantee>
            <SignatureOption>SERVICE_DEFAULT</SignatureOption>
            <ActualRateType>PAYOR_ACCOUNT_PACKAGE</ActualRateType>
            <RatedShipmentDetails>
               <EffectiveNetDiscount>
                  <Currency>USD</Currency>
                  <Amount>0.0</Amount>
               </EffectiveNetDiscount>
               <ShipmentRateDetail>
                  <RateType>PAYOR_ACCOUNT_PACKAGE</RateType>
                  <RateZone>5</RateZone>
                  <RatedWeightMethod>DIM</RatedWeightMethod>
                  <DimDivisor>139</DimDivisor>
                  <FuelSurchargePercent>11.75</FuelSurchargePercent>
                  <TotalBillingWeight>
                     <Units>LB</Units>
                     <Value>13.0</Value>
                  </TotalBillingWeight>
                  <TotalDimWeight>
                     <Units>LB</Units>
                     <Value>13.0</Value>
                  </TotalDimWeight>
                  <TotalBaseCharge>
                     <Currency>USD</Currency>
                     <Amount>16.87</Amount>
                  </TotalBaseCharge>
                  <TotalFreightDiscounts>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalFreightDiscounts>
                  <TotalNetFreight>
                     <Currency>USD</Currency>
                     <Amount>16.87</Amount>
                  </TotalNetFreight>
                  <TotalSurcharges>
                     <Currency>USD</Currency>
                     <Amount>1.98</Amount>
                  </TotalSurcharges>
                  <TotalNetFedExCharge>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetFedExCharge>
                  <TotalTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalTaxes>
                  <TotalNetCharge>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetCharge>
                  <TotalRebates>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalRebates>
                  <TotalDutiesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalDutiesAndTaxes>
                  <TotalAncillaryFeesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalAncillaryFeesAndTaxes>
                  <TotalDutiesTaxesAndFees>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalDutiesTaxesAndFees>
                  <TotalNetChargeWithDutiesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetChargeWithDutiesAndTaxes>
                  <Surcharges>
                     <SurchargeType>FUEL</SurchargeType>
                     <Level>PACKAGE</Level>
                     <Description>FedEx Ground Fuel</Description>
                     <Amount>
                        <Currency>USD</Currency>
                        <Amount>1.98</Amount>
                     </Amount>
                  </Surcharges>
               </ShipmentRateDetail>
               <RatedPackages>
                  <GroupNumber>1</GroupNumber>
                  <EffectiveNetDiscount>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </EffectiveNetDiscount>
                  <PackageRateDetail>
                     <RateType>PAYOR_ACCOUNT_PACKAGE</RateType>
                     <RatedWeightMethod>DIM</RatedWeightMethod>
                     <BillingWeight>
                        <Units>LB</Units>
                        <Value>13.0</Value>
                     </BillingWeight>
                     <DimWeight>
                        <Units>LB</Units>
                        <Value>13.0</Value>
                     </DimWeight>
                     <BaseCharge>
                        <Currency>USD</Currency>
                        <Amount>16.87</Amount>
                     </BaseCharge>
                     <TotalFreightDiscounts>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalFreightDiscounts>
                     <NetFreight>
                        <Currency>USD</Currency>
                        <Amount>16.87</Amount>
                     </NetFreight>
                     <TotalSurcharges>
                        <Currency>USD</Currency>
                        <Amount>1.98</Amount>
                     </TotalSurcharges>
                     <NetFedExCharge>
                        <Currency>USD</Currency>
                        <Amount>18.85</Amount>
                     </NetFedExCharge>
                     <TotalTaxes>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalTaxes>
                     <NetCharge>
                        <Currency>USD</Currency>
                        <Amount>18.85</Amount>
                     </NetCharge>
                     <TotalRebates>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalRebates>
                     <Surcharges>
                        <SurchargeType>FUEL</SurchargeType>
                        <Level>PACKAGE</Level>
                        <Description>FedEx Ground Fuel</Description>
                        <Amount>
                           <Currency>USD</Currency>
                           <Amount>1.98</Amount>
                        </Amount>
                     </Surcharges>
                  </PackageRateDetail>
               </RatedPackages>
            </RatedShipmentDetails>
            <RatedShipmentDetails>
               <ShipmentRateDetail>
                  <RateType>PAYOR_LIST_PACKAGE</RateType>
                  <RateZone>5</RateZone>
                  <RatedWeightMethod>DIM</RatedWeightMethod>
                  <DimDivisor>139</DimDivisor>
                  <FuelSurchargePercent>11.75</FuelSurchargePercent>
                  <TotalBillingWeight>
                     <Units>LB</Units>
                     <Value>13.0</Value>
                  </TotalBillingWeight>
                  <TotalDimWeight>
                     <Units>LB</Units>
                     <Value>13.0</Value>
                  </TotalDimWeight>
                  <TotalBaseCharge>
                     <Currency>USD</Currency>
                     <Amount>16.87</Amount>
                  </TotalBaseCharge>
                  <TotalFreightDiscounts>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalFreightDiscounts>
                  <TotalNetFreight>
                     <Currency>USD</Currency>
                     <Amount>16.87</Amount>
                  </TotalNetFreight>
                  <TotalSurcharges>
                     <Currency>USD</Currency>
                     <Amount>1.98</Amount>
                  </TotalSurcharges>
                  <TotalNetFedExCharge>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetFedExCharge>
                  <TotalTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalTaxes>
                  <TotalNetCharge>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetCharge>
                  <TotalRebates>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalRebates>
                  <TotalDutiesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalDutiesAndTaxes>
                  <TotalAncillaryFeesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalAncillaryFeesAndTaxes>
                  <TotalDutiesTaxesAndFees>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalDutiesTaxesAndFees>
                  <TotalNetChargeWithDutiesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetChargeWithDutiesAndTaxes>
                  <Surcharges>
                     <SurchargeType>FUEL</SurchargeType>
                     <Level>PACKAGE</Level>
                     <Description>FedEx Ground Fuel</Description>
                     <Amount>
                        <Currency>USD</Currency>
                        <Amount>1.98</Amount>
                     </Amount>
                  </Surcharges>
               </ShipmentRateDetail>
               <RatedPackages>
                  <GroupNumber>1</GroupNumber>
                  <PackageRateDetail>
                     <RateType>PAYOR_LIST_PACKAGE</RateType>
                     <RatedWeightMethod>DIM</RatedWeightMethod>
                     <BillingWeight>
                        <Units>LB</Units>
                        <Value>13.0</Value>
                     </BillingWeight>
                     <DimWeight>
                        <Units>LB</Units>
                        <Value>13.0</Value>
                     </DimWeight>
                     <BaseCharge>
                        <Currency>USD</Currency>
                        <Amount>16.87</Amount>
                     </BaseCharge>
                     <TotalFreightDiscounts>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalFreightDiscounts>
                     <NetFreight>
                        <Currency>USD</Currency>
                        <Amount>16.87</Amount>
                     </NetFreight>
                     <TotalSurcharges>
                        <Currency>USD</Currency>
                        <Amount>1.98</Amount>
                     </TotalSurcharges>
                     <NetFedExCharge>
                        <Currency>USD</Currency>
                        <Amount>18.85</Amount>
                     </NetFedExCharge>
                     <TotalTaxes>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalTaxes>
                     <NetCharge>
                        <Currency>USD</Currency>
                        <Amount>18.85</Amount>
                     </NetCharge>
                     <TotalRebates>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalRebates>
                     <Surcharges>
                        <SurchargeType>FUEL</SurchargeType>
                        <Level>PACKAGE</Level>
                        <Description>FedEx Ground Fuel</Description>
                        <Amount>
                           <Currency>USD</Currency>
                           <Amount>1.98</Amount>
                        </Amount>
                     </Surcharges>
                  </PackageRateDetail>
               </RatedPackages>
            </RatedShipmentDetails>
         </RateReplyDetails>
      </RateReply>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

答:
You can use the XmlDocument to load the xml and iterate through node to get its value.
See below example</p>
```<code>    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.LoadXml(xml);
    XmlNode totalNet = xmlDocument.SelectSingleNode("//*[local-name()='TotalNetChargeWithDutiesAndTaxes']");
    if (totalNet.ChildNodes.Count > 0)
    {
        foreach (XmlNode i in totalNet)
        {
            if (i.InnerText != null && i.Name=='Amount')
            {
                amtValue=i.InnerText
            }
        }
    }
</code>```

Body:
I need to parse out the Amount node inside the first TotalNetChargeWithDutiesAndTaxes parent node in the sample XML below. How do I do this? I've tried a bunch of stuff but I can't figure out a way to specifically get the value by name of nodes.

The code below is what I have so far, but this is a really hacky way of doing this. I don't know if I can rely on the Amount node always being the second element of the TotalNetChargeWithDutiesAndTaxes node, so I need a way to search this XML doc specifically by the names of the nodes.

Dim elemList as XmlNodeList = Doc.GetElementsByTagName("TotalNetChargeWithDutiesAndTaxes")

MsgBox(elemList(0).ChildNodes(1).InnerText)

The full XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <RateReply xmlns="http://fedex.com/ws/rate/v31">
         <HighestSeverity>SUCCESS</HighestSeverity>
         <Notifications>
            <Severity>SUCCESS</Severity>
            <Source>crs</Source>
            0
            <Message>Request was successfully processed. </Message>
            <LocalizedMessage>Request was successfully processed. </LocalizedMessage>
         </Notifications>
         <TransactionDetail>
            <CustomerTransactionId>94c345b5-55d6-4a44-9c97-d5809179eaa4</CustomerTransactionId>
         </TransactionDetail>
         <Version>
            <ServiceId>crs</ServiceId>
            <Major>31</Major>
            <Intermediate>0</Intermediate>
            <Minor>0</Minor>
         </Version>
         <RateReplyDetails>
            <ServiceType>FEDEX_GROUND</ServiceType>
            <ServiceDescription>
               <ServiceType>FEDEX_GROUND</ServiceType>
               92
               <Names>
                  <Type>long</Type>
                  <Encoding>utf-8</Encoding>
                  <Value>FedEx GroundÂ®</Value>
               </Names>
               <Names>
                  <Type>long</Type>
                  <Encoding>ascii</Encoding>
                  <Value>FedEx Ground</Value>
               </Names>
               <Names>
                  <Type>medium</Type>
                  <Encoding>utf-8</Encoding>
                  <Value>GroundÂ®</Value>
               </Names>
               <Names>
                  <Type>medium</Type>
                  <Encoding>ascii</Encoding>
                  <Value>Ground</Value>
               </Names>
               <Names>
                  <Type>short</Type>
                  <Encoding>utf-8</Encoding>
                  <Value>FG</Value>
               </Names>
               <Names>
                  <Type>short</Type>
                  <Encoding>ascii</Encoding>
                  <Value>FG</Value>
               </Names>
               <Names>
                  <Type>abbrv</Type>
                  <Encoding>ascii</Encoding>
                  <Value>SG</Value>
               </Names>
               <Description>FedEx Ground</Description>
               <AstraDescription>FXG</AstraDescription>
            </ServiceDescription>
            <PackagingType>YOUR_PACKAGING</PackagingType>
            <DestinationAirportId>ORD</DestinationAirportId>
            <IneligibleForMoneyBackGuarantee>false</IneligibleForMoneyBackGuarantee>
            <SignatureOption>SERVICE_DEFAULT</SignatureOption>
            <ActualRateType>PAYOR_ACCOUNT_PACKAGE</ActualRateType>
            <RatedShipmentDetails>
               <EffectiveNetDiscount>
                  <Currency>USD</Currency>
                  <Amount>0.0</Amount>
               </EffectiveNetDiscount>
               <ShipmentRateDetail>
                  <RateType>PAYOR_ACCOUNT_PACKAGE</RateType>
                  <RateZone>5</RateZone>
                  <RatedWeightMethod>DIM</RatedWeightMethod>
                  <DimDivisor>139</DimDivisor>
                  <FuelSurchargePercent>11.75</FuelSurchargePercent>
                  <TotalBillingWeight>
                     <Units>LB</Units>
                     <Value>13.0</Value>
                  </TotalBillingWeight>
                  <TotalDimWeight>
                     <Units>LB</Units>
                     <Value>13.0</Value>
                  </TotalDimWeight>
                  <TotalBaseCharge>
                     <Currency>USD</Currency>
                     <Amount>16.87</Amount>
                  </TotalBaseCharge>
                  <TotalFreightDiscounts>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalFreightDiscounts>
                  <TotalNetFreight>
                     <Currency>USD</Currency>
                     <Amount>16.87</Amount>
                  </TotalNetFreight>
                  <TotalSurcharges>
                     <Currency>USD</Currency>
                     <Amount>1.98</Amount>
                  </TotalSurcharges>
                  <TotalNetFedExCharge>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetFedExCharge>
                  <TotalTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalTaxes>
                  <TotalNetCharge>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetCharge>
                  <TotalRebates>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalRebates>
                  <TotalDutiesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalDutiesAndTaxes>
                  <TotalAncillaryFeesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalAncillaryFeesAndTaxes>
                  <TotalDutiesTaxesAndFees>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalDutiesTaxesAndFees>
                  <TotalNetChargeWithDutiesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetChargeWithDutiesAndTaxes>
                  <Surcharges>
                     <SurchargeType>FUEL</SurchargeType>
                     <Level>PACKAGE</Level>
                     <Description>FedEx Ground Fuel</Description>
                     <Amount>
                        <Currency>USD</Currency>
                        <Amount>1.98</Amount>
                     </Amount>
                  </Surcharges>
               </ShipmentRateDetail>
               <RatedPackages>
                  <GroupNumber>1</GroupNumber>
                  <EffectiveNetDiscount>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </EffectiveNetDiscount>
                  <PackageRateDetail>
                     <RateType>PAYOR_ACCOUNT_PACKAGE</RateType>
                     <RatedWeightMethod>DIM</RatedWeightMethod>
                     <BillingWeight>
                        <Units>LB</Units>
                        <Value>13.0</Value>
                     </BillingWeight>
                     <DimWeight>
                        <Units>LB</Units>
                        <Value>13.0</Value>
                     </DimWeight>
                     <BaseCharge>
                        <Currency>USD</Currency>
                        <Amount>16.87</Amount>
                     </BaseCharge>
                     <TotalFreightDiscounts>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalFreightDiscounts>
                     <NetFreight>
                        <Currency>USD</Currency>
                        <Amount>16.87</Amount>
                     </NetFreight>
                     <TotalSurcharges>
                        <Currency>USD</Currency>
                        <Amount>1.98</Amount>
                     </TotalSurcharges>
                     <NetFedExCharge>
                        <Currency>USD</Currency>
                        <Amount>18.85</Amount>
                     </NetFedExCharge>
                     <TotalTaxes>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalTaxes>
                     <NetCharge>
                        <Currency>USD</Currency>
                        <Amount>18.85</Amount>
                     </NetCharge>
                     <TotalRebates>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalRebates>
                     <Surcharges>
                        <SurchargeType>FUEL</SurchargeType>
                        <Level>PACKAGE</Level>
                        <Description>FedEx Ground Fuel</Description>
                        <Amount>
                           <Currency>USD</Currency>
                           <Amount>1.98</Amount>
                        </Amount>
                     </Surcharges>
                  </PackageRateDetail>
               </RatedPackages>
            </RatedShipmentDetails>
            <RatedShipmentDetails>
               <ShipmentRateDetail>
                  <RateType>PAYOR_LIST_PACKAGE</RateType>
                  <RateZone>5</RateZone>
                  <RatedWeightMethod>DIM</RatedWeightMethod>
                  <DimDivisor>139</DimDivisor>
                  <FuelSurchargePercent>11.75</FuelSurchargePercent>
                  <TotalBillingWeight>
                     <Units>LB</Units>
                     <Value>13.0</Value>
                  </TotalBillingWeight>
                  <TotalDimWeight>
                     <Units>LB</Units>
                     <Value>13.0</Value>
                  </TotalDimWeight>
                  <TotalBaseCharge>
                     <Currency>USD</Currency>
                     <Amount>16.87</Amount>
                  </TotalBaseCharge>
                  <TotalFreightDiscounts>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalFreightDiscounts>
                  <TotalNetFreight>
                     <Currency>USD</Currency>
                     <Amount>16.87</Amount>
                  </TotalNetFreight>
                  <TotalSurcharges>
                     <Currency>USD</Currency>
                     <Amount>1.98</Amount>
                  </TotalSurcharges>
                  <TotalNetFedExCharge>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetFedExCharge>
                  <TotalTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalTaxes>
                  <TotalNetCharge>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetCharge>
                  <TotalRebates>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalRebates>
                  <TotalDutiesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalDutiesAndTaxes>
                  <TotalAncillaryFeesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalAncillaryFeesAndTaxes>
                  <TotalDutiesTaxesAndFees>
                     <Currency>USD</Currency>
                     <Amount>0.0</Amount>
                  </TotalDutiesTaxesAndFees>
                  <TotalNetChargeWithDutiesAndTaxes>
                     <Currency>USD</Currency>
                     <Amount>18.85</Amount>
                  </TotalNetChargeWithDutiesAndTaxes>
                  <Surcharges>
                     <SurchargeType>FUEL</SurchargeType>
                     <Level>PACKAGE</Level>
                     <Description>FedEx Ground Fuel</Description>
                     <Amount>
                        <Currency>USD</Currency>
                        <Amount>1.98</Amount>
                     </Amount>
                  </Surcharges>
               </ShipmentRateDetail>
               <RatedPackages>
                  <GroupNumber>1</GroupNumber>
                  <PackageRateDetail>
                     <RateType>PAYOR_LIST_PACKAGE</RateType>
                     <RatedWeightMethod>DIM</RatedWeightMethod>
                     <BillingWeight>
                        <Units>LB</Units>
                        <Value>13.0</Value>
                     </BillingWeight>
                     <DimWeight>
                        <Units>LB</Units>
                        <Value>13.0</Value>
                     </DimWeight>
                     <BaseCharge>
                        <Currency>USD</Currency>
                        <Amount>16.87</Amount>
                     </BaseCharge>
                     <TotalFreightDiscounts>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalFreightDiscounts>
                     <NetFreight>
                        <Currency>USD</Currency>
                        <Amount>16.87</Amount>
                     </NetFreight>
                     <TotalSurcharges>
                        <Currency>USD</Currency>
                        <Amount>1.98</Amount>
                     </TotalSurcharges>
                     <NetFedExCharge>
                        <Currency>USD</Currency>
                        <Amount>18.85</Amount>
                     </NetFedExCharge>
                     <TotalTaxes>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalTaxes>
                     <NetCharge>
                        <Currency>USD</Currency>
                        <Amount>18.85</Amount>
                     </NetCharge>
                     <TotalRebates>
                        <Currency>USD</Currency>
                        <Amount>0.0</Amount>
                     </TotalRebates>
                     <Surcharges>
                        <SurchargeType>FUEL</SurchargeType>
                        <Level>PACKAGE</Level>
                        <Description>FedEx Ground Fuel</Description>
                        <Amount>
                           <Currency>USD</Currency>
                           <Amount>1.98</Amount>
                        </Amount>
                     </Surcharges>
                  </PackageRateDetail>
               </RatedPackages>
            </RatedShipmentDetails>
         </RateReplyDetails>
      </RateReply>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Body:
You can use the XmlDocument to load the xml and iterate through node to get its value.
See below example

    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.LoadXml(xml);
    XmlNode totalNet = xmlDocument.SelectSingleNode("//*[local-name()='TotalNetChargeWithDutiesAndTaxes']");
    if (totalNet.ChildNodes.Count > 0)
    {
        foreach (XmlNode i in totalNet)
        {
            if (i.InnerText != null && i.Name=='Amount')
            {
                amtValue=i.InnerText
            }
        }
    }


问:
Allow slash & æ,ø,å in preg_match
As the title says, I simply need to allow a normal slash in preg_match. I thought it was something like / or something. But that doesn't work.

I also need to allow european letters: æ,ø,å. How is this done?

Could someone tell me this? :-)

Example

```<code>if(preg_match("/^[a-zA-Z -]+$/", $_POST["last_name"]) == 0)
                {
                    $errMsg = "Dit efternavn må kun indeholde bogstaver, mellemrum og bindestreg.<br>";
                }
</code>```

And then I'm doing a
if(count($errMsg)==0){
 }

Thanks in advance.

答:
Those characters can be used normally, in order to use slashes (/). you will need to escape them with a backslash (\). Like so:

```<code>preg_match("%^[-a-zA-Z æøå\/]+$%");
</code>```

Also note that you can use any character as a delimiter, it may be wise to use characters that are not likely to appear in the pattern itself (in this case, I chose %).

Title: Allow slash & æ,ø,å in preg_match

Body:
As the title says, I simply need to allow a normal slash in preg_match. I thought it was something like / or something. But that doesn't work.

I also need to allow european letters: æ,ø,å. How is this done?

Could someone tell me this? :-)

Example

if(preg_match("/^[a-zA-Z -]+$/", $_POST["last_name"]) == 0)
                {
                    $errMsg = "Dit efternavn må kun indeholde bogstaver, mellemrum og bindestreg.
";
                }

And then I'm doing a
if(count($errMsg)==0){
 }

Thanks in advance.

Body:
Those characters can be used normally, in order to use slashes (/). you will need to escape them with a backslash (\). Like so:

preg_match("%^[-a-zA-Z æøå\/]+$%");

Also note that you can use any character as a delimiter, it may be wise to use characters that are not likely to appear in the pattern itself (in this case, I chose %).


问:
Expanding __consumer_offsets topics to multiple new nodes in cluster
Initially we had a 5 node Kafka cluster which was expanded to 7 nodes. Post expansion, the heavier topics were added with more partitions and reassignment was done to spread them to the additional nodes and the setup is working as expected. Is it safe to add more partitions to the __consumer_offsets topic as well and run the partition assignment script to evenly distribute the partitions across the cluster. Since this is a Kafka internal topic, I am quite cautious before making any changes.

The Kafka version used is 2.4

答: There shouldn't be any problem in reassignment of __consumer_offsets topic. It is just like any other topic in Kafka</p>


问:
How to sort the date in dd-mm-yyyy format in c++
Suggest way to store and sort in c++.

input:

```<code>01-02-2022
15-01-2022
20-10-2021
25-12-2022
</code>```

答:
If you want to sort the dates represented as strings, you will have to parse the strings to order the dates chronologically. You can do this in-flight, if you don't need the parsed dates, or you can first parse all dates and then operate on the parsed data.

I'll show an example that does parsing in-flight, splitting the parsing and ordering parts is an exercise for the reader.

```<code>void sort_dates(std::vector< std::string >& dates)
{
    std::sort(dates.begin(), dates.end(),
        [](std::string const& left, std::string const& right)
        {
            // Parse dates
            unsigned int ly, lm, ld;
            if (std::sscanf(left.c_str(), "%u-%u-%u", &ld, &lm, &ly) != 3)
                throw std::invalid_argument("Date is in invalid format: " + left);

            unsigned int ry, rm, rd;
            if (std::sscanf(right.c_str(), "%u-%u-%u", &rd, &rm, &ry) != 3)
                throw std::invalid_argument("Date is in invalid format: " + right);

            // Compare the dates chronologically: return true if left < right
            if (ly < ry)
                return true;
            else if (ly > ry)
                return false;

            if (lm < rm)
                return true;
            else if (lm > rm)
                return false;

            return ld < rd;
        }
    );
}
</code>```

Body:
Suggest way to store and sort in c++.

input:

01-02-2022
15-01-2022
20-10-2021
25-12-2022

Body:
If you want to sort the dates represented as strings, you will have to parse the strings to order the dates chronologically. You can do this in-flight, if you don't need the parsed dates, or you can first parse all dates and then operate on the parsed data.

I'll show an example that does parsing in-flight, splitting the parsing and ordering parts is an exercise for the reader.

void sort_dates(std::vector< std::string >& dates)
{
    std::sort(dates.begin(), dates.end(),
        [](std::string const& left, std::string const& right)
        {
            // Parse dates
            unsigned int ly, lm, ld;
            if (std::sscanf(left.c_str(), "%u-%u-%u", &ld, &lm, &ly) != 3)
                throw std::invalid_argument("Date is in invalid format: " + left);

            unsigned int ry, rm, rd;
            if (std::sscanf(right.c_str(), "%u-%u-%u", &rd, &rm, &ry) != 3)
                throw std::invalid_argument("Date is in invalid format: " + right);

            // Compare the dates chronologically: return true if left < right
            if (ly < ry)
                return true;
            else if (ly > ry)
                return false;

            if (lm < rm)
                return true;
            else if (lm > rm)
                return false;

            return ld < rd;
        }
    );
}


问:
How to stop Wordpress TinyMCE from stripping content of empty html tags e.g.

I'm displaying some content in two columns in a Wordpress post, so I've got two divs displaying half each:

```<code><div class="half">Left column.</div>
<div class="half last">Right column.</div>
</code>```

But of course I also need to clear this, which I usually do with this afterwards:

```<code><div style="clear:both;"></div>
</code>```

but this keeps getting stripped out whenever I save the article or view the visual editor as well as any other empty html tags e.g. icons. Is there a better way to do this?

答:
The way I've found around this is to add an element with the class hidden with some text in it. Then use the .hidden class to hide that element. Tiny MCE was stripping the non-breaking space from my content.

So, it would look like this:

```<code><div class="clearfix"><span class="hidden">Clearfix</span></div>
</code>```

Body:
I'm displaying some content in two columns in a Wordpress post, so I've got two divs displaying half each:

Left column.

Right column.

But of course I also need to clear this, which I usually do with this afterwards:

but this keeps getting stripped out whenever I save the article or view the visual editor as well as any other empty html tags e.g. icons. Is there a better way to do this?

Body:
The way I've found around this is to add an element with the class hidden with some text in it. Then use the .hidden class to hide that element. Tiny MCE was stripping the non-breaking space from my content.

So, it would look like this:

<div class="clearfix"><span class="hidden">Clearfix</span></div>


问:
unknown status code: 17028 A safety_net_token was passed, but no matching SHA-256 was registered
unknown status code: 17028 A safety_net_token was passed, but no matching SHA-256 was registered in the Firebase console. Please make sure that this application’s packageName/SHA256 pair is registered in the Firebase Console.

hello there, i m facing this issues while developing application, i have tried to fix and these are the steps i have done so far but the same result:

correctly configured the firebase and my flutter application by using the steps on firebase

i have signed my app and added the signing key both debug and release keys, both SHA-1 key and SHA-256 key

I have enabled Android Verification in google cloud page also

i have enabled the authentication provider, phone authentication enabled, password/email enabled

in addition to that when i use testing phone number i added to the console and the otp code i insert, my app works perfectly
but when trying to authenticate the phone using  other un registered phone numbers it keeps showing me error.

i have cheched flutter doctor -v it has no error
also execute flutter commands there is nothing error related thing on the result. I have used the following firebase plugins

firebase_auth: ^0.18.4+1
firebase_core: ^0.5.3
cloud_firestore: ^0.14.4
firebase_admob:
firebase_messaging: ^7.0.3
firebase_storage: ^5.2.0

any help from you would be appreciated

答: I face a similar problem.  So Please Add SHA-256 Key On Firebase Not SHA-1</p>


问:
How to alter a queue table's column from byte semantics to character semantics (Oracle)?
How can I alter a queue table's column from byte semantics to character semantics? (oracle 10/11g)

Thanks advance.

答: If I'm reading the Oracle documentation correctly, ALTER TABLE should work as expected - the only restriction mentioned there is that you cannot add a new column to a queue table.</p>


问:
MySQL: Search for coincidences and differences in two tables
I need to find matchs between two tables, but also need to display when there is no match.

Table1: id, dni_number, name, business_id

Table2: id, dni, business_id

I need to form a table like this:

id
dni
name
business_id
is_match

1
12365478
John Doe
15451
1

1
22365478
Karen Doe
23451
0

is_match meaning 1: it found the dni in table1 and also in table2, 0 for not match

The query should have a where condition to find matchs from certain business_id

Any help will be much appreciated. Thanks in advance

答:
```<code>SELECT
tblA.id,
1 as is_match
FROM tblA, tblB
WHERE tblA.id = tblB.id

UNION ALL

SELECT
tblA.id,
0 as is_match
FROM tblA, tblB
WHERE tblA.id != tblB.id

</code>```


问:
how to use discord.py to put a custom prescense on a users account?
I want to make a program that shows the current song playing on a users (mine) apple music app on MacOS and display the info in the users' discord presence (not on a bot account), similar to the Spotify integration. However, all of the docs I'm reading for how to use discord.py, it only talks about using it with a bot, and I cannot find how to just use it for the user. I may not be looking in the right place but I'm not sure. Is there a way to just use it with a user, or do you need a bot to use discord.py?

I'm kinda dumb so sorry in advance and please help.

答:
You will need to use a self-bot for this purpose and since it's against Discord's TOS I wouldn't recommend it.

import discord

client = discord.Client()

client.change_presence(
    activity = discord.Activity(
        type = discord.ActivityType.listening,
        song = "I am so screwed!"
    )
)

client.run("YOUR TOKEN")
```


问:
Trying to insert value in class method
I'm trying to pass an argument from the get_name() to post() and I'm not sure how to do this correctly</p>
```<code>from bs4 import BeautifulSoup
import requests

webhook = 'my webhook'

class Item:
    def __init__(self, url):
        self.url = url
        self.page = requests.get(url)
        self.soup = BeautifulSoup(self.page.content, 'html.parser')

    def post(self):
        requests.post(webhook, json={'username' : 'scraper', 'content' : variable}) #how do i do this

    def get_name(self):
        name = self.soup.find('h2').get_text()
        post(name)

    def get_price(self):
        price = self.soup.find('span' {'class' : 'text-lg wait-for-i18n-format-render'})
        post(price)
</code>```

答:
Two (maybe three) problems:

post is not a function the enclosing scope; it is a class attribute of the class Item, and needs to be accessed as such from Item or an instance of Item.

post needs to take an additional argument to be used as the value of the content key.

Item.post should probably return the return value of requests.post, as the caller may want to that in order to, for example, check the result of the POST request.

Your class should look like

```<code>class Item:
    def __init__(self, url):
        self.url = url
        self.page = requests.get(url)
        self.soup = BeautifulSoup(self.page.content, 'html.parser')

    def post(self, variable):
        return requests.post(webhook, json={'username' : 'scraper', 'content' : variable})

    def get_name(self):
        name = self.soup.find('h2').get_text()
        self.post(name)

    def get_price(self):
        price = self.soup.find('span' {'class' : 'text-lg wait-for-i18n-format-render'})
        self.post(price)
</code>```

Title: Trying to insert value in class method

Body:
I'm trying to pass an argument from the get_name() to post() and I'm not sure how to do this correctly

from bs4 import BeautifulSoup
import requests

webhook = 'my webhook'

class Item:
    def __init__(self, url):
        self.url = url
        self.page = requests.get(url)
        self.soup = BeautifulSoup(self.page.content, 'html.parser')

    def post(self):
        requests.post(webhook, json={'username' : 'scraper', 'content' : variable}) #how do i do this

    def get_name(self):
        name = self.soup.find('h2').get_text()
        post(name)

    def get_price(self):
        price = self.soup.find('span' {'class' : 'text-lg wait-for-i18n-format-render'})
        post(price)

Body:
Two (maybe three) problems:

post is not a function the enclosing scope; it is a class attribute of the class Item, and needs to be accessed as such from Item or an instance of Item.

post needs to take an additional argument to be used as the value of the content key.

Item.post should probably return the return value of requests.post, as the caller may want to that in order to, for example, check the result of the POST request.

Your class should look like

class Item:
    def __init__(self, url):
        self.url = url
        self.page = requests.get(url)
        self.soup = BeautifulSoup(self.page.content, 'html.parser')

    def post(self, variable):
        return requests.post(webhook, json={'username' : 'scraper', 'content' : variable})

    def get_name(self):
        name = self.soup.find('h2').get_text()
        self.post(name)

    def get_price(self):
        price = self.soup.find('span' {'class' : 'text-lg wait-for-i18n-format-render'})
        self.post(price)


问:
How to do this in one line using PHP
I have the following structure:

```<code>$par4 = json_decode($source_code)->$par1->$par2->$par3;
$par5 = $par4[0]->attributes->attribute[1]->value;
</code>```

where par1, par2 and par3 are strings. How do I chain the par4 and par5 on one line.

This does not work because of the array / object nesting I guess:

```<code>json_decode($source_code)->$par1->$par2->$par3[0]->attributes->attribute[1]->value;
</code>```

Here's the error:

```<code>Undefined property: stdClass::$o
</code>```

答:
What about

```<code>$par5 = current(json_decode($source_code)->$par1->$par2->$par3)->attributes->attribute[1]->value;
</code>```

This works if you are always need in the first (0th) value of the array.

You can also create a function that returns the nth-value:

```<code>function third_value($arr) { return $arr[2]; }
$par5 = third_value(json_decode($source_code)->$par1->$par2->$par3)->attributes->attribute[1]->value;
</code>```

Title: How to do this in one line using PHP

Body:
I have the following structure:

$par4 = json_decode($source_code)->$par1->$par2->$par3;
$par5 = $par4[0]->attributes->attribute[1]->value;

where par1, par2 and par3 are strings. How do I chain the par4 and par5 on one line.

This does not work because of the array / object nesting I guess:

json_decode($source_code)->$par1->$par2->$par3[0]->attributes->attribute[1]->value;

Here's the error:

Undefined property: stdClass::$o

Body:
What about

$par5 = current(json_decode($source_code)->$par1->$par2->$par3)->attributes->attribute[1]->value;

This works if you are always need in the first (0th) value of the array.

You can also create a function that returns the nth-value:

function third_value($arr) { return $arr[2]; }
$par5 = third_value(json_decode($source_code)->$par1->$par2->$par3)->attributes->attribute[1]->value;


问:
How to retrieve the original data from nls model in R?
non-linear least square (nls() function in core R) generates a list object with a bunch of useful info inside, is there also the original data that were the input of the model? I suspect yes, as functions as predict() or fitted() are actually defined on this object and generate predictions in ranges of the original fitted data. So, how can one access this data through the model object?

Imagine this setting

```<code># generating some data
generated_data <- hist(rnorm(1000, 50, 10))
data <- data.frame(x = generated_data$mids, y = generated_data$counts)

# a dummy model
my_model <- nls(y ~ N * dnorm(x, m, s), data=data, start=c(m=55, s=12, N=sum(data$y)) )
</code>```

How can I access x and y values by the my_model object?

答:
Broom has nice features for dealing with many models. You can use broom::augment() with added benefits :)

If you don't want to use broom, then Kamil's answer works.

```<code>library(dplyr)
library(broom)
my_model %>% augment()
</code>```
```<code># A tibble: 13 × 4
      x     y .fitted  .resid
  <dbl> <int>   <dbl>   <dbl>
1  22.5     6    4.27   1.73
2  27.5    18   15.1    2.88
3  32.5    45   41.6    3.36
4  37.5    94   89.1    4.87
5  42.5   137  148.   -11.3
6  47.5   191  192.    -0.740
# … with 7 more rows
</code>```

Body:
non-linear least square (nls() function in core R) generates a list object with a bunch of useful info inside, is there also the original data that were the input of the model? I suspect yes, as functions as predict() or fitted() are actually defined on this object and generate predictions in ranges of the original fitted data. So, how can one access this data through the model object?

Imagine this setting

# generating some data
generated_data <- hist(rnorm(1000, 50, 10))
data <- data.frame(x = generated_data$mids, y = generated_data$counts)

# a dummy model
my_model <- nls(y ~ N * dnorm(x, m, s), data=data, start=c(m=55, s=12, N=sum(data$y)) )

How can I access x and y values by the my_model object?

Body:
Broom has nice features for dealing with many models. You can use broom::augment() with added benefits :)

If you don't want to use broom, then Kamil's answer works.

library(dplyr)
library(broom)
my_model %>% augment()

# A tibble: 13 × 4
      x     y .fitted  .resid
  <dbl> <int>   <dbl>   <dbl>
1  22.5     6    4.27   1.73
2  27.5    18   15.1    2.88
3  32.5    45   41.6    3.36
4  37.5    94   89.1    4.87
5  42.5   137  148.   -11.3
6  47.5   191  192.    -0.740
# … with 7 more rows


问:
Javascript: using "!!" in boolean context
Is there any reason to use !!someValue (which is equivalent to Boolean(someValue)) in a boolean context? In other words, in situations like if (someValue) ..., does it make sense to write if (!!someValue) ...?

It hurts my eyes and I think it's redundant, but I want to verify that there aren't any edge cases that require it - because I came across a codebase where this seems to be the default way of checking for truthiness.

Clarification: yes, in the general case !!someValue will convert someValue to a boolean; I'm referring to contexts where the runtime will automatically convert someValue to true or false.

答:
You never need to use a double bang to convert a boolean value to boolean.</p>
```<code>boolean === !!boolean
</code>```

Body:
You never need to use a double bang to convert a boolean value to boolean.

boolean === !!boolean


问:
How to add in a missing day to gridded dataset?
So I have this dataset that runs on a strict 365-day calendar year, apparently meaning that data for December 31st isn't recorded on leap years. This leaves my "day" variable in netCDF files stuck at 365 instead of 366. For the type of analysis I'm doing in R, I need to add in December 31st on those leap years. Is there a way, either with netCDF or raster tools in R, to add in a "null" 366th day with the same attributes as the other days, but all points having no data/only the established fill value (e.g., "NA", "-9999")?

If so, as kind of a bonus, I have another dataset that's a little trickier. It's missing days at random points in the year, but originally came in GRIB/GRIB2 format. If the dates run from January 1st to June 1st, and then June 2nd is completely missing, but June 3rd through December 31st is intact, how should I move forward converting them all into one netCDF file with a "blank" data day for June 2nd? What I was initially thinking was concatenating those GRIB/GRIB2 files from January 1st to June 1st and writing a netCDF file for it, create a blank netCDF file with some fill value for June 2nd, and then concatenating those GRIB/GRIB2 files from June 3rd to December 31st and writing a netCDF file for it, and then combining all of those netCDF files somehow in R. If anyone has any ideas how I might create that blank file that matches all the attributes of the other dates, or how I might combine them all in R, please let me know!

答:
Figured it out! After reading in my netCDF file with raster::brick(file) I could create a simple raster to match it with the raster::raster function as follows:

file_dec31 <- raster(ncols=y, nrows=x, resolution=fileres, xmn=filexmn, xmx=filexmx, ymn=fileymn, ymx=filexmx, vals=NAvalue)

I then simply stacked the original file as follows:

raster::stack(file, file_dec31)

This gave me a working version that I could write back into netCDF with raster::writeRaster! This approach should work for stacking together three different raster versions for the second example as well.


问:
Flutter http.post body is an empty object on nodejs?
My Flutter http.post request is sending an empty body to my Node.js server. Here is my front-end code:

```<code>var response = await http.post(Uri.parse('$host/api/new'),
            body: {
              'id': '$id',
              'token': token
            });
</code>```

The post is reaching my node.js server, but the body is an empty object. What am I doing wrong?

答:
Adding this to the post request fixed it for me:

```<code>headers: {
      HttpHeaders.contentTypeHeader: 'application/json',
    },
</code>```

Then adding this around the body:

```<code>jsonEncode({ ... })
</code>```

And importing this:

```<code>import 'dart:io';
</code>```

Body:
My Flutter http.post request is sending an empty body to my Node.js server. Here is my front-end code:

var response = await http.post(Uri.parse('$host/api/new'),
            body: {
              'id': '$id',
              'token': token
            });

The post is reaching my node.js server, but the body is an empty object. What am I doing wrong?

Body:
Adding this to the post request fixed it for me:

headers: {
      HttpHeaders.contentTypeHeader: 'application/json',
    },

Then adding this around the body:

jsonEncode({ ... })

And importing this:

import 'dart:io';


问:
How to use \n new line in VB msgbox() ...?
What is the alternative to \n (for new line) in a MsgBox()?

答: do not forget to set the Multiline property to true in textbox</p>


问:
Vue.js <keep-alive> in template for slot not working
I'm working with a component that was built out called 'Stepper' it's a basic component that has the steps at the top to guide the user through a process. In this stepper we have a dynamic number of slots that are produced and we pass a component in to fill that slot.

Stepper.vue

...

    <slot :name="`${step.name}`" />

...
```
<p>Parent.vue</p>
<pre class="lang-html prettyprint-override"><code>...
<Stepper :items="steps"
  <template v-for="step in steps" v-slot:[step.name] :key="step.name">
    <keep-alive>
      <component :is="step.component" />
    </keep-alive>
  </template>
</Stepper>
...

<script lang="ts">
...
import Stepper from "@/components/Stepper.vue";
import Component1 from "@/components/Component1.vue";
import Component2 from "@/components/Component2.vue";

export default defineComponent({
  name: "ParentComponent",
  components: {
    Stepper,
    Component1,
    Component2,
  },
  setup() {
    const steps = ref([
      {
        name: "step1",
        label: "Step 1",
        component: "Component1",
      },
      {
        name: "step2",
        label: "Step 2",
        component: "Component2",
      },
    ]);

    return {
      steps,
    }
  }
</script>
</code>```

All in all everything is working. The component for each step displays, the steps increment so on and so forth. The issue we're having is that the <keep-alive> is not working. Every time you go back or forth in the steps the component re-renders and we're seeing the onMounted hook called. Granted we can pre-populate the form with some 'saved' data if needed but would be nice if we could get the <keep-alive> to work. We've also tried adding the :include="[COMPONENT_NAMES]" to the <keep-alive> as well, to no avail.

Edit: Updated code snippet with more details.

答:
Make sure you're not testing this in your development environment that usually has caches disabled. Therefore if you don't have a cached reference the keep-alive wont work.

This means that Vue does not have to create a new instance every single time you switch components. **Instead, it just uses the cached reference whenever you come back to it**. Keep-Alive is what VueJS calls an abstract element – meaning that it does not render a DOM element nor does it show up as a component.

Also you could have the cache disabled in the Console tools.

To be certain you can check this setting:

#another edit:

I have done some more research, and adding a key to your Keep-alive component

<component :is="step.component" :key="UniqueIdentifier" />

will help your vue-router understand that this component is changed.

Check out this other SA answer: vue Keep-alive not working

Body:
I'm working with a component that was built out called 'Stepper' it's a basic component that has the steps at the top to guide the user through a process. In this stepper we have a dynamic number of slots that are produced and we pass a component in to fill that slot.

Stepper.vue

...

    <slot :name="`${step.name}`" />

...

Parent.vue

...
<Stepper :items="steps"
  <template v-for="step in steps" v-slot:[step.name] :key="step.name">
    <keep-alive>
      <component :is="step.component" />
    </keep-alive>
  </template>
</Stepper>
...

All in all everything is working. The component for each step displays, the steps increment so on and so forth. The issue we're having is that the <keep-alive> is not working. Every time you go back or forth in the steps the component re-renders and we're seeing the onMounted hook called. Granted we can pre-populate the form with some 'saved' data if needed but would be nice if we could get the <keep-alive> to work. We've also tried adding the :include="[COMPONENT_NAMES]" to the <keep-alive> as well, to no avail.

Edit: Updated code snippet with more details.


问:
Reading in a positive number in C
I'm trying to find the most efficient way to read in a positive number in C. I can't use just scanf("%u", &var) because scanf takes the two's complement of negative numbers thereby screwing up the number. I also don't really want to read characters in manually into a buffer, because that requires me to know before-hand the maximum number of digits, which really I only want to be limited by UINT_MAX.

Any ideas, things I've most probably overlooked?

答:
Maybe somtehing like this:</p>

```<code>char sign = getchar();
if ('-' == sign) {
    //error
} else {
    ungetchar(sign);
    scanf("%u", &var)
}
</code>```

Title: Reading in a positive number in C

Body:
Maybe somtehing like this:

char sign = getchar();
if ('-' == sign) {
    //error
} else {
    ungetchar(sign);
    scanf("%u", &var)
}


问:
Exclude node_modules from "problems"
I'm running this task:

```<code>{
        "taskName": "tsc watch",
        "command": "tsc -w",
        "type": "shell",
        "problemMatcher": "$tsc-watch"
}
</code>```

with this tsconfig:

```<code>{
    "compileOnSave": true,
    "files": [
        "src/index.ts"
    ],
    "compilerOptions": {
        "module": "commonjs",
        "sourceMap": true,
        "outDir": "dist/"
    },
    "exclude": [
        "node_modules"
    ]
}
</code>```

the file index.ts only has one line in it:

```<code>console.log('Is it working?');
</code>```

And the "problems" tab is filled with HTML related warnings from random npm modules. Why? And how do i stop it?

Edit1:

I managed to find a hack that works, by excluding the node_modules folder from the explorer:

```<code>/* settings.json */
{
    "files.exclude": {
        "**/node_modules": true
    }
}
</code>```

However this is a hack, and i still want a proper answer..

答:
All you should need is a tsconfig.json with:

```<code>{
    "compilerOptions": {
        "skipLibCheck": true,
    }
}
</code>```

Title: Exclude node_modules from "problems"

Body:
I'm running this task:

{
        "taskName": "tsc watch",
        "command": "tsc -w",
        "type": "shell",
        "problemMatcher": "$tsc-watch"
}

with this tsconfig:

{
    "compileOnSave": true,
    "files": [
        "src/index.ts"
    ],
    "compilerOptions": {
        "module": "commonjs",
        "sourceMap": true,
        "outDir": "dist/"
    },
    "exclude": [
        "node_modules"
    ]
}

the file index.ts only has one line in it:

console.log('Is it working?');

And the "problems" tab is filled with HTML related warnings from random npm modules. Why? And how do i stop it?

Edit1:

I managed to find a hack that works, by excluding the node_modules folder from the explorer:

/* settings.json */
{
    "files.exclude": {
        "**/node_modules": true
    }
}

However this is a hack, and i still want a proper answer..

Body:
All you should need is a tsconfig.json with:

{
    "compilerOptions": {
        "skipLibCheck": true,
    }
}