问:
How to pass value to pagination DataSourcec in kotlin
I have to fetch pagination data based on a particular id. The id is getting in activity through intents.
Then how can i pass that value to my datasource.
I am using mvvm architecture</p>

答:
So you can do something like that

Activity

```<code>
class MainActivity : BaseActivity() {
    lateinit var binding: ActivityMainBinding
    var value: Int = 0
    private val viewModel: MainActivityViewModel by lazy {
        ViewModelProvider(this, MainActivityViewModel.Factory(value)).get(
            MainActivityViewModel::class.java
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        /*
        * get data from intent here and assign to value like
        */
        value=intent.getIntExtra("keyName",0)

        binding.viewModel = viewModel
        binding.lifecycleOwner = this
    }

}

</code>```

As our view model is lazy initalized so only the updated value it will get.

Now your view model

```<code>class MainActivityViewModel(value: Int) : BaseViewModel() {

    init {
/*
do initiaize your data source here now
*/

    }

    class Factory(val value: Int) : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(MainActivityViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return MainActivityViewModel(value) as T
            }
            throw IllegalArgumentException("Unable to construct viewmodel")
        }
    }
}
</code>```

Now inside init block you can initialize your data source. Now you have the value in view model which was send through intent. I am using factory for view model creation.

Body:
So you can do something like that

Activity

class MainActivity : BaseActivity() {
    lateinit var binding: ActivityMainBinding
    var value: Int = 0
    private val viewModel: MainActivityViewModel by lazy {
        ViewModelProvider(this, MainActivityViewModel.Factory(value)).get(
            MainActivityViewModel::class.java
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        /*
        * get data from intent here and assign to value like
        */
        value=intent.getIntExtra("keyName",0)

        binding.viewModel = viewModel
        binding.lifecycleOwner = this
    }

}

As our view model is lazy initalized so only the updated value it will get.

Now your view model

class MainActivityViewModel(value: Int) : BaseViewModel() {

    init {
/*
do initiaize your data source here now
*/

    }

    class Factory(val value: Int) : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(MainActivityViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return MainActivityViewModel(value) as T
            }
            throw IllegalArgumentException("Unable to construct viewmodel")
        }
    }
}

Now inside init block you can initialize your data source. Now you have the value in view model which was send through intent. I am using factory for view model creation.


来源: stackexchange

问:
PowerShell: unable to loop through files located in other directory than the script file itself
I am trying to test if I can loop through .xml files located in a different directory than the .ps1 script itself:

```<code>$files = Get-ChildItem -Path 'C:\ps_scripts\configs'

foreach ($file in $files) {
    $xml = [xml](Get-Content $file.FullName)
    Write-Host $xml
}
</code>```

When I run the above script, I get several empty lines as the output. I also tried to add -Recurse parameter in the first line, but the problem persists.
If I type in the PowerShell terminal $files = Get-ChildItem -Path 'C:\ps_scripts\configs', then the $files variable returns a list of files as I expect:

```<code>PS C:\ps_scripts> $files = Get-ChildItem -Path 'C:\ps_scripts\configs'
PS C:\ps_scripts> $files

    Directory: C:\ps_scripts\configs

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        12/2/2019   9:09 AM           3820 ams_merge_ab.xml
-a----        12/2/2019   9:09 AM           3894 ams_merge_ba.xml
-a----        12/2/2019   9:09 AM           4451 ams_merge_cg.xml
-a----        2/10/2020  12:28 PM           4029 ams_merge_de.xml
-a----        12/3/2019   3:22 PM           4222 ams_merge_so.xml
</code>```

If $files actually do contain the list of files in the directory, then why the foreach block fails to return anything?

答:
Given the code in my original post, I was using Write-Host $xml in order to check if XML filenames' values are returned. As mentioned, I only got empty lines as the output.
But when I modify this line like this -> Write-Host $xml.'process-config'.firstDate --- $file, then I get the value stored between <firstDate> tags of each XML file:

```<code>2019-12-02 --- ams_merge_ab.xml
2019-12-02 --- ams_merge_ba.xml
2019-12-02 --- ams_merge_cg.xml
2020-01-20 --- ams_merge_de.xml
2019-12-02 --- ams_merge_so.xml
</code>```

So I was thinking that there was something wrong with my looping method but it works if I just add XML tag names separated by dot right after $xml variable

ContentLicense: CC BY-SA 4.0

Body:
I am trying to test if I can loop through .xml files located in a different directory than the .ps1 script itself:

$files = Get-ChildItem -Path 'C:\ps_scripts\configs'

foreach ($file in $files) {
    $xml = [xml](Get-Content $file.FullName)
    Write-Host $xml
}

When I run the above script, I get several empty lines as the output. I also tried to add -Recurse parameter in the first line, but the problem persists.
If I type in the PowerShell terminal $files = Get-ChildItem -Path 'C:\ps_scripts\configs', then the $files variable returns a list of files as I expect:

PS C:\ps_scripts> $files = Get-ChildItem -Path 'C:\ps_scripts\configs'
PS C:\ps_scripts> $files

    Directory: C:\ps_scripts\configs

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        12/2/2019   9:09 AM           3820 ams_merge_ab.xml
-a----        12/2/2019   9:09 AM           3894 ams_merge_ba.xml
-a----        12/2/2019   9:09 AM           4451 ams_merge_cg.xml
-a----        2/10/2020  12:28 PM           4029 ams_merge_de.xml
-a----        12/3/2019   3:22 PM           4222 ams_merge_so.xml

If $files actually do contain the list of files in the directory, then why the foreach block fails to return anything?

Body:
Given the code in my original post, I was using Write-Host $xml in order to check if XML filenames' values are returned. As mentioned, I only got empty lines as the output.
But when I modify this line like this -> Write-Host $xml.'process-config'.firstDate --- $file, then I get the value stored between <firstDate> tags of each XML file:

2019-12-02 --- ams_merge_ab.xml
2019-12-02 --- ams_merge_ba.xml
2019-12-02 --- ams_merge_cg.xml
2020-01-20 --- ams_merge_de.xml
2019-12-02 --- ams_merge_so.xml

So I was thinking that there was something wrong with my looping method but it works if I just add XML tag names separated by dot right after $xml variable


问:
How to get the smallest item from the second items of a tuple list?
First of all sorry for the confusing title, I had no idead how to explain my problem without an example.

I have the following graph

```<code>graph = {
    1: [(3, 5), (4, 1),  (5, 4)],
    2: [(5, 9)],
    3: [(5, 1), (6, 1)],
    4: [(2, 11), (8, 2)],
    5: [(4, 6), (2, 6)],
    6: [(7, 1)],
    7: [(5, 7), (2, 1)],
    8: [(2, 6)],
}
</code>```

I want to be able to get the smallest number from the second item of the tupels for a given number. For example, if I gave the function the number 1 I would want it to return the 1 from the second tupel. If the input was 4 instead I would expect it to return a 2 form the second tupel.

My current approach is min((graph[s])[1]), but this doesn't really work and mostly returns Index Errors.

Edit:
I solved the problem with (min(graph[s])[0], min(graph[s])[1])[1] now (for some reason) it works in all cases (the problems were with lists that only contained one tupel).

答:
Just use:</p>

```<code>s = 7
print(min(min(graph[s], key= lambda t:min(t))))
</code>```

Body:
First of all sorry for the confusing title, I had no idead how to explain my problem without an example.

I have the following graph

graph = {
    1: [(3, 5), (4, 1),  (5, 4)],
    2: [(5, 9)],
    3: [(5, 1), (6, 1)],
    4: [(2, 11), (8, 2)],
    5: [(4, 6), (2, 6)],
    6: [(7, 1)],
    7: [(5, 7), (2, 1)],
    8: [(2, 6)],
}

I want to be able to get the smallest number from the second item of the tupels for a given number. For example, if I gave the function the number 1 I would want it to return the 1 from the second tupel. If the input was 4 instead I would expect it to return a 2 form the second tupel.

My current approach is min((graph[s])[1]), but this doesn't really work and mostly returns Index Errors.

Edit:
I solved the problem with (min(graph[s])[0], min(graph[s])[1])[1] now (for some reason) it works in all cases (the problems were with lists that only contained one tupel).

Body:
Just use:

s = 7
print(min(min(graph[s], key= lambda t:min(t))))


问:
Is there an elegant way to pass multiple functions with different amount of parameters into another function in python?
This block of code looks insanely similar and I'm looking for a way to create one function from the both of them:

```<code>guardians = ["guardianPogchamp", "guardianKappa", "guardianKappaPride", "guardianSmorc", "guardianTrihard"]

with pocofixtures.poco.freeze() as frozen_poco:
    for guardian in guardians:
        if guardian == 'guardianLul':
            assert_text_equal(frozen_poco(guardian).offspring("countdown"),"Immune")
        else:
            assert_text_match(frozen_poco(guardian).offspring("countdown"),"Not Immune")

with pocofixtures.poco.freeze() as frozen_poco:
    for guardian in guardians:
        if guardian == 'guardianLul':
            assert_visible(frozen_poco(guardian).offspring("PetContainer"))
        else:
            assert_not_visible(frozen_poco(guardian).offspring("PetContainer"))
</code>```

This is one of the solutions I tried:

```<code>def custom_assert(func1, func1Args, func2, func2Args):
    guardians = ["guardianPogchamp", "guardianKappa", "guardianKappaPride", "guardianSmorc", "guardianTrihard"]

    with pocofixtures.poco.freeze() as frozen_poco:
        for guardian in guardians:
            if guardian == 'guardianLul':
                func1(*func1Args)
            else:
                func2(*func2Args)

custom_assert(assert_text_equal, (frozen_poco(guardian).offspring("countdown"), "Immune") , assert_text_match, (frozen_poco(guardian).offspring("countdown"),"Not Immune"))
custom_assert(assert_visible, frozen_poco(guardian).offspring("PetContainer"), assert_not_visible, frozen_poco(guardian).offspring("PetContainer"))
</code>```

But the variables frozen_poco and guardian are only defined inside the function and not when it is called so the code doesn't run. I also tried unpacking and repacking the the variables inside the function but it slows down the runtime a lot. I know there should be an elegant solution to this but i don't know what

答:
Your callback functions can take frozen_poco and guardian, or frozen_poco(guardian) as args:

```<code>custom_assert(
    lambda fp, g: assert_text_equal(fp(g).offspring("countdown"), "Immune") ,
    lambda fp, g: assert_text_match(fp(g).offspring("countdown"),"Not Immune"))
</code>```

And called like:

```<code>func1(frozen_poco, guardian)
func2(frozen_poco, guardian)
</code>```

Body:
This block of code looks insanely similar and I'm looking for a way to create one function from the both of them:

guardians = ["guardianPogchamp", "guardianKappa", "guardianKappaPride", "guardianSmorc", "guardianTrihard"]

with pocofixtures.poco.freeze() as frozen_poco:
    for guardian in guardians:
        if guardian == 'guardianLul':
            assert_text_equal(frozen_poco(guardian).offspring("countdown"),"Immune")
        else:
            assert_text_match(frozen_poco(guardian).offspring("countdown"),"Not Immune")

with pocofixtures.poco.freeze() as frozen_poco:
    for guardian in guardians:
        if guardian == 'guardianLul':
            assert_visible(frozen_poco(guardian).offspring("PetContainer"))
        else:
            assert_not_visible(frozen_poco(guardian).offspring("PetContainer"))

This is one of the solutions I tried:

def custom_assert(func1, func1Args, func2, func2Args):
    guardians = ["guardianPogchamp", "guardianKappa", "guardianKappaPride", "guardianSmorc", "guardianTrihard"]

    with pocofixtures.poco.freeze() as frozen_poco:
        for guardian in guardians:
            if guardian == 'guardianLul':
                func1(*func1Args)
            else:
                func2(*func2Args)

custom_assert(assert_text_equal, (frozen_poco(guardian).offspring("countdown"), "Immune") , assert_text_match, (frozen_poco(guardian).offspring("countdown"),"Not Immune"))
custom_assert(assert_visible, frozen_poco(guardian).offspring("PetContainer"), assert_not_visible, frozen_poco(guardian).offspring("PetContainer"))

But the variables frozen_poco and guardian are only defined inside the function and not when it is called so the code doesn't run. I also tried unpacking and repacking the the variables inside the function but it slows down the runtime a lot. I know there should be an elegant solution to this but i don't know what

Body:
Your callback functions can take frozen_poco and guardian, or frozen_poco(guardian) as args:

custom_assert(
    lambda fp, g: assert_text_equal(fp(g).offspring("countdown"), "Immune") ,
    lambda fp, g: assert_text_match(fp(g).offspring("countdown"),"Not Immune"))

And called like:

func1(frozen_poco, guardian)
func2(frozen_poco, guardian)


问:
How to return a hash containing an array of file names for each owner name?
There is a hash named "files" as following :

```<code>files = {
       'file1.txt' => 'John',
       'file2.rb'  => 'Andrew',
       'file3.txt' => 'John'
}
</code>```

Expected result:

A method that takes this hash as argument and return the hash containing the array of files for
respective owner. For e.g

```<code>{
  'John'   =>  ['file1.txt','file3.txt'],
  'Andrew' =>  ['file2.rb']
}

</code>```

答:
Here you want to iterate over the file hash and for each key value pair you need to check if it already exists in your new hash, then you just want to add the file name to the array or you create a new key value pair.

```<code>def change_hash(file_hash)
  new_hash = {}
  file_hash.each do |file_name, person|
    if new_hash[person]
      new_hash[person] << file_name
    else
      new_hash[person] = [file_name]
    end
  end
  new_hash
end
</code>```

If you struggle with this, you want to look on how you can manipulate hashes (and arrays) in Ruby. Let me know if you have any more questions.

Body:
There is a hash named "files" as following :

files = {
       'file1.txt' => 'John',
       'file2.rb'  => 'Andrew',
       'file3.txt' => 'John'
}

Expected result:

A method that takes this hash as argument and return the hash containing the array of files for
respective owner. For e.g

{
  'John'   =>  ['file1.txt','file3.txt'],
  'Andrew' =>  ['file2.rb']
}

Body:
Here you want to iterate over the file hash and for each key value pair you need to check if it already exists in your new hash, then you just want to add the file name to the array or you create a new key value pair.

def change_hash(file_hash)
  new_hash = {}
  file_hash.each do |file_name, person|
    if new_hash[person]
      new_hash[person] << file_name
    else
      new_hash[person] = [file_name]
    end
  end
  new_hash
end

If you struggle with this, you want to look on how you can manipulate hashes (and arrays) in Ruby. Let me know if you have any more questions.


问:
Cannot Install TensorFlow on this Platform
I'm trying to install Tensorflow on a computer with a J1800 CPU. I know this CPU does not have the AVX extension. I'm trying to find a wheel package of tensorflow without an AVX extension. Every wheel I try gets the same error. Here's one example:

pip3 install https://raw.githubusercontent.com/fo40225/tensorflow-windows-wheel/master/1.14.0/py37/CPU/sse2/tensorflow-1.14.0-cp37-cp37m-win_amd64.whl

: ERROR: tensorflow-1.14.0-cp37-cp37m-win_amd64.whl is not a supported wheel on this platform.

I'm running  Python  3.8 64Bit

Does anyone know a wheel that will work on this CPU? Or am I making another mistake?

答:
Only tensorflow >= 2.2 is available on python 3.8.

In order to work with tensorflow 1.14 you need to use another version of python (3.6 or 3.7)


问:
Create two dataframes from two dataframes based on multiindex in one dataframe and columns in another dataframe
I m not sure if this has been answered before. But my requirement is that
I have a dataframe like this:

df1:

```<code>         A  B
I1 I2

x11 x12  a11 b11
x12 x22  a21 b21
</code>```

Note that this has multiindex of [I1, I2] and columns [A, B]

and then another dataframe like this:

df2:

```<code>    I1   I2
  0  x11  x12
  1  y11  y12
</code>```

This has columns [I1, I2] which is the same as multiindex of df1.

Now what I would like to create is two dataframes like below:

df3 which has rows for which the index in df1 matches to that of column values in df2

```<code>A  B
a11 b11
</code>```

df4 with the remaining i.e.

```<code>A  B
a21 b21
</code>```

I know how to do this using iterrows() but it is not efficient. Looking for a vectorized solution. Thanks.

答:
Just to record another way of doing it, posting this:

I could set_index on df2 with [I1, I2] and then do a isin like:

is_index_there = df1.index.isin(df2.set_index([I1, I2]).index)

and then use that to create separate dfs like :

df3 = df1.loc[is_index_there == True] and

df4 = df2.loc[is_index_there == False]

Body:
I m not sure if this has been answered before. But my requirement is that
I have a dataframe like this:

df1:

         A  B
I1 I2

x11 x12  a11 b11
x12 x22  a21 b21

Note that this has multiindex of [I1, I2] and columns [A, B]

and then another dataframe like this:

df2:

    I1   I2
  0  x11  x12
  1  y11  y12

This has columns [I1, I2] which is the same as multiindex of df1.

Now what I would like to create is two dataframes like below:

df3 which has rows for which the index in df1 matches to that of column values in df2

A  B
a11 b11

df4 with the remaining i.e.

A  B
a21 b21

I know how to do this using iterrows() but it is not efficient. Looking for a vectorized solution. Thanks.


问:
Flutter WebRTC Cant connect to peers. Failed to set remote answer sdp: Called in wrong state: kStable
So I'm using flutter (And flutter for web) to build a WebRTC client. I have a spring-boot server acting as the go-between for two clients. They both subscribe to a WebSocket to get messages from the other. It does nothing more than that.

I'm getting Error: InvalidStateError: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: kStable

I don't know why this error is happening.

Here's the code for the signalling

```<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;

  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;
    }
    var description = answer.data['description'];
    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 {
    await createStream();
    _peerConnection = await createPeerConnection(_iceServers, _config);
    _peerConnection.onSignalingState = (state) {
      isNegotiating = state != RTCSignalingState.RTCSignalingStateStable;
    };
    _peerConnection.onAddTrack = (MediaStream stream, _) {
      this.onAddRemoteStream(stream);
      print("sending stream from track");
    };

    _peerConnection.onAddStream = (MediaStream stream) {
      this.onAddRemoteStream(stream);
      print("sending stream");
    };
    _peerConnection.onRemoveStream =
        (MediaStream stream) => this.onRemoveRemoteStream(stream);
    _peerConnection.onIceCandidate = (RTCIceCandidate candidate) {
      print("sending 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': [
      {"url" : "stun:stun2.1.google.com:19302"},
      {'url' : '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', // Provide your own width, height and frame rate here
          'minHeight': '480',
          'minFrameRate': '30',
        },
        'facingMode': 'user',
        'optional': [],
      }
    };

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

My first problem was I was not setting the local description for the offer/answer stage.

However, when I add a new stun server, I get the same exception. Either way, I don't get a remote stream showing.

答:
So when I was creating the offer and answer I wasn't setting local description. So there's that. </p>

<p>It's still not showing remote connections though. </p>

Body:
So I'm using flutter (And flutter for web) to build a WebRTC client. I have a spring-boot server acting as the go-between for two clients. They both subscribe to a WebSocket to get messages from the other. It does nothing more than that.

I'm getting Error: InvalidStateError: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: kStable

I don't know why this error is happening.

Here's the code for the signalling

 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;

  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;
    }
    var description = answer.data['description'];
    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 {
    await createStream();
    _peerConnection = await createPeerConnection(_iceServers, _config);
    _peerConnection.onSignalingState = (state) {
      isNegotiating = state != RTCSignalingState.RTCSignalingStateStable;
    };
    _peerConnection.onAddTrack = (MediaStream stream, _) {
      this.onAddRemoteStream(stream);
      print("sending stream from track");
    };

    _peerConnection.onAddStream = (MediaStream stream) {
      this.onAddRemoteStream(stream);
      print("sending stream");
    };
    _peerConnection.onRemoveStream =
        (MediaStream stream) => this.onRemoveRemoteStream(stream);
    _peerConnection.onIceCandidate = (RTCIceCandidate candidate) {
      print("sending 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': [
      {"url" : "stun:stun2.1.google.com:19302"},
      {'url' : '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', // Provide your own width, height and frame rate here
          'minHeight': '480',
          'minFrameRate': '30',
        },
        'facingMode': 'user',
        'optional': [],
      }
    };

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

My first problem was I was not setting the local description for the offer/answer stage.

However, when I add a new stun server, I get the same exception. Either way, I don't get a remote stream showing.

Body:
So when I was creating the offer and answer I wasn't setting local description. So there's that.

It's still not showing remote connections though.


问:
SQL query to convert Date to another format
Thanks for your help. I am not able to make out the type/format of the "Value" in a Date column.I guess its in Julian Date format.

The Column  is      paid_month and the values are below.

```<code>                  200901
                  200902
</code>```

So,please help in writing SQL query  to convert the above values(Mostly in Julian Format) in the Date Column to normal date (MM/DD/YYYY) .

Thanks
Rohit

Hi,

I am sorry for missing in giving the whole information.

1)Its a Oracle Database.
2)The column given is Paid_Month with values 200901,200902

3)I am also confused that the above value gives month & year.Day isnt given if my guess is right.

4)If its not in Julian format ,then also please help me the SQL to get at least mm/yyyy

I am using a Oracle DB and running the query
THANKS i GOT THE ANSWER.

**Now,i have to do the reverse meaning converting a date 01/09/2010 to a String which has 6 digits.
Pls help with syntax-
select to_char(01/01/2010,**

答:
```<code>SELECT (paid_month % 100) + "/01/" + (paid_month/100) AS paid_day
FROM tbl;
</code>```

I'm not sure about how oracle concatenates strings. Often, you see || in SQL:

```<code>SELECT foo || bar FROM ...
</code>```

or functions:

```<code>SELECT cat (foo, bar) FROM ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Thanks for your help. I am not able to make out the type/format of the "Value" in a Date column.I guess its in Julian Date format.

The Column  is      paid_month and the values are below.

                  200901
                  200902

So,please help in writing SQL query  to convert the above values(Mostly in Julian Format) in the Date Column to normal date (MM/DD/YYYY) .

Thanks
Rohit

Hi,

I am sorry for missing in giving the whole information.

1)Its a Oracle Database.
2)The column given is Paid_Month with values 200901,200902

3)I am also confused that the above value gives month & year.Day isnt given if my guess is right.

4)If its not in Julian format ,then also please help me the SQL to get at least mm/yyyy

I am using a Oracle DB and running the query
THANKS i GOT THE ANSWER.

**Now,i have to do the reverse meaning converting a date 01/09/2010 to a String which has 6 digits.
Pls help with syntax-
select to_char(01/01/2010,**

Body:
SELECT (paid_month % 100) + "/01/" + (paid_month/100) AS paid_day
FROM tbl;

I'm not sure about how oracle concatenates strings. Often, you see || in SQL:

SELECT foo || bar FROM ...

or functions:

SELECT cat (foo, bar) FROM ...


问:
LocalDateTime format with time zone and milliseconds
I'm trying to write a DateTimeFormatter to parse the following format:

```<code>2020-05-29T07:51:33.106-07:00
</code>```

I have looked at ISO_OFFSET_DATE_TIME, but the problem is it does not contain milliseconds. So I decided to write on my own.

It is easy to do so without timezone:

```<code>public static void main (String[] args) throws java.lang.Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    System.out.println(
        LocalDateTime.parse("2020-05-29T07:51:33.106", formatter)
    );
}
</code>```

It works just fine

But when I tried to add a timezone in the format as

```<code>public static void main (String[] args) throws java.lang.Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    System.out.println(
        LocalDateTime.parse("2020-05-29T07:51:33.106-07:00", formatter)
    );
}
</code>```

It now fails with an exception that the timezone is unable to be parsed.

```<code>Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-05-29T07:51:33.106-07:00' could not be parsed at index 23
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2049)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1951)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at Ideone.main(Main.java:16)
</code>```

How to parse a timezone in such a format?

答:
From the Javadoc (emphasis mine):

Offset Z: This formats the offset based on the number of pattern letters. One, two or three letters outputs the hour and minute, without a colon, such as '+0130'. The output will be '+0000' when the offset is zero. Four letters outputs the full form of localized offset, equivalent to four letters of Offset-O. The output will be the corresponding localized offset text if the offset is zero. Five letters outputs the hour, minute, with optional second if non-zero, with colon. It outputs 'Z' if the offset is zero. Six or more letters throws IllegalArgumentException.

Change the single Z to ZZZZZ.

Body:
I'm trying to write a DateTimeFormatter to parse the following format:

2020-05-29T07:51:33.106-07:00

I have looked at ISO_OFFSET_DATE_TIME, but the problem is it does not contain milliseconds. So I decided to write on my own.

It is easy to do so without timezone:

public static void main (String[] args) throws java.lang.Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    System.out.println(
        LocalDateTime.parse("2020-05-29T07:51:33.106", formatter)
    );
}

It works just fine

But when I tried to add a timezone in the format as

public static void main (String[] args) throws java.lang.Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    System.out.println(
        LocalDateTime.parse("2020-05-29T07:51:33.106-07:00", formatter)
    );
}

It now fails with an exception that the timezone is unable to be parsed.

Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-05-29T07:51:33.106-07:00' could not be parsed at index 23
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2049)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1951)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at Ideone.main(Main.java:16)

How to parse a timezone in such a format?


问:
Is the file mode flag “ios::app” used to delete a file if it already exists?
I had this question in mind about the file mode flag ios::app. Is it used to delete a file if it already exists?

答:
No, the flag std::ios::app isn't used to delete a file if already exists.

When std::ios::app flag is set, all output operations are performed at the end of the file.

Rather you could use to delete a file if exists (you must have filesystem library which exists in c++17 and above):

```<code>try {
    if (std::filesystem::remove("file.txt"))
        std::cout << "file deleted.\n";
    else
        std::cout << "file not found.\n";

} catch (const std::filesystem::filesystem_error &err) {
    std::cout << "FS error: " << err.what() << '\n';
}
</code>```

Body:
No, the flag std::ios::app isn't used to delete a file if already exists.

When std::ios::app flag is set, all output operations are performed at the end of the file.

Rather you could use to delete a file if exists (you must have filesystem library which exists in c++17 and above):

try {
    if (std::filesystem::remove("file.txt"))
        std::cout << "file deleted.\n";
    else
        std::cout << "file not found.\n";

} catch (const std::filesystem::filesystem_error &err) {
    std::cout << "FS error: " << err.what() << '\n';
}


问:
Ansible for Windows
I am trying to set up my ansible host to connect to windows.  However ping is failing with the following error:

sudo ansible win -m win_ping
hostname | UNREACHABLE! => {
    "changed": false,
    "msg": "basic: HTTPConnectionPool(host='hostname', port=5986): Read timed out. (read timeout=30)",
    "unreachable": true
}

pywinrm is installed on my linux box and WinRM is installed on the windows box.

Hosts file:

[win]
systemname
[win:vars]
ansible_user=username
ansible_password=passord
ansible_connection=winrm
ansible_winrm_scheme=http
ansible_winrm_server_cert_validation=ignore
ansible_winrm_transport=basic```

Appreciate any advice.
Thanks.

答: Disabling the Windows Firewall (Domain, private and public networks) in the Windows box, fixed the issue for me.</p>

Title: Ansible for Windows

Body:
I am trying to set up my ansible host to connect to windows.  However ping is failing with the following error:

sudo ansible win -m win_ping
hostname | UNREACHABLE! => {
    "changed": false,
    "msg": "basic: HTTPConnectionPool(host='hostname', port=5986): Read timed out. (read timeout=30)",
    "unreachable": true
}

pywinrm is installed on my linux box and WinRM is installed on the windows box.

Hosts file:

[win]
systemname
[win:vars]
ansible_user=username
ansible_password=passord
ansible_connection=winrm
ansible_winrm_scheme=http
ansible_winrm_server_cert_validation=ignore
ansible_winrm_transport=basic

Appreciate any advice.
Thanks.


问:
Dart: Convert int to int Function()
Is there any way to convert an int to a int Function() in Dart?

For example:

```<code>a to ()=>a
</code>```

答:
You mean like this? This function will return a function which returns the int value you provided when the method was created.

```<code>int Function() intToIntFunction(int i) => () => i;
</code>```

Updated

You can also do this if you want the current value of the integer each time the method are called:

```<code>void main() {
  int a = 5;
  int Function() funA = () => a;

  print(funA()); // 5
  a++;
  print(funA()); // 6
}
</code>```

Title: Dart: Convert int to int Function()

Body:
Is there any way to convert an int to a int Function() in Dart?

For example:

a to ()=>a

Body:
You mean like this? This function will return a function which returns the int value you provided when the method was created.

int Function() intToIntFunction(int i) => () => i;

Updated

You can also do this if you want the current value of the integer each time the method are called:

void main() {
  int a = 5;
  int Function() funA = () => a;

  print(funA()); // 5
  a++;
  print(funA()); // 6
}


问:
Display the word document from wwwroot folder instead of downloading: ASP.Net Core
I am trying to show the document located inside wwwroot folder in my .NET MVC Core application folder in an iframe.

Scenario:

I have a list of document on my Razor page: MyRazor.cshtml and there is a button for each list. When I click that button it takes me to the details of individual document using its Id.

When the page loads, the document gets downloaded instead of showing in iframe src.

Controller:

```<code>public ActionResult GetArticles(int id)
    {
        try
        {
            Articles getArticles = _articleRepository.GetArticles(id);
            return View(getArticles);
        }
        catch (Exception)
        {

            return NotFound();
        }
    }
</code>```

View:

```<code><div class="card">
    <iframe id="documentViewer" src="~/docs/@Html.DisplayFor(model => model.WordDocumentFile)" width="100%" height="700px;" frameborder="0"></iframe>
</div>
</code>```

which is undesirable. I just want the show that document inside my iframe.

What am I missing?

答:
Yongqing Yu's answer sort of stated it, but I just want to elaborate that if the PDF is in your wwwroot folder, all you need to do is

On a view, ~/ is already relative to the static files stored in wwwroot

Body:
I am trying to show the document located inside wwwroot folder in my .NET MVC Core application folder in an iframe.

Scenario:

I have a list of document on my Razor page: MyRazor.cshtml and there is a button for each list. When I click that button it takes me to the details of individual document using its Id.

When the page loads, the document gets downloaded instead of showing in iframe src.

Controller:

public ActionResult GetArticles(int id)
    {
        try
        {
            Articles getArticles = _articleRepository.GetArticles(id);
            return View(getArticles);
        }
        catch (Exception)
        {

            return NotFound();
        }
    }

View:

     model.WordDocumentFile)" width="100%" height="700px;" frameborder="0">

which is undesirable. I just want the show that document inside my iframe.

What am I missing?

Body:
Yongqing Yu's answer sort of stated it, but I just want to elaborate that if the PDF is in your wwwroot folder, all you need to do is

<iframe src="~/docs/mypdf.pdf">

On a view, ~/ is already relative to the static files stored in wwwroot


问:
Using AsParallel on an IEnumerable - Will it have any benefit of parallelism at all?
```<code>IEnumerable<char> GetChars()
        {
            int i = int.MinValue;
            while (i++ < int.MaxValue)
            {
                yield return (char)('A' + (i % 26));
            }
        }
</code>```

Is there any benefit of applying AsParallel to above character enumerable?

GetChars().AsParallel().REST_OF_THE_QUERY

Because, from my knowledge for this to work in parallel on many threads, there needs to be partition of the data for different threads available in parallel. But here I think the enumerator will be a bottleneck because it can not run in parallel?

Will AsParallel be able to fetch data in parallel from this enumerator and utilize the benefit of multithreading?

答:
Regarding the query:

```<code>GetChars().AsParallel().REST_OF_THE_QUERY
</code>```

The REST_OF_THE_QUERY will be parallelized. The GetChars will not be parallelized, and will run exclusively in the current thread. The AsParallel parallelizes what follows it (as long as each subsequent operator returns a ParallelQuery). It doesn't parallelize what precedes it.

Update: GSerg pointed out in the comments that with GetChars().AsParallel() the current thread ID keeps changing inside GetChars, although it appears to be some locking involved, as no two threads enter GetChars at the same time. My experiments matched these observations. This means that the PLINQ library cannot be used for querying a data source that requires thread affinity. For example the code below throws an exception in WinForms:

```<code>private void Button1_Click(object sender, EventArgs e)
{
    Control.CheckForIllegalCrossThreadCalls = true;
    int count = GetHandles().AsParallel().Count();
    MessageBox.Show($"Controls: {count}");
}

private IEnumerable<IntPtr> GetHandles()
{
    foreach (Control control in this.Controls)
    {
        yield return control.Handle;
    }
}
</code>```

InvalidOperationException: Cross-thread operation not valid: Control 'Button1' accessed from a thread other than the thread it was created on.

Without .AsParallel(), no exception is thrown.

Body:
IEnumerable<char> GetChars()
        {
            int i = int.MinValue;
            while (i++ < int.MaxValue)
            {
                yield return (char)('A' + (i % 26));
            }
        }

Is there any benefit of applying AsParallel to above character enumerable?

GetChars().AsParallel().REST_OF_THE_QUERY

Because, from my knowledge for this to work in parallel on many threads, there needs to be partition of the data for different threads available in parallel. But here I think the enumerator will be a bottleneck because it can not run in parallel?

Will AsParallel be able to fetch data in parallel from this enumerator and utilize the benefit of multithreading?

Body:
Regarding the query:

GetChars().AsParallel().REST_OF_THE_QUERY

The REST_OF_THE_QUERY will be parallelized. The GetChars will not be parallelized, and will run exclusively in the current thread. The AsParallel parallelizes what follows it (as long as each subsequent operator returns a ParallelQuery). It doesn't parallelize what precedes it.

Update: GSerg pointed out in the comments that with GetChars().AsParallel() the current thread ID keeps changing inside GetChars, although it appears to be some locking involved, as no two threads enter GetChars at the same time. My experiments matched these observations. This means that the PLINQ library cannot be used for querying a data source that requires thread affinity. For example the code below throws an exception in WinForms:

private void Button1_Click(object sender, EventArgs e)
{
    Control.CheckForIllegalCrossThreadCalls = true;
    int count = GetHandles().AsParallel().Count();
    MessageBox.Show($"Controls: {count}");
}

private IEnumerable<IntPtr> GetHandles()
{
    foreach (Control control in this.Controls)
    {
        yield return control.Handle;
    }
}

InvalidOperationException: Cross-thread operation not valid: Control 'Button1' accessed from a thread other than the thread it was created on.

Without .AsParallel(), no exception is thrown.


问:
C++ Converting MIDI Note ID in a note
I have a Midi keyboard that when plugged in my program i can red the values of each pressed if but i have been having difficulties into finding an appropriate method to convert each Note ID into a specific note.

the key id jumps from 128 to 640 to 1152 to 1408 it increases for each key i press.

this are some ways that i have tried to convert the id to notes but none have been able to produce the scale that i wanted.

```<code>FTYPE CSscaleConvert(const int noteID)
{
    double d12th = pow(2.0, 1.0 / 12.0);
    //noteID = noteID * 0.01;
    //return 12 * log2((noteID / 100) / 440.0);
    return 0.256 * pow(d12th, noteID);
    //return 440 * log2(noteID * 0.01 - 69) / 12;
    //return noteID * 0.256;
    //return noteID;
}
</code>```

答:
For anyone else that might encounter this I previosuly used this to try to acess the data
wcout << "Velocity is " << HIWORD(dwParam1) << endl; //velocity
wcout << "Key ID is " << LOWORD(dwParam1) << endl; //keyID

but this was the correct way to do it

HIBYTE(dwParam1) << endl; //NoteNumber i think?
LOBYTE(dwParam1) << endl; //Velocity i think?

Title: C++ Converting MIDI Note ID in a note

Body:
I have a Midi keyboard that when plugged in my program i can red the values of each pressed if but i have been having difficulties into finding an appropriate method to convert each Note ID into a specific note.

the key id jumps from 128 to 640 to 1152 to 1408 it increases for each key i press.

this are some ways that i have tried to convert the id to notes but none have been able to produce the scale that i wanted.

FTYPE CSscaleConvert(const int noteID)
{
    double d12th = pow(2.0, 1.0 / 12.0);
    //noteID = noteID * 0.01;
    //return 12 * log2((noteID / 100) / 440.0);
    return 0.256 * pow(d12th, noteID);
    //return 440 * log2(noteID * 0.01 - 69) / 12;
    //return noteID * 0.256;
    //return noteID;
}


问:
reference to table range in vba
I want to import my data from Excel to SQL. I wrote some code - when I used Set rng = Application.Range"F5:H10") it works.
However, I want to use a table since the amount of data changes every time. How can I use an Excel table in this part of my code?

Thanks

答:
One way:

```<code>Sub Table2Range()
    Dim rng As Range
    Set rng = ActiveSheet.ListObjects(1).Range
    MsgBox rng.Address(0, 0)
End Sub
</code>```

Note:

You get the header as well as the data-body.

Title: reference to table range in vba

Body:
One way:

Sub Table2Range()
    Dim rng As Range
    Set rng = ActiveSheet.ListObjects(1).Range
    MsgBox rng.Address(0, 0)
End Sub

Note:

You get the header as well as the data-body.


问:
Compiling vim with Python3 (installed via Homebrew) support?
I have python3 installed via homebrew: brew install python3 --framework

I have the vim source (7.3) downloaded in /usr/src

I run:

```<code>./configure --prefix=/usr/local --enable-rubyinterp --enable-python3interp --disable-gpm --enable-gui=no --enable-multibyte
</code>```

And in my src/auto/config.log I see:

```<code>configure:5442: checking --enable-python3interp argument
configure:5451: result: yes
configure:5456: checking for python3
configure:5489: result: no
</code>```

I googled around some, and found this, so I tried making the symlink for python3.2 and then running configure like this:

```<code>./configure --prefix=/usr/local --enable-rubyinterp --enable-python3interp --disable-gpm --enable-gui=no --enable-multibyte --with-python3-config-dir=/usr/local/Cellar/python3/3.2/Frameworks/Python.framework/Versions/3.2/lib/python3.2/config-3.2m
</code>```

And my log shows the same error. What do I need to do to get vim compiled with Python3 support?

And no: I do not want to use MacVim.

```<code>➜ ls -al /System/Library/Frameworks/Python.framework/Versions
total 16
drwxr-xr-x   7 root  wheel  238 May 28 15:33 .
drwxr-xr-x   7 root  wheel  238 Sep 21  2010 ..
drwxr-xr-x   8 root  wheel  272 Sep 17  2010 2.3
drwxr-xr-x  12 root  wheel  408 Dec  1 12:49 2.5
drwxr-xr-x  12 root  wheel  408 Dec  1 12:49 2.6
lrwxr-xr-x   1 root  wheel   70 May 28 15:33 Current -> /usr/local/Cellar/python3/3.2/Frameworks/Python.framework/Versions/3.2
lrwxr-xr-x   1 root  wheel    3 Sep 17  2010 old-Current -> 2.6

➜ which python3.2
/usr/local/bin/python3.2
</code>```

UPDATE: I've gotten it working a la this post with Python 2.7.1 via Homebrew, but still no joy with Python 3...

答:
When you test to see if it worked, make sure you use the Vim binary created by the build - not the mvim script. mvim (even if you call the version on your source tree) will look in /Applications/ for MacVim.app first.

Maybe this will give you some joy:

```<code>./configure \
  --enable-python3interp=dynamic \
  --with-python3-config-dir=/usr/local/Cellar/python3/3.2/Frameworks/Python.framework/Versions/3.2/lib/python3.2/config/
</code>```

Body:
I have python3 installed via homebrew: brew install python3 --framework

I have the vim source (7.3) downloaded in /usr/src

I run:

./configure --prefix=/usr/local --enable-rubyinterp --enable-python3interp --disable-gpm --enable-gui=no --enable-multibyte

And in my src/auto/config.log I see:

configure:5442: checking --enable-python3interp argument
configure:5451: result: yes
configure:5456: checking for python3
configure:5489: result: no

I googled around some, and found this, so I tried making the symlink for python3.2 and then running configure like this:

./configure --prefix=/usr/local --enable-rubyinterp --enable-python3interp --disable-gpm --enable-gui=no --enable-multibyte --with-python3-config-dir=/usr/local/Cellar/python3/3.2/Frameworks/Python.framework/Versions/3.2/lib/python3.2/config-3.2m

And my log shows the same error. What do I need to do to get vim compiled with Python3 support?

And no: I do not want to use MacVim.

➜ ls -al /System/Library/Frameworks/Python.framework/Versions
total 16
drwxr-xr-x   7 root  wheel  238 May 28 15:33 .
drwxr-xr-x   7 root  wheel  238 Sep 21  2010 ..
drwxr-xr-x   8 root  wheel  272 Sep 17  2010 2.3
drwxr-xr-x  12 root  wheel  408 Dec  1 12:49 2.5
drwxr-xr-x  12 root  wheel  408 Dec  1 12:49 2.6
lrwxr-xr-x   1 root  wheel   70 May 28 15:33 Current -> /usr/local/Cellar/python3/3.2/Frameworks/Python.framework/Versions/3.2
lrwxr-xr-x   1 root  wheel    3 Sep 17  2010 old-Current -> 2.6

➜ which python3.2
/usr/local/bin/python3.2

UPDATE: I've gotten it working a la this post with Python 2.7.1 via Homebrew, but still no joy with Python 3...

Body:
When you test to see if it worked, make sure you use the Vim binary created by the build - not the mvim script. mvim (even if you call the version on your source tree) will look in /Applications/ for MacVim.app first.

Maybe this will give you some joy:

./configure \
  --enable-python3interp=dynamic \
  --with-python3-config-dir=/usr/local/Cellar/python3/3.2/Frameworks/Python.framework/Versions/3.2/lib/python3.2/config/


问:
Converting each row of a dataframe into a string and assigning it as a column to another dataset in pandas
I have a dataset:

```<code>id   name   address   phone   email
123  abc    123 abc   12345   info@abc.com
456  cbs    456 cbs   67890   info@cbs.com
758  nbc    789 nbc   11121   info@nbc.com
</code>```

I want to create a new dataset, where it retains the first two columns (id and name) and has the third column, which will have a string that is a combination of values of address, phone and email. In other words, I need it to look like this:

```<code>id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '456 cbs   67890   info@cbs.com'
758  nbc    '789 nbc   11121   info@nbc.com'
</code>```

This is the code I have:

```<code>df_transformed = df[['id','name']]
df_meta = df[['address','phone','email']]
df_meta_str = df_meta.iloc[:].to_string(header=False, index=False)
df_transformed['meta_str'] = df_meta_str
</code>```

But what I get is:

```<code>id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '123 abc   12345   info@abc.com'
758  nbc    '123 abc   12345   info@abc.com'
</code>```

I think the problem is that df_meta_str has the data in all rows combined as one big string.

What would be a way to achieve a separate string on a separate row?

答:
You can use simple str concatenation:

```<code>df['meta_str'] = df.address + ' ' + df.phone.astype(str) + ' ' + df.email

df.drop(['address','phone','email'], 1, inplace=True)
</code>```

Output:

```<code>id   name   meta_str
123  abc    123 abc 12345 info@abc.com
456  cbs    456 cbs 67890 info@cbs.com
758  nbc    789 nbc 11121 info@nbc.com
</code>```

OR

use df.apply method:

```<code>df['meta_str'] = df[['address','phone','email']].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)
</code>```

Body:
I have a dataset:

id   name   address   phone   email
123  abc    123 abc   12345   info@abc.com
456  cbs    456 cbs   67890   info@cbs.com
758  nbc    789 nbc   11121   info@nbc.com

I want to create a new dataset, where it retains the first two columns (id and name) and has the third column, which will have a string that is a combination of values of address, phone and email. In other words, I need it to look like this:

id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '456 cbs   67890   info@cbs.com'
758  nbc    '789 nbc   11121   info@nbc.com'

This is the code I have:

df_transformed = df[['id','name']]
df_meta = df[['address','phone','email']]
df_meta_str = df_meta.iloc[:].to_string(header=False, index=False)
df_transformed['meta_str'] = df_meta_str

But what I get is:

id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '123 abc   12345   info@abc.com'
758  nbc    '123 abc   12345   info@abc.com'

I think the problem is that df_meta_str has the data in all rows combined as one big string.

What would be a way to achieve a separate string on a separate row?

Body:
You can use simple str concatenation:

df['meta_str'] = df.address + ' ' + df.phone.astype(str) + ' ' + df.email

df.drop(['address','phone','email'], 1, inplace=True)

Output:

id   name   meta_str
123  abc    123 abc 12345 info@abc.com
456  cbs    456 cbs 67890 info@cbs.com
758  nbc    789 nbc 11121 info@nbc.com

OR

use df.apply method:

df['meta_str'] = df[['address','phone','email']].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)


问:
Eclipse PDT JavaScript support includes only ECMAScript 3
I have Eclipse (PDT) 2020-03 (4.15.0) installed with JSDT too.

I have an existing PHP project with JavaScript support enabled, but included ECMAScript libraries are stuck on version 3 (1999!!).

How can I change ECMAScript included version? Thank you!

答: Upcoming Eclipse 2020-06 replaces old JSDT with WildWebDeveloper. This version fully support latest ECMA.</p>


问:
Decrypting an HTTP Header with aes_gcm_dec in HA Proxy
I'm trying to use the HA Proxy aes_gcm_dec converter, but the documentation is sparse to say the least, and I can't find any examples of its use in the community.

I have a client that is sending up a AES GCM 128 encrypted message in an HTTP header, like this:

```<code>curl -H "X-Routing-Key: e4+DM/EkJQl4jAAOxNtDZb4dd5Q=" localhost:8000
</code>```

I'm using HA Proxy to decrypt that header and forward it to the backend server in decrypted form. Here's my frontend config for that:

```<code>http-request set-header X-Routing-Key %[req.hdr(X-Routing-Key),b64dec,aes_gcm_dec(128,4+6ONmgZoNex0arqdTr7bA==,Zm9vb2Zvb29mb29wZm9vbw==,4QMQhILaVLC9oxyB8hGoZA==)]
</code>```

The aead tag is hardcoded on the server for now, based on a simple python script I wrote for generating the encrypted secret. In the future it will probably be passed up by the client -- same with the nonce. Also, note the b64dec converter before the aes_gcm_dec converter. I'm not sure whether or not it's needed. I've tried it both ways and neither works in the current setup.

When I try to do this, HA Proxy silently fails. The header is set to an empty string when it reaches the backend. Even with debug verbosity, HA Proxy doesn't log anything, but clearly something is wrong. Does anyone know what I'm doing wrong here?

答:
I have provided this answer on the HAProxy community Slack chat but in case someone finds this on Google you would do something as follows in HAProxy

```<code>http-request set-var(txn.enc) req.hdr(X-Routing-Key),url_dec,b64dec,bytes(32)
http-request set-var(txn.nonce) req.hdr(X-Routing-Key),url_dec,b64dec,bytes(0,16),base64
http-request set-var(txn.aead_tag) req.hdr(X-Routing-Key),url_dec,b64dec,bytes(16,16),base64
http-request set-header X-Routing-Key %[var(txn.enc),aes_gcm_dec(128,txn.nonce,5AbcQVztUg4LYr406puUkw==,txn.aead_tag)]
</code>```

Make sure your AES output contains the ciphered text, nonce, and aead tag. In the referenced Python it would be something like this:

```<code>print("X-Routing-Key: %s" % (base64.b64encode(b"".join([aesCipher.nonce, authTag, ciphertext]))).decode('utf-8'))
</code>```

Body:
I'm trying to use the HA Proxy aes_gcm_dec converter, but the documentation is sparse to say the least, and I can't find any examples of its use in the community.

I have a client that is sending up a AES GCM 128 encrypted message in an HTTP header, like this:

curl -H "X-Routing-Key: e4+DM/EkJQl4jAAOxNtDZb4dd5Q=" localhost:8000

I'm using HA Proxy to decrypt that header and forward it to the backend server in decrypted form. Here's my frontend config for that:

http-request set-header X-Routing-Key %[req.hdr(X-Routing-Key),b64dec,aes_gcm_dec(128,4+6ONmgZoNex0arqdTr7bA==,Zm9vb2Zvb29mb29wZm9vbw==,4QMQhILaVLC9oxyB8hGoZA==)]

The aead tag is hardcoded on the server for now, based on a simple python script I wrote for generating the encrypted secret. In the future it will probably be passed up by the client -- same with the nonce. Also, note the b64dec converter before the aes_gcm_dec converter. I'm not sure whether or not it's needed. I've tried it both ways and neither works in the current setup.

When I try to do this, HA Proxy silently fails. The header is set to an empty string when it reaches the backend. Even with debug verbosity, HA Proxy doesn't log anything, but clearly something is wrong. Does anyone know what I'm doing wrong here?

Body:
I have provided this answer on the HAProxy community Slack chat but in case someone finds this on Google you would do something as follows in HAProxy

http-request set-var(txn.enc) req.hdr(X-Routing-Key),url_dec,b64dec,bytes(32)
http-request set-var(txn.nonce) req.hdr(X-Routing-Key),url_dec,b64dec,bytes(0,16),base64
http-request set-var(txn.aead_tag) req.hdr(X-Routing-Key),url_dec,b64dec,bytes(16,16),base64
http-request set-header X-Routing-Key %[var(txn.enc),aes_gcm_dec(128,txn.nonce,5AbcQVztUg4LYr406puUkw==,txn.aead_tag)]

Make sure your AES output contains the ciphered text, nonce, and aead tag. In the referenced Python it would be something like this:

print("X-Routing-Key: %s" % (base64.b64encode(b"".join([aesCipher.nonce, authTag, ciphertext]))).decode('utf-8'))


问:
Empty STARTED task in Django Admin Monitor
Have empty record in Django Admin Monitor in Tasks section. It appears once per few hours. Everything works good, but looks like sometimes data is missed.
Backend is custom for Amazon SQS. I am almost sure that problem is here, but I can't reproduce this. Maybe some one have proposition what can cause such behavior or how can I get more information?

Now have CELERY_IGNORE_RESULT = True, can turning this on give more information?

答:
sometime happened also to me, but only when I'm playing with the cam, sometimes when I stop it and restart after a bit seems that cam lost some info.
I think that your celery cam sometime miss some infos or don't  receive some signal for some reason. Make also sure that you have just one celerycam process running on all your servers.</p>


问:
Querying panda DataFrame column to the main datasource
Hi Guys I'm new to python and I want to learn how to query a data column to my data source.

this is my panda dataframe

```<code>[In] top10_athletes = athletes.head(10)
     top10_athletes = top10_athletes.rename(columns={'index': 'Name', 'Name': 'Medal Count'})
     top10_athletes.index = np.arange(1,len(top10_athletes)+1)
     top10_athletes
[Out]
                Name                         Medal Count
1   Michael Fred Phelps, II                      28
2   Larysa Semenivna Latynina (Diriy-)           18
3   Nikolay Yefimovich Andrianov                 15
4   Ole Einar Bjrndalen                          13
5   Borys Anfiyanovych Shakhlin                  13
6   Edoardo Mangiarotti                          13
7   Takashi Ono                                  13
8   Birgit Fischer-Schmidt                       12
9   Paavo Johannes Nurmi                         12
10  Sawao Kato                                   12
</code>```

I want to query all the values in the Name column into my main data source
the only way that I could think of is this piece of code I tried searching in Google

```<code>df.query("Name == 'Michael Fred Phelps, II'")
</code>```

Thanks guys!

答:
To query by Name column you can use the following:

```<code>df[df["Name"] == 'Michael Fred Phelps, II')
</code>```

Body:
Hi Guys I'm new to python and I want to learn how to query a data column to my data source.

this is my panda dataframe

[In] top10_athletes = athletes.head(10)
     top10_athletes = top10_athletes.rename(columns={'index': 'Name', 'Name': 'Medal Count'})
     top10_athletes.index = np.arange(1,len(top10_athletes)+1)
     top10_athletes
[Out]
                Name                         Medal Count
1   Michael Fred Phelps, II                      28
2   Larysa Semenivna Latynina (Diriy-)           18
3   Nikolay Yefimovich Andrianov                 15
4   Ole Einar Bjrndalen                          13
5   Borys Anfiyanovych Shakhlin                  13
6   Edoardo Mangiarotti                          13
7   Takashi Ono                                  13
8   Birgit Fischer-Schmidt                       12
9   Paavo Johannes Nurmi                         12
10  Sawao Kato                                   12

I want to query all the values in the Name column into my main data source
the only way that I could think of is this piece of code I tried searching in Google

df.query("Name == 'Michael Fred Phelps, II'")

Thanks guys!

Body:
To query by Name column you can use the following:

df[df["Name"] == 'Michael Fred Phelps, II')


问:
dataframe: ValueError: The truth value of a Series is ambiguous
I am not sure why I am getting this strange error for this simple if condition.
I have added the function funt to check values in each row of column 'Owner',
first I am checking if row in column 'Owner has any of these values [ 'hal','jula','huli'], if yes then it should return 'cont'.
This returned value will be used to create new column(team) in dataframe df.
Whenever I try to run below code I get this error.

```<code>def funt(row):
  if df['Owner'] in ['hal','jula','huli']:   # error line
     return 'cont'
  elif df['Owner'] == "assigned":
     return "unassigned"
  elif df['Owner'] == "Other":
     return "Other"
  else:
     return "Something else"

df['team'] = df.apply(lambda row: funt(row), axis=1)
</code>```

Error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

答:
hmm, I'm assuming you want to check the value of the row item "Owner" against the list in your if statement?  Would you not instead want to write

if row['Owner'] in ['hal', 'jula', 'huli']:

as it looks that the row object is being passed into the function? df['Owner'] on the other hand would attempt to check the entire dataframe Owner column against the list, therefore resulting in multiple True/False possibilities.  Hence, "ambiguous".

Alternatively, instead of using a function like that in the first place, you could do something like this:

```<code>mappings = {"assigned": "unassigned", "other": "Other"}
df.loc[:, 'Columns1'] = [mappings[value.lower()] if value.lower() in ["assigned", "other"] else "Something else" for value in df.loc[:, 'Owner']]
</code>```

Body:
I am not sure why I am getting this strange error for this simple if condition.
I have added the function funt to check values in each row of column 'Owner',
first I am checking if row in column 'Owner has any of these values [ 'hal','jula','huli'], if yes then it should return 'cont'.
This returned value will be used to create new column(team) in dataframe df.
Whenever I try to run below code I get this error.

def funt(row):
  if df['Owner'] in ['hal','jula','huli']:   # error line
     return 'cont'
  elif df['Owner'] == "assigned":
     return "unassigned"
  elif df['Owner'] == "Other":
     return "Other"
  else:
     return "Something else"

df['team'] = df.apply(lambda row: funt(row), axis=1)

Error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Body:
hmm, I'm assuming you want to check the value of the row item "Owner" against the list in your if statement?  Would you not instead want to write

if row['Owner'] in ['hal', 'jula', 'huli']:

as it looks that the row object is being passed into the function? df['Owner'] on the other hand would attempt to check the entire dataframe Owner column against the list, therefore resulting in multiple True/False possibilities.  Hence, "ambiguous".

Alternatively, instead of using a function like that in the first place, you could do something like this:

mappings = {"assigned": "unassigned", "other": "Other"}
df.loc[:, 'Columns1'] = [mappings[value.lower()] if value.lower() in ["assigned", "other"] else "Something else" for value in df.loc[:, 'Owner']]


问:
Using JavaScript , how do I keep user input on page after it has reloaded?
I used HTML and JavaScript to allow a user to enter text and then push submit. When the user pushes submit, his text is displayed on the page. The problem is that when the page is reloaded, the text goes away. Obviously. Here is the code I have:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

        <TEXTAREA Name="content" ROWS="5" COLS="20" id = "userInput"></TEXTAREA>

        <button  onclick="display()">post</button>

```

With JavaScript, is there anyway to make input stay once the page reloads?

答:
```<code><p id="printhere"></p>
<TEXTAREA Name="content" ROWS="5" COLS="20" id="userInput"></TEXTAREA>
<button  onclick="display()">post</button>

<script>

    function display(){
        var post = document.getElementById("userInput").value;
        localStorage.setItem('userInputValue',post);
    }
    window.addEventListener('load',()=>{
        var savedUserData = localStorage.getItem('userInputValue');
        document.getElementById("printhere").innerHTML = savedUserData;
    });

</script>
</code>```

Edit for multiple input:

```<code><p id="printhere"></p>
<TEXTAREA Name="content" ROWS="5" COLS="20" id="userInput"></TEXTAREA>
<button  onclick="display()">post</button>

<script>

    var num = 0;
    function display(){
        var post = document.getElementById("userInput").value;
        localStorage.setItem(num,post);
        var savedUserData = localStorage.getItem(num);
        document.getElementById("printhere").innerHTML += savedUserData+'<br>';
        num++;
    }

    window.addEventListener('load',()=>{
        if (localStorage.length !== null) {
            for(var i = 0; i < localStorage.length; i++){
                var savedUserData = localStorage.getItem(i);
                document.getElementById("printhere").innerHTML += savedUserData+'<br>';
            }
        }

    });

</script>
</code>```

Body:
I used HTML and JavaScript to allow a user to enter text and then push submit. When the user pushes submit, his text is displayed on the page. The problem is that when the page is reloaded, the text goes away. Obviously. Here is the code I have:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

        <TEXTAREA Name="content" ROWS="5" COLS="20" id = "userInput"></TEXTAREA>

        <button  onclick="display()">post</button>

With JavaScript, is there anyway to make input stay once the page reloads?

Body:
<p id="printhere"></p>
<TEXTAREA Name="content" ROWS="5" COLS="20" id="userInput"></TEXTAREA>
<button  onclick="display()">post</button>

<script>

    function display(){
        var post = document.getElementById("userInput").value;
        localStorage.setItem('userInputValue',post);
    }
    window.addEventListener('load',()=>{
        var savedUserData = localStorage.getItem('userInputValue');
        document.getElementById("printhere").innerHTML = savedUserData;
    });

</script>

Edit for multiple input:

<p id="printhere"></p>
<TEXTAREA Name="content" ROWS="5" COLS="20" id="userInput"></TEXTAREA>
<button  onclick="display()">post</button>

<script>

    var num = 0;
    function display(){
        var post = document.getElementById("userInput").value;
        localStorage.setItem(num,post);
        var savedUserData = localStorage.getItem(num);
        document.getElementById("printhere").innerHTML += savedUserData+'<br>';
        num++;
    }

    window.addEventListener('load',()=>{
        if (localStorage.length !== null) {
            for(var i = 0; i < localStorage.length; i++){
                var savedUserData = localStorage.getItem(i);
                document.getElementById("printhere").innerHTML += savedUserData+'<br>';
            }
        }

    });

</script>


问:
How to modify the url of a request object in fetch API?
I am using Cloudflare worker which is triggered by HTTP requests. I want to take the incoming request, change the url but leave all other properties untouched, and then issue the request. The structure is loke the following: </p>

```<code>addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {

  #change the value of request.url and then...

  return fetch(request)
    .then(response => {
        return response;
    });
}
</code>```

答:
You can do this:

```<code>async function handleRequest(request) {

  #change the value of request.url and then...

  return fetch({...request, url: "someUrl"})
    .then(response => {
        return response;
    });
}
</code>```

This will overwrite the url with "someUrl"
Hope this helps :)

Body:
I am using Cloudflare worker which is triggered by HTTP requests. I want to take the incoming request, change the url but leave all other properties untouched, and then issue the request. The structure is loke the following:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {

  #change the value of request.url and then...

  return fetch(request)
    .then(response => {
        return response;
    });
}

Body:
You can do this:

async function handleRequest(request) {

  #change the value of request.url and then...

  return fetch({...request, url: "someUrl"})
    .then(response => {
        return response;
    });
}

This will overwrite the url with "someUrl"
Hope this helps :)


问:
my react code is working but when i refresh the page i get TypeError: Cannot read property 'Location' of undefined
Starting with GamePage, it provides 2 routes which renders the components GameList and GameDetailPage. Both work fine at first but When i refresh the page for Gamelist component, it still rerenders the page but when i refresh the page for GameDetailPage,  i get the error TypeError: Cannot read property 'Location' of undefined. I do not understand why it is unable to fetch data from state whenever i refresh.

gamepage.jsx

```<code>import React from "react";
import GamesList from "../../components/games-list/game-list.component";
import { Route } from "react-router-dom";
import GameDetailPage from "../gamedetailpage/gamedetailpage.component";
import {firestore,convertCollectionsSnapshotToMap} from '../../firebase/firebase.utils'
import {connect} from 'react-redux'
import {updateFootballGames} from '../../redux/games/games.actions'

class GamePage extends React.Component {

  unsubscribeFromSnapshot=null;

  //whenever the component mounts the state will be updated with the football games.
  componentDidMount(){
    const {updateFootballGames}=this.props
    const gameRef=firestore.collection('footballgames')
    gameRef.onSnapshot(async snapshot=>{
      const collectionsMap=convertCollectionsSnapshotToMap(snapshot)
      updateFootballGames(collectionsMap)
    })
  }
  render() {
    const { match } = this.props;
    return (
      <div className="game-page">
        <h1>games page</h1>
        <Route exact path={`${match.path}`} component={GamesList} />
        <Route path={`${match.path}/:linkUrl`} component={GameDetailPage}
         />
      </div>
    );
  }
}

const mapStateToProps=state=>({
  games:state.games.games
})

const mapDispatchToProps=dispatch=>({
  updateFootballGames:collectionsMap=>
  dispatch(updateFootballGames(collectionsMap))
})

export default connect(mapStateToProps, mapDispatchToProps)(GamePage);
</code>```

gamedetailpage.component.jsx

```<code>  import React from "react";
    import { connect } from "react-redux";
    import GamePreview from '../../components/game-preview/game-preview.component'
    import GameDetails from '../../components/game-details/game-details.component'

const GameDetailPage = (props) => {
    const {games, match} = props
    const urlparam =match.params.linkUrl
    // const games_array = Object.entries(games)
    const gameObj=games[urlparam]
    console.log('prop',gameObj)

    return (
      <div className="game-list">
          <GameDetails game = {gameObj}/>
      </div>

    );

};

const mapStateToProps = (state) => ({
  games: state.games.games,
});

export default connect(mapStateToProps)(GameDetailPage);
</code>```

game_details.component.jsx

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

const GameDetails = (props) => {
    console.log(props.game.Location)

    return(
    <div>
    Location:{props.game.Location}
    <br/>
    Price:{props.game.Price}
    </div>

    )
}

export default GameDetails;
</code>```

gamelist.component.jsx

```<code>import React from "react";
import './game-list.styles.scss'
import GamePreview from "../game-preview/game-preview.component";
import {connect} from 'react-redux'

const GameList=(props)=>{
    const {games}=props
    console.log(games)
    const game_list=Object.entries(games)
    console.log(game_list)
    return (
      <div className="game-list">
        {game_list.map(game =>
                <GamePreview game = {game[1]}/>)}
      </div>

    );
  }

const mapStateToProps=state=>({
  games:state.games.games
})

export default connect(mapStateToProps)(GameList);
</code>```

gamepreview.component.jsx

```<code>import React from "react";
import "./game-preview.styles.scss";
import { withRouter, Route } from "react-router-dom";

import GamePreviewDetail from "../game-preview-detail/game-preview-detail.component";

const GamePreview = (props) => {
  const { Location, Time, linkUrl, Price } = props.game;
  const { history, match } = props;
  return (
    <div
      className="game-preview"
      onClick={() => history.push(`${match.url}/${linkUrl}`)}
    >
      <div className="game-preview-image">
        <p>Picture goes here</p>
      </div>
      {/* <GamePreviewDetail name = {Location} price={Price}/> */}
      <p>Location:{Location}</p>
      <p>Price:{Price}</p>
    </div>
  );
};

export default withRouter(GamePreview);
</code>```

app.js

```<code>import React from 'react';
import './App.css';
//import dependencies
import { Route, Switch } from "react-router-dom";
//import pages
import HomePage from './pages/homepage/homepage'
import GamesPage from './pages/gamespage/gamespage'
import SignInSignUp from './pages/signin-signup-page/signin-signup-page'

import GameDetailPage from "./pages/gamedetailpage/gamedetailpage.component";

import Header from './components/header/header.component';

import { auth, createUserProfileDocument } from './firebase/firebase.utils';

class App extends React.Component{
  constructor() {
    super();

    this.state = {
      currentUser: null
    }
  }

  unsubscribeFromAuth = null

  componentDidMount() {
  this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
    if (userAuth) {
      const userRef = await createUserProfileDocument(userAuth);
      // check if the snapshot has changed (subscribe)
      // get the user that we just created or that already exists in the db
      userRef.onSnapshot(snapshot => {
        this.setState({
          currentUser: {
            id: snapshot.id,
            ...snapshot.data()}
        })
      })
    } else {
      this.setState({currentUser: userAuth})
    }

    })
  }

  componentWillUnmount() {
    this.unsubscribeFromAuth();
  }

  render(){
    return(
      <div>
        <Header currentUser = {this.state.currentUser}/>
         <Switch>
          <Route exact path="/" component={HomePage} />
          <Route path="/games" component={GamesPage} />
          <Route exact path="/signin" component={SignInSignUp} />
        </Switch>
      </div>
    )
  }
}
export default App;
</code>```

答:
I would try using useParams hook instead. Then capturing any changes of linkUrl with useEffect hook. Also introducing gameObj with useState.

useParams returns an object of key/value pairs of URL parameters. Use it to access match.params of the current <Route>.

If you're familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

Try to modify <GameDetailPage /> component as the following:

```<code>import React, { useState, useEffect } from 'react';
import { useParams } from "react-router-dom";
// other imports

const GameDetailPage = (props) => {
   const { games } = props;
   let { linkUrl } = useParams();
   const [ gameObj, setGameObj ] = useState(null);

   useEffect(() => {
      if (games) {
         const newGameObj = games[linkUrl];
         console.log('game object', newGameObj);

         setGameObj(newGameObj);
      }
   }, [games, linkUrl]);

   return <div className="game-list">
      { gameObj && <GameDetails game={ gameObj } /> }
   </div>
}
</code>```

+1 - null check:

Also you can see a null check in the return statement for gameObj which helps rendering only that case once you have a value in games array with found linkUrl value.

I hope this helps!

Body:
Starting with GamePage, it provides 2 routes which renders the components GameList and GameDetailPage. Both work fine at first but When i refresh the page for Gamelist component, it still rerenders the page but when i refresh the page for GameDetailPage,  i get the error TypeError: Cannot read property 'Location' of undefined. I do not understand why it is unable to fetch data from state whenever i refresh.

gamepage.jsx

import React from "react";
import GamesList from "../../components/games-list/game-list.component";
import { Route } from "react-router-dom";
import GameDetailPage from "../gamedetailpage/gamedetailpage.component";
import {firestore,convertCollectionsSnapshotToMap} from '../../firebase/firebase.utils'
import {connect} from 'react-redux'
import {updateFootballGames} from '../../redux/games/games.actions'

class GamePage extends React.Component {

  unsubscribeFromSnapshot=null;

  //whenever the component mounts the state will be updated with the football games.
  componentDidMount(){
    const {updateFootballGames}=this.props
    const gameRef=firestore.collection('footballgames')
    gameRef.onSnapshot(async snapshot=>{
      const collectionsMap=convertCollectionsSnapshotToMap(snapshot)
      updateFootballGames(collectionsMap)
    })
  }
  render() {
    const { match } = this.props;
    return (

games page

        <Route exact path={`${match.path}`} component={GamesList} />
        <Route path={`${match.path}/:linkUrl`} component={GameDetailPage}
         />

    );
  }
}

const mapStateToProps=state=>({
  games:state.games.games
})

const mapDispatchToProps=dispatch=>({
  updateFootballGames:collectionsMap=>
  dispatch(updateFootballGames(collectionsMap))
})

export default connect(mapStateToProps, mapDispatchToProps)(GamePage);

gamedetailpage.component.jsx

  import React from "react";
    import { connect } from "react-redux";
    import GamePreview from '../../components/game-preview/game-preview.component'
    import GameDetails from '../../components/game-details/game-details.component'

const GameDetailPage = (props) => {
    const {games, match} = props
    const urlparam =match.params.linkUrl
    // const games_array = Object.entries(games)
    const gameObj=games[urlparam]
    console.log('prop',gameObj)

    return (

          <GameDetails game = {gameObj}/>

    );

};

const mapStateToProps = (state) => ({
  games: state.games.games,
});

export default connect(mapStateToProps)(GameDetailPage);

game_details.component.jsx

import React from 'react';

const GameDetails = (props) => {
    console.log(props.game.Location)

    return(

    Location:{props.game.Location}

    Price:{props.game.Price}

    )
}

export default GameDetails;

gamelist.component.jsx

import React from "react";
import './game-list.styles.scss'
import GamePreview from "../game-preview/game-preview.component";
import {connect} from 'react-redux'

const GameList=(props)=>{
    const {games}=props
    console.log(games)
    const game_list=Object.entries(games)
    console.log(game_list)
    return (

        {game_list.map(game =>
                <GamePreview game = {game[1]}/>)}

    );
  }

const mapStateToProps=state=>({
  games:state.games.games
})

export default connect(mapStateToProps)(GameList);

gamepreview.component.jsx

import React from "react";
import "./game-preview.styles.scss";
import { withRouter, Route } from "react-router-dom";

import GamePreviewDetail from "../game-preview-detail/game-preview-detail.component";

const GamePreview = (props) => {
  const { Location, Time, linkUrl, Price } = props.game;
  const { history, match } = props;
  return (

 history.push(`${match.url}/${linkUrl}`)}
    >

Picture goes here

      {/* <GamePreviewDetail name = {Location} price={Price}/> */}

Location:{Location}

Price:{Price}

  );
};

export default withRouter(GamePreview);

app.js

import React from 'react';
import './App.css';
//import dependencies
import { Route, Switch } from "react-router-dom";
//import pages
import HomePage from './pages/homepage/homepage'
import GamesPage from './pages/gamespage/gamespage'
import SignInSignUp from './pages/signin-signup-page/signin-signup-page'

import GameDetailPage from "./pages/gamedetailpage/gamedetailpage.component";

import Header from './components/header/header.component';

import { auth, createUserProfileDocument } from './firebase/firebase.utils';

class App extends React.Component{
  constructor() {
    super();

    this.state = {
      currentUser: null
    }
  }

  unsubscribeFromAuth = null

  componentDidMount() {
  this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
    if (userAuth) {
      const userRef = await createUserProfileDocument(userAuth);
      // check if the snapshot has changed (subscribe)
      // get the user that we just created or that already exists in the db
      userRef.onSnapshot(snapshot => {
        this.setState({
          currentUser: {
            id: snapshot.id,
            ...snapshot.data()}
        })
      })
    } else {
      this.setState({currentUser: userAuth})
    }

    })
  }

  componentWillUnmount() {
    this.unsubscribeFromAuth();
  }

  render(){
    return(

         <Switch>
          <Route exact path="/" component={HomePage} />
          <Route path="/games" component={GamesPage} />
          <Route exact path="/signin" component={SignInSignUp} />
        </Switch>

    )
  }
}
export default App;

Body:
I would try using useParams hook instead. Then capturing any changes of linkUrl with useEffect hook. Also introducing gameObj with useState.

useParams returns an object of key/value pairs of URL parameters. Use it to access match.params of the current <Route>.

If you're familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

Try to modify <GameDetailPage /> component as the following:

import React, { useState, useEffect } from 'react';
import { useParams } from "react-router-dom";
// other imports

const GameDetailPage = (props) => {
   const { games } = props;
   let { linkUrl } = useParams();
   const [ gameObj, setGameObj ] = useState(null);

   useEffect(() => {
      if (games) {
         const newGameObj = games[linkUrl];
         console.log('game object', newGameObj);

         setGameObj(newGameObj);
      }
   }, [games, linkUrl]);

   return <div className="game-list">
      { gameObj && <GameDetails game={ gameObj } /> }
   </div>
}

+1 - null check:

Also you can see a null check in the return statement for gameObj which helps rendering only that case once you have a value in games array with found linkUrl value.

I hope this helps!