问:
React native navigation back arrow missing on iOS 14
When upgrading to iOS 14 the back arrow disappeared when using stack navigation. I have come to the conclusion that it has something to do with our react-native version. I created a new project using https://reactnative.dev/docs/environment-setup with the following setup:

```<code>"@react-native-community/masked-view": "^0.1.10",
"react": "16.13.1",
"react-native": "0.63.2",
"react-native-gesture-handler": "^1.8.0",
"react-native-reanimated": "^1.13.0",
"react-native-safe-area-context": "^3.1.7",
"react-native-screens": "^2.10.1",
"react-navigation": "^4.4.0",
"react-navigation-stack": "^2.8.2"
</code>```

With that, the back arrow is showing. However our setup is the following:

```<code>"@react-native-community/masked-view": "^0.1.10",
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-gesture-handler": "^1.8.0",
"react-native-reanimated": "^1.13.0",
"react-native-safe-area-context": "^3.1.7",
"react-native-screens": "^2.10.1",
"react-navigation": "^4.4.0",
"react-navigation-stack": "^2.8.2"
</code>```

With that setup the back arrow is not showing. My App.js looks like this in both cases:

```<code>import 'react-native-gesture-handler';
import React from 'react';
import {Button, View, Text} from 'react-native';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </View>
    );
  }
}

class DetailsScreen extends React.Component {
  render() {
    return (
      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>Details Screen</Text>
      </View>
    );
  }
}

const AppNavigator = createStackNavigator(
  {
    Home: HomeScreen,
    Details: DetailsScreen,
  },
  {
    initialRouteName: 'Home',
  },
);

const AppContainer = createAppContainer(AppNavigator);

export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}
</code>```

An obvious solution would be to upgrade the react-native version but we would like to avoid this at the moment because it is quite a time-consuming task. You could also use headerBackImage but I would like to use the "native" way. So I wanted to ask if anyone knows how to fix this if there is some asset that is not linked properly or something.

答:
There is a very easy way to fix this: simply add the following to package.json:

"postinstall": "npx react-native-fix-image"

See: https://github.com/imhuy/react-native-fix-image

Body:
When upgrading to iOS 14 the back arrow disappeared when using stack navigation. I have come to the conclusion that it has something to do with our react-native version. I created a new project using https://reactnative.dev/docs/environment-setup with the following setup:

"@react-native-community/masked-view": "^0.1.10",
"react": "16.13.1",
"react-native": "0.63.2",
"react-native-gesture-handler": "^1.8.0",
"react-native-reanimated": "^1.13.0",
"react-native-safe-area-context": "^3.1.7",
"react-native-screens": "^2.10.1",
"react-navigation": "^4.4.0",
"react-navigation-stack": "^2.8.2"

With that, the back arrow is showing. However our setup is the following:

"@react-native-community/masked-view": "^0.1.10",
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-gesture-handler": "^1.8.0",
"react-native-reanimated": "^1.13.0",
"react-native-safe-area-context": "^3.1.7",
"react-native-screens": "^2.10.1",
"react-navigation": "^4.4.0",
"react-navigation-stack": "^2.8.2"

With that setup the back arrow is not showing. My App.js looks like this in both cases:

import 'react-native-gesture-handler';
import React from 'react';
import {Button, View, Text} from 'react-native';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </View>
    );
  }
}

class DetailsScreen extends React.Component {
  render() {
    return (
      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>Details Screen</Text>
      </View>
    );
  }
}

const AppNavigator = createStackNavigator(
  {
    Home: HomeScreen,
    Details: DetailsScreen,
  },
  {
    initialRouteName: 'Home',
  },
);

const AppContainer = createAppContainer(AppNavigator);

export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}

An obvious solution would be to upgrade the react-native version but we would like to avoid this at the moment because it is quite a time-consuming task. You could also use headerBackImage but I would like to use the "native" way. So I wanted to ask if anyone knows how to fix this if there is some asset that is not linked properly or something.


来源: stackexchange

问:
Get android architecture vith bash
How to get processor architecture without dpkg using android command line

with dpkg bash code

```<code>case `dpkg --print-architecture` in
                aarch64)
                        archurl="arm64" ;;
                arm)
                        archurl="armhf" ;;
                amd64)
                        archurl="amd64" ;;
                x86_64)
                        archurl="amd64" ;;
                i*86)
                        archurl="i386" ;;
                x86)
                        archurl="i386" ;;
                *)
                        echo "unknown architecture"; exit 1 ;;
                esac
</code>```

答:
```<code>#!/system/bin/sh

case `arch` in
 aarch64)
    archurl="arm64" ;;
arm)
    archurl="armhf" ;;
amd64)
    archurl="amd64" ;;
x86_64)
    archurl="amd64" ;;
i*86)
    archurl="i386" ;;
x86)
    archurl="i386" ;;
*)
    echo "unknown architecture"; exit 1 ;;
esac
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get android architecture vith bash

Body:
How to get processor architecture without dpkg using android command line

with dpkg bash code

case `dpkg --print-architecture` in
                aarch64)
                        archurl="arm64" ;;
                arm)
                        archurl="armhf" ;;
                amd64)
                        archurl="amd64" ;;
                x86_64)
                        archurl="amd64" ;;
                i*86)
                        archurl="i386" ;;
                x86)
                        archurl="i386" ;;
                *)
                        echo "unknown architecture"; exit 1 ;;
                esac


问:
Detecting if an enemy was shot by bullet
I am trying to learn Godot by making a simple 2D shooter, but am running into a problem. I do not know how to detect if an enemy has been shot by a bullet. My bullets are Area2D nodes with a Sprite, and CollisionShape2D node attached. My enemies are KinematicBody2D nodes with a Sprite, and CollisionShape2D node attached. The enemy also has a timer attached, but that is not important.

Here is the enemy code:

```<code>extends KinematicBody2D

var speed = 200
var velocity = Vector2(-0.5, 1)
var bullet_preload = preload("res://Enemy/EnemyBullet.tscn")

func _ready():
    randomize()
    velocity.y = [1, -1][randi() % 2]

func _physics_process(delta):
    var collision = move_and_collide(velocity * speed * delta)
    if collision:
        velocity = velocity.bounce(collision.normal)
    if position.x < -20:
        print("Enemy Despawned")
        queue_free()
    if $ShootDelay.time_left == 0:
        var bullet = bullet_preload.instance()
        bullet.position.x = position.x - 18
        bullet.position.y = position.y + 6
        get_parent().add_child(bullet)
        $ShootDelay.start()
</code>```

Here is my player bullet code:

```<code>extends Area2D

var speed = 600
var velocity = Vector2(1, 0)

func _process(delta):
    position.x += speed * delta
    if position.x > 1044:
        queue_free()

func _on_PlayerBullet_body_entered(body):
    queue_free()
</code>```

It may be important to note that the player bullet and enemy scenes are not in the same scene tree, and there is no way (that I know of) of sending a signal between them. They are both being instanced to my main root node that contains the entire game via code.

If I need to include other details, please let me know.

答:
On your _on_PlayerBullet_body_entered you a body that has a reference to whatever the Area2D collided with, you can use it to communicate with it.

For example, you can call a method on it. Which could, of course could be queue_free:

```<code>func _on_PlayerBullet_body_entered(body):
    body.queue_free()
    queue_free()
</code>```

However, I'm going to suggest against it. Instead let us come up with a method that you can implement to have whatever behavior you want:

```<code>func _on_PlayerBullet_body_entered(body):
    body.shot()
    queue_free()
</code>```

Of course, we have the problem that we are not sure if it has that method… So, let us check for it:

```<code>func _on_PlayerBullet_body_entered(body):
    if body.has_method(shot):
        body.shot()

    queue_free()
</code>```

Then you would add that method on the objects that react to the bullet impact. Back to queue_free, it could be:

```<code>func shot() -> void:
    queue_free()
</code>```

Or you could have it be something like this:

```<code>var health := 5

func shot() -> void:
    health -= 1
    if health <= 0:
        queue_free()
</code>```

Or, you could have it set a flag and deal with it on _physics_process or where and whenever appropiate:

```<code>var was_shot := 5

func _physics_process(_delta) -> void:
    if was_shot:
        queue_free()

func shot() -> void:
    was_shot = true
