问:
How can I make a hh: mm:ss countdown with a 6 digit timestamp?
I have made a countdown, but it's not working properly. Please run the following working snippet.

     tiempoUltimoCambioScrubber()

     function tiempoUltimoCambioScrubber() {

                var resJson;
                var now;
                var remainingTime;
                var lastChange;
                var dateux;
                var resultx;
                var trueOrFalse;
                var dateObj;
                var m;
                var h;
                var s;
                var timeString;

                setInterval(function () {
                       // the below response is the result of a HTTP request
                        response = [ {
                            dataType : "BINARY",
                            value : true,
                            timestamp : 1590724809944,
                            annotation : null
                          }];

                        resJson = response;

                        lastChange = resJson[0].timestamp;

                        trueOrFalse = resJson[0].value;

                        now = new Date().getTime();

                        remainingTime = now - lastChange;

                        // $scope.remainingTime = remainingTime;

                        dateObj = new Date(remainingTime * 1000);
                        h = dateObj.getUTCHours();
                        m = dateObj.getUTCMinutes();
                        s = dateObj.getSeconds();

                        timeString = h.toString().padStart(2, '0') + ':' +
                          m.toString().padStart(2, '0') + ':' +
                          s.toString().padStart(2, '0');

                        // $scope.timeString = timeString;

                        console.log(timeString);

                        // if (!trueOrFalse) {
                        //     // Here I'll reset the counter to 0
                        // }

                }, 1000);
              }```

The subtraction corresponds to a maximum of 15 minutes timestamp.  Because the response object gets updated each 15 minutes; remainingTime = now - lastChange; is always a value very similar to this: 540519 .. a 6 digit number.. And my counter behaves like crazy with a tiny timestamp like that... How can I manage to make this counter works with this tiny remainingTime variable?

Thanks.

答:
Your problem is that you are multiplying remainingTime by 1000 when you create dateObj, but it is already a millisecond value so doesn't need it. Change that line to

```<code>dateObj = new Date(remainingTime);
</code>```

and the counter correctly goes up in seconds (as defined by your input to setInterval).

tiempoUltimoCambioScrubber()

function tiempoUltimoCambioScrubber() {

  var resJson;
  var now;
  var remainingTime;
  var lastChange;
  var dateux;
  var resultx;
  var trueOrFalse;
  var dateObj;
  var m;
  var h;
  var s;
  var timeString;

  setInterval(function() {
    // the below response is the result of a HTTP request
    response = [{
      dataType: "BINARY",
      value: true,
      timestamp: 1590724809944,
      annotation: null
    }];

    resJson = response;

    lastChange = resJson[0].timestamp;

    trueOrFalse = resJson[0].value;

    now = new Date().getTime();

    remainingTime = now - lastChange;

    // $scope.remainingTime = remainingTime;

    dateObj = new Date(remainingTime);
    h = dateObj.getUTCHours();
    m = dateObj.getUTCMinutes();
    s = dateObj.getSeconds();

    timeString = h.toString().padStart(2, '0') + ':' +
      m.toString().padStart(2, '0') + ':' +
      s.toString().padStart(2, '0');

    // $scope.timeString = timeString;

    console.log(timeString);

    // if (!trueOrFalse) {
    //     // Here I'll reset the counter to 0
    // }

  }, 1000);
}```

Body:
I have made a countdown, but it's not working properly. Please run the following working snippet.

     tiempoUltimoCambioScrubber()

     function tiempoUltimoCambioScrubber() {

                var resJson;
                var now;
                var remainingTime;
                var lastChange;
                var dateux;
                var resultx;
                var trueOrFalse;
                var dateObj;
                var m;
                var h;
                var s;
                var timeString;

                setInterval(function () {
                       // the below response is the result of a HTTP request
                        response = [ {
                            dataType : "BINARY",
                            value : true,
                            timestamp : 1590724809944,
                            annotation : null
                          }];

                        resJson = response;

                        lastChange = resJson[0].timestamp;

                        trueOrFalse = resJson[0].value;

                        now = new Date().getTime();

                        remainingTime = now - lastChange;

                        // $scope.remainingTime = remainingTime;

                        dateObj = new Date(remainingTime * 1000);
                        h = dateObj.getUTCHours();
                        m = dateObj.getUTCMinutes();
                        s = dateObj.getSeconds();

                        timeString = h.toString().padStart(2, '0') + ':' +
                          m.toString().padStart(2, '0') + ':' +
                          s.toString().padStart(2, '0');

                        // $scope.timeString = timeString;

                        console.log(timeString);

                        // if (!trueOrFalse) {
                        //     // Here I'll reset the counter to 0
                        // }

                }, 1000);
              }

The subtraction corresponds to a maximum of 15 minutes timestamp.  Because the response object gets updated each 15 minutes; remainingTime = now - lastChange; is always a value very similar to this: 540519 .. a 6 digit number.. And my counter behaves like crazy with a tiny timestamp like that... How can I manage to make this counter works with this tiny remainingTime variable?

Thanks.

Body:
Your problem is that you are multiplying remainingTime by 1000 when you create dateObj, but it is already a millisecond value so doesn't need it. Change that line to

dateObj = new Date(remainingTime);

and the counter correctly goes up in seconds (as defined by your input to setInterval).

tiempoUltimoCambioScrubber()

function tiempoUltimoCambioScrubber() {

  var resJson;
  var now;
  var remainingTime;
  var lastChange;
  var dateux;
  var resultx;
  var trueOrFalse;
  var dateObj;
  var m;
  var h;
  var s;
  var timeString;

  setInterval(function() {
    // the below response is the result of a HTTP request
    response = [{
      dataType: "BINARY",
      value: true,
      timestamp: 1590724809944,
      annotation: null
    }];

    resJson = response;

    lastChange = resJson[0].timestamp;

    trueOrFalse = resJson[0].value;

    now = new Date().getTime();

    remainingTime = now - lastChange;

    // $scope.remainingTime = remainingTime;

    dateObj = new Date(remainingTime);
    h = dateObj.getUTCHours();
    m = dateObj.getUTCMinutes();
    s = dateObj.getSeconds();

    timeString = h.toString().padStart(2, '0') + ':' +
      m.toString().padStart(2, '0') + ':' +
      s.toString().padStart(2, '0');

    // $scope.timeString = timeString;

    console.log(timeString);

    // if (!trueOrFalse) {
    //     // Here I'll reset the counter to 0
    // }

  }, 1000);
}


来源: stackexchange

问:
Parsing a CSV string in Shell Script and writing it to a File
I am not a Linux scripting expert and I have exhausted my knowledge on this matter. Here is my situation.

I have a list of states passed as a command line argument to a shell script ( e.g "AL,AK,AS,AZ,AR,CA..." ). The Shell script needs to extract each of the state code and write it to a file ( states.txt) , with each state in one line. See below

```<code>AL
AK
AS
AZ
AR
CA
..
..
</code>```

How can this be achieved using a linux shell script.

Thanks in advance.

答:
I think awk is the simplest solution, but you could try using cut in a loop.
Sample script (outputs to stdout, but you can just redirect it):

```<code>#!/bin/bash

# Check for input
if (( ${#1} == 0 )); then
  echo No input data supplied
  exit
fi

# Initialise first input
i=$1

# While $i still contains commas
while { echo $i| grep , > /dev/null; }; do
  # Get first item of $i
  j=`echo $i | cut -d ',' -f '1'`

  # Shift off the first item of $i
  i=`echo $i | cut --complement -d ',' -f '1'`

  echo $j
done

# Display the last item
echo $i
</code>```

Then you can just run it as ./script.sh "AL,AK,AS,AZ,AR,CA" > states.txt (assuming you save it as script.sh in the local directory and give it execute permission)

ContentLicense: CC BY-SA 3.0

Body:
I am not a Linux scripting expert and I have exhausted my knowledge on this matter. Here is my situation.

I have a list of states passed as a command line argument to a shell script ( e.g "AL,AK,AS,AZ,AR,CA..." ). The Shell script needs to extract each of the state code and write it to a file ( states.txt) , with each state in one line. See below

AL
AK
AS
AZ
AR
CA
..
..

How can this be achieved using a linux shell script.

Thanks in advance.

Body:
I think awk is the simplest solution, but you could try using cut in a loop.
Sample script (outputs to stdout, but you can just redirect it):

#!/bin/bash

