问:
How to input decimal numbers in ag-grid cells
Using numericCellEditor in such way (without cellEditorParams):

```<code>var columnDefs = [
    {
        cellEditor: 'numericCellEditor'
    },
]
</code>```

Decumal numbers (1.25, 3.675 etc.) input is not possible. What cell editor to choose (or, maybe, how to tune numericCellEditor) to work with decimals, i.e. so I could edit values, and in opened editing fields I could'n print letters or other non-numeric symbols, but I could input dot or comma as decimal separator.

答:
As an improvement on the solution offered by Pavel,  you could use the following to allow up to one decimal point (but not more than one).

Add this function (where this.eInput is your html input):

function isCharTheFirstDecimal(charStr) {
  return !!/\./.test(charStr) && !/\./.test(this.eInput.value);
}
```

<p><br><br>
And then change isKeyPressedNumeric to:
</p>

```function isKeyPressedNumeric(event) {
    var charCode = this.getCharCodeFromEvent(event);
    var charStr = String.fromCharCode(charCode);
    return this.isCharNumeric(charStr) ||
    this.isCharTheFirstDecimal(charStr);
}
```

<p>
<br><br>
The other functions used (which are all from the example in the ag-grid documentation here: https://www.ag-grid.com/javascript-grid-cell-editing) are below:</p>

<pre class="lang-js prettyprint-override"><code>getCharCodeFromEvent(event) {
    event = event || window.event;
    return typeof event.which == "undefined" ? event.keyCode : event.which;
}

isCharNumeric(charStr) {
    return !!/\d/.test(charStr);
}
</code>```

Body:
Using numericCellEditor in such way (without cellEditorParams):

var columnDefs = [
    {
        cellEditor: 'numericCellEditor'
    },
]

Decumal numbers (1.25, 3.675 etc.) input is not possible. What cell editor to choose (or, maybe, how to tune numericCellEditor) to work with decimals, i.e. so I could edit values, and in opened editing fields I could'n print letters or other non-numeric symbols, but I could input dot or comma as decimal separator.

Body:
As an improvement on the solution offered by Pavel,  you could use the following to allow up to one decimal point (but not more than one).

Add this function (where this.eInput is your html input):

function isCharTheFirstDecimal(charStr) {
  return !!/\./.test(charStr) && !/\./.test(this.eInput.value);
}

And then change isKeyPressedNumeric to:

function isKeyPressedNumeric(event) {
    var charCode = this.getCharCodeFromEvent(event);
    var charStr = String.fromCharCode(charCode);
    return this.isCharNumeric(charStr) ||
    this.isCharTheFirstDecimal(charStr);
}

The other functions used (which are all from the example in the ag-grid documentation here: https://www.ag-grid.com/javascript-grid-cell-editing) are below:

getCharCodeFromEvent(event) {
    event = event || window.event;
    return typeof event.which == "undefined" ? event.keyCode : event.which;
}

isCharNumeric(charStr) {
    return !!/\d/.test(charStr);
}


来源: stackexchange

问:
How do I use D3js in Wordpress?
I have installed wordpress as well as the plugin for d3js. Now, what is the best way to upload the data so that I can make and serve graphs on the fly?

If I upload the csv files directly, where do I store it? Does it matter?

If I want to store the data in a third party site, what can I use? Preferably free service.

I have made graphs in my localmachine and I want to publish those graphs now.

答:
After going through lot of websites, youtube videos, here's my solution:

Install File Manager plugin

Add a folder for your d3 projects (ex: d3-projects/project_1), this should be inside public_html folder along with wp-admin, wp-content

Ensure that javascript code is embedded in your index.html page

Add index.html & css file to the project_1 folder

Preview your D3js chart at your_site_url/project_1

ContentLicense: CC BY-SA 3.0

Title: How do I use D3js in Wordpress?

ContentLicense: CC BY-SA 4.0


问:
Flutter WebRTC audio but no video
So I'm building a video calling application using flutter, flutterWeb, and the WebRTC package.

I have a spring boot server sitting in the middle to pass the messages between the two clients.

Each side shows the local video, but neither shows the remote. Audio does work though. I got som nasty feedback loops. Testing with headphones showed that audio does indeed work.

My singaling code

```<code>typedef void StreamStateCallback(MediaStream stream);

class CallingService {
  String sendToUserId;
  String currentUserId;
  final String authToken;
  final StompClient _client;
  final StreamStateCallback onAddRemoteStream;
  final StreamStateCallback onRemoveRemoteStream;
  final StreamStateCallback onAddLocalStream;
  RTCPeerConnection _peerConnection;
  List<RTCIceCandidate> _remoteCandidates = [];
  String destination;
  var hasOffer = false;
  var isNegotiating = false;
  MediaStream _localStream;

  final Map<String, dynamic> _constraints = {
    'mandatory': {
      'OfferToReceiveAudio': true,
      'OfferToReceiveVideo': true,
    },
    'optional': [],
  };

  CallingService(
      this._client,
      this.sendToUserId,
      this.currentUserId,
      this.authToken,
      this.onAddRemoteStream,
      this.onRemoveRemoteStream,
      this.onAddLocalStream) {
    destination = '/app/start-call/$sendToUserId';
    print("destination $destination");
    _client.subscribe(
        destination: destination,
        headers: {'Authorization': "$authToken"},
        callback: (StompFrame frame) => processMessage(jsonDecode(frame.body)));
  }

  Future<void> startCall() async {
    await processRemoteStream();
    RTCSessionDescription description =
        await _peerConnection.createOffer(_constraints);
    await _peerConnection.setLocalDescription(description);
    var message = RtcMessage(RtcMessageType.OFFER, currentUserId, {
      'description': {'sdp': description.sdp, 'type': description.type},
    });
    sendMessage(message);
  }

  Future<void> processMessage(Map<String, dynamic> messageJson) async {
    var message = RtcMessage.fromJson(messageJson);
    if (message.from == currentUserId) {
      return;
    }
    print("processing ${message.messageType.toString()}");
    switch (message.messageType) {
      case RtcMessageType.BYE:
        // TODO: Handle this case.
        break;
      case RtcMessageType.LEAVE:
        // TODO: Handle this case.
        break;
      case RtcMessageType.CANDIDATE:
        await processCandidate(message);
        break;
      case RtcMessageType.ANSWER:
        await processAnswer(message);
        break;
      case RtcMessageType.OFFER:
        await processOffer(message);
        break;
    }
  }

  Future<void> processCandidate(RtcMessage candidate) async {
    Map<String, dynamic> map = candidate.data['candidate'];
    var rtcCandidate = RTCIceCandidate(
      map['candidate'],
      map['sdpMid'],
      map['sdpMLineIndex'],
    );
    if (_peerConnection != null) {
      _peerConnection.addCandidate(rtcCandidate);
    } else {
      _remoteCandidates.add(rtcCandidate);
    }
  }

  Future<void> processAnswer(RtcMessage answer) async {
    if (isNegotiating) {
      return;
    }
    isNegotiating = true;
    var description = answer.data['description'];
    if (_peerConnection == null) {
      return;
    }
    await _peerConnection.setRemoteDescription(
        RTCSessionDescription(description['sdp'], description['type']));
  }

  Future<void> processOffer(RtcMessage offer) async {
    await processRemoteStream();
    var description = offer.data['description'];
    await _peerConnection.setRemoteDescription(
        new RTCSessionDescription(description['sdp'], description['type']));
    var answerDescription = await _peerConnection.createAnswer(_constraints);
    await _peerConnection.setLocalDescription(answerDescription);
    var answerMessage = RtcMessage(RtcMessageType.ANSWER, currentUserId, {
      'description': {
        'sdp': answerDescription.sdp,
        'type': answerDescription.type
      },
    });
    sendMessage(answerMessage);
    if (_remoteCandidates.isNotEmpty) {
      _remoteCandidates
          .forEach((candidate) => _peerConnection.addCandidate(candidate));
      _remoteCandidates.clear();
    }
  }

  Future<void> processRemoteStream() async {
    _localStream = await createStream();
    _peerConnection = await createPeerConnection(_iceServers, _config);
    _peerConnection.addStream(_localStream);
    _peerConnection.onSignalingState = (state) {
      //isNegotiating = state != RTCSignalingState.RTCSignalingStateStable;
    };

    _peerConnection.onAddStream = (MediaStream stream) {
      this.onAddRemoteStream(stream);
    };
    _peerConnection.onRemoveStream =
        (MediaStream stream) => this.onRemoveRemoteStream(stream);
    _peerConnection.onIceCandidate = (RTCIceCandidate candidate) {
      var data = {
        'candidate': {
          'sdpMLineIndex': candidate.sdpMlineIndex,
          'sdpMid': candidate.sdpMid,
          'candidate': candidate.candidate,
        },
      };
      var message = RtcMessage(RtcMessageType.CANDIDATE, currentUserId, data);
      sendMessage(message);
    };
  }

  void sendMessage(RtcMessage message) {
    _client.send(
        destination: destination,
        headers: {'Authorization': "$authToken"},
        body: jsonEncode(message.toJson()));
  }

  Map<String, dynamic> _iceServers = {
    'iceServers': [
      {'urls': 'stun:stun.l.google.com:19302'},
      /*
       * turn server configuration example.
      {
        'url': 'turn:123.45.67.89:3478',
        'username': 'change_to_real_user',
        'credential': 'change_to_real_secret'
      },
       */
    ]
  };

  final Map<String, dynamic> _config = {
    'mandatory': {},
    'optional': [
      {'DtlsSrtpKeyAgreement': true},
    ],
  };

  Future<MediaStream> createStream() async {
    final Map<String, dynamic> mediaConstraints = {
      'audio': true,
      'video': {
        'mandatory': {
          'minWidth': '640',
          'minHeight': '480',
          'minFrameRate': '30',
        },
        'facingMode': 'user',
        'optional': [],
      }
    };

    MediaStream stream = await navigator.getUserMedia(mediaConstraints);
    if (this.onAddLocalStream != null) {
      this.onAddLocalStream(stream);
    }
    return stream;
  }
}
</code>```

Here are my widgets

```<code>class _CallScreenState extends State<CallScreen> {
  StompClient _client;
  CallingService _callingService;
  RTCVideoRenderer _localRenderer = new RTCVideoRenderer();
  RTCVideoRenderer _remoteRenderer = new RTCVideoRenderer();
  final UserService userService = GetIt.instance.get<UserService>();

  void onConnectCallback(StompClient client, StompFrame connectFrame) async {
    var currentUser = await userService.getCurrentUser();
    _callingService = CallingService(
        _client,
        widget.intent.toUserId.toString(),
        currentUser.id.toString(),
        widget.intent.authToken,
        onAddRemoteStream,
        onRemoveRemoteStream,
        onAddLocalStream);
    if (widget.intent.initialMessage != null) {
      _callingService.processMessage(jsonDecode(widget.intent.initialMessage));
    } else {
      _callingService.startCall();
    }
  }

  void onAddRemoteStream(MediaStream stream) {
    _remoteRenderer.srcObject = stream;
  }

  void onRemoveRemoteStream(MediaStream steam) {
    _remoteRenderer.srcObject = null;
  }

  void onAddLocalStream(MediaStream stream) {
    _localRenderer.srcObject = stream;
  }

  @override
  void initState() {
    super.initState();
    _localRenderer.initialize();
    _remoteRenderer.initialize();
    _client = StompClient(
      config: StompConfig(
        url: 'ws://${DomainService.getDomainBase()}/stomp',
        onConnect: onConnectCallback,
        onWebSocketError: (dynamic error) => print(error.toString()),
        stompConnectHeaders: {'Authorization': "${widget.intent.authToken}"},
        onDisconnect: (message) => print("disconnected ${message.body}"),),
    );
    _client.activate();
  }

  @override
  Widget build(BuildContext context) {
    return PlatformScaffold(
      pageTitle: "",
      child: Flex(
        direction: Axis.vertical,
        children: [
          Flexible(
            flex: 1,
            child: RTCVideoView(_localRenderer),
          ),
          Flexible(
            flex: 1,
            child: RTCVideoView(_remoteRenderer),
          )
        ],
      ),
    );
  }
}
</code>```

I put a print statment in the the widget on the addRemoteStream callback, and it's getting called. So some kind of stream is being sent. I'm just not sure why the video isnt' showing.

答:
So my problem was that I wasn't adding queued candidates to the caller.

I added

```<code>sendMessage(answerMessage);
if (_remoteCandidates.isNotEmpty) {
  _remoteCandidates
      .forEach((candidate) => _peerConnection.addCandidate(candidate));
  _remoteCandidates.clear();
}
</code>```

to the processAnswer method and it works just fine!

Title: Flutter WebRTC audio but no video

Body:
So I'm building a video calling application using flutter, flutterWeb, and the WebRTC package.

I have a spring boot server sitting in the middle to pass the messages between the two clients.

Each side shows the local video, but neither shows the remote. Audio does work though. I got som nasty feedback loops. Testing with headphones showed that audio does indeed work.

My singaling code

typedef void StreamStateCallback(MediaStream stream);

class CallingService {
  String sendToUserId;
  String currentUserId;
  final String authToken;
  final StompClient _client;
  final StreamStateCallback onAddRemoteStream;
  final StreamStateCallback onRemoveRemoteStream;
  final StreamStateCallback onAddLocalStream;
  RTCPeerConnection _peerConnection;
  List<RTCIceCandidate> _remoteCandidates = [];
  String destination;
  var hasOffer = false;
  var isNegotiating = false;
  MediaStream _localStream;

  final Map<String, dynamic> _constraints = {
    'mandatory': {
      'OfferToReceiveAudio': true,
      'OfferToReceiveVideo': true,
    },
    'optional': [],
  };

  CallingService(
      this._client,
      this.sendToUserId,
      this.currentUserId,
      this.authToken,
      this.onAddRemoteStream,
      this.onRemoveRemoteStream,
      this.onAddLocalStream) {
    destination = '/app/start-call/$sendToUserId';
    print("destination $destination");
    _client.subscribe(
        destination: destination,
        headers: {'Authorization': "$authToken"},
        callback: (StompFrame frame) => processMessage(jsonDecode(frame.body)));
  }

  Future<void> startCall() async {
    await processRemoteStream();
    RTCSessionDescription description =
        await _peerConnection.createOffer(_constraints);
    await _peerConnection.setLocalDescription(description);
    var message = RtcMessage(RtcMessageType.OFFER, currentUserId, {
      'description': {'sdp': description.sdp, 'type': description.type},
    });
    sendMessage(message);
  }

  Future<void> processMessage(Map<String, dynamic> messageJson) async {
    var message = RtcMessage.fromJson(messageJson);
    if (message.from == currentUserId) {
      return;
    }
    print("processing ${message.messageType.toString()}");
    switch (message.messageType) {
      case RtcMessageType.BYE:
        // TODO: Handle this case.
        break;
      case RtcMessageType.LEAVE:
        // TODO: Handle this case.
        break;
      case RtcMessageType.CANDIDATE:
        await processCandidate(message);
        break;
      case RtcMessageType.ANSWER:
        await processAnswer(message);
        break;
      case RtcMessageType.OFFER:
        await processOffer(message);
        break;
    }
  }

  Future<void> processCandidate(RtcMessage candidate) async {
    Map<String, dynamic> map = candidate.data['candidate'];
    var rtcCandidate = RTCIceCandidate(
      map['candidate'],
      map['sdpMid'],
      map['sdpMLineIndex'],
    );
    if (_peerConnection != null) {
      _peerConnection.addCandidate(rtcCandidate);
    } else {
      _remoteCandidates.add(rtcCandidate);
    }
  }

  Future<void> processAnswer(RtcMessage answer) async {
    if (isNegotiating) {
      return;
    }
    isNegotiating = true;
    var description = answer.data['description'];
    if (_peerConnection == null) {
      return;
    }
    await _peerConnection.setRemoteDescription(
        RTCSessionDescription(description['sdp'], description['type']));
  }

  Future<void> processOffer(RtcMessage offer) async {
    await processRemoteStream();
    var description = offer.data['description'];
    await _peerConnection.setRemoteDescription(
        new RTCSessionDescription(description['sdp'], description['type']));
    var answerDescription = await _peerConnection.createAnswer(_constraints);
    await _peerConnection.setLocalDescription(answerDescription);
    var answerMessage = RtcMessage(RtcMessageType.ANSWER, currentUserId, {
      'description': {
        'sdp': answerDescription.sdp,
        'type': answerDescription.type
      },
    });
    sendMessage(answerMessage);
    if (_remoteCandidates.isNotEmpty) {
      _remoteCandidates
          .forEach((candidate) => _peerConnection.addCandidate(candidate));
      _remoteCandidates.clear();
    }
  }

  Future<void> processRemoteStream() async {
    _localStream = await createStream();
    _peerConnection = await createPeerConnection(_iceServers, _config);
    _peerConnection.addStream(_localStream);
    _peerConnection.onSignalingState = (state) {
      //isNegotiating = state != RTCSignalingState.RTCSignalingStateStable;
    };

    _peerConnection.onAddStream = (MediaStream stream) {
      this.onAddRemoteStream(stream);
    };
    _peerConnection.onRemoveStream =
        (MediaStream stream) => this.onRemoveRemoteStream(stream);
    _peerConnection.onIceCandidate = (RTCIceCandidate candidate) {
      var data = {
        'candidate': {
          'sdpMLineIndex': candidate.sdpMlineIndex,
          'sdpMid': candidate.sdpMid,
          'candidate': candidate.candidate,
        },
      };
      var message = RtcMessage(RtcMessageType.CANDIDATE, currentUserId, data);
      sendMessage(message);
    };
  }

  void sendMessage(RtcMessage message) {
    _client.send(
        destination: destination,
        headers: {'Authorization': "$authToken"},
        body: jsonEncode(message.toJson()));
  }

  Map<String, dynamic> _iceServers = {
    'iceServers': [
      {'urls': 'stun:stun.l.google.com:19302'},
      /*
       * turn server configuration example.
      {
        'url': 'turn:123.45.67.89:3478',
        'username': 'change_to_real_user',
        'credential': 'change_to_real_secret'
      },
       */
    ]
  };

  final Map<String, dynamic> _config = {
    'mandatory': {},
    'optional': [
      {'DtlsSrtpKeyAgreement': true},
    ],
  };

  Future<MediaStream> createStream() async {
    final Map<String, dynamic> mediaConstraints = {
      'audio': true,
      'video': {
        'mandatory': {
          'minWidth': '640',
          'minHeight': '480',
          'minFrameRate': '30',
        },
        'facingMode': 'user',
        'optional': [],
      }
    };

    MediaStream stream = await navigator.getUserMedia(mediaConstraints);
    if (this.onAddLocalStream != null) {
      this.onAddLocalStream(stream);
    }
    return stream;
  }
}

Here are my widgets

class _CallScreenState extends State<CallScreen> {
  StompClient _client;
  CallingService _callingService;
  RTCVideoRenderer _localRenderer = new RTCVideoRenderer();
  RTCVideoRenderer _remoteRenderer = new RTCVideoRenderer();
  final UserService userService = GetIt.instance.get<UserService>();

  void onConnectCallback(StompClient client, StompFrame connectFrame) async {
    var currentUser = await userService.getCurrentUser();
    _callingService = CallingService(
        _client,
        widget.intent.toUserId.toString(),
        currentUser.id.toString(),
        widget.intent.authToken,
        onAddRemoteStream,
        onRemoveRemoteStream,
        onAddLocalStream);
    if (widget.intent.initialMessage != null) {
      _callingService.processMessage(jsonDecode(widget.intent.initialMessage));
    } else {
      _callingService.startCall();
    }
  }

  void onAddRemoteStream(MediaStream stream) {
    _remoteRenderer.srcObject = stream;
  }

  void onRemoveRemoteStream(MediaStream steam) {
    _remoteRenderer.srcObject = null;
  }

  void onAddLocalStream(MediaStream stream) {
    _localRenderer.srcObject = stream;
  }

  @override
  void initState() {
    super.initState();
    _localRenderer.initialize();
    _remoteRenderer.initialize();
    _client = StompClient(
      config: StompConfig(
        url: 'ws://${DomainService.getDomainBase()}/stomp',
        onConnect: onConnectCallback,
        onWebSocketError: (dynamic error) => print(error.toString()),
        stompConnectHeaders: {'Authorization': "${widget.intent.authToken}"},
        onDisconnect: (message) => print("disconnected ${message.body}"),),
    );
    _client.activate();
  }

  @override
  Widget build(BuildContext context) {
    return PlatformScaffold(
      pageTitle: "",
      child: Flex(
        direction: Axis.vertical,
        children: [
          Flexible(
            flex: 1,
            child: RTCVideoView(_localRenderer),
          ),
          Flexible(
            flex: 1,
            child: RTCVideoView(_remoteRenderer),
          )
        ],
      ),
    );
  }
}

I put a print statment in the the widget on the addRemoteStream callback, and it's getting called. So some kind of stream is being sent. I'm just not sure why the video isnt' showing.

Body:
So my problem was that I wasn't adding queued candidates to the caller.

I added

sendMessage(answerMessage);
if (_remoteCandidates.isNotEmpty) {
  _remoteCandidates
      .forEach((candidate) => _peerConnection.addCandidate(candidate));
  _remoteCandidates.clear();
}

to the processAnswer method and it works just fine!


问:
How to reload the whole UIViewController page
I want to reload my UIViewController after I return back from another UIViewController

In my ReviewController I have this code to open the WriteReviewController

let newViewController = WriteReviewController()
navigationController?.present(newViewController, animated: true, completion: nil)
```

<p>In my <code>WriteReviewController</code>, I use</p>

<pre class="lang-swift prettyprint-override"><code>self.dismiss(animated: true, completion: nil)
</code>```

to return back to the ReviewController.
I want to make the ReviewController to reload page so that the new review can show up on the page. Thank you in advance.

答:
First of all, it's UIViewController, not UIController.
Secondly - it depends if you have to pass data back  from your WriteReviewController or not.

If yes, you need to create a protocol with a function to pass back the new review.

If you simply want to reload your data model for the ReviewController, you can simply do your reloading logic in viewWillAppear(animated:) function, inherited by UIViewController.

Let me know which way you need further help with and I can help you with writing the code.

EDIT: I'm pretty sure answer 1 is correct, so here's some help:

// assuming you have a struct like this for your Review data model
struct Review {
    var reviewText: String
    var author: String
}

// add this code to your ReviewController
protocol WriteReviewDelegate: class {
    func newReviewHasBeenWritten(_ review: Review)
}
class ReviewController: UIViewController {
    // ...
}
// make that ReviewController conform to this class
extension ReviewController: WriteReviewDelegate {
    func newReviewHasBeenWritten(_ review: Review) {
        // save the review to your model here
        // afterwards, update your UI to show the new review
    }
}

// add the following code to your WriteReviewController
class WriteReviewController {
    weak var delegate: WriteReviewDelegate?

    func saveReview() {
        // called when the user wants to  save a new review
        // notify the delegate (your ReviewController), that there's a new Review
        self.delegate?.newReviewHasBeenWritten(self.review)
        // then dismiss it, for example
        self.dismiss(animated: true, completion: nil)
    }
}

```

Body:
I want to reload my UIViewController after I return back from another UIViewController

In my ReviewController I have this code to open the WriteReviewController

let newViewController = WriteReviewController()
navigationController?.present(newViewController, animated: true, completion: nil)

In my WriteReviewController, I use

self.dismiss(animated: true, completion: nil)

to return back to the ReviewController.
I want to make the ReviewController to reload page so that the new review can show up on the page. Thank you in advance.


问:
Re-uploading a file with AJAX after it was changed causes net::ERR_UPLOAD_FILE_CHANGED in Chrome
I have a simple HTML form that sends an selected file via AJAX to an API endpoint.

If I do the following steps:

Press the Upload button and make an POST request to upload the file

Change the selected file on the filesystem (in a text editor), without picking it again in the file picker.

Press the Upload button again, and make as second POST request

Chrome will fail the second request with an error: net::ERR_UPLOAD_FILE_CHANGED. Note that if you change the file before the initial upload, the file will be uploaded without a problem. The error happens only on the second upload, when you change the file after an initial successful upload. I am testing this with CSV files, and changing them in a text editor.

There does not seem to be a way to isolate that error.

Is there any way around this?

If not, is it possible to catch this specific error, and display a meaningful message to the user. The error that Fetch returns in the promise has no specific info about this. The only place where I see the ERR_UPLOAD_FILE_CHANGED is in the browser dev console.

I am pretty sure that there was not any problem with this about a year ago (early 2019), as the possibility to re-upload a changed file, played in nicely in our UI flow. Now we need to force the user to pick the file again. So my assumption that this was introduced with a recent chrome update.

Here is a simplified snippet of the code:

```<code><html>
<head>
        <script type='text/javascript'>
        document.addEventListener("DOMContentLoaded", function(){

                const button = document.querySelector('#btnSubmit');

                button.addEventListener('click', () => {
                        const form = new FormData(document.querySelector('#theForm'));
                        const url = '/my-api'
                        const request = new Request(url, {
                                method: 'POST',
                                body: form
                        });

                        fetch(request).then(function() {
                                console.log("ok");
                        }).catch(function(err) {
                                console.log(err);
                        });
                });
        });
        </script>

</head>
<body>
        <form enctype="multipart/form-data" action="" method="post" id='theForm'>
                <input type="file" name="csvfile" id="csvfile" value="" /></td>
                <input type="button" name="uploadCSV" value="Upload" id='btnSubmit'/>
        </form>
</body>
</html>
</code>```

EDIT: The bug is marked as WontFix on bugs.chromium.org: https://bugs.chromium.org/p/chromium/issues/detail?id=1086707#c7

答:
I managed to get a more descriptive error using the javascript File Reader. After the the file is changed and the button is pressed for the second time, the FileReader throws a somewhat more descriptive message:

DOMException: The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.

At least this is an error that can be caught and displayed to the user, so they are aware that they need to re-select the file.

Here is the snippet:

```<code><html>
    <head>
        <title>Test</title>
        <script type='text/javascript'>
        document.addEventListener("DOMContentLoaded", function(){

            const button = document.querySelector('#btnSubmit');

            button.addEventListener('click', () => {
                let inputElement = document.getElementById('csvfile');

                for (let i = 0; i < inputElement.files.length; i++) {
                    const file = inputElement.files[i];

                    console.log(file);

                    const reader = new FileReader();
                    reader.readAsText(file, "UTF-8");

                    reader.onload = function (evt) {
                        console.log(evt.target.result);
                    }

                    reader.onerror = function (err) {
                        // read error caught here
                        console.log(err);
                        console.log(err.target.error);
                    }

                }

            });
        });
        </script>

    </head>
    <body>
        <form enctype="multipart/form-data" action="" method="post" id='theForm'>
                <input type="file" name="csvfile" id="csvfile" value="" />
                <input type="button" name="uploadCSV" value="Upload" id='btnSubmit'/>
        </form>
    </body>
</html>
</code>```

It seems that there is no way around this at the moment (June 2020). There is an open bug on Chromium:

https://bugs.chromium.org/p/chromium/issues/detail?id=1084880&q=ERR_UPLOAD_FILE_CHANGED&can=2

Body:
I have a simple HTML form that sends an selected file via AJAX to an API endpoint.

If I do the following steps:

Press the Upload button and make an POST request to upload the file

Change the selected file on the filesystem (in a text editor), without picking it again in the file picker.

Press the Upload button again, and make as second POST request

Chrome will fail the second request with an error: net::ERR_UPLOAD_FILE_CHANGED. Note that if you change the file before the initial upload, the file will be uploaded without a problem. The error happens only on the second upload, when you change the file after an initial successful upload. I am testing this with CSV files, and changing them in a text editor.

There does not seem to be a way to isolate that error.

Is there any way around this?

If not, is it possible to catch this specific error, and display a meaningful message to the user. The error that Fetch returns in the promise has no specific info about this. The only place where I see the ERR_UPLOAD_FILE_CHANGED is in the browser dev console.

I am pretty sure that there was not any problem with this about a year ago (early 2019), as the possibility to re-upload a changed file, played in nicely in our UI flow. Now we need to force the user to pick the file again. So my assumption that this was introduced with a recent chrome update.

Here is a simplified snippet of the code:

        <form enctype="multipart/form-data" action="" method="post" id='theForm'>
                <input type="file" name="csvfile" id="csvfile" value="" />
                <input type="button" name="uploadCSV" value="Upload" id='btnSubmit'/>
        </form>

EDIT: The bug is marked as WontFix on bugs.chromium.org: https://bugs.chromium.org/p/chromium/issues/detail?id=1086707#c7

Body:
I managed to get a more descriptive error using the javascript File Reader. After the the file is changed and the button is pressed for the second time, the FileReader throws a somewhat more descriptive message:

DOMException: The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.

At least this is an error that can be caught and displayed to the user, so they are aware that they need to re-select the file.

Here is the snippet:

<html>
    <head>
        <title>Test</title>
        <script type='text/javascript'>
        document.addEventListener("DOMContentLoaded", function(){

            const button = document.querySelector('#btnSubmit');

            button.addEventListener('click', () => {
                let inputElement = document.getElementById('csvfile');

                for (let i = 0; i < inputElement.files.length; i++) {
                    const file = inputElement.files[i];

                    console.log(file);

                    const reader = new FileReader();
                    reader.readAsText(file, "UTF-8");

                    reader.onload = function (evt) {
                        console.log(evt.target.result);
                    }

                    reader.onerror = function (err) {
                        // read error caught here
                        console.log(err);
                        console.log(err.target.error);
                    }

                }

            });
        });
        </script>

    </head>
    <body>
        <form enctype="multipart/form-data" action="" method="post" id='theForm'>
                <input type="file" name="csvfile" id="csvfile" value="" />
                <input type="button" name="uploadCSV" value="Upload" id='btnSubmit'/>
        </form>
    </body>
</html>

It seems that there is no way around this at the moment (June 2020). There is an open bug on Chromium:

https://bugs.chromium.org/p/chromium/issues/detail?id=1084880&q=ERR_UPLOAD_FILE_CHANGED&can=2


问:
Iterating over Numpy Array rows in python even with 1 row / 2 columns array
I am trying to iterate over the rows of a numpy array. The array may consist of two columns and multiple rows like [[a, b], [c, d], ...], or sometimes a single row like [a, b].

For the one-dimensional array, when I use enumerate to iterate over rows, python yields the individual elements a then b instead of the complete row [a, b] all at once.

How to I iterate the one-dimensional case in the same way as I would the 2D case?

答:
Numpy iterates over the first dimension no matter what. Check the shape before you iterate.

```<code>>>> x = np.array([1, 2])
>>> x.ndim
1

>>> y = np.array([[1, 2], [3, 4], [5, 6]])
>>> y.ndim
2
</code>```

Probably the simplest method is to always wrap in a call to np.array:

```<code>>>> x = np.array(x, ndmin=2, copy=False)
>>> y = np.array(y, ndmin=2, copy=False)
</code>```

This will prepend a dimension of shape 1 to your array as necessary. It has the advantage that your inputs don't even have to be arrays, just something that can be converted to an array.

Another option is to use the atleast_2d function:

```<code>>>> x = np.atleast_2d(x)
</code>```

All that being said, you are likely sacrificing most of the benefits of using numpy in the first place by attempting a vanilla python loop. Try to vectorize your operation instead.

Body:
Numpy iterates over the first dimension no matter what. Check the shape before you iterate.

>>> x = np.array([1, 2])
>>> x.ndim
1

>>> y = np.array([[1, 2], [3, 4], [5, 6]])
>>> y.ndim
2

Probably the simplest method is to always wrap in a call to np.array:

>>> x = np.array(x, ndmin=2, copy=False)
>>> y = np.array(y, ndmin=2, copy=False)

This will prepend a dimension of shape 1 to your array as necessary. It has the advantage that your inputs don't even have to be arrays, just something that can be converted to an array.

Another option is to use the atleast_2d function:

>>> x = np.atleast_2d(x)

All that being said, you are likely sacrificing most of the benefits of using numpy in the first place by attempting a vanilla python loop. Try to vectorize your operation instead.


问:
updateOne with multiple parameter set to true not working in mongodb 3.6.1
We upgraded to a newer db running Mongo 3.6.18 and existing code has stopped working.

(After countless hours of soul searching and nail biting...) I have traced it to the following code:

```<code>    $this->st_manager->update_record(
                    [
                        'user_id'       => $driverId,
                        'Display_lng'   => $item['lng'],
                        'Display_lat'   => $item['lat'],
                    ], [
                        '$set' => $update_params,
                    ], [
                        'upsert'        => false,
                        'multiple'      => true,
                    ]
                );
</code>```

My update_record code is simply this:

```<code>    public function update_record( $findquery, $newdata, $option ) {
    $this->collection->updateOne( $findquery, $newdata, $option );
}
</code>```

答:
.updateOne() doesn't have multiple option, as it's intended to update only one document.

If you want to update multiple documents use .updateMany() instead.

Note that .updateMany() doesn't need the option multiple to be passed (and doesn't accept it), as it's already intended to update multiple documents.

Body:
We upgraded to a newer db running Mongo 3.6.18 and existing code has stopped working.

(After countless hours of soul searching and nail biting...) I have traced it to the following code:

    $this->st_manager->update_record(
                    [
                        'user_id'       => $driverId,
                        'Display_lng'   => $item['lng'],
                        'Display_lat'   => $item['lat'],
                    ], [
                        '$set' => $update_params,
                    ], [
                        'upsert'        => false,
                        'multiple'      => true,
                    ]
                );

My update_record code is simply this:

    public function update_record( $findquery, $newdata, $option ) {
    $this->collection->updateOne( $findquery, $newdata, $option );
}


问:
Adding disqus to post.html breaks the whole page in github pages
I have such Github pages - https://github.com/Diyago/Diyago.github.io

Its created from a template using Jekyll. To add comments section, I created post.html with disqus code sniptset under __layour folder:

```<code><div id="disqus_thread"></div>
<script>

/**
*  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://https-diyago-github-io.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</code>```

Disqus itself seems to work - fine, but the whole site content disappeared.

But should this information as well:

How to fix the problem?

答:
Fixed this way in post.html</p>

```<code>---
layout: default
---
<article class="post h-entry" itemscope itemtype="http://schema.org/BlogPosting">
  <link href = "images/icon.png" rel="icon" type="image/png">
  <header class="post-header">
    <h1 class="post-title p-name" itemprop="name headline">{{ page.title | escape }}</h1>
    <p class="post-meta">
      {%- assign date_format = site.minima.date_format | default: "%b %-d, %Y" -%}
      <time class="dt-published" datetime="{{ page.date | date_to_xmlschema }}" itemprop="datePublished">
        {{ page.date | date: date_format }}
      </time>
      {%- if page.modified_date -%}
        ~
        {%- assign mdate = page.modified_date | date_to_xmlschema -%}
        <time class="dt-modified" datetime="{{ mdate }}" itemprop="dateModified">
          {{ mdate | date: date_format }}
        </time>
      {%- endif -%}
      {%- if page.author -%}
        • {% for author in page.author %}
          <span itemprop="author" itemscope itemtype="http://schema.org/Person">
            <span class="p-author h-card" itemprop="name">{{ author }}</span></span>
            {%- if forloop.last == false %}, {% endif -%}
        {% endfor %}
      {%- endif -%}</p>

  </header>
  <link href = "images/icon.png" rel="icon" type="image/png">
  <div class="post-content e-content" itemprop="articleBody">
    {{ content }}
  </div>

  {%- if site.disqus.shortname -%}
    {%- include disqus_comments.html -%}
  {%- endif -%}

  <a class="u-url" href="{{ page.url | relative_url }}" hidden></a>
</article>
<link href = "images/icon.png" rel="icon" type="image/png">

<div id="disqus_thread"></div>
<script>

/**
*  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://https-diyago-github-io.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</code>```

Body:
I have such Github pages - https://github.com/Diyago/Diyago.github.io

Its created from a template using Jekyll. To add comments section, I created post.html with disqus code sniptset under __layour folder:

Please enable JavaScript to view the comments powered by Disqus.

Disqus itself seems to work - fine, but the whole site content disappeared.

But should this information as well:

How to fix the problem?

Body:
Fixed this way in post.html

---
layout: default
---
<article class="post h-entry" itemscope itemtype="http://schema.org/BlogPosting">
  <link href = "images/icon.png" rel="icon" type="image/png">
  <header class="post-header">
    <h1 class="post-title p-name" itemprop="name headline">{{ page.title | escape }}</h1>
    <p class="post-meta">
      {%- assign date_format = site.minima.date_format | default: "%b %-d, %Y" -%}
      <time class="dt-published" datetime="{{ page.date | date_to_xmlschema }}" itemprop="datePublished">
        {{ page.date | date: date_format }}
      </time>
      {%- if page.modified_date -%}
        ~
        {%- assign mdate = page.modified_date | date_to_xmlschema -%}
        <time class="dt-modified" datetime="{{ mdate }}" itemprop="dateModified">
          {{ mdate | date: date_format }}
        </time>
      {%- endif -%}
      {%- if page.author -%}
        • {% for author in page.author %}
          <span itemprop="author" itemscope itemtype="http://schema.org/Person">
            <span class="p-author h-card" itemprop="name">{{ author }}</span></span>
            {%- if forloop.last == false %}, {% endif -%}
        {% endfor %}
      {%- endif -%}</p>

  </header>
  <link href = "images/icon.png" rel="icon" type="image/png">
  <div class="post-content e-content" itemprop="articleBody">
    {{ content }}
  </div>

  {%- if site.disqus.shortname -%}
    {%- include disqus_comments.html -%}
  {%- endif -%}

  <a class="u-url" href="{{ page.url | relative_url }}" hidden></a>
</article>
<link href = "images/icon.png" rel="icon" type="image/png">

<div id="disqus_thread"></div>
<script>

/**
*  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://https-diyago-github-io.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>


问:
How to get a pk from Django URL into ajax
I have a django url that uses a primary key in it, and I want to be able to reference it in my javascript/ajax snippet. I can't find any examples online though, is this possible or do I need to do something like remove all letters from the url?

urls.py

```<code>path('survey/<int:pk>/record_question/', QuestionRecordView.as_view(), name='survey-question-record'),
</code>```

答:
There are couple of ways to do this.
Easiest way is the following.

You can always get the url parameter in the template layer by using the syntax {{ param_name }}

So, if your url is

```<code>path('survey/<int:pk>/record_question/', QuestionRecordView.as_view(), name='survey-question-record'),
</code>```

then use,

```<code>{{ pk }}
</code>```

in your template HTML file. This will give you access to the url parameter --> pk.

To pass this value to your ajax you can declare this value inside a script tag in your html and then call your ajax function with this as an argument.

eg:

```<code><script>
    var pk = {{ pk }} ;
</script>
</code>```

Next you can use this variable in a js file ajax function or in the same html. If you are using a separate js file, just make sure to link that js file to this html.

eg:

```<code><script>
    Foo.foo = {
            id = pk
            $.ajax({
                url: url,
                data: {
                    'id': id
                },
                success: function (data) {
                   your_logic
                }
            });
        },
    }
</script>
</code>```

Body:
I have a django url that uses a primary key in it, and I want to be able to reference it in my javascript/ajax snippet. I can't find any examples online though, is this possible or do I need to do something like remove all letters from the url?

urls.py

path('survey/<int:pk>/record_question/', QuestionRecordView.as_view(), name='survey-question-record'),

Body:
There are couple of ways to do this.
Easiest way is the following.

You can always get the url parameter in the template layer by using the syntax {{ param_name }}

So, if your url is

path('survey/<int:pk>/record_question/', QuestionRecordView.as_view(), name='survey-question-record'),

then use,

{{ pk }}

in your template HTML file. This will give you access to the url parameter --> pk.

To pass this value to your ajax you can declare this value inside a script tag in your html and then call your ajax function with this as an argument.

eg:

<script>
    var pk = {{ pk }} ;
</script>

Next you can use this variable in a js file ajax function or in the same html. If you are using a separate js file, just make sure to link that js file to this html.

eg:

<script>
    Foo.foo = {
            id = pk
            $.ajax({
                url: url,
                data: {
                    'id': id
                },
                success: function (data) {
                   your_logic
                }
            });
        },
    }
</script>


问:
How to solve linear symbolic equations in matlab
I'm trying to solve the following linear symbolic system (20 equations) in Matlab, I get all the values in the solution as zeros, is there any mistake in my implementation?
the data used in the code is here
data</p>

```<code>%---------------------
% clear and close all
%---------------------
clearvars
close all
clc
%---------------------
% Data type long
%---------------------
format long g
%---------------------
% Read data
%---------------------
load('data.mat')
%---------------------------
% Symbolic variables
syms X11 X12 X13 X14 X21 X22 X23 X24 X31 X32 X33 X34 X41 X42 X43 X44;
%========================
% Quadric 4 x 4 matrix
Q = [X11, X12, X13, X14;
    X21, X22, X23, X24;
    X31, X32, X33, X34;
    X41, X42, X43, X44];

% loop all projections
for i=1:10
    % for wach projection matrix
    P = PPM(:, :, i);

    % Autocalibration equation
    DIAC(3*(i-1)+1:3*i,:) = P * Q * P';

    L(2*(i-1)+1:2*i,1) = DIAC(3*(i-1)+1:3*i-1,3)==0 ;
end

[A,B] = equationsToMatrix(L,[X11, X12, X13, X14,...
     X21, X22, X23, X24, X31, X32, X33, X34,X41, X42, X43, X44]);

Sol = linsolve(A,B)
</code>```

答:
The solution is explained at this site, following the explanation I have got:</p>

```<code>[Mat,B] = equationsToMatrix(L,[X11, X12, X13, X14,...
     X21, X22, X23, X24, X31, X32, X33, X34,X41, X42, X43, X44]);
% Solution is here
Sol = linsolve(Mat,B);
</code>```

Body:
I'm trying to solve the following linear symbolic system (20 equations) in Matlab, I get all the values in the solution as zeros, is there any mistake in my implementation?
the data used in the code is here
data

%---------------------
% clear and close all
%---------------------
clearvars
close all
clc
%---------------------
% Data type long
%---------------------
format long g
%---------------------
% Read data
%---------------------
load('data.mat')
%---------------------------
% Symbolic variables
syms X11 X12 X13 X14 X21 X22 X23 X24 X31 X32 X33 X34 X41 X42 X43 X44;
%========================
% Quadric 4 x 4 matrix
Q = [X11, X12, X13, X14;
    X21, X22, X23, X24;
    X31, X32, X33, X34;
    X41, X42, X43, X44];

% loop all projections
for i=1:10
    % for wach projection matrix
    P = PPM(:, :, i);

    % Autocalibration equation
    DIAC(3*(i-1)+1:3*i,:) = P * Q * P';

    L(2*(i-1)+1:2*i,1) = DIAC(3*(i-1)+1:3*i-1,3)==0 ;
end

[A,B] = equationsToMatrix(L,[X11, X12, X13, X14,...
     X21, X22, X23, X24, X31, X32, X33, X34,X41, X42, X43, X44]);

Sol = linsolve(A,B)

Body:
The solution is explained at this site, following the explanation I have got:

[Mat,B] = equationsToMatrix(L,[X11, X12, X13, X14,...
     X21, X22, X23, X24, X31, X32, X33, X34,X41, X42, X43, X44]);
% Solution is here
Sol = linsolve(Mat,B);


问:
React native not re-rendering after state change
I was trying to make an authentication flow using context api and reducer ,
I had a file named GlobalState where I am keeping all my authentication state with tokens.I also had reducer to update the state.
Inside my GlobalState file there is function loginFb which will update the state according to the response from my rest API .
When I try to console the sate I can see that my state is changed after login , but my app is not re-rendering . I am expecting my app to re-render  on  state change and move to HomeStackScreens .

following is my app.js

```<code>import 'react-native-gesture-handler';
import React, {useContext} from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createMaterialBottomTabNavigator} from '@reactnavigation/material-bottom-tabs';
import {createStackNavigator} from '@react-navigation/stack';
import AsyncStorage from '@react-native-community/async-storage';
import HomeTabs from './screens/HomeTabs';
import Login from './screens/Login';
import {GlobalContext, GlobalProvider} from './context/GlobalState';

const AuthStack = createStackNavigator();
const HomeStack = createStackNavigator();

const AuthStackScreen = () => {
  return (
    <AuthStack.Navigator screenOptions={{}}>
      <AuthStack.Screen name="Login" component={Login} />
    </AuthStack.Navigator>
  );
};

const HomeStackScreens = () => {
  return (
    <HomeStack.Navigator
      screenOptions={{
        headerTintColor: 'white',
        headerStyle: {backgroundColor: '#37966f', elevation: 0},
      }}>
      <HomeStack.Screen name="Home" component={HomeTabs} />
    </HomeStack.Navigator>
  );
};

function App() {

  React.useEffect(() => {
    // Fetch the token from storage then navigate to our appropriate place
    const bootstrapAsync = async () => {
      let userToken;
      console.log('is Signedin :', isSignedIn);

      try {
        userToken = await AsyncStorage.getItem('authTocken');
        if (userToken) console.log('autTocken:' + userToken);
        else console.log('no tocken');
      } catch (e) {

        console.log('no tocken');
      }

    };

    bootstrapAsync();
  }, []);
  const {authState, isSignedIn} = useContext(GlobalContext);
  return (
    <GlobalProvider>
      <NavigationContainer>
        {console.log('from app:', authState, 'signedin', isSignedIn)}
        {isSignedIn ? <HomeStackScreens /> : <AuthStackScreen />}
      </NavigationContainer>
    </GlobalProvider>
  );
}

export default App;
</code>```

Globalstate.js

```<code>import React, {createContext, useReducer} from 'react';
import AppReducer from './AppReducers';
import AsyncStorage from '@react-native-community/async-storage';

//Initial State

const initialState = {
  authTocken: '',
  refreshTocken: '',
  fbToken: '',
  isSignedIn: false,
};

export const GlobalContext = createContext(initialState);
export const GlobalProvider = ({children}) => {
  const [authState, dispatch] = useReducer(AppReducer, initialState);

  async function loginFb(fbToken) {
    // loginFb: async fbToken=>{
    await fetch(
      'https://api_url?accessToken=' +
        fbToken,
      {
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      },
    )
      .then((resp) => resp.json())
      .then(async function (data) {
        await AsyncStorage.setItem('authTocken', data.token);
        await AsyncStorage.setItem('refreshTocken', data.refreshToken);
        await AsyncStorage.setItem('fbToken', fbToken);
        dispatch({
          type: 'SIGN_IN',
          payload: data,
        });
      })
      .catch((error) => {
        console.log('found error', error);
      });
  }
  return (
    <GlobalContext.Provider
      value={{authState, loginFb, isSignedIn: authState.isSignedIn}}>
      {children}
    </GlobalContext.Provider>
  );
};
</code>```

AppReducer.js

```<code>export default (state, action) => {
  switch (action.type) {
    case 'SIGN_IN': {
      return {
        ...state,
        isSignedIn: true,
        refreshTocken: action.payload.refreshToken,
        authTocken: action.payload.token,
      };
    }

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

答:
instead of having

```<code>export default App;
</code>```

changed to

```<code>export default () => (
  <GlobalProvider>
     <App />
   </GlobalProvider>
    )
</code>```

now its working

Body:
I was trying to make an authentication flow using context api and reducer ,
I had a file named GlobalState where I am keeping all my authentication state with tokens.I also had reducer to update the state.
Inside my GlobalState file there is function loginFb which will update the state according to the response from my rest API .
When I try to console the sate I can see that my state is changed after login , but my app is not re-rendering . I am expecting my app to re-render  on  state change and move to HomeStackScreens .

following is my app.js

import 'react-native-gesture-handler';
import React, {useContext} from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createMaterialBottomTabNavigator} from '@reactnavigation/material-bottom-tabs';
import {createStackNavigator} from '@react-navigation/stack';
import AsyncStorage from '@react-native-community/async-storage';
import HomeTabs from './screens/HomeTabs';
import Login from './screens/Login';
import {GlobalContext, GlobalProvider} from './context/GlobalState';

const AuthStack = createStackNavigator();
const HomeStack = createStackNavigator();

const AuthStackScreen = () => {
  return (
    <AuthStack.Navigator screenOptions={{}}>
      <AuthStack.Screen name="Login" component={Login} />
    </AuthStack.Navigator>
  );
};

const HomeStackScreens = () => {
  return (
    <HomeStack.Navigator
      screenOptions={{
        headerTintColor: 'white',
        headerStyle: {backgroundColor: '#37966f', elevation: 0},
      }}>
      <HomeStack.Screen name="Home" component={HomeTabs} />
    </HomeStack.Navigator>
  );
};

function App() {

  React.useEffect(() => {
    // Fetch the token from storage then navigate to our appropriate place
    const bootstrapAsync = async () => {
      let userToken;
      console.log('is Signedin :', isSignedIn);

      try {
        userToken = await AsyncStorage.getItem('authTocken');
        if (userToken) console.log('autTocken:' + userToken);
        else console.log('no tocken');
      } catch (e) {

        console.log('no tocken');
      }

    };

    bootstrapAsync();
  }, []);
  const {authState, isSignedIn} = useContext(GlobalContext);
  return (
    <GlobalProvider>
      <NavigationContainer>
        {console.log('from app:', authState, 'signedin', isSignedIn)}
        {isSignedIn ? <HomeStackScreens /> : <AuthStackScreen />}
      </NavigationContainer>
    </GlobalProvider>
  );
}

export default App;

Globalstate.js

import React, {createContext, useReducer} from 'react';
import AppReducer from './AppReducers';
import AsyncStorage from '@react-native-community/async-storage';

//Initial State

const initialState = {
  authTocken: '',
  refreshTocken: '',
  fbToken: '',
  isSignedIn: false,
};

export const GlobalContext = createContext(initialState);
export const GlobalProvider = ({children}) => {
  const [authState, dispatch] = useReducer(AppReducer, initialState);

  async function loginFb(fbToken) {
    // loginFb: async fbToken=>{
    await fetch(
      'https://api_url?accessToken=' +
        fbToken,
      {
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      },
    )
      .then((resp) => resp.json())
      .then(async function (data) {
        await AsyncStorage.setItem('authTocken', data.token);
        await AsyncStorage.setItem('refreshTocken', data.refreshToken);
        await AsyncStorage.setItem('fbToken', fbToken);
        dispatch({
          type: 'SIGN_IN',
          payload: data,
        });
      })
      .catch((error) => {
        console.log('found error', error);
      });
  }
  return (
    <GlobalContext.Provider
      value={{authState, loginFb, isSignedIn: authState.isSignedIn}}>
      {children}
    </GlobalContext.Provider>
  );
};

AppReducer.js

export default (state, action) => {
  switch (action.type) {
    case 'SIGN_IN': {
      return {
        ...state,
        isSignedIn: true,
        refreshTocken: action.payload.refreshToken,
        authTocken: action.payload.token,
      };
    }

    default:
      return state;
  }
};

Body:
instead of having

export default App;

changed to

export default () => (
  <GlobalProvider>
     <App />
   </GlobalProvider>
    )

now its working


问:
Add column of empty lists to DataFrame
Similar to this question How to add an empty column to a dataframe?, I am interested in knowing the best way to add a column of empty lists to a DataFrame.

What I am trying to do is basically initialize a column and as I iterate over the rows to process some of them, then add a filled list in this new column to replace the initialized value.

For example, if below is my initial DataFrame:

```<code>df = pd.DataFrame(d = {'a': [1,2,3], 'b': [5,6,7]}) # Sample DataFrame

>>> df
   a  b
0  1  5
1  2  6
2  3  7
</code>```

Then I want to ultimately end up with something like this, where each row has been processed separately (sample results shown):

```<code>>>> df
   a  b          c
0  1  5     [5, 6]
1  2  6     [9, 0]
2  3  7  [1, 2, 3]
</code>```

Of course, if I try to initialize like df['e'] = [] as I would with any other constant, it thinks I am trying to add a sequence of items with length 0, and hence fails.

If I try initializing a new column as None or NaN, I run in to the following issues when trying to assign a list to a location.

```<code>df['d'] = None

>>> df
   a  b     d
0  1  5  None
1  2  6  None
2  3  7  None
</code>```

Issue 1 (it would be perfect if I can get this approach to work! Maybe something trivial I am missing):

```<code>>>> df.loc[0,'d'] = [1,3]

...
ValueError: Must have equal len keys and value when setting with an iterable
</code>```

Issue 2 (this one works, but not without a warning because it is not guaranteed to work as intended):

```<code>>>> df['d'][0] = [1,3]

C:\Python27\Scripts\ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
</code>```

Hence I resort to initializing with empty lists and extending them as needed. There are a couple of methods I can think of to initialize this way, but is there a more straightforward way?

Method 1:

```<code>df['empty_lists1'] = [list() for x in range(len(df.index))]

>>> df
   a  b   empty_lists1
0  1  5             []
1  2  6             []
2  3  7             []
</code>```

Method 2:

```<code> df['empty_lists2'] = df.apply(lambda x: [], axis=1)

>>> df
   a  b   empty_lists1   empty_lists2
0  1  5             []             []
1  2  6             []             []
2  3  7             []             []
</code>```

Summary of questions:

Is there any minor syntax change that can be addressed in Issue 1 that can allow a list to be assigned to a None/NaN initialized field?

If not, then what is the best way to initialize a new column with empty lists?

答:
Canonical solutions: List comprehension, map and apply

Obligatory disclaimer: avoid using lists in pandas columns where possible, list columns are slow to work with because they are objects and those are inherently hard to vectorize.

With that out of the way, here are the canonical methods of introducing a column of empty lists:

```<code># List comprehension
df['c'] = [[] for _ in range(df.shape[0])]
df

   a  b   c
0  1  5  []
1  2  6  []
2  3  7  []
</code>```

There's also these shorthands involving apply and map:

```<code>from collections import defaultdict
# map any column with defaultdict
df['c'] = df.iloc[:,0].map(defaultdict(list))
# same as,
df['c'] = df.iloc[:,0].map(lambda _: [])

# apply with defaultdict
df['c'] = df.apply(defaultdict(list), axis=1)
# same as,
df['c'] = df.apply(lambda _: [], axis=1)

df

   a  b   c
0  1  5  []
1  2  6  []
2  3  7  []
</code>```

Things you should NOT do

Some folks believe multiplying an empty list is the way to go, unfortunately this is wrong and will usually lead to hard-to-debug issues. Here's an MVP:

```<code># WRONG
df['c'] = [[]] * len(df)
df.at[0, 'c'].append('abc')
df.at[1, 'c'].append('def')
df

   a  b           c
0  1  5  [abc, def]
1  2  6  [abc, def]
2  3  7  [abc, def]
</code>```

```<code># RIGHT
df['c'] = [[] for _ in range(df.shape[0])]
df.at[0, 'c'].append('abc')
df.at[1, 'c'].append('def')
df

a  b      c
0  1  5  [abc]
1  2  6  [def]
2  3  7     []
</code>```

In the first case, a single empty list is created and its reference is replicated across all the rows, so you see updates to one reflected to all of them. In the latter case each row is assigned its own empty list, so this is not a concern.

Title: Add column of empty lists to DataFrame

Body:
Similar to this question How to add an empty column to a dataframe?, I am interested in knowing the best way to add a column of empty lists to a DataFrame.

What I am trying to do is basically initialize a column and as I iterate over the rows to process some of them, then add a filled list in this new column to replace the initialized value.

For example, if below is my initial DataFrame:

df = pd.DataFrame(d = {'a': [1,2,3], 'b': [5,6,7]}) # Sample DataFrame

>>> df
   a  b
0  1  5
1  2  6
2  3  7

Then I want to ultimately end up with something like this, where each row has been processed separately (sample results shown):

>>> df
   a  b          c
0  1  5     [5, 6]
1  2  6     [9, 0]
2  3  7  [1, 2, 3]

Of course, if I try to initialize like df['e'] = [] as I would with any other constant, it thinks I am trying to add a sequence of items with length 0, and hence fails.

If I try initializing a new column as None or NaN, I run in to the following issues when trying to assign a list to a location.

df['d'] = None

>>> df
   a  b     d
0  1  5  None
1  2  6  None
2  3  7  None

Issue 1 (it would be perfect if I can get this approach to work! Maybe something trivial I am missing):

>>> df.loc[0,'d'] = [1,3]

...
ValueError: Must have equal len keys and value when setting with an iterable

Issue 2 (this one works, but not without a warning because it is not guaranteed to work as intended):

>>> df['d'][0] = [1,3]

C:\Python27\Scripts\ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

Hence I resort to initializing with empty lists and extending them as needed. There are a couple of methods I can think of to initialize this way, but is there a more straightforward way?

Method 1:

df['empty_lists1'] = [list() for x in range(len(df.index))]

>>> df
   a  b   empty_lists1
0  1  5             []
1  2  6             []
2  3  7             []

Method 2:

 df['empty_lists2'] = df.apply(lambda x: [], axis=1)

>>> df
   a  b   empty_lists1   empty_lists2
0  1  5             []             []
1  2  6             []             []
2  3  7             []             []

Summary of questions:

Is there any minor syntax change that can be addressed in Issue 1 that can allow a list to be assigned to a None/NaN initialized field?

If not, then what is the best way to initialize a new column with empty lists?

Body:
Canonical solutions: List comprehension, map and apply

Obligatory disclaimer: avoid using lists in pandas columns where possible, list columns are slow to work with because they are objects and those are inherently hard to vectorize.

With that out of the way, here are the canonical methods of introducing a column of empty lists:

# List comprehension
df['c'] = [[] for _ in range(df.shape[0])]
df

   a  b   c
0  1  5  []
1  2  6  []
2  3  7  []

There's also these shorthands involving apply and map:

from collections import defaultdict
# map any column with defaultdict
df['c'] = df.iloc[:,0].map(defaultdict(list))
# same as,
df['c'] = df.iloc[:,0].map(lambda _: [])

# apply with defaultdict
df['c'] = df.apply(defaultdict(list), axis=1)
# same as,
df['c'] = df.apply(lambda _: [], axis=1)

df

   a  b   c
0  1  5  []
1  2  6  []
2  3  7  []

Things you should NOT do

Some folks believe multiplying an empty list is the way to go, unfortunately this is wrong and will usually lead to hard-to-debug issues. Here's an MVP:

# WRONG
df['c'] = [[]] * len(df)
df.at[0, 'c'].append('abc')
df.at[1, 'c'].append('def')
df

   a  b           c
0  1  5  [abc, def]
1  2  6  [abc, def]
2  3  7  [abc, def]

# RIGHT
df['c'] = [[] for _ in range(df.shape[0])]
df.at[0, 'c'].append('abc')
df.at[1, 'c'].append('def')
df

a  b      c
0  1  5  [abc]
1  2  6  [def]
2  3  7     []

In the first case, a single empty list is created and its reference is replicated across all the rows, so you see updates to one reflected to all of them. In the latter case each row is assigned its own empty list, so this is not a concern.


问:
How to eliminate elements with certain characters or phrases from a list in python?
I have a list of plant names from an excel spreadsheet that I have extracted with pandas. After removing duplicates and making the entire list lower-case, I wanted to remove characters like parenthesis, apostrophes, dashes, and phrases like "A" and "The" to further eliminate any possible duplicates so that in a list like: ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin") only "Pumpkin" would remain. Note I don't want to remove just the characters from the string, but the entire string from the list.

```<code>def checkSyntax(str):
    boolean = None

    regexes = ["a ", "the ", "^\W"]
    combined = "(" + ")|(".join(regexes) + ")"
    match = re.match('combined', str)
    if match == None:
        boolean = True

    return boolean

def elimInvalidNames(names):
    new_names = [s for s in names if checkSyntax(s)]
    return new_names

test_list = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")
test_list = list(map(lambda x: x.lower(), test_list))
test_list = elimInvalidNames(test_list)
print(test_list)
</code>```

For some reason this gets rid of "the" and "a" but not parenthesis, dashes, or apostrophes.

答:
If you want to use regular expressions, then use re.search as this will attempt to match the expression at any part of the string. The re.match function only attempts to match the expression at the start of the string.

For example, the following code filters the list to ['Pumpkin']:

```<code>import re
invalid_names_re = re.compile(r"(A )|(The )|[()\-']", re.IGNORECASE)                                                                                names = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")

filtered_names = [name for name in names if not invalid_names_re.search(name)]
</code>```

Body:
I have a list of plant names from an excel spreadsheet that I have extracted with pandas. After removing duplicates and making the entire list lower-case, I wanted to remove characters like parenthesis, apostrophes, dashes, and phrases like "A" and "The" to further eliminate any possible duplicates so that in a list like: ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin") only "Pumpkin" would remain. Note I don't want to remove just the characters from the string, but the entire string from the list.

def checkSyntax(str):
    boolean = None

    regexes = ["a ", "the ", "^\W"]
    combined = "(" + ")|(".join(regexes) + ")"
    match = re.match('combined', str)
    if match == None:
        boolean = True

    return boolean

def elimInvalidNames(names):
    new_names = [s for s in names if checkSyntax(s)]
    return new_names

test_list = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")
test_list = list(map(lambda x: x.lower(), test_list))
test_list = elimInvalidNames(test_list)
print(test_list)

For some reason this gets rid of "the" and "a" but not parenthesis, dashes, or apostrophes.

Body:
If you want to use regular expressions, then use re.search as this will attempt to match the expression at any part of the string. The re.match function only attempts to match the expression at the start of the string.

For example, the following code filters the list to ['Pumpkin']:

import re
invalid_names_re = re.compile(r"(A )|(The )|[()\-']", re.IGNORECASE)                                                                                names = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")

filtered_names = [name for name in names if not invalid_names_re.search(name)]


问:
Pyspark - Reading JSON from each file from a directory and putting it into its own Dataframe
I want to create 1 dataframe per file found in the directory

Json in each file looks like:

```<code>[{
    "a": "Need Help",
    "b": 6377,
    "c": "Member",
    "d": 721,
    "timestamp": 1590990807.475662
  },
  {
    "a": "Need Help",
    "b": 6377,
    "c": "Member",
    "d": 721,
    "timestamp": 1590990807.475673
  },
  {
    "a": "Need Help",
    "b": 6377,
    "c": "Member",
    "d": 721,
    "timestamp": 1590990807.475678
  }]
</code>```

I could do that with below code:

```<code>rdd = sparkSession.sparkContext.wholeTextFiles("/content/sample_data/test_data")
dict = rdd.collectAsMap()
for row,value in dict.items():
 df = spark.read.json(row)
 df.show()
</code>```

Is there a better way to achieve the same?
Thanks in Advance.

答:
I think the creation of the first rdd is redundant, why not just iterate over the text files in the directory and create a dataframe for each file?

import glob

path = /content/sample_data/test_data

all_files = glob.glob(path + "/*.txt")

for filename in all_files:
    df = spark.read.json(filename)
    df.show()
```

Body:
I want to create 1 dataframe per file found in the directory

Json in each file looks like:

[{
    "a": "Need Help",
    "b": 6377,
    "c": "Member",
    "d": 721,
    "timestamp": 1590990807.475662
  },
  {
    "a": "Need Help",
    "b": 6377,
    "c": "Member",
    "d": 721,
    "timestamp": 1590990807.475673
  },
  {
    "a": "Need Help",
    "b": 6377,
    "c": "Member",
    "d": 721,
    "timestamp": 1590990807.475678
  }]

I could do that with below code:

rdd = sparkSession.sparkContext.wholeTextFiles("/content/sample_data/test_data")
dict = rdd.collectAsMap()
for row,value in dict.items():
 df = spark.read.json(row)
 df.show()

Is there a better way to achieve the same?
Thanks in Advance.


问:
How to save output in python to .txt file
So basically i bought a book that teaches the basics of python and how to create a random number generator so I decided to go one step further and make a random password generator I found a tutorial online that gave me a good example of why and what is used to make a password generator but i want the output to be saved to a .txt file I do not know what i need to implement to get the result i want this is what i have i'm using python3.

```<code>import random

chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, @,#$%^&*.'

number = input('Number of passwords - ')
number = int(number)

length = input('password length? - ')
length = int(length)

answer = input

for P in range(number):
    password = ''
for C in range(length):
    password += random.choice(chars)
    print(password)

password = open("passlist.txt", "a")
password.write(password)
password.close()

file = open('passlist', 'w')
file.write(password)
file.close()
</code>```

this is what i get in shell

```<code> Traceback (most recent call last):
      File "C:\User\Desktop\passgen.py", line 21, in <module>
        password.write(password)
    TypeError: write() argument must be str, not _io.TextIOWrapper
</code>```

答:
When you open a new file and set it equal to a variable, you are actually creating an _io.TextIOWrapper object. So in this line of code, you are creating this object and storing it in password, getting rid of the password generated in the previous lines of code.

password = open("passlist.txt", "a")

You are then trying to write to the passlist.txt file with this line:

password.write(password)

You are telling password, now an _io.TextIOWrapper object, to write to the passfile.txt the _io.TextIOWrapper object, not the password generated beforehand. This function is expecting a string, and you are now passing an _io.TextIOWrapper object. Since password is no longer a string, that is why you are running into the error.

To fix this, I would suggest creating a new variable:

```<code>txtFileWriter = open("passlist.txt", "a")
txtFileWriter.write(password)
txtFileWriter.close()
</code>```

You may find that after fixing this, only one value is being stored inside your text file. I would recommend properly nesting your for loops:

```<code>for P in range(number):
    password = ''
    for C in range(length):
        password += random.choice(chars)
    print(password)
</code>```

The meaning of these for loops can be translated as:
For each password, set the password = ' ' and for each character, add one random character to password.

The problem with this is that you will only have one password after the for loops are complete. You are setting the password value to ' ' each time you run through the outer loop. The only password that will be saved, will be the last value. In order to fix this, I recommend using a list.

I recommend reading through this documentation

I don't want to spoon feed the answers since I realize you are learning python, so I will leave it here. You will want to create a list and then append a value to that list each time you generate a password. After some reading, hopefully this will make sense.

Body:
So basically i bought a book that teaches the basics of python and how to create a random number generator so I decided to go one step further and make a random password generator I found a tutorial online that gave me a good example of why and what is used to make a password generator but i want the output to be saved to a .txt file I do not know what i need to implement to get the result i want this is what i have i'm using python3.

import random

chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, @,#$%^&*.'

number = input('Number of passwords - ')
number = int(number)

length = input('password length? - ')
length = int(length)

answer = input

for P in range(number):
    password = ''
for C in range(length):
    password += random.choice(chars)
    print(password)

password = open("passlist.txt", "a")
password.write(password)
password.close()

file = open('passlist', 'w')
file.write(password)
file.close()

this is what i get in shell

 Traceback (most recent call last):
      File "C:\User\Desktop\passgen.py", line 21, in <module>
        password.write(password)
    TypeError: write() argument must be str, not _io.TextIOWrapper

Body:
When you open a new file and set it equal to a variable, you are actually creating an _io.TextIOWrapper object. So in this line of code, you are creating this object and storing it in password, getting rid of the password generated in the previous lines of code.

password = open("passlist.txt", "a")

You are then trying to write to the passlist.txt file with this line:

password.write(password)

You are telling password, now an _io.TextIOWrapper object, to write to the passfile.txt the _io.TextIOWrapper object, not the password generated beforehand. This function is expecting a string, and you are now passing an _io.TextIOWrapper object. Since password is no longer a string, that is why you are running into the error.

To fix this, I would suggest creating a new variable:

txtFileWriter = open("passlist.txt", "a")
txtFileWriter.write(password)
txtFileWriter.close()

You may find that after fixing this, only one value is being stored inside your text file. I would recommend properly nesting your for loops:

for P in range(number):
    password = ''
    for C in range(length):
        password += random.choice(chars)
    print(password)

The meaning of these for loops can be translated as:
For each password, set the password = ' ' and for each character, add one random character to password.

The problem with this is that you will only have one password after the for loops are complete. You are setting the password value to ' ' each time you run through the outer loop. The only password that will be saved, will be the last value. In order to fix this, I recommend using a list.

I recommend reading through this documentation

I don't want to spoon feed the answers since I realize you are learning python, so I will leave it here. You will want to create a list and then append a value to that list each time you generate a password. After some reading, hopefully this will make sense.


问:
Django CBV: Programmatically save HTML page to PDF file on the server
Visiting the relevant url, an html page is rendered. I need to programmatically save this html page to a pdf file on the server.

views.py

```<code>class PdfView(DetailView):
    model = TheModel
    template_name = 'pdf.html'
</code>```

urls.py

```<code>urlpatterns = [
    url(
        r'^(?P<pk>[0-9]+)/$',
        PdfDataView.as_view(),
        name='pdf-data',
    ),
]
</code>```

答:
This function worked for me.    </p>

```<code>def render_to_pdf(template_src, context_dict={}):
        template = get_template(template_src)
        html = template.render(context_dict)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        if not pdf.err:
            f = open('test2.pdf', 'wb')
            myfile = File(f)
            myfile.write(result.getvalue())
            return HttpResponse(result.getvalue(), content_type='application/pdf')
        return None
</code>```

Body:
Visiting the relevant url, an html page is rendered. I need to programmatically save this html page to a pdf file on the server.

views.py

class PdfView(DetailView):
    model = TheModel
    template_name = 'pdf.html'

urls.py

urlpatterns = [
    url(
        r'^(?P<pk>[0-9]+)/$',
        PdfDataView.as_view(),
        name='pdf-data',
    ),
]

Body:
This function worked for me.

def render_to_pdf(template_src, context_dict={}):
        template = get_template(template_src)
        html = template.render(context_dict)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        if not pdf.err:
            f = open('test2.pdf', 'wb')
            myfile = File(f)
            myfile.write(result.getvalue())
            return HttpResponse(result.getvalue(), content_type='application/pdf')
        return None


问:
Update XML file with C#
I have a xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<ApplicationConfiguration xmlns="http://test.org/SDK/Configuration.xsd">
    <ApplicationName>
        <ApplicationUri>123</ApplicationUri>
        <ApplicationUri>456</ApplicationUri>
    </ApplicationName>
</ApplicationConfiguration>
</code>```

What I want is set the value of ApplicationUri from 456 to 789 in C# code.

I wrote this code:

```<code>string docaddress = "testfile.xml";

XDocument doc = XDocument.Load(docaddress);
doc.Element("ApplicationConfiguration")
            .Elements("ApplicationName").FirstOrDefault()
            .SetElementValue("ApplicationUri", "789");
doc.Save(docaddress);
</code>```

The problems are:

There is no error while running. I think the element ApplicationConfiguration is not correct. But when I delete the line xmlns=... from the xml file, it runs normally

The value 789 is replaced with 123, but not 456 as I want (same element name)

Can you tell me how to fix those problems?

答:
IMHO, here is an easiest method.

It is taking care of the XML default namespace.

No loops. Set based approach.

c#

```<code>void Main()
{
    const string fileName = @"e:\temp\hala.xml";
    const string searchFor = "456";
    const string replaceWith = "789";

    XDocument doc = XDocument.Load(fileName);
    XNamespace ns = doc.Root.GetDefaultNamespace();

    // step #1: find element based on the search value
    XElement xmlFragment = doc.Descendants(ns + "ApplicationUri")
        .Where(d => d.Value.Equals(searchFor)).FirstOrDefault();

    // step #2: if found, set its value
    if(xmlFragment != null)
        xmlFragment.SetValue(replaceWith);

    doc.Save(fileName);
}
</code>```

Title: Update XML file with C#

Body:
I have a xml file:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationConfiguration xmlns="http://test.org/SDK/Configuration.xsd">
    <ApplicationName>
        <ApplicationUri>123</ApplicationUri>
        <ApplicationUri>456</ApplicationUri>
    </ApplicationName>
</ApplicationConfiguration>

What I want is set the value of ApplicationUri from 456 to 789 in C# code.

I wrote this code:

string docaddress = "testfile.xml";

XDocument doc = XDocument.Load(docaddress);
doc.Element("ApplicationConfiguration")
            .Elements("ApplicationName").FirstOrDefault()
            .SetElementValue("ApplicationUri", "789");
doc.Save(docaddress);

The problems are:

There is no error while running. I think the element ApplicationConfiguration is not correct. But when I delete the line xmlns=... from the xml file, it runs normally

The value 789 is replaced with 123, but not 456 as I want (same element name)

Can you tell me how to fix those problems?

Body:
IMHO, here is an easiest method.

It is taking care of the XML default namespace.

No loops. Set based approach.

c#

void Main()
{
    const string fileName = @"e:\temp\hala.xml";
    const string searchFor = "456";
    const string replaceWith = "789";

    XDocument doc = XDocument.Load(fileName);
    XNamespace ns = doc.Root.GetDefaultNamespace();

    // step #1: find element based on the search value
    XElement xmlFragment = doc.Descendants(ns + "ApplicationUri")
        .Where(d => d.Value.Equals(searchFor)).FirstOrDefault();

    // step #2: if found, set its value
    if(xmlFragment != null)
        xmlFragment.SetValue(replaceWith);

    doc.Save(fileName);
}


问:
How to send data to Thingsboard via HTTP
I am using thingsboard on my local machine (windows) and I need to send data from CSV file  with HTTP POST request, to do so I need to write a JAVA program which will allow sending data from a JSON file  to thingsboard platfom.
Do you have any suggestions how can I do that?

答:
It is quite straight forward, no need to authentications and it's about Telemetry Upload API. Since you do not have any example of your csv, and assuming for that you may find tons of guide I just bring here an example of performing a POST http request to THINGSBOARD server using python http client, based on your requirements it can be done in any language.

you should only:

Convert your data from csv or any format to the following format in data dictionary, with proper timestamp as ts and other variables in a field of values. If you don't put ts it'll stamp the entry time of data on it. The ts must be in milliseconds.

Convert it to json

Use host IP address, the PORT and access token of that device in the url as in the example.

```<code>  import requests, json

  IP, PORT, access_token = ???.???.???.??? # host address of Thingsboard server
  PORT = 8080 # normally it should be 8080
  access_token = XXXXXXXX # you can copy it easily from device panel of Thingsboard

  data = [
    {
      "ts": 1591123823000,
      "values": {
        "TEMPERATURES": 100,
        "DEW_POINT": 28,
        "VALUE_X": 0
      }
    },
    {
      "ts": 1591123883000,
      "values": {
        "TEMPERATURES": 150,
        "DEW_POINT": 26,
        "VALUE_X": 10
      }
    },
    {
      "ts": 1591123943000,
      "values": {
        "TEMPERATURES": 200,
        "DEW_POINT": 25,
        "VALUE_X": -10
      }
    }
  ]

  data = json.dumps(data)

  headers = {'Content-Type': 'application/json',}

  url_post = 'http(s)://{}:{}/api/v1/{}/telemetry'.format(IP, PORT, access_token)

  response = requests.post(url_post, headers=headers, data=data)
</code>```

Body:
It is quite straight forward, no need to authentications and it's about Telemetry Upload API. Since you do not have any example of your csv, and assuming for that you may find tons of guide I just bring here an example of performing a POST http request to THINGSBOARD server using python http client, based on your requirements it can be done in any language.

you should only:

Convert your data from csv or any format to the following format in data dictionary, with proper timestamp as ts and other variables in a field of values. If you don't put ts it'll stamp the entry time of data on it. The ts must be in milliseconds.

Convert it to json

Use host IP address, the PORT and access token of that device in the url as in the example.

  import requests, json

  IP, PORT, access_token = ???.???.???.??? # host address of Thingsboard server
  PORT = 8080 # normally it should be 8080
  access_token = XXXXXXXX # you can copy it easily from device panel of Thingsboard

  data = [
    {
      "ts": 1591123823000,
      "values": {
        "TEMPERATURES": 100,
        "DEW_POINT": 28,
        "VALUE_X": 0
      }
    },
    {
      "ts": 1591123883000,
      "values": {
        "TEMPERATURES": 150,
        "DEW_POINT": 26,
        "VALUE_X": 10
      }
    },
    {
      "ts": 1591123943000,
      "values": {
        "TEMPERATURES": 200,
        "DEW_POINT": 25,
        "VALUE_X": -10
      }
    }
  ]

  data = json.dumps(data)

  headers = {'Content-Type': 'application/json',}

  url_post = 'http(s)://{}:{}/api/v1/{}/telemetry'.format(IP, PORT, access_token)

  response = requests.post(url_post, headers=headers, data=data)


问:
context is slow or being called twice
I have an issue with the Context I am using for my auth. If I console.log when logged in, first I get false, and then a second later it logs again with the token etc. So, something is wrong with my code.

Here is my auth hook:

```<code>import { useState, useCallback, useEffect } from "react";

export const useAuth = () => {
  const [token, setToken] = useState(false);
  const [userId, setUserId] = useState(false);

  const login = useCallback((uid, token) => {
    setToken(token);
    setUserId(uid);
    localStorage.setItem(
      "userData",
      JSON.stringify({
        userId: uid,
        token: token,
      })
    );
  }, []);

  const logout = useCallback(() => {
    setToken(null);
    setUserId(null);
    localStorage.removeItem("userData");
  }, []);

  useEffect(() => {
    const storedData = JSON.parse(localStorage.getItem("userData"));
    if (storedData && storedData.token) {
      login(storedData.userId, storedData.token);
    }
  }, [login]);

  return { token, login, logout, userId };
};
</code>```

The auth context:

```<code>import { createContext } from "react";

export const AuthContext = createContext({
  isLoggedIn: false,
  userId: null,
  token: null,
  login: () => {},
  logout: () => {},
});
</code>```

Example of the component where I have the issue (basically in all components I am using this auth context)

```<code>import React, { useContext, useState } from "react";
import AdminCard from "../components/adminCards/AdminCard";
import { AuthContext } from "../../shared/context/auth-context";

const Dashboard = () => {
  const auth = useContext(AuthContext);
  console.log(auth);
  return (
    <div className="admin-wrapper">
      <div className="main-panel">
        <div className="row">
          <div className="wrapper">
            <div className="col-3">
              <AdminCard title="Contact Enquiries" />
              <AdminCard title="Card 2" />
              <AdminCard title="Card 3" />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
</code>```

In console I first see 'false' and then a second later I see the contents of 'auth'.

Example of App.js

```<code>const App = () => {
   const { token, login, logout, userId } = useAuth();
  return (
    <>
      <AuthContext.Provider
        value={{
          isLoggedIn: !!token,
          token: token,
          userId: userId,
          login: login,
          logout: logout,
        }}
      >
 <Router>
<Switch>
   <Route path="/" exact>
    <Dashboard />
   </Route>
</Switch>
</Router>
</AuthContext.Provider>
</>
};

export default App;
</code>```

An example of the issue is if I log in and navigate to the dashboard via clicking on a link I have no problem. If I am on the dashboard and I refresh the browser, I get a 403 error and the request fails because the token was not available yet when sending the request.

```<code>  useEffect(() => {
    const getItems = async () => {
      const config = {
        method: "get",
        url: "http://localhost:8000/api/admin/somedata",
        headers: { Authorization: "Bearer " + auth.token },
      };
      const responseData = await Axios(config);
      setItems(responseData.data);
      console.log(responseData.data);
    };
    getItems();
  }, []);
</code>```

To clarify, I only have this issue if I refresh the browser.

答:
This is React itself. What you can do is that you can use an useEffect hook as following,

```<code>useEffect(() => {
  auth && doSomethingWithAuth(auth);
}, [auth])
</code>```

However, the ideal solution would be showing some loading component while your auth token is being read. You can basically extract your provider to be another component. Then you can try to read your auth variable in your provider component. While starting the reading operation, set a state as authLoading and set it as false when the auth change to be truthy (with an useEffect hook again).Finally, if authLoading === true, show some loading component/text, else show the children of the provider.

Hope this helps!

Title: context is slow or being called twice

Body:
I have an issue with the Context I am using for my auth. If I console.log when logged in, first I get false, and then a second later it logs again with the token etc. So, something is wrong with my code.

Here is my auth hook:

import { useState, useCallback, useEffect } from "react";

export const useAuth = () => {
  const [token, setToken] = useState(false);
  const [userId, setUserId] = useState(false);

  const login = useCallback((uid, token) => {
    setToken(token);
    setUserId(uid);
    localStorage.setItem(
      "userData",
      JSON.stringify({
        userId: uid,
        token: token,
      })
    );
  }, []);

  const logout = useCallback(() => {
    setToken(null);
    setUserId(null);
    localStorage.removeItem("userData");
  }, []);

  useEffect(() => {
    const storedData = JSON.parse(localStorage.getItem("userData"));
    if (storedData && storedData.token) {
      login(storedData.userId, storedData.token);
    }
  }, [login]);

  return { token, login, logout, userId };
};

The auth context:

import { createContext } from "react";

export const AuthContext = createContext({
  isLoggedIn: false,
  userId: null,
  token: null,
  login: () => {},
  logout: () => {},
});

Example of the component where I have the issue (basically in all components I am using this auth context)

import React, { useContext, useState } from "react";
import AdminCard from "../components/adminCards/AdminCard";
import { AuthContext } from "../../shared/context/auth-context";

const Dashboard = () => {
  const auth = useContext(AuthContext);
  console.log(auth);
  return (

              <AdminCard title="Contact Enquiries" />
              <AdminCard title="Card 2" />
              <AdminCard title="Card 3" />

  );
};

export default Dashboard;

In console I first see 'false' and then a second later I see the contents of 'auth'.

Example of App.js

const App = () => {
   const { token, login, logout, userId } = useAuth();
  return (
    <>
      <AuthContext.Provider
        value={{
          isLoggedIn: !!token,
          token: token,
          userId: userId,
          login: login,
          logout: logout,
        }}
      >
 <Router>
<Switch>
   <Route path="/" exact>
    <Dashboard />
   </Route>
</Switch>
</Router>
</AuthContext.Provider>
</>
};

export default App;

An example of the issue is if I log in and navigate to the dashboard via clicking on a link I have no problem. If I am on the dashboard and I refresh the browser, I get a 403 error and the request fails because the token was not available yet when sending the request.

  useEffect(() => {
    const getItems = async () => {
      const config = {
        method: "get",
        url: "http://localhost:8000/api/admin/somedata",
        headers: { Authorization: "Bearer " + auth.token },
      };
      const responseData = await Axios(config);
      setItems(responseData.data);
      console.log(responseData.data);
    };
    getItems();
  }, []);

To clarify, I only have this issue if I refresh the browser.

Body:
This is React itself. What you can do is that you can use an useEffect hook as following,

useEffect(() => {
  auth && doSomethingWithAuth(auth);
}, [auth])

However, the ideal solution would be showing some loading component while your auth token is being read. You can basically extract your provider to be another component. Then you can try to read your auth variable in your provider component. While starting the reading operation, set a state as authLoading and set it as false when the auth change to be truthy (with an useEffect hook again).Finally, if authLoading === true, show some loading component/text, else show the children of the provider.

Hope this helps!


问:
Azure AD Account vs Active Directory vs Tenant
I am failing to understand the difference and use of Azure Active Directory and Tenant. Subscriptions are services running under a tenant. But I can't understand the relationship between multi-tenant subscriptions or how directories are related to tenants Please help.</p>

答:
A tenant is a dedicated instance of an Azure AD directory that your organization receives when it signs up for a Microsoft cloud service such as Azure or Office 365. https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/active-directory-whatis

Each Azure tenant has a dedicated and trusted Azure AD directory. The Azure AD directory includes the tenant's users, groups, and apps and is used to perform identity and access management functions for tenant resources.


问:
I keep getting Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag
here is the code

```<code>import React from 'react';

function Home() {
  return (
      <div className="home">
        <h1>This is my home page!</h1>
      </div>
      <h2>Welcome and take a look around</h2>
      </div>
  );
}

export default Home;
</code>```

Here is the error

```<code>./src/components/home.js   Line 9:7:  Parsing error: Adjacent JSX
elements must be wrapped in an enclosing tag. Did you want a JSX
fragment <>...</>?

   7 |       <h1>This is my home page!</h1>
   8 |       </div>
   9 |       <h2>Welcome and take a look around</h2>
     |       ^
  10 |       </div>
</code>```

答:
At first, you didn't use  for the second div section(line9). Also, you should put all of your elements in a section such as ,,,etc.</p>

```<code>import React from 'react';

function Home() {
  return (
      <React.fragment className="home">
        <h1>This is my home page!</h1>
        <h2>Welcome and take a look around</h2>
      </React.fragment>
  );
}

export default Home;
</code>```

Body:
here is the code

import React from 'react';

function Home() {
  return (

This is my home page!

Welcome and take a look around

  );
}

export default Home;

Here is the error

./src/components/home.js   Line 9:7:  Parsing error: Adjacent JSX
elements must be wrapped in an enclosing tag. Did you want a JSX
fragment <>...</>?

   7 |
This is my home page!

   8 |

   9 |
Welcome and take a look around

     |       ^
  10 |

Body:
At first, you didn't use  for the second div section(line9). Also, you should put all of your elements in a section such as ,,,etc.

import React from 'react';

function Home() {
  return (
      <React.fragment className="home">
        <h1>This is my home page!</h1>
        <h2>Welcome and take a look around</h2>
      </React.fragment>
  );
}

export default Home;