</code>```

Of course, aside form queue_free you may want to instance some other scene (e.g. a corpse or an explosion) or play an animation or something like that.

Body:
I am trying to learn Godot by making a simple 2D shooter, but am running into a problem. I do not know how to detect if an enemy has been shot by a bullet. My bullets are Area2D nodes with a Sprite, and CollisionShape2D node attached. My enemies are KinematicBody2D nodes with a Sprite, and CollisionShape2D node attached. The enemy also has a timer attached, but that is not important.

Here is the enemy code:

extends KinematicBody2D

var speed = 200
var velocity = Vector2(-0.5, 1)
var bullet_preload = preload("res://Enemy/EnemyBullet.tscn")

func _ready():
    randomize()
    velocity.y = [1, -1][randi() % 2]

func _physics_process(delta):
    var collision = move_and_collide(velocity * speed * delta)
    if collision:
        velocity = velocity.bounce(collision.normal)
    if position.x < -20:
        print("Enemy Despawned")
        queue_free()
    if $ShootDelay.time_left == 0:
        var bullet = bullet_preload.instance()
        bullet.position.x = position.x - 18
        bullet.position.y = position.y + 6
        get_parent().add_child(bullet)
        $ShootDelay.start()

Here is my player bullet code:

extends Area2D

var speed = 600
var velocity = Vector2(1, 0)

func _process(delta):
    position.x += speed * delta
    if position.x > 1044:
        queue_free()

func _on_PlayerBullet_body_entered(body):
    queue_free()

It may be important to note that the player bullet and enemy scenes are not in the same scene tree, and there is no way (that I know of) of sending a signal between them. They are both being instanced to my main root node that contains the entire game via code.

If I need to include other details, please let me know.

Body:
On your _on_PlayerBullet_body_entered you a body that has a reference to whatever the Area2D collided with, you can use it to communicate with it.

For example, you can call a method on it. Which could, of course could be queue_free:

func _on_PlayerBullet_body_entered(body):
    body.queue_free()
    queue_free()

However, I'm going to suggest against it. Instead let us come up with a method that you can implement to have whatever behavior you want:

func _on_PlayerBullet_body_entered(body):
    body.shot()
    queue_free()

Of course, we have the problem that we are not sure if it has that method… So, let us check for it:

func _on_PlayerBullet_body_entered(body):
    if body.has_method(shot):
        body.shot()

    queue_free()

Then you would add that method on the objects that react to the bullet impact. Back to queue_free, it could be:

func shot() -> void:
    queue_free()

Or you could have it be something like this:

var health := 5

func shot() -> void:
    health -= 1
    if health <= 0:
        queue_free()

Or, you could have it set a flag and deal with it on _physics_process or where and whenever appropiate:

var was_shot := 5

func _physics_process(_delta) -> void:
    if was_shot:
        queue_free()

func shot() -> void:
    was_shot = true

Of course, aside form queue_free you may want to instance some other scene (e.g. a corpse or an explosion) or play an animation or something like that.


问:
Best way to parse non-uniform JSON in python (Nested/Non Nested)
I'm querying an API and would like to store the results of that API, the JSON response looks something like this:

```<code>{
    "name": "John Smith",
    "id": 123456,
    "geo": {
        "region": {
            "city": false
        },
        "country": "United States",
        "ethnicity": "White",
      }
}
</code>```

The dictionary I'm trying to parse it into looks like this:

```<code>dictP = {
        "name": "",
        "id": 0,
        "geo.region.city": "",
        "geo.country": "",
        "geo.ethnicity": ""
}
</code>```

There's a lot more data, about 120 data points being returned, lots of nested/non nested; so I'm excluding a big chunk of data thats useless to me. Only extracting what i need. The issue is sometimes the data is missing, IE:

```<code>{
    "name": "John Smith",
    "id": 123456,
    "geo": {
        "region": null,
        "country": "United States",
        "ethnicity": "White",
      }
}
</code>```

and:

```<code>{
    "name": "John Smith",
    "id": 123456,
    "geo": null
}
</code>```

or:

```<code>{
    "name": "John Smith",
    "id": null,
    "geo": null
}
</code>```

What's the best way to parse this? I have about 75 data points i want to parse, writing if/else statements or try/except statements 75 times does not make sense. The data needs to all be uniform because I'm saving to CSV, so ultimately I'd like to fill "None" for missing data, i can't seem to find a library that does this. Advice appreciated.

答:
How about FlatDict?.

import json
from flatdict import FlatDict

response_as_json = json.loads(response_as_text)  # convert into python dictionary
result = dict(FlatDict(response_as_json, delimiter='.'))
```
<p>Above output a python dictionary looks like this:</p>
<pre class="lang-py prettyprint-override"><code>{'geo.country': 'United States',
 'geo.ethnicity': 'White',
 'geo.region': None,
 'id': 123456,
 'name': 'John Smith'}
</code>```

EDIT:

I forgot the part about CSV.
Once you have flat dictionaries, you can just put them into pandas.

>>> d1
{'name': 'John Smith', 'id': 123456, 'geo.region.city': False, 'geo.country': 'United States', 'geo.ethnicity': 'White'}
>>> d2
{'name': 'John Smith', 'id': 123456, 'geo.region': None, 'geo.country': 'United States', 'geo.ethnicity': 'White'}

>>> import pandas as pd
>>> list_of_dict = [d1, d2]  # Put as many as you want in this list.
>>> table = pd.DataFrame(list_of_dict)
>>> table
         name      id geo.region.city    geo.country geo.ethnicity  geo.region
0  John Smith  123456           False  United States         White         NaN
1  John Smith  123456             NaN  United States         White         NaN

>>> table.to_csv(path_to_csv)
```

Body:
I'm querying an API and would like to store the results of that API, the JSON response looks something like this:

{
    "name": "John Smith",
    "id": 123456,
    "geo": {
        "region": {
            "city": false
        },
        "country": "United States",
        "ethnicity": "White",
      }
}

The dictionary I'm trying to parse it into looks like this:

dictP = {
        "name": "",
        "id": 0,
        "geo.region.city": "",
        "geo.country": "",
        "geo.ethnicity": ""
}

There's a lot more data, about 120 data points being returned, lots of nested/non nested; so I'm excluding a big chunk of data thats useless to me. Only extracting what i need. The issue is sometimes the data is missing, IE:

{
    "name": "John Smith",
    "id": 123456,
    "geo": {
        "region": null,
        "country": "United States",
        "ethnicity": "White",
      }
}

and:

{
    "name": "John Smith",
    "id": 123456,
    "geo": null
}

or:

{
    "name": "John Smith",
    "id": null,
    "geo": null
}

What's the best way to parse this? I have about 75 data points i want to parse, writing if/else statements or try/except statements 75 times does not make sense. The data needs to all be uniform because I'm saving to CSV, so ultimately I'd like to fill "None" for missing data, i can't seem to find a library that does this. Advice appreciated.

Body:
How about FlatDict?.

import json
from flatdict import FlatDict

response_as_json = json.loads(response_as_text)  # convert into python dictionary
result = dict(FlatDict(response_as_json, delimiter='.'))

Above output a python dictionary looks like this:

{'geo.country': 'United States',
 'geo.ethnicity': 'White',
 'geo.region': None,
 'id': 123456,
 'name': 'John Smith'}

EDIT:

I forgot the part about CSV.
Once you have flat dictionaries, you can just put them into pandas.

>>> d1
{'name': 'John Smith', 'id': 123456, 'geo.region.city': False, 'geo.country': 'United States', 'geo.ethnicity': 'White'}
>>> d2
{'name': 'John Smith', 'id': 123456, 'geo.region': None, 'geo.country': 'United States', 'geo.ethnicity': 'White'}

>>> import pandas as pd
>>> list_of_dict = [d1, d2]  # Put as many as you want in this list.
>>> table = pd.DataFrame(list_of_dict)
>>> table
         name      id geo.region.city    geo.country geo.ethnicity  geo.region
0  John Smith  123456           False  United States         White         NaN
1  John Smith  123456             NaN  United States         White         NaN

>>> table.to_csv(path_to_csv)


问:
Wrapping h5 in Link tag made h5 dissappear
I am trying to make a component go to localhost:3000/second. The header for the component(AddNote) displays when I dont wrap it in a Link tag, but when I do, the whole page becomes blank, including the "My Notes" which is supposed to be displayed by default.</p>
```<code>import React, {useState} from 'react';
import './App.css';
import {BrowserRouter as Router, Routes, Route, Switch} from 'react-router-dom';
import AddNote from './components/noteDisplay/addNote/newNote.js'
import FirstPage from './components/noteDisplay/firstPage.js'
import NoteDisplay from './components/noteDisplay/noteDisplay.js'
import secondPage from './components/secondPage/secondContainer.js'
const App = () => {

  return (

        <div className="App">

          <h1 className="app-title">My notes</h1>

          <Router>
            <div>
              <Routes>

                <Route path='/second' element={<secondPage />}/>
                {/*<Route path='/' element={<NoteDisplay/>}/>*/}

              </Routes>

            </div>

          </Router>
          <AddNote/>

        </div>

  );
}
</code>```
```<code>import React from 'react';
import { Route, BrowserRouter as Router, Link, Switch } from 'react-router-dom';
import NoteDisplay from '../noteDisplay';
import { v4 as uuidv4 } from 'uuid';

const AddNote = () => {
    console.log('hi')
    return (
        <div>
            <Link to="/second">
                <h5 className="add-note">New note</h5>
            </Link>
        </div>

    )

}
export default AddNote;
</code>```

答:
You need to change your <Link /> code to be something like below.

const AddNote = () => {
  return (

        <Link href="/second">New Note</Link>

  );
};
```

See the official Next.js documentation for how to use it - it explains it in greater detail!

Body:
I am trying to make a component go to localhost:3000/second. The header for the component(AddNote) displays when I dont wrap it in a Link tag, but when I do, the whole page becomes blank, including the "My Notes" which is supposed to be displayed by default.

import React, {useState} from 'react';
import './App.css';
import {BrowserRouter as Router, Routes, Route, Switch} from 'react-router-dom';
import AddNote from './components/noteDisplay/addNote/newNote.js'
import FirstPage from './components/noteDisplay/firstPage.js'
import NoteDisplay from './components/noteDisplay/noteDisplay.js'
import secondPage from './components/secondPage/secondContainer.js'
const App = () => {

  return (

My notes

          <Router>

              <Routes>

                <Route path='/second' element={<secondPage />}/>
                {/*<Route path='/' element={<NoteDisplay/>}/>*/}

              </Routes>

          </Router>
          <AddNote/>

  );
}

import React from 'react';
import { Route, BrowserRouter as Router, Link, Switch } from 'react-router-dom';
import NoteDisplay from '../noteDisplay';
import { v4 as uuidv4 } from 'uuid';

const AddNote = () => {
    console.log('hi')
    return (

            <Link to="/second">

New note

            </Link>

    )

}
export default AddNote;

Body:
You need to change your <Link /> code to be something like below.

const AddNote = () => {
  return (
    <div>
      <h5>
        <Link href="/second">New Note</Link>
      </h5>
    </div>
  );
};

See the official Next.js documentation for how to use it - it explains it in greater detail!


问:
How can i do Navigator.push in a modal bottom sheet only (not the parent page)
In my app, i am trying to create a comments section. In this section, i want a user to be able to reply to another user's comment in a fashion akin to the YouTube app. I have managed to create a modal bottom sheet showing the top level comments and it is working quite well, withthe aid of several stream builders. However, the problem im facing is the second level comments (replies to people's comments.). I want to make it so that  user taps on a comment and is taken to a page (still in the modal bottom sheet) where he sees all replies to the comment and can also comment on his own, and if he presses back, he goes right back to where he was and can continue scrolling through the top level comments.

Akin to how the YouTube app looks.
I had the idea of using Navigator.push inside the bottom sheet, to overlay a new page on top of the currently existing page in the modal bottom sheet and in this new page, the second level comments (replies) for a particular comment are to be displayed. But, when i call Navigator.push, the entire page changes. The whole parent page shifts to the new page, instead of just the stuff in the bottom sheet. So, that's my problem. I'm open to ideas.

the code behind my comment bottom sheet:

```<code>  showModalBottomSheet(
  context: context,
  builder: (context) {
    return
    Container(
      child: StatefulBuilder(
        builder: (BuildContext context, setTheModalState) {
          setModalState = setTheModalState;
          return Container(
            child: Column(
              children: <Widget>[
                Expanded(
                  child: StreamBuilder(listview))])}))}
</code>```

This is what i have designed so far. The tricky bit now is making a new page in the modal sheet on press of the reply button (the message icon)

This is what a YouTube comment system looks like.

The code for the comment section:

```<code>showModalBottomSheet(
  context: context,
  builder: (context) {
    return
    Container(
      child: StatefulBuilder(
        builder: (BuildContext context, setTheModalState) {
          setModalState = setTheModalState;
          return Container(
            child: Column(
              children: <Widget>[
                Expanded(
                  child: StreamBuilder(
                    stream: Firestore.instance
                        .collection("Replies")
                        .document(dream.documentID)
                        .collection(dream.documentID)
                        .orderBy('time', descending: true)
                        .snapshots(),
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) {
                        return Center(
                          child: SpinKitDoubleBounce(
                            color: Colors.blue,
                          ),
                        );
                      } else {
                        dynamic replies = snapshot.data.documents;

                        return ListView.builder(
                          itemCount: replies.length,
                          reverse: true,
                          itemBuilder: (context, index) {
                            if (replies[index]["text"] != "" &&
                                replies[index]["images"] == null) {
                              return _buildStringCommment(
                                  replies[index], true);
                            } else {
                              if (replies[index]["images"].length == 1) {
                                return _buildCommentFromOneImage(
                                    replies[index], true);
                              } else {
                                if (replies[index]["images"].length == 2) {
                                  return _buildCommentFromTwoImages(
                                      replies[index], true);
                                } else {
                                  if (replies[index]["images"].length ==
                                      3) {
                                    return _buildCommentFromThreeImages(
                                        replies[index], true);
                                  } else {
                                    if (replies[index]["images"].length ==
                                        4) {
                                      return _buildCommentFromFourImages(
                                          replies[index], true);
                                    } else {
                                      if (replies[index]["images"].length ==
                                          5) {
                                        return _buildCommmentFromFiveImages(
                                            replies[index], true);
                                      } else {
                                        return _buildMessageFromMoreThanFiveImages(
                                            replies[index], true);
                                      }
                                    }
                                  }
                                }
                              }
                            }
                          },
                        );
                      }
                    },
                  ),
                ),
                theTypeReplyThingie(dream, context, true)
              ],
            ),
          );
        },
      ),
    );
  },
);
</code>```

"the type reply thingie" is the widget that has the text input form and the send button.

答:
Just show another ModalBottomSheet inside the main one
Here's an example,</p>
```<code>ElevatedButton(
          onPressed: () {
            showModalBottomSheet(
                context: context,
                builder: (context) {
                  return ElevatedButton(
                      onPressed: () {
                        showModalBottomSheet(
                            context: context,
                            builder: (context) {
                              return Container(
                                child: Center(
                                  child: ElevatedButton(
                                    child: Text('back'),
                                    onPressed: () =>
                                        Navigator.pop(context),
                                  ),
                                ),
                              );
                            });
                      },
                      child: Text('Next Bottom'));
                });
          },
          child: Text('press Me'),
        )
</code>```

Body:
In my app, i am trying to create a comments section. In this section, i want a user to be able to reply to another user's comment in a fashion akin to the YouTube app. I have managed to create a modal bottom sheet showing the top level comments and it is working quite well, withthe aid of several stream builders. However, the problem im facing is the second level comments (replies to people's comments.). I want to make it so that  user taps on a comment and is taken to a page (still in the modal bottom sheet) where he sees all replies to the comment and can also comment on his own, and if he presses back, he goes right back to where he was and can continue scrolling through the top level comments.

Akin to how the YouTube app looks.
I had the idea of using Navigator.push inside the bottom sheet, to overlay a new page on top of the currently existing page in the modal bottom sheet and in this new page, the second level comments (replies) for a particular comment are to be displayed. But, when i call Navigator.push, the entire page changes. The whole parent page shifts to the new page, instead of just the stuff in the bottom sheet. So, that's my problem. I'm open to ideas.

the code behind my comment bottom sheet:

  showModalBottomSheet(
  context: context,
  builder: (context) {
    return
    Container(
      child: StatefulBuilder(
        builder: (BuildContext context, setTheModalState) {
          setModalState = setTheModalState;
          return Container(
            child: Column(
              children: <Widget>[
                Expanded(
                  child: StreamBuilder(listview))])}))}

This is what i have designed so far. The tricky bit now is making a new page in the modal sheet on press of the reply button (the message icon)

This is what a YouTube comment system looks like.

The code for the comment section:

showModalBottomSheet(
  context: context,
  builder: (context) {
    return
    Container(
      child: StatefulBuilder(
        builder: (BuildContext context, setTheModalState) {
          setModalState = setTheModalState;
          return Container(
            child: Column(
              children: <Widget>[
                Expanded(
                  child: StreamBuilder(
                    stream: Firestore.instance
                        .collection("Replies")
                        .document(dream.documentID)
                        .collection(dream.documentID)
                        .orderBy('time', descending: true)
                        .snapshots(),
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) {
                        return Center(
                          child: SpinKitDoubleBounce(
                            color: Colors.blue,
                          ),
                        );
                      } else {
                        dynamic replies = snapshot.data.documents;

                        return ListView.builder(
                          itemCount: replies.length,
                          reverse: true,
                          itemBuilder: (context, index) {
                            if (replies[index]["text"] != "" &&
                                replies[index]["images"] == null) {
                              return _buildStringCommment(
                                  replies[index], true);
                            } else {
                              if (replies[index]["images"].length == 1) {
                                return _buildCommentFromOneImage(
                                    replies[index], true);
                              } else {
                                if (replies[index]["images"].length == 2) {
                                  return _buildCommentFromTwoImages(
                                      replies[index], true);
                                } else {
                                  if (replies[index]["images"].length ==
                                      3) {
                                    return _buildCommentFromThreeImages(
                                        replies[index], true);
                                  } else {
                                    if (replies[index]["images"].length ==
                                        4) {
                                      return _buildCommentFromFourImages(
                                          replies[index], true);
                                    } else {
                                      if (replies[index]["images"].length ==
                                          5) {
                                        return _buildCommmentFromFiveImages(
                                            replies[index], true);
                                      } else {
                                        return _buildMessageFromMoreThanFiveImages(
                                            replies[index], true);
                                      }
                                    }
                                  }
                                }
                              }
                            }
                          },
                        );
                      }
                    },
                  ),
                ),
                theTypeReplyThingie(dream, context, true)
              ],
            ),
          );
        },
      ),
    );
  },
);

"the type reply thingie" is the widget that has the text input form and the send button.

Body:
Just show another ModalBottomSheet inside the main one
Here's an example,

ElevatedButton(
          onPressed: () {
            showModalBottomSheet(
                context: context,
                builder: (context) {
                  return ElevatedButton(
                      onPressed: () {
                        showModalBottomSheet(
                            context: context,
                            builder: (context) {
                              return Container(
                                child: Center(
                                  child: ElevatedButton(
                                    child: Text('back'),
                                    onPressed: () =>
                                        Navigator.pop(context),
                                  ),
                                ),
                              );
                            });
                      },
                      child: Text('Next Bottom'));
                });
          },
          child: Text('press Me'),
        )


问:
SwiftUI: Binding on property of struct derived from environment object
I have two structs in my task manager app:

struct Task {
    var identifier: String
    var title: String
    var tags: [String] // Array of tag identifiers
}
struct Tag {
    var identifier: String
    var title: String
}
```
<p>I then have a class to store them:</p>
<pre class="lang-swift prettyprint-override"><code>class TaskStore: ObservableObject {
    @Published var tasks = [String:Task]()
    @Published var tags = [String:Tag]()
}
</code>```

which I pass to my root view as an .environmentObject(taskStore).

Correct me if any of the following is wrong (against bad practices):

In my TaskView I have:

    @EnvironmentObject var taskStore: TaskStore

    var taskIdentifier: String // Passed from parent view

    private var task: Task {
        get {
            return taskStore.tasks[taskIdentifier]! // Looks up the task in the store
        }
    }
    private var tags: [Tag] {
        get {
            return taskStore.tags
        }
    }
```

The issue is, when learning SwiftUI I was told when making certain components (like a picker that let's you alter the tags array in this case) that it should accept a binding to the value/collection, or say I want to make the task title editable, I need a binding to the task.title property, both of which I can't do because (based on the way I'm defining and computing task) I can't get a binding on task.

Am I doing something against best practices here? Or where along this path did I diverge from the right way of storing points of truth in an environment object, and make them editable in sub views.

答:
No, you're not necessarily doing something against best practices. I think in SwiftUI, the concepts of data model storage and manipulation quickly become more complex than, for example, what Apple tends to show in its demo code. With a real app, with a single source of truth, like you seem to be using, you're going to have to come up with some ways to bind the data to your views.

One solution is to write Bindings with your own get and set properties that interact with your ObservableObject. That might look like this, for example:

```<code>struct TaskView : View {
    var taskIdentifier: String // Passed from parent view

    @EnvironmentObject private var taskStore: TaskStore

    private var taskBinding : Binding<Task> {
        Binding {
            taskStore.tasks[taskIdentifier] ?? .init(identifier: "", title: "", tags: [])
        } set: {
            taskStore.tasks[taskIdentifier] = $0
        }
    }

    var body: some View {
        TextField("Task title", text: taskBinding.title)
    }
}
</code>```

If you're averse to this sort of thing, one way to avoid it is to use CoreData. Because the models are made into ObservableObjects by the system, you can generally avoid this sort of thing and directly pass around and manipulate your models. However, that doesn't necessarily mean that it is the right (or better) choice either.

You may also want to explore TCA which is an increasingly popular state management and view binding library that provides quite a few built-in solutions for the type of thing you're looking at doing.

Body:
I have two structs in my task manager app:

struct Task {
    var identifier: String
    var title: String
    var tags: [String] // Array of tag identifiers
}
struct Tag {
    var identifier: String
    var title: String
}

I then have a class to store them:

class TaskStore: ObservableObject {
    @Published var tasks = [String:Task]()
    @Published var tags = [String:Tag]()
}

which I pass to my root view as an .environmentObject(taskStore).

Correct me if any of the following is wrong (against bad practices):

In my TaskView I have:

    @EnvironmentObject var taskStore: TaskStore

    var taskIdentifier: String // Passed from parent view

    private var task: Task {
        get {
            return taskStore.tasks[taskIdentifier]! // Looks up the task in the store
        }
    }
    private var tags: [Tag] {
        get {
            return taskStore.tags
        }
    }

The issue is, when learning SwiftUI I was told when making certain components (like a picker that let's you alter the tags array in this case) that it should accept a binding to the value/collection, or say I want to make the task title editable, I need a binding to the task.title property, both of which I can't do because (based on the way I'm defining and computing task) I can't get a binding on task.

Am I doing something against best practices here? Or where along this path did I diverge from the right way of storing points of truth in an environment object, and make them editable in sub views.

Body:
No, you're not necessarily doing something against best practices. I think in SwiftUI, the concepts of data model storage and manipulation quickly become more complex than, for example, what Apple tends to show in its demo code. With a real app, with a single source of truth, like you seem to be using, you're going to have to come up with some ways to bind the data to your views.

One solution is to write Bindings with your own get and set properties that interact with your ObservableObject. That might look like this, for example:

struct TaskView : View {
    var taskIdentifier: String // Passed from parent view

    @EnvironmentObject private var taskStore: TaskStore

    private var taskBinding : Binding<Task> {
        Binding {
            taskStore.tasks[taskIdentifier] ?? .init(identifier: "", title: "", tags: [])
        } set: {
            taskStore.tasks[taskIdentifier] = $0
        }
    }

    var body: some View {
        TextField("Task title", text: taskBinding.title)
    }
}

If you're averse to this sort of thing, one way to avoid it is to use CoreData. Because the models are made into ObservableObjects by the system, you can generally avoid this sort of thing and directly pass around and manipulate your models. However, that doesn't necessarily mean that it is the right (or better) choice either.

You may also want to explore TCA which is an increasingly popular state management and view binding library that provides quite a few built-in solutions for the type of thing you're looking at doing.


问:
Unable to Dockerize Vite React-Typescript Project
I am trying to dockerize a Vite React-Typescript boilerplate setup, but I unable to connect to the container.

Installed vite-react-typescript boilerplate:

npm init vite@latest vite-docker-demo -- --template react-ts

Dockerfile

```<code># Declare the base image
FROM node:lts-alpine3.14
# Build step
# 1. copy package.json and package-lock.json to /app dir
RUN mkdir /app
COPY package*.json /app
# 2. Change working directory to newly created app dir
WORKDIR /app
# 3 . Install dependencies
RUN npm ci
# 4. Copy the source code to /app dir
COPY . .
# 5. Expose port 3000 on the container
EXPOSE 3000
# 6. Run the app
CMD ["npm", "run", "dev"]
</code>```

Command to run docker container in detached mode and open local dev port 3000 on host:
docker run -d -p 3000:3000 vite

The vite instance seems to be running just fine within the container (docker logs output):

```<code>> vite-docker@0.0.0 dev /app
> vite

Pre-bundling dependencies:
  react
  react-dom
(this will be run only when your dependencies or config have changed)

  vite v2.4.4 dev server running at:

  > Local: http://localhost:3000/
  > Network: use `--host` to expose

  ready in 244ms.
</code>```

However, when I navigate to http://localhost:3000/ within Chrome. I see an error indicating The connection was reset.

Any help resolving this issue would be greatly appreciated!

答:
in package.json use script

```<code>"dev": "vite --host"
</code>```

example:

```<code>  "scripts": {
    "dev": "vite --host",
    "build": "tsc && vite build",
    "serve": "vite preview"
  },
</code>```

or run with vite --host

Body:
I am trying to dockerize a Vite React-Typescript boilerplate setup, but I unable to connect to the container.

Installed vite-react-typescript boilerplate:

npm init vite@latest vite-docker-demo -- --template react-ts

Dockerfile

# Declare the base image
FROM node:lts-alpine3.14
# Build step
# 1. copy package.json and package-lock.json to /app dir
RUN mkdir /app
COPY package*.json /app
# 2. Change working directory to newly created app dir
WORKDIR /app
# 3 . Install dependencies
RUN npm ci
# 4. Copy the source code to /app dir
COPY . .
# 5. Expose port 3000 on the container
EXPOSE 3000
# 6. Run the app
CMD ["npm", "run", "dev"]

Command to run docker container in detached mode and open local dev port 3000 on host:
docker run -d -p 3000:3000 vite

The vite instance seems to be running just fine within the container (docker logs output):

> vite-docker@0.0.0 dev /app
> vite

Pre-bundling dependencies:
  react
  react-dom
(this will be run only when your dependencies or config have changed)

  vite v2.4.4 dev server running at:

  > Local: http://localhost:3000/
  > Network: use `--host` to expose

  ready in 244ms.

However, when I navigate to http://localhost:3000/ within Chrome. I see an error indicating The connection was reset.

Any help resolving this issue would be greatly appreciated!

Body:
in package.json use script

"dev": "vite --host"

example:

  "scripts": {
    "dev": "vite --host",
    "build": "tsc && vite build",
    "serve": "vite preview"
  },

or run with vite --host


问:
python regex to select everything before and after a particular string
I am trying to apply regex on one of the columns in pandas dataframe, this column has text data in it, I am trying to extract a specific block. This is a sample of how my data will look like,

```<code>Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

INDICATION:
Fall some time ago with ataxia since. Recent admission with
tachybrady syndrome.
</code>```

I am trying to extract text from the beginning of the given string up to the first blank line following the first line containing 'Patient Referred from'., the entities may or may not appear in same order except the "Patient Referred from" which will always be the first entity, but there wont be any empty line until that entire block is finished. I have tried this below one,

```<code>import re
def extract_patient_details(s):

    match = re.search('(?s)Patient Referred(.*?)(?:(?:\r*\n){2})', s)
    return match.group(0)

extract_patient_details(s)
</code>```

The above snippet works fine and gives me this output:

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head
```
<p>But what I want is:</p>
<pre class="lang-none prettyprint-override"><code>Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head
</code>```

答:
re.DOTALL plays an important role in your case.

def extract_patient_details(s):
    match = re.search(r'^(.*Patient Referred.*?)(?:\r?\n){2}', s, re.DOTALL)
    return match.group(1)
```
<p>In <code>pandas</code>, you can use <code>extract</code> method as well.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import re

# Create a sample dataframe
df = pd.DataFrame([
    {'diagnosis': '''Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

INDICATION:
Fall some time ago with ataxia since. Recent admission with
tachybrady syndrome.'''}
])

pat = re.compile(r'^(.*Patient Referred.*?)(?:\r?\n){2}', re.DOTALL)
df_extracted = df.diagnosis.str.extract(pat, expand=True)
</code>```

Answer to the OP's comment:

In order to extract the latter part additionally, you can write code like this:

Using your original function:

def extract_patient_details(s):
    match = re.search(r'^(.*Patient Referred.*?)(?:\r?\n){2}(.*)$', s, re.DOTALL)
    return match.groups()
```
<h4>Using pandas:</h4>
<pre class="lang-py prettyprint-override"><code>pat = re.compile(r'^(.*Patient Referred.*?)(?:\r?\n){2}(.*)$', re.DOTALL)
df_extracted = df.diagnosis.str.extract(pat, expand=True)
</code>```

Body:
I am trying to apply regex on one of the columns in pandas dataframe, this column has text data in it, I am trying to extract a specific block. This is a sample of how my data will look like,

Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

INDICATION:
Fall some time ago with ataxia since. Recent admission with
tachybrady syndrome.

I am trying to extract text from the beginning of the given string up to the first blank line following the first line containing 'Patient Referred from'., the entities may or may not appear in same order except the "Patient Referred from" which will always be the first entity, but there wont be any empty line until that entire block is finished. I have tried this below one,

import re
def extract_patient_details(s):

    match = re.search('(?s)Patient Referred(.*?)(?:(?:\r*\n){2})', s)
    return match.group(0)

extract_patient_details(s)

The above snippet works fine and gives me this output:

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

But what I want is:

Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

Body:
re.DOTALL plays an important role in your case.

def extract_patient_details(s):
    match = re.search(r'^(.*Patient Referred.*?)(?:\r?\n){2}', s, re.DOTALL)
    return match.group(1)

In pandas, you can use extract method as well.

import pandas as pd
import re

# Create a sample dataframe
df = pd.DataFrame([
    {'diagnosis': '''Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

INDICATION:
Fall some time ago with ataxia since. Recent admission with
tachybrady syndrome.'''}
])

pat = re.compile(r'^(.*Patient Referred.*?)(?:\r?\n){2}', re.DOTALL)
df_extracted = df.diagnosis.str.extract(pat, expand=True)

Answer to the OP's comment:

In order to extract the latter part additionally, you can write code like this:

Using your original function:

def extract_patient_details(s):
    match = re.search(r'^(.*Patient Referred.*?)(?:\r?\n){2}(.*)$', s, re.DOTALL)
    return match.groups()

Using pandas:

pat = re.compile(r'^(.*Patient Referred.*?)(?:\r?\n){2}(.*)$', re.DOTALL)
df_extracted = df.diagnosis.str.extract(pat, expand=True)


问:
Unable to automatically map azure storage share using terraform and Azure VM extensions on Windows VM
Problem statement
I am trying to automatically map an Azure file share to Windows VMs using Azure VM extension. The VM extension installs successfully, the command runs but on logging into the VM I see that my drive is disconnected.

On trying to access it, I get an incorrect username or password error. However, running the PowerShell script on the machine correctly maps the network drive and I can access it.

Code

```<code>resource "azurerm_virtual_machine_extension" "test" {
  # Custom VM extension documentation https://learn.microsoft.com/en-us/azure/virtual-machines/extensions/custom-script-windows
  # additional documentation http://teknews.cloud/bootstrapping-azure-vms-with-terraform/, https://github.com/terraform-providers/terraform-provider-azurerm/issues/728
  name = "network_share"
  location = "${azurerm_resource_group.main.location}"
  resource_group_name = "${azurerm_resource_group.main.name}"
  #virtual_machine_name = "${azurerm_virtual_machine.vm.name}"
  virtual_machine_name = "${element(azurerm_virtual_machine.vm.*.name, count.index)}"
  publisher = "Microsoft.Compute"
  type = "CustomScriptExtension"
  type_handler_version = "1.9"
  count = "${var.vm_count}"

  settings = <<SETTINGS
  {
      "commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(data.template_file.net_fileshare_script.rendered)}')) | Out-File -filepath net_fileshare_script.ps1\" && powershell -File net_fileshare_script.ps1"
  }
  SETTINGS

  depends_on = ["azurerm_virtual_machine.vm"]
}

data "template_file" "net_fileshare_script" {
  template = "${file("./scripts/net_fileshare_script.ps1")}"
}
</code>```

答:
I tried the solutions above, but without success.

1 - I did it another way, I kept the powershell that makes the connection in storage

2 - I created a powershell script to create a windows task scheduler pointing to item 1

3 - In Terraform I created a line to execute the taskScheduller created in item

Body:
Problem statement
I am trying to automatically map an Azure file share to Windows VMs using Azure VM extension. The VM extension installs successfully, the command runs but on logging into the VM I see that my drive is disconnected.

On trying to access it, I get an incorrect username or password error. However, running the PowerShell script on the machine correctly maps the network drive and I can access it.

Code

resource "azurerm_virtual_machine_extension" "test" {
  # Custom VM extension documentation https://learn.microsoft.com/en-us/azure/virtual-machines/extensions/custom-script-windows
  # additional documentation http://teknews.cloud/bootstrapping-azure-vms-with-terraform/, https://github.com/terraform-providers/terraform-provider-azurerm/issues/728
  name = "network_share"
  location = "${azurerm_resource_group.main.location}"
  resource_group_name = "${azurerm_resource_group.main.name}"
  #virtual_machine_name = "${azurerm_virtual_machine.vm.name}"
  virtual_machine_name = "${element(azurerm_virtual_machine.vm.*.name, count.index)}"
  publisher = "Microsoft.Compute"
  type = "CustomScriptExtension"
  type_handler_version = "1.9"
  count = "${var.vm_count}"

  settings = <<SETTINGS
  {
      "commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(data.template_file.net_fileshare_script.rendered)}')) | Out-File -filepath net_fileshare_script.ps1\" && powershell -File net_fileshare_script.ps1"
  }
  SETTINGS

  depends_on = ["azurerm_virtual_machine.vm"]
}

data "template_file" "net_fileshare_script" {
  template = "${file("./scripts/net_fileshare_script.ps1")}"
}


问:
Typescript issue: Type '...' is not assignable to type '...'
I'm using nestJS,
I have 2 services,
in the 1st service:

```<code>async getOrganizations (attributes: (keyof Organization)[]): Promise<Partial<Organization>[]> {

    const organizations = await this.organizationRepository.find({select: attributes})

    return organizations;
    //returns [{id:1, name: "x"},{id:2, name: "y"},..]

  }
</code>```

in the 2nd service:

```<code>async getOrganizations(): Promise<CustomerResponseDto[]> {
        const attributes : (keyof Organization)[] = ['id', 'name'];

        let organizations = await this.1stService.getOrganizations(attributes);

        organizations = organizations.map((organization)=>{
            return {
                ...organization,
                type: 'Organization'
            }
        })

        return organizations;
    //returns [{id:1, name: "x", type: 'Organization'},{id:2, name: "y", type: 'Organization'},..]
    }
</code>```

and the CustomerResponseDto:

```<code>export interface CustomerResponseDto {
    readonly id: number;
    readonly name: string;
    readonly type: string;
}
</code>```

now I'm getting the following error:

```<code>Type 'Partial<Organization>[]' is not assignable to type 'CustomerResponseDto[]'.
  Property 'type' is missing in type 'Partial<Organization>' but required in type 'CustomerResponseDto'.
    22 |         })
    23 |
  > 24 |         return organizations;
       |         ^^^^^^^^^^^^^^^^^^^^^
    25 |     }

</code>```

please advise

答:
It works now, the issue was related to variable naming
in 2nd service
I changed:

```<code>organizations = organizations.map((organization)=>{
            return {
                ...organization,
                type: 'Organization'
            }
</code>```

to be

```<code>const organizationsWithType = organizations.map(({ id, name })=>{
            return {
                id,
                name,
                type: 'Organization'
            }
        })
</code>```

Body:
I'm using nestJS,
I have 2 services,
in the 1st service:

async getOrganizations (attributes: (keyof Organization)[]): Promise<Partial<Organization>[]> {

    const organizations = await this.organizationRepository.find({select: attributes})

    return organizations;
    //returns [{id:1, name: "x"},{id:2, name: "y"},..]

  }

in the 2nd service:

async getOrganizations(): Promise<CustomerResponseDto[]> {
        const attributes : (keyof Organization)[] = ['id', 'name'];

        let organizations = await this.1stService.getOrganizations(attributes);

        organizations = organizations.map((organization)=>{
            return {
                ...organization,
                type: 'Organization'
            }
        })

        return organizations;
    //returns [{id:1, name: "x", type: 'Organization'},{id:2, name: "y", type: 'Organization'},..]
    }

and the CustomerResponseDto:

export interface CustomerResponseDto {
    readonly id: number;
    readonly name: string;
    readonly type: string;
}

now I'm getting the following error:

Type 'Partial<Organization>[]' is not assignable to type 'CustomerResponseDto[]'.
  Property 'type' is missing in type 'Partial<Organization>' but required in type 'CustomerResponseDto'.
    22 |         })
    23 |
  > 24 |         return organizations;
       |         ^^^^^^^^^^^^^^^^^^^^^
    25 |     }

please advise

Body:
It works now, the issue was related to variable naming
in 2nd service
I changed:

organizations = organizations.map((organization)=>{
            return {
                ...organization,
                type: 'Organization'
            }

to be

const organizationsWithType = organizations.map(({ id, name })=>{
            return {
                id,
                name,
                type: 'Organization'
            }
        })


问:
How to segregate by one factor but colour by another in ggplot2 R?
In my dataset, I have segregated the data by a parameter par for either Black or Red noise that are staggered in represtation. Now, for both species, I want to colour the "Black" noise as black, and "Red" as red. Furthermore, I want to join the points by par -- specifically, I want to join par -- No with a Dashed line, and Yes as a solid line. I tried the piece of code attached (and multiple versions of it)..but no luck. Any suggestions?

```<code>#Data

set.seed(100)
sp <- factor(c("A","A","A","A","B","B","B","B"))
par <- factor(c("No","No","Yes","Yes","No","No","Yes","Yes"))
y <- rnorm(8, 2,3)
noise <- factor(c("Black","Red","Black","Red","Black","Red","Black","Red"))

df <- data.frame(sp, par, y, noise)
df$noise <- factor(df$noise, levels = c("Black","Red"))
</code>```

```<code>  library(ggplot2)
    ggplot(data = df, aes(x = noise, y = y, fill = par, color = par)) +
      geom_point(size = 4) +
      facet_wrap(.~sp) +
      theme_classic() +
      scale_fill_manual(values = c("black","red")) +   scale_color_manual(values = c("black","red")) +
      geom_line(aes(linetype=par)) + scale_linetype_manual(name = "indicator", values = c(2,1,2))
      geom_path(aes(group = par,linetype=par), geom = "path")

</code>```

ERROR: geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

答:
In your code, you forget to add a + to link geom_path() with the ggplot(). Since the aes() of geom_point() and geom_path() doesn't match, you'll need to include them in the corresponding geom_*().

```<code>library(tidyverse)

ggplot(data = df, aes(x = noise, y = y, group = par, linetype = par)) +
  geom_point(aes(fill = noise, color = noise, ), size = 4) +
  facet_wrap(.~sp) +
  theme_classic() +
  scale_fill_manual(values = c("black","red")) +
  scale_color_manual(values = c("black","red")) +
  geom_line() +
  scale_linetype_manual(name = "indicator", values = c(2,1,2)) +
  geom_path()
</code>```

Body:
In my dataset, I have segregated the data by a parameter par for either Black or Red noise that are staggered in represtation. Now, for both species, I want to colour the "Black" noise as black, and "Red" as red. Furthermore, I want to join the points by par -- specifically, I want to join par -- No with a Dashed line, and Yes as a solid line. I tried the piece of code attached (and multiple versions of it)..but no luck. Any suggestions?

#Data

set.seed(100)
sp <- factor(c("A","A","A","A","B","B","B","B"))
par <- factor(c("No","No","Yes","Yes","No","No","Yes","Yes"))
y <- rnorm(8, 2,3)
noise <- factor(c("Black","Red","Black","Red","Black","Red","Black","Red"))

df <- data.frame(sp, par, y, noise)
df$noise <- factor(df$noise, levels = c("Black","Red"))

  library(ggplot2)
    ggplot(data = df, aes(x = noise, y = y, fill = par, color = par)) +
      geom_point(size = 4) +
      facet_wrap(.~sp) +
      theme_classic() +
      scale_fill_manual(values = c("black","red")) +   scale_color_manual(values = c("black","red")) +
      geom_line(aes(linetype=par)) + scale_linetype_manual(name = "indicator", values = c(2,1,2))
      geom_path(aes(group = par,linetype=par), geom = "path")

ERROR: geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

Body:
In your code, you forget to add a + to link geom_path() with the ggplot(). Since the aes() of geom_point() and geom_path() doesn't match, you'll need to include them in the corresponding geom_*().

library(tidyverse)

ggplot(data = df, aes(x = noise, y = y, group = par, linetype = par)) +
  geom_point(aes(fill = noise, color = noise, ), size = 4) +
  facet_wrap(.~sp) +
  theme_classic() +
  scale_fill_manual(values = c("black","red")) +
  scale_color_manual(values = c("black","red")) +
  geom_line() +
  scale_linetype_manual(name = "indicator", values = c(2,1,2)) +
  geom_path()


问:
WSL2: Why do I have to shutdown WSL to restart WSL after restarting PC
I have my windows set up WSL with Ubuntu. It has been working fine for a while, until I upgraded to WSL2.

The problem is: every time I start up my PC (or restarting my PC), it lost the connection from Ubuntu to Windows drives.

I got the message like this:

```<code>cd: Input/output error: /mnt/d/
</code>```

The above problem could be solved easily by running this:

```<code>wsl.exe --shutdown
</code>```

I want to solve this problem permanently, instead of shutting down WSL every time I got the problem.

Any idea how to fix this permanently?

答: I haven't seen this issue anymore from the last 2 months. For more info, I upgraded windows to Windows 11 and always do Windows Update. Look like one of the latest windows update fixed this problem. So I can confirm that the issue stopped happening for me from the last 2 months.</p>

Body:
I have my windows set up WSL with Ubuntu. It has been working fine for a while, until I upgraded to WSL2.

The problem is: every time I start up my PC (or restarting my PC), it lost the connection from Ubuntu to Windows drives.

I got the message like this:

cd: Input/output error: /mnt/d/

The above problem could be solved easily by running this:

wsl.exe --shutdown

I want to solve this problem permanently, instead of shutting down WSL every time I got the problem.

Any idea how to fix this permanently?


问:
Best language for Android and Raspberry Pi
I'm looking for opinions on the best development language to use to maintain one set of high-level application code for apps that can execute on Android and Raspberry Pi.</p>

答:
Thank you for taking the time to offer your thoughts.

I've decided to use Dart, along with the Webstorm IDE.  Dart is an OOP language, multiplatform (potentially platform independent), and can compile to bytecode, Javascript or host object code.  It sounds pretty exciting... we'll see after I have completed a couple of projects ;-)

https://dart.dev/overview


问:
Android Studio Bumblebee Navigation can't access FragmentDirections for action
I create such action before Android Studio bumblebee update and it was working fine.

```<code>fragment_button.setOnClickListener{
val action = FeedFragmentDirections.actionFeedFragmentToCountryFragment()
Navigation.findNavController(it).navigate(action)
}
</code>```

But currently FragmentDirections are not accessible.I don't know where the problem comes from, I guess I can't manage to add navigation.

My build.gradle:

```<code>buildscript {
    dependencies {
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.0")
    }
}
plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'androidx.navigation.safeargs.kotlin' version '2.4.0' apply false
    id 'com.google.gms.google-services' version '4.3.0' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My build.gradle App

```<code>plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
    id 'kotlin-android-extensions'
}

android {
    dataBinding {
        enabled = true
}
dependencies {
    def navVersion = '2.4.0'

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation "androidx.navigation:navigation-fragment-ktx:$navVersion"
    implementation "androidx.navigation:navigation-ui-ktx:$navVersion"
}
</code>```

答:
I am retracting my previous answer!

After a bit of research, I realized the plugin block in your project-level build.gradle has the purpose of assigning dependencies that can be used by subprojects!

https://docs.gradle.org/current/userguide/plugins.html#sec:subprojects_plugins_dsl

Instead of declaring:

```<code>plugins {
...
id 'androidx.navigation.safeargs.kotlin' version '2.4.0' apply false
...
}
</code>```

You want to add id 'androidx.navigation.safeargs.kotlin' to the app-level plugins block so it can be used directly in your project.

Body:
I create such action before Android Studio bumblebee update and it was working fine.

fragment_button.setOnClickListener{
val action = FeedFragmentDirections.actionFeedFragmentToCountryFragment()
Navigation.findNavController(it).navigate(action)
}

But currently FragmentDirections are not accessible.I don't know where the problem comes from, I guess I can't manage to add navigation.

My build.gradle:

buildscript {
    dependencies {
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.0")
    }
}
plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'androidx.navigation.safeargs.kotlin' version '2.4.0' apply false
    id 'com.google.gms.google-services' version '4.3.0' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My build.gradle App

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
    id 'kotlin-android-extensions'
}

android {
    dataBinding {
        enabled = true
}
dependencies {
    def navVersion = '2.4.0'

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation "androidx.navigation:navigation-fragment-ktx:$navVersion"
    implementation "androidx.navigation:navigation-ui-ktx:$navVersion"
}

Body:
I am retracting my previous answer!

After a bit of research, I realized the plugin block in your project-level build.gradle has the purpose of assigning dependencies that can be used by subprojects!

https://docs.gradle.org/current/userguide/plugins.html#sec:subprojects_plugins_dsl

Instead of declaring:

plugins {
...
id 'androidx.navigation.safeargs.kotlin' version '2.4.0' apply false
...
}

You want to add id 'androidx.navigation.safeargs.kotlin' to the app-level plugins block so it can be used directly in your project.


问:
Tools for Monitoring Web Services, Windows Services, App Pools and MSMQ health
I am tasked with rewriting a series of legacy services (win and web + msmq). Because of the state they are in, I cannot quickly add functionality to them so they 'call home' to report status/health. I need to do the following:

Poll win service for status: if not 'running', take action

Monitor win service cpu usage: if above X for Y period, take action

Monitor a MSMQ for # of messages: if above X, take action

Monitor a table: if most recent record is older than X take action

Monitor a web service mem and CPU usage: if above x, take action

Open web page: if  not found, take action

The potential actions to take are:

Start or Restart win service

Recycle app pool

Send Email

Write record to history table in database

I know I can eventually accomplish all this by writing custom libraries that can be used by wcf or other services, but I wanted to investigate off the shelf products or tools that could do all or some of this.

What tools are available to do some or all of these tasks?

Thanks,

答: At a simple level, Performance Monitor can perform tasks when MSMQ queue levels reach a set level. There are also MSMQ Management Packs for SCOM.</p>

ContentLicense: CC BY-SA 3.0


问:
Flutter Make api call when home button(middle android button) is pressed and user comes back on app
In my app i have screens that fetched data from the Api, and sometimes the backend can update or change something on the api, so if the user is using the app, and the user presses the home button (middle android button. the circle) and comes back to the app later, i dont see the data being updated so no api call is being made, but when i press the back button and come back to the app the api call is being made same as when i close the app and remove it from the opened app history and open it again, the api call is being made, so i need that to happened the same when the home button is pressed, the user gets out the app by pressing the home button, comes back and the api call will be made. I looked in to it and i was told i need to use WidgetsBindingObserver class. Any help would be appreciated, let me know if you need any code to post.

i tried this but it wont work

```<code>
class _StopWorkingScreenState extends State<StopWorkingScreen>
    with WidgetsBindingObserver {
  late Future<Response> futureDataForStatus;

  @override
  void initState() {
    super.initState();
    futureDataForStatus = getLocationStatus();
    WidgetsBinding.instance!.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive:
        print("Inactive");
        break;
      case AppLifecycleState.paused:
        print("Paused");
        break;
      case AppLifecycleState.resumed:
        futureDataForStatus;
        break;
    }
  }
</code>```

答:
You need to call the function in your switch operator, not just pass a variable.

You could do something like:

```<code>@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  switch (state) {
    ...
    case AppLifecycleState.resumed:
      setState(() {
        futureDataForStatus = getLocationStatus();
      });
      break;
    }
}
</code>```

This will update the state on opening of the app and reload the view with new data (assuming you are using futureDataForStatus as future of a FutureBuilder somewhere on the page.

Body:
In my app i have screens that fetched data from the Api, and sometimes the backend can update or change something on the api, so if the user is using the app, and the user presses the home button (middle android button. the circle) and comes back to the app later, i dont see the data being updated so no api call is being made, but when i press the back button and come back to the app the api call is being made same as when i close the app and remove it from the opened app history and open it again, the api call is being made, so i need that to happened the same when the home button is pressed, the user gets out the app by pressing the home button, comes back and the api call will be made. I looked in to it and i was told i need to use WidgetsBindingObserver class. Any help would be appreciated, let me know if you need any code to post.

i tried this but it wont work

class _StopWorkingScreenState extends State<StopWorkingScreen>
    with WidgetsBindingObserver {
  late Future<Response> futureDataForStatus;

  @override
  void initState() {
    super.initState();
    futureDataForStatus = getLocationStatus();
    WidgetsBinding.instance!.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive:
        print("Inactive");
        break;
      case AppLifecycleState.paused:
        print("Paused");
        break;
      case AppLifecycleState.resumed:
        futureDataForStatus;
        break;
    }
  }

Body:
You need to call the function in your switch operator, not just pass a variable.

You could do something like:

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  switch (state) {
    ...
    case AppLifecycleState.resumed:
      setState(() {
        futureDataForStatus = getLocationStatus();
      });
      break;
    }
}

This will update the state on opening of the app and reload the view with new data (assuming you are using futureDataForStatus as future of a FutureBuilder somewhere on the page.


问:
SQS triggering lambda in Serverless has latency
I have a use case below

StepFunction -> Lambda -> EventBridge to SQS triggering lambda

When the message receives to Eventbridge it will then publish to SQS and SQS will trigger the lambda. What I have noticed here is every time some message is pushed it takes almost 21 Sec to reach the final lambda.

Configuration of SQS:

Visibility Timeout: 30 sec

Dead letter Queue: Enabled

Delay Delivery: 0

receiveMessageDelay: Tried both Short and long poll

Lambda is inside VPC

When I did my analysis, all the bridges is happening in instant but SQS triggering Lambda takes 21 Sec.

All the Blogs am referring to say, it will happen in instant but for me no luck.

Am not sure if my configuration is wrong. Any help is more valuable to me.

Thanks,
Guna

答:
Expanding on Guna's own answer, we had the same problem, and found that the reason was a documented SQS limitation because we had a batchSize configured of 100 and a maximumBatchingWindow of 1.

AWS states:

If you're using a batch window and your SQS queue contains very low traffic, Lambda might wait for up to 20 seconds before invoking your function. This is true even if you set a batch window lower than 20 seconds.

Source: https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html

Once we removed both the batchSize and maximumBatchingWindow configuration settings, the SQS-Lambda invocation latency dramatically decreased.


问:
order only number in dataframe rows by rows import from csv
I want to get ascending order all number of dataframe imported from a CSV file row-by-row:

I tried:

```<code>df_tirage = pd.read_csv('lotodata.csv', sep = ',', usecols=['day','month_year','num0','num1','num2','num3','num4','chance'])
for eachline in df_tirage:
    line = map(str, eachline.split(","))
    sorted_line = sorted(line)
</code>```

答:
If I'm understanding it correctly, something might the following should do the trick.

```<code>df_tirage = pd.read_csv('lotodata.csv', sep = ',', usecols=['day','month_year','num0','num1','num2','num3','num4','chance'])

def sorter(num_arr):
    return np.sort(num_arr)

df_tirage[['num0', 'num1', 'num2', 'num3', 'num4']] = df_tirage.apply(lambda row : sorter(row[2:-1]), axis=1, result_type='expand')
</code>```

We're essentially applying a sorting function row by row using lambda and then unpacking the sorted values into dataframe columns as we go.

Body:
I want to get ascending order all number of dataframe imported from a CSV file row-by-row:

I tried:

df_tirage = pd.read_csv('lotodata.csv', sep = ',', usecols=['day','month_year','num0','num1','num2','num3','num4','chance'])
for eachline in df_tirage:
    line = map(str, eachline.split(","))
    sorted_line = sorted(line)

Body:
If I'm understanding it correctly, something might the following should do the trick.

df_tirage = pd.read_csv('lotodata.csv', sep = ',', usecols=['day','month_year','num0','num1','num2','num3','num4','chance'])

def sorter(num_arr):
    return np.sort(num_arr)

df_tirage[['num0', 'num1', 'num2', 'num3', 'num4']] = df_tirage.apply(lambda row : sorter(row[2:-1]), axis=1, result_type='expand')

We're essentially applying a sorting function row by row using lambda and then unpacking the sorted values into dataframe columns as we go.


问:
how to give a line below the Textview in android
I want to add uderline which cover the fill parent width below the textview to show the textview look like the heading.

```<code>        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="10dp"
            android:layout_marginStart="10dp"
            android:lines="1"
            android:maxLines="2"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/black" />
</code>```

Thanks in advance

答: Insert a divider, on width, start with about 200dp and go from there.  Change Background color to what you want, change gravity to center horizontal.  You can mess with the height as you please.</p>

Body:
I want to add uderline which cover the fill parent width below the textview to show the textview look like the heading.

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="10dp"
            android:layout_marginStart="10dp"
            android:lines="1"
            android:maxLines="2"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/black" />

Thanks in advance


问:
How can I display Crystal XI reports inside a Delphi 2007 application?
The most recent Crystal XI component for Delphi was released for Delphi 7.  That VCL component compiles in D2007, but gives me errors at runtime.  What is the best way to display a database-connected Crystal Report in a Delphi 2007 application?</p>

答:
I too have been disappointed with the lack of effort by Crystal Reports with respect to application integration.  I use the RDC, and from what I understand this is being deprecated and emphasis is being placed on .Net.

My application has these files in the uses clause:
   CRRDC, CRAXDRT_TLB,

It works ok.  The because drawback is parameter passing.  In my option the parameter dialog boxes which come with the viewer are terrible.  So I use my own Delphi application to prompt for parameters and pass them to the report.

OwnerDisplayName: kogus

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: M Schenkel


问:
Standard compliant host to network endianess conversion
I am amazed at how many topics on StackOverflow deal with finding out the endianess of the system and converting endianess. I am even more amazed that there are hundreds of different answers to these two questions. All proposed solutions that I have seen so far are based on undefined behaviour, non-standard compiler extensions or OS-specific header files. In my opinion, this question is only a duplicate if an existing answer gives a standard-compliant, efficient (e.g., use x86-bswap), compile time-enabled solution.

Surely there must be a standard-compliant solution available that I am unable to find in the huge mess of old "hacky" ones. It is also somewhat strange that the standard library does not include such a function. Perhaps the attitude towards such issues is changing, since C++20 introduced a way to detect endianess into the standard (via std::endian), and C++23 will probably include std::byteswap, which flips endianess.

In any case, my questions are these:

Starting at what C++ standard is there a portable standard-compliant way of performing host to network byte order conversion?

I argue below that it's possible in C++20. Is my code correct and can it be improved?

Should such a pure-c++ solution be preferred to OS specific functions such as, e.g., POSIX-htonl? (I think yes)

I think I can give a C++23 solution that is OS-independent, efficient (no system call, uses x86-bswap) and portable to little-endian and big-endian systems (but not portable to mixed-endian systems):

// requires C++23. see https://gcc.godbolt.org/z/6or1sEvKn
#include <type_traits>
#include <utility>
#include <bit>

constexpr inline auto host_to_net(std::integral auto i) {
    static_assert(std::endian::native == std::endian::big || std::endian::native == std::endian::little);
    if constexpr (std::endian::native == std::endian::big) {
        return i;
    } else {
        return std::byteswap(i);
    }
}
```
<p>Since <code>std::endian</code> is available in C++20, one can give a <strong>C++20 solution for <code>host_to_net</code></strong> by implementing <code>byteswap</code> manually. A solution is described here, quote:</p>
<pre class="lang-cpp prettyprint-override"><code>// requires C++17
#include <climits>
#include <cstdint>
#include <type_traits>

template<class T, std::size_t... N>
constexpr T bswap_impl(T i, std::index_sequence<N...>) {
  return ((((i >> (N * CHAR_BIT)) & (T)(unsigned char)(-1)) <<
           ((sizeof(T) - 1 - N) * CHAR_BIT)) | ...);
}; //                                        ^~~~~ fold expression
template<class T, class U = typename std::make_unsigned<T>::type>
constexpr U bswap(T i) {
  return bswap_impl<U>(i, std::make_index_sequence<sizeof(T)>{});
}
</code>```

The linked answer also provides a C++11 byteswap, but that one seems to be less efficient (not compiled to x86-bswap). I think there should be an efficient C++11 way of doing this, too (using either less template-nonsense or even more) but I don't care about older C++ and didn't really try.

Assuming I am correct, the remaining question is: can one can determine system endianess before C++20 at compile time in a standard-compliant and compiler-agnostic way? None of the answers here seem to do achieve this. They use reinterpret_cast (not compile time), OS-headers, union aliasing (which I believe is UB in C++), etc. Also, for some reason, they try to do it "at runtime" although a compiled executable will always run under the same endianess.)

One could do it outside of constexpr context and hope it's optimized away. On the other hand, one could use system-defined preprocessor definitions and account for all platforms, as seems to be the approach taken by Boost. Or maybe (although I would guess the other way is better?) use macros and pick platform-specific htnl-style functions from networking libraries(done, e.g., here (GitHub))?

答:
compile time-enabled solution.

Consider whether this is useful requirement in the first place. The program isn't going to be communicating with another system at compile time. What is the case where you would need to use the serialised integer in a compile time constant context?

Starting at what C++ standard is there a portable standard-compliant way of performing host to network byte order conversion?

It's possible to write such function in standard C++ since C++98. That said, later standards bring tasty template goodies that make this nicer.

There isn't such function in the standard library as of the latest standard.

Should such a pure-c++ solution be preferred to OS specific functions such as, e.g., POSIX-htonl? (I think yes)

Advantage of POSIX is that it's less important to write tests to make sure that it works correctly.

Advantage of pure C++ function is that you don't need platform specific alternatives to those that don't conform to POSIX.

Also, the POSIX htonX are only for 16 bit and 32 bit integers. You could instead use htobeXX functions instead that are in some *BSD and in Linux (glibc).

Here is what I have been using since C+17. Some notes beforehand:

Since endianness conversion is always1 for purposes of serialisation, I write the result directly into a buffer. When converting to host endianness, I read from a buffer.

I don't use CHAR_BIT because network doesn't know my byte size anyway. Network byte is an octet, and if your CPU is different, then these functions won't work. Correct handling of non-octet byte is possible but unnecessary work unless you need to support network communication on such system. Adding an assert might be a good idea.

I prefer to call it big endian rather than "network" endian. There's a chance that a reader isn't aware of the convention that de-facto endianness of network is big.

Instead of checking "if native endianness is X, do Y else do Z", I prefer to write a function that works with all native endianness. This can be done with bit shifts.

Yeah, it's constexpr. Not because it needs to be, but just because it can be. I haven't been able to produce an example where dropping constexpr would produce worse code.

```<code>// helper to promote an integer type
template <class T>
using promote_t = std::decay_t<decltype(+std::declval<T>())>;

template <class T, std::size_t... I>
constexpr void
host_to_big_impl(
    unsigned char* buf,
    T t,
    [[maybe_unused]] std::index_sequence<I...>) noexcept
{
    using U = std::make_unsigned_t<promote_t<T>>;
    constexpr U lastI = sizeof(T) - 1u;
    constexpr U bits = 8u;
    U u = t;
    ( (buf[I] = u >> ((lastI - I) * bits)), ... );
}

template <class T, std::size_t... I>
constexpr void
host_to_big(unsigned char* buf, T t) noexcept
{
    using Indices = std::make_index_sequence<sizeof(T)>;
    return host_to_big_impl<T>(buf, t, Indices{});
}
</code>```

1 In all use cases I've encountered. Conversions from integer to integer can be implemented by delegating these if you have such case, although they cannot be constexpr due to need for reinterpret_cast.

Body:
I am amazed at how many topics on StackOverflow deal with finding out the endianess of the system and converting endianess. I am even more amazed that there are hundreds of different answers to these two questions. All proposed solutions that I have seen so far are based on undefined behaviour, non-standard compiler extensions or OS-specific header files. In my opinion, this question is only a duplicate if an existing answer gives a standard-compliant, efficient (e.g., use x86-bswap), compile time-enabled solution.

Surely there must be a standard-compliant solution available that I am unable to find in the huge mess of old "hacky" ones. It is also somewhat strange that the standard library does not include such a function. Perhaps the attitude towards such issues is changing, since C++20 introduced a way to detect endianess into the standard (via std::endian), and C++23 will probably include std::byteswap, which flips endianess.

In any case, my questions are these:

Starting at what C++ standard is there a portable standard-compliant way of performing host to network byte order conversion?

I argue below that it's possible in C++20. Is my code correct and can it be improved?

Should such a pure-c++ solution be preferred to OS specific functions such as, e.g., POSIX-htonl? (I think yes)

I think I can give a C++23 solution that is OS-independent, efficient (no system call, uses x86-bswap) and portable to little-endian and big-endian systems (but not portable to mixed-endian systems):

// requires C++23. see https://gcc.godbolt.org/z/6or1sEvKn
#include <type_traits>
#include <utility>
#include <bit>

constexpr inline auto host_to_net(std::integral auto i) {
    static_assert(std::endian::native == std::endian::big || std::endian::native == std::endian::little);
    if constexpr (std::endian::native == std::endian::big) {
        return i;
    } else {
        return std::byteswap(i);
    }
}

Since std::endian is available in C++20, one can give a C++20 solution for host_to_net by implementing byteswap manually. A solution is described here, quote:

// requires C++17
#include <climits>
#include <cstdint>
#include <type_traits>

template<class T, std::size_t... N>
constexpr T bswap_impl(T i, std::index_sequence<N...>) {
  return ((((i >> (N * CHAR_BIT)) & (T)(unsigned char)(-1)) <<
           ((sizeof(T) - 1 - N) * CHAR_BIT)) | ...);
}; //                                        ^~~~~ fold expression
template<class T, class U = typename std::make_unsigned<T>::type>
constexpr U bswap(T i) {
  return bswap_impl(i, std::make_index_sequence<sizeof(T)>{});
}

The linked answer also provides a C++11 byteswap, but that one seems to be less efficient (not compiled to x86-bswap). I think there should be an efficient C++11 way of doing this, too (using either less template-nonsense or even more) but I don't care about older C++ and didn't really try.

Assuming I am correct, the remaining question is: can one can determine system endianess before C++20 at compile time in a standard-compliant and compiler-agnostic way? None of the answers here seem to do achieve this. They use reinterpret_cast (not compile time), OS-headers, union aliasing (which I believe is UB in C++), etc. Also, for some reason, they try to do it "at runtime" although a compiled executable will always run under the same endianess.)

One could do it outside of constexpr context and hope it's optimized away. On the other hand, one could use system-defined preprocessor definitions and account for all platforms, as seems to be the approach taken by Boost. Or maybe (although I would guess the other way is better?) use macros and pick platform-specific htnl-style functions from networking libraries(done, e.g., here (GitHub))?

Body:
compile time-enabled solution.

Consider whether this is useful requirement in the first place. The program isn't going to be communicating with another system at compile time. What is the case where you would need to use the serialised integer in a compile time constant context?

Starting at what C++ standard is there a portable standard-compliant way of performing host to network byte order conversion?

It's possible to write such function in standard C++ since C++98. That said, later standards bring tasty template goodies that make this nicer.

There isn't such function in the standard library as of the latest standard.

Should such a pure-c++ solution be preferred to OS specific functions such as, e.g., POSIX-htonl? (I think yes)

Advantage of POSIX is that it's less important to write tests to make sure that it works correctly.

Advantage of pure C++ function is that you don't need platform specific alternatives to those that don't conform to POSIX.

Also, the POSIX htonX are only for 16 bit and 32 bit integers. You could instead use htobeXX functions instead that are in some *BSD and in Linux (glibc).

Here is what I have been using since C+17. Some notes beforehand:

Since endianness conversion is always1 for purposes of serialisation, I write the result directly into a buffer. When converting to host endianness, I read from a buffer.

I don't use CHAR_BIT because network doesn't know my byte size anyway. Network byte is an octet, and if your CPU is different, then these functions won't work. Correct handling of non-octet byte is possible but unnecessary work unless you need to support network communication on such system. Adding an assert might be a good idea.

I prefer to call it big endian rather than "network" endian. There's a chance that a reader isn't aware of the convention that de-facto endianness of network is big.

Instead of checking "if native endianness is X, do Y else do Z", I prefer to write a function that works with all native endianness. This can be done with bit shifts.

Yeah, it's constexpr. Not because it needs to be, but just because it can be. I haven't been able to produce an example where dropping constexpr would produce worse code.

// helper to promote an integer type
template <class T>
using promote_t = std::decay_t<decltype(+std::declval<T>())>;

template <class T, std::size_t... I>
constexpr void
host_to_big_impl(
    unsigned char* buf,
    T t,
    [[maybe_unused]] std::index_sequence<I...>) noexcept
{
    using U = std::make_unsigned_t<promote_t<T>>;
    constexpr U lastI = sizeof(T) - 1u;
    constexpr U bits = 8u;
    U u = t;
    ( (buf[I] = u >> ((lastI - I) * bits)), ... );
}

template <class T, std::size_t... I>
constexpr void
host_to_big(unsigned char* buf, T t) noexcept
{
    using Indices = std::make_index_sequence<sizeof(T)>;
    return host_to_big_impl<T>(buf, t, Indices{});
}

1 In all use cases I've encountered. Conversions from integer to integer can be implemented by delegating these if you have such case, although they cannot be constexpr due to need for reinterpret_cast.


问:
Multilabel classification in scikit-learn with hyperparameter search: specifying averaging
I am working on a simple multioutput classification problem and noticed this error showing up whenever running the below code:

```<code>ValueError: Target is multilabel-indicator but average='binary'. Please
choose another average setting, one of [None, 'micro', 'macro', 'weighted', 'samples'].
</code>```

I understand the problem it is referencing, i.e., when evaluating multilabel models one needs to explicitly set the type of averaging. Nevertheless, I am unable to figure out where this average argument should go to, since only accuracy_score, precision_score, recall_score built-in methods have this argument which I do not use explicitly in my code. Moreover, since I am doing a RandomizedSearch, I cannot just pass a precision_score(average='micro') to the scoring or refit arguments either, since precision_score() requires correct and true y labels to be passed. This is why this former SO question and this one here, both with a similar issue, didn't help.

My code with example data generation is as follows:

```<code>from sklearn.datasets import make_multilabel_classification
from sklearn.naive_bayes import MultinomialNB
from sklearn.multioutput import MultiOutputClassifier
from sklearn.model_selection import RandomizedSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler

X, Y = make_multilabel_classification(
    n_samples=1000,
    n_features=2,
    n_classes=5,
    n_labels=2
)

pipe = Pipeline(
    steps = [
        ('scaler', MinMaxScaler()),
        ('model', MultiOutputClassifier(MultinomialNB()))
    ]
)

search = RandomizedSearchCV(
    estimator = pipe,
    param_distributions={'model__estimator__alpha': (0.01,1)},
    scoring = ['accuracy', 'precision', 'recall'],
    refit = 'precision',
    cv = 5
).fit(X, Y)
</code>```

What am I missing?

答:
From the table of scoring metrics, note f1_micro, f1_macro, etc., and the notes "suffixes apply as with ‘f1’" given for precision and recall.  So e.g.

search = RandomizedSearchCV(
    ...
    scoring = ['accuracy', 'precision_micro', 'recall_macro'],
    ...
)
```

Body:
I am working on a simple multioutput classification problem and noticed this error showing up whenever running the below code:

ValueError: Target is multilabel-indicator but average='binary'. Please
choose another average setting, one of [None, 'micro', 'macro', 'weighted', 'samples'].

I understand the problem it is referencing, i.e., when evaluating multilabel models one needs to explicitly set the type of averaging. Nevertheless, I am unable to figure out where this average argument should go to, since only accuracy_score, precision_score, recall_score built-in methods have this argument which I do not use explicitly in my code. Moreover, since I am doing a RandomizedSearch, I cannot just pass a precision_score(average='micro') to the scoring or refit arguments either, since precision_score() requires correct and true y labels to be passed. This is why this former SO question and this one here, both with a similar issue, didn't help.

My code with example data generation is as follows:

from sklearn.datasets import make_multilabel_classification
from sklearn.naive_bayes import MultinomialNB
from sklearn.multioutput import MultiOutputClassifier
from sklearn.model_selection import RandomizedSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler

X, Y = make_multilabel_classification(
    n_samples=1000,
    n_features=2,
    n_classes=5,
    n_labels=2
)

pipe = Pipeline(
    steps = [
        ('scaler', MinMaxScaler()),
        ('model', MultiOutputClassifier(MultinomialNB()))
    ]
)

search = RandomizedSearchCV(
    estimator = pipe,
    param_distributions={'model__estimator__alpha': (0.01,1)},
    scoring = ['accuracy', 'precision', 'recall'],
    refit = 'precision',
    cv = 5
).fit(X, Y)

What am I missing?


问:
How to save a html page modified as it is on browser?
So, the idea here is that i got a table.html file in my computer that I'd like to open and change (either via inspect or input or what it got to work), and them save it in some way.

I've tried downloading the file but it downloads the original, no matter if I use variables, inputs, or inspect.

Maybe if there was a way to change original file directly?

I don't know much PHP but using javascript/python could it be done?

答:
If you're looking to literally save the changes of an html file modified as it is on browser, it might be possible using python and maybe other languages but I'm not an expert in them.

As far as I know, edits made on browser don't get updated to the html file itself, or even the browser's cache.

So if it's even possible, the easiest solution I can think of is a really botched and situational pyautogui scraper to get the data from table.html displayed on the browser into a text editor to change the html file itself, and then you can save the table.html with your changes made to it.