# Check for input
if (( ${#1} == 0 )); then
  echo No input data supplied
  exit
fi

# Initialise first input
i=$1

# While $i still contains commas
while { echo $i| grep , > /dev/null; }; do
  # Get first item of $i
  j=`echo $i | cut -d ',' -f '1'`

  # Shift off the first item of $i
  i=`echo $i | cut --complement -d ',' -f '1'`

  echo $j
done

# Display the last item
echo $i

Then you can just run it as ./script.sh "AL,AK,AS,AZ,AR,CA" > states.txt (assuming you save it as script.sh in the local directory and give it execute permission)


问:
Unregistering BroadcastReceiver registered in Activity context results in IllegalArgumentException crash
The crash is pretty strange one.

In onStart, BroadcastReceiver that is stored in the Activity field is registered. In onStop, this BroadcastReceiver is unregistered. When BroadcastReceiver was successfully registered, I also set isRegistered field to true, and before I unregister the receiver, I check this field to see if we need

However, in Crashlytics I see that sometimes this fails, and the whole app crashes with IllegalArgumentException with Receiver not registered message, which originates from android.app.LoadedApk#forgetReceiverDispatcher. Which is pretty strange, considering that I check the flag, right?

After I looked into ContextImpl and LoadedApk classes which handle registration/unregistration and added some reflection-based diagnostics, it got even more mysterious. In short, on every crash like that I will extract the map of existing Context to BroadcastReceiver (see ContextImpl.java:1590 and LoadedApk.java:1361).

When it unregisters normally, without a crash I can see a map like this:

```<code>com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide
com.mypackage.myapp.MyActivity1 instance -> list of instances that are registered for Activity1
com.mypackage.myapp.MyActivity2 instance -> list of instances that are registered for Activity2
...
</code>```

However, in the event of the crash this map looks like this:

```<code>com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide
</code>```

i.e. there are no activities in which my BroadcastReceiver is registered, even though I never called unregisterReceiver!

It only happens in one specific activity, so my first guess was that this activity is leaked somehow, onDestroy lifecycle gets called, Activity entry get removed from receivers map, and then obviously the receiver won't be there when we try to unregister it. However, if that's the case, why is onStop being called after onDestroy then? And why then the receivers list is completely empty?

And if it's not the leak, then what can lead to such puzzling behaviour? I truly hope that somebody else has experienced such a strange occurrence, and may be able to help me, because right now I'm all out of ideas.

答:
Edited

Lets just say I've felt the pain. For the sake of my own problem I just found a fix, but, to answer your question I really dived deeply into docs and SO older questions even wrote simple code and checked some lifeCycle tests myself(in which I though I had found the answer which I was wrong). I couldn't find the reason this incident happens, but to fix it I suggest wrap the register/unRegister in a try catch block:

```<code>private void registerBroadcastReceiver() {
    try {
        appUpdateReceiver = new AppUpdateReceiver();
        registerReceiver(appUpdateReceiver, appUpdateIntentFilter);
    } catch (IllegalArgumentException e) {
        // already registered
    }
}

private void unRegisterBroadCastReceiver() {
    try {
        unregisterReceiver(appUpdateReceiver);
    } catch (IllegalArgumentException e) {
        // already unregistered
    }
}
</code>```

Please provide some code so the community can look into this matter more deeply. And thanks for mentioning the LoadedApk class.

ContentLicense: CC BY-SA 4.0

Body:
The crash is pretty strange one.

In onStart, BroadcastReceiver that is stored in the Activity field is registered. In onStop, this BroadcastReceiver is unregistered. When BroadcastReceiver was successfully registered, I also set isRegistered field to true, and before I unregister the receiver, I check this field to see if we need

However, in Crashlytics I see that sometimes this fails, and the whole app crashes with IllegalArgumentException with Receiver not registered message, which originates from android.app.LoadedApk#forgetReceiverDispatcher. Which is pretty strange, considering that I check the flag, right?

After I looked into ContextImpl and LoadedApk classes which handle registration/unregistration and added some reflection-based diagnostics, it got even more mysterious. In short, on every crash like that I will extract the map of existing Context to BroadcastReceiver (see ContextImpl.java:1590 and LoadedApk.java:1361).

When it unregisters normally, without a crash I can see a map like this:

com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide
com.mypackage.myapp.MyActivity1 instance -> list of instances that are registered for Activity1
com.mypackage.myapp.MyActivity2 instance -> list of instances that are registered for Activity2
...

However, in the event of the crash this map looks like this:

com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide

i.e. there are no activities in which my BroadcastReceiver is registered, even though I never called unregisterReceiver!

It only happens in one specific activity, so my first guess was that this activity is leaked somehow, onDestroy lifecycle gets called, Activity entry get removed from receivers map, and then obviously the receiver won't be there when we try to unregister it. However, if that's the case, why is onStop being called after onDestroy then? And why then the receivers list is completely empty?

And if it's not the leak, then what can lead to such puzzling behaviour? I truly hope that somebody else has experienced such a strange occurrence, and may be able to help me, because right now I'm all out of ideas.

Body:
Edited

Lets just say I've felt the pain. For the sake of my own problem I just found a fix, but, to answer your question I really dived deeply into docs and SO older questions even wrote simple code and checked some lifeCycle tests myself(in which I though I had found the answer which I was wrong). I couldn't find the reason this incident happens, but to fix it I suggest wrap the register/unRegister in a try catch block:

private void registerBroadcastReceiver() {
    try {
        appUpdateReceiver = new AppUpdateReceiver();
        registerReceiver(appUpdateReceiver, appUpdateIntentFilter);
    } catch (IllegalArgumentException e) {
        // already registered
    }
}

private void unRegisterBroadCastReceiver() {
    try {
        unregisterReceiver(appUpdateReceiver);
    } catch (IllegalArgumentException e) {
        // already unregistered
    }
}

Please provide some code so the community can look into this matter more deeply. And thanks for mentioning the LoadedApk class.


问:
Under what conditions does MSVC C++ Compiler sometimes write the array size directly before the pointer returned from function operator new[]?
I'm currently working on a memory tracker for work, and we are overloading the function operator new[], in its many variations.  While writing some unit tests, I stumbled across the fact that MSVC C++ 2019 (using the ISO C++ 17 Standard(std:c++17) compiler setting), writes the size of the allocated array of objects directly before the pointer returned to the caller, but only sometimes.  I have been unable to find any documented conditions under which this will occur.  Can anyone please explain what those conditions are, how I can detect them at runtime, and or point me to any documentation?

To even determine this was happening, I had to disassemble the code. Here is the C++:

```<code>const size_t k_NumFoos = 6;
Foo* pFoo = new Foo[k_NumFoos];
</code>```

And here is the disassembly:

```<code>00007FF747BB3683  call        operator new[] (07FF747A00946h)
00007FF747BB3688  mov         qword ptr [rbp+19E8h],rax
00007FF747BB368F  cmp         qword ptr [rbp+19E8h],0
00007FF747BB3697  je          ____C_A_T_C_H____T_E_S_T____0+0FF7h (07FF747BB36F7h)
00007FF747BB3699  mov         rax,qword ptr [rbp+19E8h]
00007FF747BB36A0  mov         qword ptr [rax],6
00007FF747BB36A7  mov         rax,qword ptr [rbp+19E8h]
00007FF747BB36AE  add         rax,8
00007FF747BB36B2  mov         qword ptr [rbp+1B58h],rax
</code>```

The cmp and je lines are from the Catch2 library we are using for our unit tests.  The subsequent two movs, following the je, are where it's writing the array size.  The next three lines (mov, add, mov) are where it's moving the pointer to after where it has written the array size.  This is all well and good, mostly.

We are also using MS's VirtualAlloc as the allocator internal to the overloaded function operator new[].  The address returned from VirtualAlloc must be aligned for the function operator new[] that uses std::align_t, and when the alignment is greater than the default max alignment, the moving of the pointer in those last three lines of disassembly are messing with the aligned address being returned.  Initially, I thought all allocations made with function operator new[] would have this behavior.  So, I tested some other uses of function operator new[], and found it to be true in all cases I tested.  I wrote the code to adjust for this behavior, and then ran into a case where it doesn't exhibit the behavior of writing the array size before the returned allocation.

Here is the C++ of where it is not writing the array size before the returned allocation:

```<code>char **utf8Argv = new char *[ argc ];
</code>```

argc is equal to 1.  The line comes from the Session::applyCommandLine method in the Catch2 library.  The disassembly looks like so:

```<code>00007FF73E189C6A  call        operator new[] (07FF73E07D6D8h)
00007FF73E189C6F  mov         qword ptr [rbp+168h],rax
00007FF73E189C76  mov         rax,qword ptr [rbp+168h]
00007FF73E189C7D  mov         qword ptr [utf8Argv],rax
</code>```

Notice after the call to operator new[] (07FF73E07D6F8h) there is no writing of the array size.  When looking at the two for differences, I can see that one writes to a pointer, while the other writes to a pointer to a pointer.  However, none of that information is available internally, at runtime, to function operator new[], as far as I know.

The code here comes from a Debug | x64 build.  Any ideas on how to determine when this behavior will occur?

Update (for convo below):
Class Foo:

```<code>template<size_t ArrLen>
class TFoo
{
public:
    TFoo()
    {
        memset(m_bar, 0, ArrLen);
    }
    TFoo(const TFoo<ArrLen>& other)
    {
        strncpy_s(m_bar, other.m_bar, ArrLen);
    }
    TFoo(TFoo<ArrLen>&& victim)
    {
        strncpy_s(m_bar, victim.m_bar, ArrLen);
    }
    ~TFoo()
    {
    }
    TFoo<ArrLen>& operator= (const TFoo<ArrLen>& other)
    {
        strncpy_s(m_bar, other.m_bar, ArrLen);
    }
    TFoo<ArrLen>& operator= (TFoo<ArrLen>&& victim)
    {
        strncpy_s(m_bar, victim.m_bar, ArrLen);
    }

    const char* GetBar()
    {
        return m_bar;
    }
    void SetBar(const char bar[ArrLen])
    {
        strncpy_s(m_bar, bar, ArrLen);
    }

protected:
    char m_bar[ArrLen];
};
using Foo = TFoo<8>;
</code>```

答:
At a guess, I would think the compiler would write the number of objects allocated out before the pointer returned to you when it is allocating objects which have a destructor that needs to be called when you call delete [].  Under those circumstances, the compiler has to emit code to destroy each of the objects allocated when you call delete [], and to do that, it needs to know how many objects are present in the array.

OTOH, for something like char *, no count is needed, and so, as a minor optimisation, none is emitted, or so it would seem.

I don't suppose you'll find this documented anywhere and the behaviour might change in future versions of the compiler.  It doesn't seem to be part of the standard.

Body:
I'm currently working on a memory tracker for work, and we are overloading the function operator new[], in its many variations.  While writing some unit tests, I stumbled across the fact that MSVC C++ 2019 (using the ISO C++ 17 Standard(std:c++17) compiler setting), writes the size of the allocated array of objects directly before the pointer returned to the caller, but only sometimes.  I have been unable to find any documented conditions under which this will occur.  Can anyone please explain what those conditions are, how I can detect them at runtime, and or point me to any documentation?

To even determine this was happening, I had to disassemble the code. Here is the C++:

const size_t k_NumFoos = 6;
Foo* pFoo = new Foo[k_NumFoos];

And here is the disassembly:

00007FF747BB3683  call        operator new[] (07FF747A00946h)
00007FF747BB3688  mov         qword ptr [rbp+19E8h],rax
00007FF747BB368F  cmp         qword ptr [rbp+19E8h],0
00007FF747BB3697  je          ____C_A_T_C_H____T_E_S_T____0+0FF7h (07FF747BB36F7h)
00007FF747BB3699  mov         rax,qword ptr [rbp+19E8h]
00007FF747BB36A0  mov         qword ptr [rax],6
00007FF747BB36A7  mov         rax,qword ptr [rbp+19E8h]
00007FF747BB36AE  add         rax,8
00007FF747BB36B2  mov         qword ptr [rbp+1B58h],rax

The cmp and je lines are from the Catch2 library we are using for our unit tests.  The subsequent two movs, following the je, are where it's writing the array size.  The next three lines (mov, add, mov) are where it's moving the pointer to after where it has written the array size.  This is all well and good, mostly.

We are also using MS's VirtualAlloc as the allocator internal to the overloaded function operator new[].  The address returned from VirtualAlloc must be aligned for the function operator new[] that uses std::align_t, and when the alignment is greater than the default max alignment, the moving of the pointer in those last three lines of disassembly are messing with the aligned address being returned.  Initially, I thought all allocations made with function operator new[] would have this behavior.  So, I tested some other uses of function operator new[], and found it to be true in all cases I tested.  I wrote the code to adjust for this behavior, and then ran into a case where it doesn't exhibit the behavior of writing the array size before the returned allocation.

Here is the C++ of where it is not writing the array size before the returned allocation:

char **utf8Argv = new char *[ argc ];

argc is equal to 1.  The line comes from the Session::applyCommandLine method in the Catch2 library.  The disassembly looks like so:

00007FF73E189C6A  call        operator new[] (07FF73E07D6D8h)
00007FF73E189C6F  mov         qword ptr [rbp+168h],rax
00007FF73E189C76  mov         rax,qword ptr [rbp+168h]
00007FF73E189C7D  mov         qword ptr [utf8Argv],rax

Notice after the call to operator new[] (07FF73E07D6F8h) there is no writing of the array size.  When looking at the two for differences, I can see that one writes to a pointer, while the other writes to a pointer to a pointer.  However, none of that information is available internally, at runtime, to function operator new[], as far as I know.

The code here comes from a Debug | x64 build.  Any ideas on how to determine when this behavior will occur?

Update (for convo below):
Class Foo:

template<size_t ArrLen>
class TFoo
{
public:
    TFoo()
    {
        memset(m_bar, 0, ArrLen);
    }
    TFoo(const TFoo<ArrLen>& other)
    {
        strncpy_s(m_bar, other.m_bar, ArrLen);
    }
    TFoo(TFoo<ArrLen>&& victim)
    {
        strncpy_s(m_bar, victim.m_bar, ArrLen);
    }
    ~TFoo()
    {
    }
    TFoo<ArrLen>& operator= (const TFoo<ArrLen>& other)
    {
        strncpy_s(m_bar, other.m_bar, ArrLen);
    }
    TFoo<ArrLen>& operator= (TFoo<ArrLen>&& victim)
    {
        strncpy_s(m_bar, victim.m_bar, ArrLen);
    }

    const char* GetBar()
    {
        return m_bar;
    }
    void SetBar(const char bar[ArrLen])
    {
        strncpy_s(m_bar, bar, ArrLen);
    }

protected:
    char m_bar[ArrLen];
};
using Foo = TFoo<8>;


问:
SwiftUI, weird NavigationLink behavior when working with actionSheet
I want to detect if the user meets the prerequisite first before I let him/her in. If the prerequisite is not met, the app will pop an actionSheet and show the user some ways to unlock the feature.
It works perfectly fine when I tap on the text. But when I tap on the blank place on the list. It just skip the Binding. And the weird thing is that in my actually project, the Binding becomes "true" even if I only set it to false.
Here's the question. Am I using the correct approach or did I miss anything? Or is this a bug?
Thank you.

```<code>struct ContentView: View {
    @State var linkOne = false
    @State var linkTwo = false
    @State var linkThree = false
    @State var actionOne = false
    @State var actionTwo = false
    @State var actionThree = false
    var body: some View {
        NavigationView{
            List{
                        NavigationLink("Destination View One", destination: DestOneView(), isActive: self.$linkOne)
                            .actionSheet(isPresented: self.$actionOne) { () -> ActionSheet in
                                ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }.onTapGesture {
                            self.actionOne = true
//                            self.linkOne = true
                        }
                        NavigationLink("Destination View Two", destination: DestTwoView(), isActive: self.$linkTwo)
                        .actionSheet(isPresented: self.$actionTwo) { () -> ActionSheet in
                        ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }
                        .onTapGesture {
                            self.actionTwo = true
//                            self.linkTwo = true
                        }
                        NavigationLink("Destination View Three", destination: DestThreeView(), isActive: self.$linkThree)
                        .actionSheet(isPresented: self.$actionThree) { () -> ActionSheet in
                        ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }
                        .onTapGesture {
                            self.actionThree = true
//                            self.linkThree = true
                        }
                    }
        }

    }
}
</code>```

Three other views.

```<code>struct DestOneView: View {
    var body: some View {
        Text("First View")
    }
}

struct DestTwoView: View {
    var body: some View {
        Text("Second View")
    }
}

struct DestThreeView: View {
    var body: some View {
        Text("Third View")
    }
}
</code>```

答:
Generally overriding gestures does not work well within the List. One of the solutions can be to use a Button to present a NavigationLink:

```<code>import SwiftUI

struct ContentView: View {
    @State private var linkOne = false
    ...

    var body: some View {
        NavigationView {
            List {
                NavigationLink(destination: SomeView(), isActive: $linkOne) {
                    EmptyView()
                }

                Button(action: {
                    // here you can perform actions
                    self.linkOne = true
                }, label: {
                    Text("Some text!")
                })

                Spacer()
            }
        }
    }
}
</code>```

Body:
I want to detect if the user meets the prerequisite first before I let him/her in. If the prerequisite is not met, the app will pop an actionSheet and show the user some ways to unlock the feature.
It works perfectly fine when I tap on the text. But when I tap on the blank place on the list. It just skip the Binding. And the weird thing is that in my actually project, the Binding becomes "true" even if I only set it to false.
Here's the question. Am I using the correct approach or did I miss anything? Or is this a bug?
Thank you.

struct ContentView: View {
    @State var linkOne = false
    @State var linkTwo = false
    @State var linkThree = false
    @State var actionOne = false
    @State var actionTwo = false
    @State var actionThree = false
    var body: some View {
        NavigationView{
            List{
                        NavigationLink("Destination View One", destination: DestOneView(), isActive: self.$linkOne)
                            .actionSheet(isPresented: self.$actionOne) { () -> ActionSheet in
                                ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }.onTapGesture {
                            self.actionOne = true
//                            self.linkOne = true
                        }
                        NavigationLink("Destination View Two", destination: DestTwoView(), isActive: self.$linkTwo)
                        .actionSheet(isPresented: self.$actionTwo) { () -> ActionSheet in
                        ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }
                        .onTapGesture {
                            self.actionTwo = true
//                            self.linkTwo = true
                        }
                        NavigationLink("Destination View Three", destination: DestThreeView(), isActive: self.$linkThree)
                        .actionSheet(isPresented: self.$actionThree) { () -> ActionSheet in
                        ActionSheet(title: Text("Hello"), message:Text("This is weird"), buttons: [ActionSheet.Button.cancel()])
                        }
                        .onTapGesture {
                            self.actionThree = true
//                            self.linkThree = true
                        }
                    }
        }

    }
}

Three other views.

struct DestOneView: View {
    var body: some View {
        Text("First View")
    }
}

struct DestTwoView: View {
    var body: some View {
        Text("Second View")
    }
}

struct DestThreeView: View {
    var body: some View {
        Text("Third View")
    }
}

Body:
Generally overriding gestures does not work well within the List. One of the solutions can be to use a Button to present a NavigationLink:

import SwiftUI

struct ContentView: View {
    @State private var linkOne = false
    ...

    var body: some View {
        NavigationView {
            List {
                NavigationLink(destination: SomeView(), isActive: $linkOne) {
                    EmptyView()
                }

                Button(action: {
                    // here you can perform actions
                    self.linkOne = true
                }, label: {
                    Text("Some text!")
                })

                Spacer()
            }
        }
    }
}


问:
C#-SQL to C#-MongoDB conversion. No DataAdapter for C#-MongoDB?
I have been trying to look for DataAdapter for MongoDB for C# informs application but I can't seem to find it anywhere. Is there even such a thing?
I am working on a Login Page where a user enters their username and password and it checks in the database whether such username and password exist or not.

Below is the SQL C# code for creating connection and checking if the username and password exist:

```<code>SqlConnection sql_con = new SqlConnection(@"Data Source= xxxxxx");

string query = "SELECT * FROM SignUp WHERE Username = '" + Username_TextBox.Text.Trim() + "' AND Password = '" + Password_TextBox.Text.Trim() + "'";

SqlDataAdapter sql_da = new SqlDataAdapter(query, sql_con);

DataTable sql_dt = new DataTable();

sql_da.Fill(sql_dt);

if (sql_dt.Rows.Count == 1 && Username_TextBox.Text.Substring(0,4) == "WRDN")
{
    //some code
}
</code>```

I found this little snippet but it has SQL written in it and the MongoDBConnection and MongoDBDataAdapter do not exist.

```<code>string connectionString = "Server=127.0.0.1;Port=27017;";

using (MongoDBConnection connection = new MongoDBConnection(connectionString))
{
    MongoDBDataAdapter dataAdapter = new MongoDBDataAdapter("SELECT City, CompanyName FROM Customers", connection);

    DataTable table = new DataTable();
    dataAdapter.Fill(table);

    Console.WriteLine("Contents of Customers.");

    foreach (DataRow row in table.Rows)
    {
        Console.WriteLine("{0}: {1}", row["City"], row["CompanyName"]);
    }
}
</code>```

How is this all actually achieved using MongoDB and C#?

答:
Okay, so I found this little package that allows you to use standard drivers to access data from a MongoDB database.

Step 1: Open Visual Studio > Tools > Manage NuGet Packages and search for CData ADO.NET Provider for MongoDB 2019.

Step 2: Download and install it.

Step 3: You'll be prompted to download a key for it. Click OK on the pop-up and your browser will open up and you'll be directed to the download page for it. Click on the Download Trial Key button. Once downloaded, install the key.

Step 4: Once it's all done, head back to your C# form and insert

```<code>using System.Data.CData.MongoDB;
</code>```

Now, you can use the MongoDBDataAdapter and MongoDBConnection to access the data from your MongoDB database.

Body:
I have been trying to look for DataAdapter for MongoDB for C# informs application but I can't seem to find it anywhere. Is there even such a thing?
I am working on a Login Page where a user enters their username and password and it checks in the database whether such username and password exist or not.

Below is the SQL C# code for creating connection and checking if the username and password exist:

SqlConnection sql_con = new SqlConnection(@"Data Source= xxxxxx");

string query = "SELECT * FROM SignUp WHERE Username = '" + Username_TextBox.Text.Trim() + "' AND Password = '" + Password_TextBox.Text.Trim() + "'";

SqlDataAdapter sql_da = new SqlDataAdapter(query, sql_con);

DataTable sql_dt = new DataTable();

sql_da.Fill(sql_dt);

if (sql_dt.Rows.Count == 1 && Username_TextBox.Text.Substring(0,4) == "WRDN")
{
    //some code
}

I found this little snippet but it has SQL written in it and the MongoDBConnection and MongoDBDataAdapter do not exist.

string connectionString = "Server=127.0.0.1;Port=27017;";

using (MongoDBConnection connection = new MongoDBConnection(connectionString))
{
    MongoDBDataAdapter dataAdapter = new MongoDBDataAdapter("SELECT City, CompanyName FROM Customers", connection);

    DataTable table = new DataTable();
    dataAdapter.Fill(table);

    Console.WriteLine("Contents of Customers.");

    foreach (DataRow row in table.Rows)
    {
        Console.WriteLine("{0}: {1}", row["City"], row["CompanyName"]);
    }
}

How is this all actually achieved using MongoDB and C#?

Body:
Okay, so I found this little package that allows you to use standard drivers to access data from a MongoDB database.

Step 1: Open Visual Studio > Tools > Manage NuGet Packages and search for CData ADO.NET Provider for MongoDB 2019.

Step 2: Download and install it.

Step 3: You'll be prompted to download a key for it. Click OK on the pop-up and your browser will open up and you'll be directed to the download page for it. Click on the Download Trial Key button. Once downloaded, install the key.

Step 4: Once it's all done, head back to your C# form and insert

using System.Data.CData.MongoDB;

Now, you can use the MongoDBDataAdapter and MongoDBConnection to access the data from your MongoDB database.


问:
modify dataframe values based on other column
```<code>data = {'Payment_type' =['Mastercard','Visa','Visa','Diners'],'Price' = [1200,600,300,5000]}

</code>```

I'm struggling with how can I modify the price based on the payment type.
This is what I code and it is wrong

```<code>for i in df['Payment_Type']:
    if i == 'Visa':
        df['Price']*0.01
    elif i=='Matercard':
        df['Price']*0.02
    elif  i == 'Diners':
        df['Price']*0.03
    else:
        df['Price']*0.04
</code>```

答:
You can do it this way:

```<code>cards = ['Visa','Mastercard','Diners']

for card in cards:
    if card == 'Visa':
        df.loc[df['Payment_type']==card,'Price'] *= 0.01
    elif card == 'Mastercard':
        df.loc[df['Payment_type']==card,'Price'] *= 0.02
    elif card == 'Diners':
        df.loc[df['Payment_type']==card,'Price'] *= 0.03
else:
    df.loc[~df['Payment_type'].isin(cards),'Price'] *= 0.04
</code>```

This uses the else branch of the for loop which is always fun to put into practise.

Body:
data = {'Payment_type' =['Mastercard','Visa','Visa','Diners'],'Price' = [1200,600,300,5000]}

I'm struggling with how can I modify the price based on the payment type.
This is what I code and it is wrong

for i in df['Payment_Type']:
    if i == 'Visa':
        df['Price']*0.01
    elif i=='Matercard':
        df['Price']*0.02
    elif  i == 'Diners':
        df['Price']*0.03
    else:
        df['Price']*0.04

Body:
You can do it this way:

cards = ['Visa','Mastercard','Diners']

for card in cards:
    if card == 'Visa':
        df.loc[df['Payment_type']==card,'Price'] *= 0.01
    elif card == 'Mastercard':
        df.loc[df['Payment_type']==card,'Price'] *= 0.02
    elif card == 'Diners':
        df.loc[df['Payment_type']==card,'Price'] *= 0.03
else:
    df.loc[~df['Payment_type'].isin(cards),'Price'] *= 0.04

This uses the else branch of the for loop which is always fun to put into practise.


问:
Misconfigured Apache server not implementing SSL properly
I need help finding the fail in my apache2 configuration so that my server runs SSL properly.

I wrote an SSL client using ruby to serve local files using SSL. I enabled the module and edited the files to enable SSLEngine but my ruby script returns an error as well as the server when trying to serve my pages. All this is being performed inside Virtual Box 6.0.20 running Ubuntu 18.04.4 LTS.

Here is a screenshot of my Ruby script

The error I get when running the script through terminal

This is the error Firefox shows me when trying to access my local server using SSL (on Ff v76.0.1)

Here are files I think might be useful

000-default.conf

default-ssl.conf

```<code><IfModule mod_ssl.c>
   <VirtualHost *:443>
    ServerAdmin vulnerable@worldseed.com
    ServerName vulnerable
    DocumentRoot /var/www/html

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

    #   SSL Engine Switch:
    #   Enable/Disable SSL for this virtual host.
    SSLEngine on

    #   A self-signed (snakeoil) certificate can be created by installing
    #   the ssl-cert package. See
    #   /usr/share/doc/apache2/README.Debian.gz for more info.
    #   If both key and certificate are stored in the same file, only the
    #   SSLCertificateFile directive is needed.
    SSLCertificateFile  /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key

    #   Server Certificate Chain:
    #   Point SSLCertificateChainFile at a file containing the
    #   concatenation of PEM encoded CA certificates which form the
    #   certificate chain for the server certificate. Alternatively
    #   the referenced file can be the same as SSLCertificateFile
    #   when the CA certificates are directly appended to the server
    #   certificate for convinience.
    #SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt

    #   Certificate Authority (CA):
    #   Set the CA certificate verification path where to find CA
    #   certificates for client authentication or alternatively one
    #   huge file containing all of them (file must be PEM encoded)
    #   Note: Inside SSLCACertificatePath you need hash symlinks
    #        to point to the certificate files. Use the provided
    #        Makefile to update the hash symlinks after changes.
    SSLCACertificatePath /etc/ssl/certs/
    SSLCACertificateFile /etc/apache2/ssl/apache.crt

    #   Certificate Revocation Lists (CRL):
    #   Set the CA revocation path where to find CA CRLs for client
    #   authentication or alternatively one huge file containing all
    #   of them (file must be PEM encoded)
    #   Note: Inside SSLCARevocationPath you need hash symlinks
    #        to point to the certificate files. Use the provided
    #        Makefile to update the hash symlinks after changes.
    #SSLCARevocationPath /etc/apache2/ssl.crl/
    #SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl

    #   Client Authentication (Type):
    #   Client certificate verification type and depth.  Types are
    #   none, optional, require and optional_no_ca.  Depth is a
    #   number which specifies how deeply to verify the certificate
    #   issuer chain before deciding the certificate is not valid.
    SSLVerifyClient none
    SSLVerifyDepth  1

    #   SSL Engine Options:
    #   Set various options for the SSL engine.
    #   o FakeBasicAuth:
    #    Translate the client X.509 into a Basic Authorisation.  This means that
    #    the standard Auth/DBMAuth methods can be used for access control.  The
    #    user name is the `one line' version of the client's X.509 certificate.
    #    Note that no password is obtained from the user. Every entry in the user
    #    file needs this password: `xxj31ZMTZzkVA'.
    #   o ExportCertData:
    #    This exports two additional environment variables: SSL_CLIENT_CERT and
    #    SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
    #    server (always existing) and the client (only existing when client
    #    authentication is used). This can be used to import the certificates
    #    into CGI scripts.
    #   o StdEnvVars:
    #    This exports the standard SSL/TLS related `SSL_*' environment variables.
    #    Per default this exportation is switched off for performance reasons,
    #    because the extraction step is an expensive operation and is usually
    #    useless for serving static content. So one usually enables the
    #    exportation for CGI and SSI requests only.
    #   o OptRenegotiate:
    #    This enables optimized SSL connection renegotiation handling when SSL
    #    directives are used in per-directory context.
    #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
    <FilesMatch "\.(cgi|shtml|phtml|php)$">
            SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory /usr/lib/cgi-bin>
            SSLOptions +StdEnvVars
    </Directory>

    #   SSL Protocol Adjustments:
    #   The safe and default but still SSL/TLS standard compliant shutdown
    #   approach is that mod_ssl sends the close notify alert but doesn't wait for
    #   the close notify alert from client. When you need a different shutdown
    #   approach you can use one of the following variables:
    #   o ssl-unclean-shutdown:
    #    This forces an unclean shutdown when the connection is closed, i.e. no
    #    SSL close notify alert is send or allowed to received.  This violates
    #    the SSL/TLS standard but is needed for some brain-dead browsers. Use
    #    this when you receive I/O errors because of the standard approach where
    #    mod_ssl sends the close notify alert.
    #   o ssl-accurate-shutdown:
    #    This forces an accurate shutdown when the connection is closed, i.e. a
    #    SSL close notify alert is send and mod_ssl waits for the close notify
    #    alert of the client. This is 100% SSL/TLS standard compliant, but in
    #    practice often causes hanging connections with brain-dead browsers. Use
    #    this only for browsers where you know that their SSL implementation
    #    works correctly.
    #   Notice: Most problems of broken clients are also related to the HTTP
    #   keep-alive facility, so you usually additionally want to disable
    #   keep-alive for those clients, too. Use variable "nokeepalive" for this.
    #   Similarly, one has to force some clients to use HTTP/1.0 to workaround
    #   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
    #   "force-response-1.0" for this.
    # BrowserMatch "MSIE [2-6]" \
    #       nokeepalive ssl-unclean-shutdown \
    #       downgrade-1.0 force-response-1.0

</VirtualHost>
</IfModule>
</code>```

Here's ssl.conf

```<code><IfModule mod_ssl.c>

# Pseudo Random Number Generator (PRNG):
# Configure one or more sources to seed the PRNG of the SSL library.
# The seed data should be of good random quality.
# WARNING! On some platforms /dev/random blocks if not enough entropy
# is available. This means you then cannot use the /dev/random device
# because it would lead to very long connection times (as long as
# it requires to make more entropy available). But usually those
# platforms additionally provide a /dev/urandom device which doesn't
# block. So, if available, use this one instead. Read the mod_ssl User
# Manual for more details.
#
SSLRandomSeed startup builtin
SSLRandomSeed startup file:/dev/urandom 512
SSLRandomSeed connect builtin
SSLRandomSeed connect file:/dev/urandom 512

##
##  SSL Global Context
##
##  All SSL configuration in this context applies both to
##  the main server and all SSL-enabled virtual hosts.
##

#
#   Some MIME-types for downloading Certificates and CRLs
#
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl .crl

#   Pass Phrase Dialog:
#   Configure the pass phrase gathering process.
#   The filtering dialog program (`builtin' is a internal
#   terminal dialog) has to provide the pass phrase on stdout.
SSLPassPhraseDialog  exec:/usr/share/apache2/ask-for-passphrase

#   Inter-Process Session Cache:
#   Configure the SSL Session Cache: First the mechanism
#   to use and second the expiring timeout (in seconds).
#   (The mechanism dbm has known memory leaks and should not be used).
#SSLSessionCache         dbm:${APACHE_RUN_DIR}/ssl_scache
SSLSessionCache     shmcb:${APACHE_RUN_DIR}/ssl_scache(512000)
SSLSessionCacheTimeout  300

#   Semaphore:
#   Configure the path to the mutual exclusion semaphore the
#   SSL engine uses internally for inter-process synchronization.
#   (Disabled by default, the global Mutex directive consolidates by default
#   this)
#Mutex file:${APACHE_LOCK_DIR}/ssl_mutex ssl-cache

#   SSL Cipher Suite:
#   List the ciphers that the client is permitted to negotiate. See the
#   ciphers(1) man page from the openssl package for list of all available
#   options.
#   Enable only secure ciphers:
SSLCipherSuite ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS:!AESCCM

# SSL server cipher order preference:
# Use server priorities for cipher algorithm choice.
# Clients may prefer lower grade encryption.  You should enable this
# option if you want to enforce stronger encryption, and can afford
# the CPU cost, and did not override SSLCipherSuite in a way that puts
# insecure ciphers first.
# Default: Off
SSLHonorCipherOrder on

#   The protocols to enable.
#   Available values: all, SSLv3, TLSv1, TLSv1.1, TLSv1.2
#   SSL v2  is no longer supported
SSLProtocol all -SSLv3

#   Allow insecure renegotiation with clients which do not yet support the
#   secure renegotiation protocol. Default: Off
#SSLInsecureRenegotiation on

#   Whether to forbid non-SNI clients to access name based virtual hosts.
#   Default: Off
#SSLStrictSNIVHostCheck On
</code>```

Can somebody help me get my server properly setup running SSL? Let me know of any other config files that  need to be checked, I just put here the ones I've been fidling the more with

Thanks in advance,
Alvaro

答:
The following lines have to be added to your site's .conf file, specifying your certificate and private key location.

SSLCertificateFile /path/to/your_domain_name.crt
  SSLCertificateKeyFile /path/to/your_private.key

In my case the default 000-default.conf ended up looking like this (No comments included)

```<code><VirtualHost vulnerable:443>

    ServerAdmin sugar@localhost
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key

 </VirtualHost>
</code>```

Once these lines were added, browser allowed me to add an exception for my self-signed certificate and my ruby script worked fine.

Body:
I need help finding the fail in my apache2 configuration so that my server runs SSL properly.

I wrote an SSL client using ruby to serve local files using SSL. I enabled the module and edited the files to enable SSLEngine but my ruby script returns an error as well as the server when trying to serve my pages. All this is being performed inside Virtual Box 6.0.20 running Ubuntu 18.04.4 LTS.

Here is a screenshot of my Ruby script

The error I get when running the script through terminal

This is the error Firefox shows me when trying to access my local server using SSL (on Ff v76.0.1)

Here are files I think might be useful

000-default.conf

default-ssl.conf

<IfModule mod_ssl.c>
   <VirtualHost *:443>
    ServerAdmin vulnerable@worldseed.com
    ServerName vulnerable
    DocumentRoot /var/www/html

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

    #   SSL Engine Switch:
    #   Enable/Disable SSL for this virtual host.
    SSLEngine on

    #   A self-signed (snakeoil) certificate can be created by installing
    #   the ssl-cert package. See
    #   /usr/share/doc/apache2/README.Debian.gz for more info.
    #   If both key and certificate are stored in the same file, only the
    #   SSLCertificateFile directive is needed.
    SSLCertificateFile  /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key

    #   Server Certificate Chain:
    #   Point SSLCertificateChainFile at a file containing the
    #   concatenation of PEM encoded CA certificates which form the
    #   certificate chain for the server certificate. Alternatively
    #   the referenced file can be the same as SSLCertificateFile
    #   when the CA certificates are directly appended to the server
    #   certificate for convinience.
    #SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt

    #   Certificate Authority (CA):
    #   Set the CA certificate verification path where to find CA
    #   certificates for client authentication or alternatively one
    #   huge file containing all of them (file must be PEM encoded)
    #   Note: Inside SSLCACertificatePath you need hash symlinks
    #        to point to the certificate files. Use the provided
    #        Makefile to update the hash symlinks after changes.
    SSLCACertificatePath /etc/ssl/certs/
    SSLCACertificateFile /etc/apache2/ssl/apache.crt

    #   Certificate Revocation Lists (CRL):
    #   Set the CA revocation path where to find CA CRLs for client
    #   authentication or alternatively one huge file containing all
    #   of them (file must be PEM encoded)
    #   Note: Inside SSLCARevocationPath you need hash symlinks
    #        to point to the certificate files. Use the provided
    #        Makefile to update the hash symlinks after changes.
    #SSLCARevocationPath /etc/apache2/ssl.crl/
    #SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl

    #   Client Authentication (Type):
    #   Client certificate verification type and depth.  Types are
    #   none, optional, require and optional_no_ca.  Depth is a
    #   number which specifies how deeply to verify the certificate
    #   issuer chain before deciding the certificate is not valid.
    SSLVerifyClient none
    SSLVerifyDepth  1

    #   SSL Engine Options:
    #   Set various options for the SSL engine.
    #   o FakeBasicAuth:
    #    Translate the client X.509 into a Basic Authorisation.  This means that
    #    the standard Auth/DBMAuth methods can be used for access control.  The
    #    user name is the `one line' version of the client's X.509 certificate.
    #    Note that no password is obtained from the user. Every entry in the user
    #    file needs this password: `xxj31ZMTZzkVA'.
    #   o ExportCertData:
    #    This exports two additional environment variables: SSL_CLIENT_CERT and
    #    SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
    #    server (always existing) and the client (only existing when client
    #    authentication is used). This can be used to import the certificates
    #    into CGI scripts.
    #   o StdEnvVars:
    #    This exports the standard SSL/TLS related `SSL_*' environment variables.
    #    Per default this exportation is switched off for performance reasons,
    #    because the extraction step is an expensive operation and is usually
    #    useless for serving static content. So one usually enables the
    #    exportation for CGI and SSI requests only.
    #   o OptRenegotiate:
    #    This enables optimized SSL connection renegotiation handling when SSL
    #    directives are used in per-directory context.
    #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
    <FilesMatch "\.(cgi|shtml|phtml|php)$">
            SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory /usr/lib/cgi-bin>
            SSLOptions +StdEnvVars
    </Directory>

    #   SSL Protocol Adjustments:
    #   The safe and default but still SSL/TLS standard compliant shutdown
    #   approach is that mod_ssl sends the close notify alert but doesn't wait for
    #   the close notify alert from client. When you need a different shutdown
    #   approach you can use one of the following variables:
    #   o ssl-unclean-shutdown:
    #    This forces an unclean shutdown when the connection is closed, i.e. no
    #    SSL close notify alert is send or allowed to received.  This violates
    #    the SSL/TLS standard but is needed for some brain-dead browsers. Use
    #    this when you receive I/O errors because of the standard approach where
    #    mod_ssl sends the close notify alert.
    #   o ssl-accurate-shutdown:
    #    This forces an accurate shutdown when the connection is closed, i.e. a
    #    SSL close notify alert is send and mod_ssl waits for the close notify
    #    alert of the client. This is 100% SSL/TLS standard compliant, but in
    #    practice often causes hanging connections with brain-dead browsers. Use
    #    this only for browsers where you know that their SSL implementation
    #    works correctly.
    #   Notice: Most problems of broken clients are also related to the HTTP
    #   keep-alive facility, so you usually additionally want to disable
    #   keep-alive for those clients, too. Use variable "nokeepalive" for this.
    #   Similarly, one has to force some clients to use HTTP/1.0 to workaround
    #   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
    #   "force-response-1.0" for this.
    # BrowserMatch "MSIE [2-6]" \
    #       nokeepalive ssl-unclean-shutdown \
    #       downgrade-1.0 force-response-1.0

</VirtualHost>
</IfModule>

Here's ssl.conf

<IfModule mod_ssl.c>

# Pseudo Random Number Generator (PRNG):
# Configure one or more sources to seed the PRNG of the SSL library.
# The seed data should be of good random quality.
# WARNING! On some platforms /dev/random blocks if not enough entropy
# is available. This means you then cannot use the /dev/random device
# because it would lead to very long connection times (as long as
# it requires to make more entropy available). But usually those
# platforms additionally provide a /dev/urandom device which doesn't
# block. So, if available, use this one instead. Read the mod_ssl User
# Manual for more details.
#
SSLRandomSeed startup builtin
SSLRandomSeed startup file:/dev/urandom 512
SSLRandomSeed connect builtin
SSLRandomSeed connect file:/dev/urandom 512

##
##  SSL Global Context
##
##  All SSL configuration in this context applies both to
##  the main server and all SSL-enabled virtual hosts.
##

#
#   Some MIME-types for downloading Certificates and CRLs
#
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl .crl

#   Pass Phrase Dialog:
#   Configure the pass phrase gathering process.
#   The filtering dialog program (`builtin' is a internal
#   terminal dialog) has to provide the pass phrase on stdout.
SSLPassPhraseDialog  exec:/usr/share/apache2/ask-for-passphrase

#   Inter-Process Session Cache:
#   Configure the SSL Session Cache: First the mechanism
#   to use and second the expiring timeout (in seconds).
#   (The mechanism dbm has known memory leaks and should not be used).
#SSLSessionCache         dbm:${APACHE_RUN_DIR}/ssl_scache
SSLSessionCache     shmcb:${APACHE_RUN_DIR}/ssl_scache(512000)
SSLSessionCacheTimeout  300

#   Semaphore:
#   Configure the path to the mutual exclusion semaphore the
#   SSL engine uses internally for inter-process synchronization.
#   (Disabled by default, the global Mutex directive consolidates by default
#   this)
#Mutex file:${APACHE_LOCK_DIR}/ssl_mutex ssl-cache

#   SSL Cipher Suite:
#   List the ciphers that the client is permitted to negotiate. See the
#   ciphers(1) man page from the openssl package for list of all available
#   options.
#   Enable only secure ciphers:
SSLCipherSuite ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS:!AESCCM

# SSL server cipher order preference:
# Use server priorities for cipher algorithm choice.
# Clients may prefer lower grade encryption.  You should enable this
# option if you want to enforce stronger encryption, and can afford
# the CPU cost, and did not override SSLCipherSuite in a way that puts
# insecure ciphers first.
# Default: Off
SSLHonorCipherOrder on

#   The protocols to enable.
#   Available values: all, SSLv3, TLSv1, TLSv1.1, TLSv1.2
#   SSL v2  is no longer supported
SSLProtocol all -SSLv3

#   Allow insecure renegotiation with clients which do not yet support the
#   secure renegotiation protocol. Default: Off
#SSLInsecureRenegotiation on

#   Whether to forbid non-SNI clients to access name based virtual hosts.
#   Default: Off
#SSLStrictSNIVHostCheck On

Can somebody help me get my server properly setup running SSL? Let me know of any other config files that  need to be checked, I just put here the ones I've been fidling the more with

Thanks in advance,
Alvaro

Body:
The following lines have to be added to your site's .conf file, specifying your certificate and private key location.

SSLCertificateFile /path/to/your_domain_name.crt
  SSLCertificateKeyFile /path/to/your_private.key

In my case the default 000-default.conf ended up looking like this (No comments included)

<VirtualHost vulnerable:443>

    ServerAdmin sugar@localhost
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key

 </VirtualHost>

Once these lines were added, browser allowed me to add an exception for my self-signed certificate and my ruby script worked fine.


问:
Easily localized alternative to SQL Server Reporting Services?
We are running into the well-documented problems with localizing our SSRS reports.

Can anyone recommend an alternative?  Presume parity (or nearly so) with SSRS' functionality, though a great many of our reports will be simple grids or graphs, with some header/footer text.  We want a means by which we can easily identify localizable strings, store them in a database, translate them, and then generate the localized "report definition" at deployment time.  The Spanish see Spanish reports, the Italians see Italian reports, etc.

Thanks everyone.

答:
There's a book called "Microsoft SQL Server Reporting Services Recipes" that has a few pages dedicated to how to localize SSRS reports. The only limitation is that parameter prompt text can still only show a single language (as it doesn't allow expressions); if you're accessing reports via a client though then it won't be an issue.

It involves creating a custom assembly in VS that has a main function that does the translation (using localization resource files, in much the same way you'd do it for an application).

Then you override the report's OnInit in custom code to initialise the custom assembly resource manager with the report name (so it knows which set of strings to look up, I suppose), and then instead of using "Name: " text in your report, you can use =Code.my_localizer.GetLocalText("Name")


问:
.NET Core MVC - Binding DateTime always Results in MinValue
I have a BirthDateproperty in my model looking like this

```<code>[Required]
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:MM/dd/yyy}")]
    public DateTime BirthDate { get; set; }
</code>```

In my view, I'm binding this property to an input using asp-for tag helper. It looks like this:

```<code><input class="form-control" type="date" name="dateofbirth" id="inputDateOfBirth" placeholder="mm/dd/yyyy" data-date-format="mm/dd/yyyy"
               max="@DateTime.Today.ToString("yyyy-MM-dd")" asp-for="FamilyMember.BirthDate" required/>
</code>```

When posting the form to the controller, the BirthDate property is always set to 01/01/0001. What am I doing wrong?

答:
Your html element is using the asp-for tag helper, but you're also specifying name="dateofbirth" and id="inputDateOfBith". Removing that will post the correct value.

Asp-for, when rendered, will populate an input element with the specified model-bound property id and name already (among other things like value, validation, etc.). You can read about this and more on Microsoft's official ASP.NET Core tag helper documentation.

Straight from their documentation:

Generates the id and name HTML attributes for the expression name specified in the asp-for attribute. asp-for="Property1.Property2" is equivalent to m => m.Property1.Property2. The name of the expression is what is used for the asp-for attribute value. See the Expression names section for additional information.

Body:
I have a BirthDateproperty in my model looking like this

[Required]
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:MM/dd/yyy}")]
    public DateTime BirthDate { get; set; }

In my view, I'm binding this property to an input using asp-for tag helper. It looks like this:

<input class="form-control" type="date" name="dateofbirth" id="inputDateOfBirth" placeholder="mm/dd/yyyy" data-date-format="mm/dd/yyyy"
               max="@DateTime.Today.ToString("yyyy-MM-dd")" asp-for="FamilyMember.BirthDate" required/>

When posting the form to the controller, the BirthDate property is always set to 01/01/0001. What am I doing wrong?


问:
getting No such PaymentMethod: error message when trying to attach paymentMethodId to customerId
new to stripe but the documentation looked pretty forward but now stock on something very rudimentary, I can see the customer created in stripe console, same as the product and the price but when I try to attach the payment method retrieved from cardElement, and send it to server i get the message that paymentMethod is not valid. I'm following stripe docs in this page
https://stripe.com/docs/billing/subscriptions/fixed-price#create-customer

In javascript i have:

```<code>    const payload = await stripe.createPaymentMethod({
        type: 'card',
        card: elements.getElement(CardElement),
        billing_details: billingDetails,
    });
</code>```

this comes back with an paymentMethod object with id

```<code> paymentMethod.id be like pm_1GoHU32eZvKYloXXXXXXX
</code>```

on the server side:

```<code>await stripe.paymentMethods.attach(paymentMethodId, {
    customer: customerId,
});
</code>```

but i get an exception like below

```<code>StripeInvalidRequestError: No such PaymentMethod: pm_1GoHU32eZvKYloXXXXXXX
at Function.generate (/root/coco/node_modules/stripe/lib/Error.js:39:16)
at IncomingMessage.<anonymous>
(/root/coco/node_modules/stripe/lib/StripeResource.js:175:33)
at Object.onceWrapper (events.js:421:28)
at IncomingMessage.emit (events.js:327:22)
at IncomingMessage.EventEmitter.emit (domain.js:485:12)
at endReadableNT (_stream_readable.js:1225:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
type: 'StripeInvalidRequestError',
raw: {
code: 'resource_missing',
doc_url: 'https://stripe.com/docs/error-codes/resource-missing',
message: 'No such PaymentMethod: pm_1GoHU32eZvKYlo2CYLA3SCaX',
</code>```

答: OK, figured it out. I copied and pasted from stripe example, Stripe is usually good with replacing their document examples with you keys but this document (posted in the question) is using a sample publishable key! </p>

Body:
new to stripe but the documentation looked pretty forward but now stock on something very rudimentary, I can see the customer created in stripe console, same as the product and the price but when I try to attach the payment method retrieved from cardElement, and send it to server i get the message that paymentMethod is not valid. I'm following stripe docs in this page
https://stripe.com/docs/billing/subscriptions/fixed-price#create-customer

In javascript i have:

    const payload = await stripe.createPaymentMethod({
        type: 'card',
        card: elements.getElement(CardElement),
        billing_details: billingDetails,
    });

this comes back with an paymentMethod object with id

 paymentMethod.id be like pm_1GoHU32eZvKYloXXXXXXX

on the server side:

await stripe.paymentMethods.attach(paymentMethodId, {
    customer: customerId,
});

but i get an exception like below

StripeInvalidRequestError: No such PaymentMethod: pm_1GoHU32eZvKYloXXXXXXX
at Function.generate (/root/coco/node_modules/stripe/lib/Error.js:39:16)
at IncomingMessage.<anonymous>
(/root/coco/node_modules/stripe/lib/StripeResource.js:175:33)
at Object.onceWrapper (events.js:421:28)
at IncomingMessage.emit (events.js:327:22)
at IncomingMessage.EventEmitter.emit (domain.js:485:12)
at endReadableNT (_stream_readable.js:1225:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
type: 'StripeInvalidRequestError',
raw: {
code: 'resource_missing',
doc_url: 'https://stripe.com/docs/error-codes/resource-missing',
message: 'No such PaymentMethod: pm_1GoHU32eZvKYlo2CYLA3SCaX',


问:
Is there a difference between using struct.calcsize() and len() in Python 3?
Is using struct.calcsize() always the same as simply using len() to get the number of bytes in a struct?

For example:

```<code>>>> import struct
>>> a = struct.pack('I', 107)
>>> len(a)
4
>>> struct.calcsize('I')
4
</code>```

For my small set of tests, they seem to agree. Is there a reason to prefer one over the other? Is it safe to use them interchangeably?

答:
struct.calcsize doesn't require you to actually pack data. This saves time and memory, and is more convenient if you don't actually have any data to pack.

If you have a format string and you want to know how big the results of packing data in that format would be, use struct.calcsize. If you have already-packed data and you want to know how big it is, use len.

Body:
Is using struct.calcsize() always the same as simply using len() to get the number of bytes in a struct?

For example:

>>> import struct
>>> a = struct.pack('I', 107)
>>> len(a)
4
>>> struct.calcsize('I')
4

For my small set of tests, they seem to agree. Is there a reason to prefer one over the other? Is it safe to use them interchangeably?


问:
Objective-C initWithInt vs. numberFromInt vs. simply @number?
Quite new to Objective-C, as I just started researching on an old macOS project for a client. One thing I noticed is that it seems when initializing/assigning an int value to an NSNumber object in Objective-C, there are different ways to do it, for example:

```<code>NSNumber *a = [NSNumber numberWithInt:10];
NSNumber *b = [[NSNumber alloc]initWithInt:10];
NSNumber *c = @10;
</code>```

As far as I can see, they all do the same thing, and the last line is the easiest to type and read, while the second line is just way too convoluted IMHO, so I'm just wondering are there any real differences in the end results from those three different methods, or situations where one specific method should be used because the others won't work?

答:
There is a difference between a & b which was important before ARC when memory management was manual, but today with automatic memory management is essentially irrelevant to the programmer as ARC handles the difference seamlessly.

In pre-ARC days a references a number object which is not owned, while b references one which is owned, and the manual management required for each is different and the programmer needs to know that.

In post-ARC days the management is automatic and the programmer generally does not need to know the difference.

Option c is a shorthand for a that was introduced later and is now the standard way of creating NSNumber objects from literal values. The form @(<expr>) is also provided to create an object from the result of evaluating an <expr>.

Body:
Quite new to Objective-C, as I just started researching on an old macOS project for a client. One thing I noticed is that it seems when initializing/assigning an int value to an NSNumber object in Objective-C, there are different ways to do it, for example:

NSNumber *a = [NSNumber numberWithInt:10];
NSNumber *b = [[NSNumber alloc]initWithInt:10];
NSNumber *c = @10;

As far as I can see, they all do the same thing, and the last line is the easiest to type and read, while the second line is just way too convoluted IMHO, so I'm just wondering are there any real differences in the end results from those three different methods, or situations where one specific method should be used because the others won't work?


问:
JS Practise background switching from white to blue
I am coding along with a course and I've triple checked that my code matches the instructors but when I run it it only changes the background of the webpage to blue instead of switching back and forth from white to blue every second like the instructor demonstrates. It also doesn't run at all when using Visual Studio so I had to switch to code pen and tried it in the console of Google chrome browser. Just want to know where it goes wrong or how to alter it to do the switching back and forth. Thank you.</p>

```<code> var body = document.querySelector("body");
 var isBlue = false;

setInterval(function(){
    if (isBlue) {
      body.style.background = "white";
    } else {
     body.style.background = "#3498db";
    }
  isBlue = isBlue;
 }, 1000);
</code>```

答:
The way you implement it is always changing the background to #3498db. Instead, you should set the boolean to the opposite every time:

var body = document.querySelector("body");
var isBlue = false;

setInterval(function(){
    if (isBlue) {
      body.style.background = "white";
    } else {
     body.style.background = "#3498db";
    }
    isBlue = !isBlue; //change this
 }, 1000);```

Body:
I am coding along with a course and I've triple checked that my code matches the instructors but when I run it it only changes the background of the webpage to blue instead of switching back and forth from white to blue every second like the instructor demonstrates. It also doesn't run at all when using Visual Studio so I had to switch to code pen and tried it in the console of Google chrome browser. Just want to know where it goes wrong or how to alter it to do the switching back and forth. Thank you.

 var body = document.querySelector("body");
 var isBlue = false;

setInterval(function(){
    if (isBlue) {
      body.style.background = "white";
    } else {
     body.style.background = "#3498db";
    }
  isBlue = isBlue;
 }, 1000);


问:
Character Picture Grid
This is my first question in stackoverflow. Happy to join the community

This is a question in one of the books:

Say you have a list of lists where each value in the inner lists is a one-charac string, like this:

```<code>grid = [['.', '.', '.', '.', '.', '.'],
    ['.', '0', '0', '.', '.', '.'],
    ['0', '0', '0', '0', '.', '.'],
    ['0', '0', '0', '0', '0', '.'],
    ['.', '0', '0', '0', '0', '0'],
    ['0', '0', '0', '0', '0', '.'],
    ['0', '0', '0', '0', '.', '.'],
    ['.', '0', '0', '.', '.', '.'],
    ['.', '.', '.', '.', '.', '.']]
</code>```

result should be:

```<code>..00.00..
.0000000.
.0000000.
..00000..
...000...
....0....
</code>```

I managed to get the answer with this code:

```<code>Num_of_grid = range(len(grid))
for y in Num_of_grid:
    for x in Num_of_grid:
        print(grid[x][y], end = "")
    print("")
</code>```

However, even tho it solves the problem but for some reason I get the following error:
Click here for error image

When I write the following
print(x, y); it shows exactly the right number of range I used in the loop... which is (0,8) but still it gives me out of range.

答:
This doesn't work because the grid isn't square.  len(grid) is 9, but len(grid[x]) (for all x) is only 6!

A less error-prone way to write an iteration over a 2d list is to simply iterate over the elements of each list:

```<code>for row in grid:
    for cell in row:
        print(cell, end="")
    print("")
</code>```

Running this, I see the image is flipped on its side -- luckily it's not too hard to transpose a 2d list with map and zip!

```<code>for row in map(list, zip(*grid)):
    for cell in row:
        print(cell, end="")
    print("")
</code>```

Or use join to just turn the whole thing into one string:

```<code>print("\n".join("".join(row) for row in map(list, zip(*grid))))
</code>```

Title: Character Picture Grid

Body:
This is my first question in stackoverflow. Happy to join the community

This is a question in one of the books:

Say you have a list of lists where each value in the inner lists is a one-charac string, like this:

grid = [['.', '.', '.', '.', '.', '.'],
    ['.', '0', '0', '.', '.', '.'],
    ['0', '0', '0', '0', '.', '.'],
    ['0', '0', '0', '0', '0', '.'],
    ['.', '0', '0', '0', '0', '0'],
    ['0', '0', '0', '0', '0', '.'],
    ['0', '0', '0', '0', '.', '.'],
    ['.', '0', '0', '.', '.', '.'],
    ['.', '.', '.', '.', '.', '.']]

result should be:

..00.00..
.0000000.
.0000000.
..00000..
...000...
....0....

I managed to get the answer with this code:

Num_of_grid = range(len(grid))
for y in Num_of_grid:
    for x in Num_of_grid:
        print(grid[x][y], end = "")
    print("")

However, even tho it solves the problem but for some reason I get the following error:
Click here for error image

When I write the following
print(x, y); it shows exactly the right number of range I used in the loop... which is (0,8) but still it gives me out of range.

Body:
This doesn't work because the grid isn't square.  len(grid) is 9, but len(grid[x]) (for all x) is only 6!

A less error-prone way to write an iteration over a 2d list is to simply iterate over the elements of each list:

for row in grid:
    for cell in row:
        print(cell, end="")
    print("")

Running this, I see the image is flipped on its side -- luckily it's not too hard to transpose a 2d list with map and zip!

for row in map(list, zip(*grid)):
    for cell in row:
        print(cell, end="")
    print("")

Or use join to just turn the whole thing into one string:

print("\n".join("".join(row) for row in map(list, zip(*grid))))


问:
How to obtain a specific field in a Firebase document
Trying to capture a specific field from my documents. Here is the code for the wrapper,

class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);
    print(user);

    // return either the Home or Authenticate widget
    if (user == null) {
      return Authenticate();
    } else {
      return FirmHomePage();
    }
  }
}
```

<p>and this is the code that we used for printing in the console.</p>

<pre class="lang-dart prettyprint-override"><code>void idss() async {
  FirebaseUser userid = await FirebaseAuth.instance.currentUser();

  var document = await Firestore.instance.collection('Users').getDocuments();
  for (var document in document.documents) {
    messagetext = document.data['JobType'];
    usettype = messagetext;
    print(messagetext);
  }
}
</code>```

We want to check our user to set a path for them.

答:
FirebaseUser userid = await FirebaseAuth.instance.currentUser();  </p>

```<code>final QuerySnapshot result = await Firestore.instance.collection('Users')
.where('uid', isEqualTo: currentUser.uid) .getDocuments();

 final List < DocumentSnapshot > documents = result.documents;

 if (documents.length == 1) {
//your code here
}else{
//your code here
}
</code>```

Body:
Trying to capture a specific field from my documents. Here is the code for the wrapper,

class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);
    print(user);

    // return either the Home or Authenticate widget
    if (user == null) {
      return Authenticate();
    } else {
      return FirmHomePage();
    }
  }
}

and this is the code that we used for printing in the console.

void idss() async {
  FirebaseUser userid = await FirebaseAuth.instance.currentUser();

  var document = await Firestore.instance.collection('Users').getDocuments();
  for (var document in document.documents) {
    messagetext = document.data['JobType'];
    usettype = messagetext;
    print(messagetext);
  }
}

We want to check our user to set a path for them.

Body:
FirebaseUser userid = await FirebaseAuth.instance.currentUser();

final QuerySnapshot result = await Firestore.instance.collection('Users')
.where('uid', isEqualTo: currentUser.uid) .getDocuments();

 final List < DocumentSnapshot > documents = result.documents;

 if (documents.length == 1) {
//your code here
}else{
//your code here
}


问:
Getting the Stacktrace
When Exception happens you can print out the StackTrace and review it.

What if you want to get the StackTrace without an exception happening?

Is there a way to do this?

答:
You can print out the stacktrace at any time by calling Environment.StackTrace</p>

```<code>string tracktrace = System.Environment.StackTrace;
</code>```

OwnerDisplayName: Debbi

LastEditorDisplayName: BtBh

Title: Getting the Stacktrace

Body:
You can print out the stacktrace at any time by calling Environment.StackTrace

string tracktrace = System.Environment.StackTrace;

OwnerDisplayName: BtBh

ContentLicense: CC BY-SA 2.5


问:
Reduce Team Foundation Server database space
I have some large projects hosted in Team Foundation Server 2010 Source Control. This projects are long time so many check-ins will occour and as we make check-ins the database grows up.

I'm afraid that size will be a problem in the future (including performance and backup space/upload time).

Is there some way to reduce this size (deleting old changesets or something else)?

答:
As of today, there are a couple of ways to clean your TFS database, and these solutions target different components of TFS such as Version Control or Test Management. AFAIK, there is no unified way to control the growth of the TFS database.

These tools are:

tf destroy

Test Attachment Cleanup Tool

witamin (destroying work items)


问:
How to view github commit history locally on Mac OS X
I'm trying to view the history of a file on GitHub locally on my Mac OS X laptop because GitHub tells me "Sorry, this commit history is taking too long to generate." (see URL https://github.com/Homebrew/homebrew-core/commits/master/Formula/pipenv.rb)

It suggests that I use this command:

git log master -- Formula/pipenv.rb

... but when I run the command I get this error:

fatal: not a git repository (or any of the parent directories): .git

Do I need to do a "git clone" first in a temporary directory, and how do I specify the GitHub address URL?

答:
Do I need to do a "git clone" first in a temporary directory

Yes. It doesn’t need to be temporary. I usually clone to the Desktop. A folder will be created as part of the clone. A clone contains the entire history; it copies the whole repository. You will then be able to do whatever you like.

how do I specify the GitHub address URL?

GitHub tells you that when you click the Clone button.


问:
How to only iterate over one argument of an matrix array if both have the same variable in python?
I am trying to eliminate some non zero entries in a matrix where the 2 adjacent diagonals to the main diagonal are nonzero.

h = np.zeros((n**2,n**2))
for i in np.arange(0, n**2):
    for j in np.arange(0,n**2):
        if(i==j):
            for i in np.arange(0,n**2,n):
                h[i,j-1] = 0

print(h)```

I want it to only eliminate the lower triangle non-zero entries, but it's erasing some entries in the upper triangle. I know this is because on the last if statement with the for loop, it is iterating for both arguments of the array, when I only want it to iterate for the first argument i, but since I set i=j, it runs for both.

The matrix I want to obtain is the following:

Desired matrix

PS: sorry for the extremely bad question format, this is my first question.

答:
Is this what you are looking for?:</p>

```<code>hamiltonian[0,1] = 1
hamiltonian[n**2-1,n**2-2] = 1
for i in np.arange(1, n**2-1):
  hamiltonian[i,i+1] = 1
  hamiltonian[i,i-1] = 1
</code>```

Body:
I am trying to eliminate some non zero entries in a matrix where the 2 adjacent diagonals to the main diagonal are nonzero.

h = np.zeros((n**2,n**2))
for i in np.arange(0, n**2):
    for j in np.arange(0,n**2):
        if(i==j):
            for i in np.arange(0,n**2,n):
                h[i,j-1] = 0

print(h)

I want it to only eliminate the lower triangle non-zero entries, but it's erasing some entries in the upper triangle. I know this is because on the last if statement with the for loop, it is iterating for both arguments of the array, when I only want it to iterate for the first argument i, but since I set i=j, it runs for both.

The matrix I want to obtain is the following:

Desired matrix

PS: sorry for the extremely bad question format, this is my first question.

Body:
Is this what you are looking for?:

hamiltonian[0,1] = 1
hamiltonian[n**2-1,n**2-2] = 1
for i in np.arange(1, n**2-1):
  hamiltonian[i,i+1] = 1
  hamiltonian[i,i-1] = 1


答:
Welcome to the SO community.

So I think it would be best to reevaluate how we are printing from our 2d array/grid.

Num_of_grid is, after the expression is evaluated, an iterable like this: [0, 1, 2, 3, 4, 5, 6, 7, 8]. You use this range for both x and y iteration, even though horizontally your shape/grid is only 6 wide. What happens, then, is that at your print statement, you're trying to access a [y] that doesn't exist. For example, like grid[x][6] (7th). As expected, you get an IndexError, which is exactly what we expected.

So what's the best way to iterate through a 2d list?

I might suggest something more succinct:

grid = [...]

for row in grid:
    for cell in row:
        print(cell, end="")
    print()
```

Title: Character Picture Grid


问:
Align all items horizontally to the left with CSS grid

I have an unknown number of items and I want them stacked horizontally to the left

I want a fixed gap between the items

The width of the items is unknown, and could have variations

I know I could use flex like below, but I'd like to know if this accomplishable with grid.

#box {
  display: flex;
  width: 300px;
  outline: 1px solid blue;
}
.item {
  background: gray;
  width: 50px;
  height: 100px;
}

#box > * + * {
  margin-left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='box'>
    <div class='item'></div>
    <div class='item'></div>
    <div class='item'></div>
    <div class='item'></div>
</div></code>```

Update

Increased the width value for the parent, to display clearer what I'm going after - the children should not take up the full parent width (unless there are many children of course).

答:
Here. I used the same measures and sizes from your example.

Depends on children width

#box {
  display: inline-grid;
  grid-auto-flow: column;
  grid-template-columns: auto;
  grid-auto-rows: 100px;
  column-gap: 10px;
  outline: 1px solid blue;
}

.item {
  background: gray;
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='box'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div></code>```

Depends on parent width

#box {
  display: grid;
  grid-auto-flow: column;
  grid-template-columns: auto;
  grid-auto-rows: 100px;
  column-gap: 10px;
  outline: 1px solid blue;
  width: 230px;
}

.item {
  background: gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='box'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div></code>```

UPDATED

Wen the size of parent is 100% width and number of children is indefinite.

#box {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fill, 50px);
  grid-auto-rows: 100px;
  column-gap: 10px;
  outline: 1px solid blue;
}

.item {
  background: gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='box'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div></code>```

Now we know, your case can be solved with grid, but I suggest you to use flex. Using grid for this task is like hitting a screw with a hammer - we can reach a goal, but using wrong tool. Grid is more useful for tables with unusual pattern of sells, better if we know the number of columns. And Flex more useful for lists of elements, like in your case. Although Flex is older and more native then Grid, works a lot more stable in all modern browsers.

Body:
I have an unknown number of items and I want them stacked horizontally to the left

I want a fixed gap between the items

The width of the items is unknown, and could have variations

I know I could use flex like below, but I'd like to know if this accomplishable with grid.

#box {
  display: flex;
  width: 300px;
  outline: 1px solid blue;
}
.item {
  background: gray;
  width: 50px;
  height: 100px;
}

#box > * + * {
  margin-left: 10px;
}

Update

Increased the width value for the parent, to display clearer what I'm going after - the children should not take up the full parent width (unless there are many children of course).

Body:
Here. I used the same measures and sizes from your example.

Depends on children width

#box {
  display: inline-grid;
  grid-auto-flow: column;
  grid-template-columns: auto;
  grid-auto-rows: 100px;
  column-gap: 10px;
  outline: 1px solid blue;
}

.item {
  background: gray;
  width: 50px;
}

<div id='box'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>

Depends on parent width

#box {
  display: grid;
  grid-auto-flow: column;
  grid-template-columns: auto;
  grid-auto-rows: 100px;
  column-gap: 10px;
  outline: 1px solid blue;
  width: 230px;
}

.item {
  background: gray;
}

<div id='box'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>

UPDATED

Wen the size of parent is 100% width and number of children is indefinite.

#box {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fill, 50px);
  grid-auto-rows: 100px;
  column-gap: 10px;
  outline: 1px solid blue;
}

.item {
  background: gray;
}

<div id='box'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>

Now we know, your case can be solved with grid, but I suggest you to use flex. Using grid for this task is like hitting a screw with a hammer - we can reach a goal, but using wrong tool. Grid is more useful for tables with unusual pattern of sells, better if we know the number of columns. And Flex more useful for lists of elements, like in your case. Although Flex is older and more native then Grid, works a lot more stable in all modern browsers.


问:
Spring JPA: avoid select before update
currently we are working on optimizing JPA queries.

In one of use, we know that update operation expected to be performed and calling save(entity) method of JPA.

However, whenever we are calling this api, select statement is getting executed before update query.

can you please suggest how to avoid such select statement execution ?

答:
We can use JPQL(or native SQL) with @Query.

```<code>@Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {

    @Query("update MyEntity as e set e.message = :message where e.id = :id")
    @Modifying
    @Transactional
    void updateWithoutSelect(long id, String message);
}
</code>```

Title: Spring JPA: avoid select before update

Body:
We can use JPQL(or native SQL) with @Query.

@Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {

    @Query("update MyEntity as e set e.message = :message where e.id = :id")
    @Modifying
    @Transactional
    void updateWithoutSelect(long id, String message);
}


问:
Android - voice recognition and saving audio file - not working on some devices
I have working solution for voice recognition and saving the audio file, but the code works only on some devices.

I have tried running this code on few devices. It seems that this solution works on android 5.0, but doesn't work on higher versions.

I'm using Intent class to do that:

```<code>System.out.println("startVoiceInput");
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
                intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
                intent.putExtra("android.speech.extra.GET_AUDIO_FORMAT", "audio/AMR");
                intent.putExtra("android.speech.extra.GET_AUDIO", true);
                try {
                    startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
                } catch (ActivityNotFoundException a) {
                    a.printStackTrace();
                }
</code>```

Recognition itself works on every device (without those lines:

```<code>intent.putExtra("android.speech.extra.GET_AUDIO_FORMAT", "audio/AMR");
intent.putExtra("android.speech.extra.GET_AUDIO", true);
</code>```

).

But with that lines, necessary to catch audio stream to save it on device, the google popup doesn't appear. I don't get any error, but this log:

```<code>D/ViewRootImpl@e232f4[RecordingActivity]: ViewPostIme pointer 0
D/ViewRootImpl@e232f4[RecordingActivity]: ViewPostIme pointer 1
I/System.out: startVoiceInput
D/ViewRootImpl@e232f4[RecordingActivity]: MSG_WINDOW_FOCUS_CHANGED 0
I/System.out: onActivityResult
D/ViewRootImpl@e232f4[RecordingActivity]: Relayout returned: old=[0,0][1080,1920] new=[0,0][1080,1920] result=0x1 surface={valid=true 527892242432} changed=false
   MSG_WINDOW_FOCUS_CHANGED 1
V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@4dc5d3e nm : com.example.acces ic=null
I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
</code>```

答:
Google Keep still uses these secret parameters. You can check it as described here. So it should work.

I checked it in my application. Google popup does not appear if your application does not have RECORD_AUDIO permission. If you add RECORD_AUDIO permission to AndroidManifest.xml then the solution described here works.

Body:
I have working solution for voice recognition and saving the audio file, but the code works only on some devices.

I have tried running this code on few devices. It seems that this solution works on android 5.0, but doesn't work on higher versions.

I'm using Intent class to do that:

System.out.println("startVoiceInput");
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
                intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
                intent.putExtra("android.speech.extra.GET_AUDIO_FORMAT", "audio/AMR");
                intent.putExtra("android.speech.extra.GET_AUDIO", true);
                try {
                    startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
                } catch (ActivityNotFoundException a) {
                    a.printStackTrace();
                }

Recognition itself works on every device (without those lines:

intent.putExtra("android.speech.extra.GET_AUDIO_FORMAT", "audio/AMR");
intent.putExtra("android.speech.extra.GET_AUDIO", true);

).

But with that lines, necessary to catch audio stream to save it on device, the google popup doesn't appear. I don't get any error, but this log:

D/ViewRootImpl@e232f4[RecordingActivity]: ViewPostIme pointer 0
D/ViewRootImpl@e232f4[RecordingActivity]: ViewPostIme pointer 1
I/System.out: startVoiceInput
D/ViewRootImpl@e232f4[RecordingActivity]: MSG_WINDOW_FOCUS_CHANGED 0
I/System.out: onActivityResult
D/ViewRootImpl@e232f4[RecordingActivity]: Relayout returned: old=[0,0][1080,1920] new=[0,0][1080,1920] result=0x1 surface={valid=true 527892242432} changed=false
   MSG_WINDOW_FOCUS_CHANGED 1
V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@4dc5d3e nm : com.example.acces ic=null
I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus