问:
What's the best way to make a difference-comparison between two (apparently) identical Raspberry Pis?
So, I've been given a piece of software, originally written on a regular ol' laptop (running Ubuntu), and asked to see if I can get it running on a Raspberry Pi.

I've installed the software (and configured it) on two seemingly-identical Raspberry Pis running the same version of Ubuntu Mate 16.04. I've done the whole update/upgrade schtick on both multiple times.

The version of the software on each of the two Pis is the same, copied from the same flash drive, run on the same directory and with the same input parameters. They're both Pi model 2b, armV7r4, etc.

On one of them, the code runs properly, produces the expected output, and finishes up in about 2-minutes-twenty.

On the other, the code inevitably segfaults after about a minute twenty.

The code also compiles without issue on each.

The only apparent hardware difference I could spot between the two Pis is that one processor runs at about twice the BogoMIPS speed as the other one.

Can anyone suggest some likely comparisons I could make between the two devices to see if I can figure out what's causing it to miraculously work on one and not on the other?

答:
It appears the issue I was working on was caused by residual, inaccessible files left over from a previous user I thought I'd thoroughly removed from the device.

When my software encountered them, it threw a fit and died.


来源: stackexchange

问:
Finding maximum

Given an integer n and array a. Finding maximum of (a[i]+a[j])*(j-i) with 1<=i<=n-1 and i+1<=j<=n

Example:

Input

```<code>5
1 3 2 5 4
</code>```

Output

```<code>21
</code>```

Explanation :With i=2 and j=5, we have the maximum of (a[i]+a[j])*(j-i) is (3+4)*(5-2)=21

Constraints:

```<code>n<=10^6
a[i]>0 with 1<=i<=n
</code>```

I can solve this problem with n<=10^4, but what should I do if n is too large, like the constraints?

答:
I started from the two excellent answers by @selbie and @kcsquared.

Their solutions gave impressive results for random inputs. What was not clear is the worst case behavior.

What sequence would correspsond to the worst case?

I finally found a critial sequence for these two answers, a triangle sequence: this sequence slightly increases up to a max, and then slightly decrease. With such a sequence and n=10^5 for example, these answers take more than 10s.

My solutions starts from @selbie solution and add two improvements:

I add @kcsquared's trick: on the right (of j), they can be only lower elements

When considering a new left element a[i], it is useless to start from i + 1 to get the second element. We can start from the current best_j

With these tricks, I was able to improve the two posted answer performances a little bit. However, it still
fails to solve the triangle sequence issue: about 10s for n = 10^5.

```<code>#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <chrono>

struct Result {
    size_t i;
    size_t j;
    int64_t value;
};

void print (const Result& res, const std::string& prefix = "") {
    std::cout << prefix;
    std::cout << "(" << res.i << ", " << res.j << ") -> " << res.value << std::endl;
}

Result findBest(const std::vector<int>& a) {
    if (a.size() < 2) {
        return { 0, 0, INT64_MIN };
    }
    int n = a.size();
    std::vector<int> next_max(n, -1);
    int current_max = n-1;
    for (int i = n-1; i >= 0; --i) {
        if (a[i] > a[current_max]) {
            current_max = i;
        }
        next_max[i] = current_max;
    }

    size_t besti = 0;
    size_t bestj = 0;
    int64_t bestvalue = INT64_MIN;
    int minimum = INT_MIN;

    for (size_t i = 0; i < a.size(); i++) {
        if (a[i] <= minimum) {
            continue;
        }
        minimum = a[i];
        size_t jmin = (bestj > i) ? bestj : i+1;
        for (size_t j = jmin; j < a.size(); j++) {
            j = next_max[j];
            value = (a[i] + (int64_t)a[j]) * (j - i);
            if (value > bestvalue) {
                bestvalue = value;
                besti = i;
                bestj = j;
            }
        }
    }
    return { besti, bestj, bestvalue };
}

int main() {
    int n = 1000000;
    int vmax = 100000000;

    std::vector<int> A (n);
    std::srand(std::time(0));
    for (int i = 0; i < n; ++i) {
        A[i] = rand() % vmax + 1;
    }

    std::cout << "n = " << n << std::endl;
    auto t0 = std::chrono::high_resolution_clock::now();
    auto res = findBest (A);
    auto t1 = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count();
    print (res, "Random: ");
    std::cout << "time = " << duration/1000 << " ms" << std::endl;

    int i_max = n/2;
    for (int i = 0; i < i_max; ++i) A[i] = i+1;
    A[i_max] = 10 * i_max;
    for (int i = i_max+1; i < n; ++i) {
        A[i] = 2*i_max - i;
    }
    t0 = std::chrono::high_resolution_clock::now();
    res = findBest (A);
    t1 = std::chrono::high_resolution_clock::now();
    duration = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count();
    print (res, "Triangle sequence: ");
    std::cout << "time = " << duration/1000 << " ms" << std::endl;

    return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Finding maximum

Body:
Given an integer n and array a. Finding maximum of (a[i]+a[j])*(j-i) with 1<=i<=n-1 and i+1<=j<=n

Example:

Input

5
1 3 2 5 4

Output

21

Explanation :With i=2 and j=5, we have the maximum of (a[i]+a[j])*(j-i) is (3+4)*(5-2)=21

Constraints:

n<=10^6
a[i]>0 with 1<=i<=n

I can solve this problem with n<=10^4, but what should I do if n is too large, like the constraints?

Body:
I started from the two excellent answers by @selbie and @kcsquared.

Their solutions gave impressive results for random inputs. What was not clear is the worst case behavior.

What sequence would correspsond to the worst case?

I finally found a critial sequence for these two answers, a triangle sequence: this sequence slightly increases up to a max, and then slightly decrease. With such a sequence and n=10^5 for example, these answers take more than 10s.

My solutions starts from @selbie solution and add two improvements:

I add @kcsquared's trick: on the right (of j), they can be only lower elements

When considering a new left element a[i], it is useless to start from i + 1 to get the second element. We can start from the current best_j

With these tricks, I was able to improve the two posted answer performances a little bit. However, it still
fails to solve the triangle sequence issue: about 10s for n = 10^5.

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <chrono>

struct Result {
    size_t i;
    size_t j;
    int64_t value;
};

void print (const Result& res, const std::string& prefix = "") {
    std::cout << prefix;
    std::cout << "(" << res.i << ", " << res.j << ") -> " << res.value << std::endl;
}

Result findBest(const std::vector<int>& a) {
    if (a.size() < 2) {
        return { 0, 0, INT64_MIN };
    }
    int n = a.size();
    std::vector<int> next_max(n, -1);
    int current_max = n-1;
    for (int i = n-1; i >= 0; --i) {
        if (a[i] > a[current_max]) {
            current_max = i;
        }
        next_max[i] = current_max;
    }

    size_t besti = 0;
    size_t bestj = 0;
    int64_t bestvalue = INT64_MIN;
    int minimum = INT_MIN;

    for (size_t i = 0; i < a.size(); i++) {
        if (a[i] <= minimum) {
            continue;
        }
        minimum = a[i];
        size_t jmin = (bestj > i) ? bestj : i+1;
        for (size_t j = jmin; j < a.size(); j++) {
            j = next_max[j];
            value = (a[i] + (int64_t)a[j]) * (j - i);
            if (value > bestvalue) {
                bestvalue = value;
                besti = i;
                bestj = j;
            }
        }
    }
    return { besti, bestj, bestvalue };
}

int main() {
    int n = 1000000;
    int vmax = 100000000;

    std::vector<int> A (n);
    std::srand(std::time(0));
    for (int i = 0; i < n; ++i) {
        A[i] = rand() % vmax + 1;
    }

    std::cout << "n = " << n << std::endl;
    auto t0 = std::chrono::high_resolution_clock::now();
    auto res = findBest (A);
    auto t1 = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count();
    print (res, "Random: ");
    std::cout << "time = " << duration/1000 << " ms" << std::endl;

    int i_max = n/2;
    for (int i = 0; i < i_max; ++i) A[i] = i+1;
    A[i_max] = 10 * i_max;
    for (int i = i_max+1; i < n; ++i) {
        A[i] = 2*i_max - i;
    }
    t0 = std::chrono::high_resolution_clock::now();
    res = findBest (A);
    t1 = std::chrono::high_resolution_clock::now();
    duration = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count();
    print (res, "Triangle sequence: ");
    std::cout << "time = " << duration/1000 << " ms" << std::endl;

    return 0;
}


问:
How to undo ALTER TABLE using sqlplus (Oracle 10g Express)?
```<code>rollback;
</code>```

doesn't seem to undo alter table changes.

Background:

I'm generating some .sql scripts (based on parsed Hibernate scripts) which are trashing my tables. Importing the full database for testing takes up to 30 minutes (also slowing my machine) and as much as I enjoy taking breaks, i'd prefer to just undo everything with a command such as rollback and try again.

btw this is Oracle 10g Express Edition Release 10.2.0.1.0

Is this even possible?

答:
This version of Oracle performs a commit on any ALTER TABLE statements.  </p>

<p>See this post:
it possible to roll back CREATE TABLE and ALTER TABLE statements in major SQL databases? </p>

ContentLicense: CC BY-SA 3.0

Body:
rollback;

doesn't seem to undo alter table changes.

Background:

I'm generating some .sql scripts (based on parsed Hibernate scripts) which are trashing my tables. Importing the full database for testing takes up to 30 minutes (also slowing my machine) and as much as I enjoy taking breaks, i'd prefer to just undo everything with a command such as rollback and try again.

btw this is Oracle 10g Express Edition Release 10.2.0.1.0

Is this even possible?

Body:
This version of Oracle performs a commit on any ALTER TABLE statements.

See this post:
it possible to roll back CREATE TABLE and ALTER TABLE statements in major SQL databases?


问:
How to get a uniformly-distributed random integer-points in an nD ball?
How to generate uniform random points inside d-dimension ball / sphere?

In this thread, @Thomas Lux has a wonderful solution of generating uniformly random points inside an nD ball with radius r=1. But now I want to generate points where their Cartesian coordinates are integers. I do not know any way except generating random points in a cube and throwing out the points with norm greater than 1.

I don't know if simply using randint or pushing np.floor() to the vector will do.

答:
Simply using round() on uniform real samples would almost work. Except the integer points near the edge of the ball would have lower probabilities of showing up. That's because the hypercube-neighborhood of a point on the edge is less than half-contained in the ball you're sampling from.

There is an easy workaround though. Generate real samples in a ball that fully contains all such hypercubes, the radius r+sqrt(n)/2 should be enough for that, then apply rounding, and finally discard the integer points that are not within distance r.

Certainly the outer ball can be much larger than the inner one, depending on r and n, but the discard rate should still be better.


问:
How to transform a string into a list of char and int using a list comprehension in Python
Given the following string:

```<code>"[10,20]"
</code>```

I want to create the following list using a list comprehension in Python:

```<code>['[', 10, ',', 20, ']']
</code>```

Being 10 and 20 integers and the rest of the elements in the list chars.

I assume that I would need a to use something similar to what itertools.groupby(iterable, key=None) provides:

Make an iterator that returns consecutive keys and groups from the
iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the iterable
needs to already be sorted on the same key function.

However Python's group by returns an iterator with consecutive keys and groups. In my case the keys would change so I guess I'd need a similar iterator that returns the groups based on a filter. Any ideas?

答:
Use str.isdigit as your grouping key and convert groups that have a key of True to integers:</p>
```<code>from itertools import groupby

s = "[10,20]"

r = [[str,int][k]("".join(g)) for k,g in groupby(s,key=str.isdigit)]

print(r)
['[', 10, ',', 20, ']']
</code>```

Body:
Given the following string:

"[10,20]"

I want to create the following list using a list comprehension in Python:

['[', 10, ',', 20, ']']

Being 10 and 20 integers and the rest of the elements in the list chars.

I assume that I would need a to use something similar to what itertools.groupby(iterable, key=None) provides:

Make an iterator that returns consecutive keys and groups from the
iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the iterable
needs to already be sorted on the same key function.

However Python's group by returns an iterator with consecutive keys and groups. In my case the keys would change so I guess I'd need a similar iterator that returns the groups based on a filter. Any ideas?

Body:
Use str.isdigit as your grouping key and convert groups that have a key of True to integers:

from itertools import groupby

s = "[10,20]"

r = [[str,int][k]("".join(g)) for k,g in groupby(s,key=str.isdigit)]

print(r)
['[', 10, ',', 20, ']']


问:
Android studio, kotlin fails when trying to use immersive mode
I'm trying to learn android studio, android, and kotlin. Mostly this has been straightforward but with a few glitches. One such glitch is the following for which I could use some help:

I'm trying to create a phone view in immersive mode. According to the documentation (https://developer.android.com/training/system-ui/immersive) the following function should do the trick.

```<code>private fun hideSystemBars() {
    val windowInsetsController =
        ViewCompat.getWindowInsetsController(window.decorView) ?: return
    // Configure the behavior of the hidden system bars
    windowInsetsController.systemBarsBehavior =
        WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
    // Hide both the status bar and the navigation bar
    windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
}// end hideSystemBars function

</code>```

I set this in the main Activity onCreate function as follows

```<code>    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

       binding = ActivityMainBinding.inflate(layoutInflater)

        requestWindowFeature(Window.FEATURE_NO_TITLE)
        supportActionBar?.hide()

        setContentView(binding.root)
        hideSystemBars()

    }// end onCreate function
</code>```

Unfortunately I seem to missing something basic as this always fails because
ViewCompat.getWindowInsetsController(window.decorView) always returns null (I ran several tests to verify this)

I've verified that window.decorView is not null and looks okay. As a precaution I replaced the hideSystemBars() function call with window.decorView.doOnLayout {hideSystemBars()} in case the layout wasn't complete but this doesn't help. In fact, from some addition tests I ran use of the window.decorView.doOnLayout {} doesn't seem to work either no matter what function is used in the brackets (another glitch I don't understand)

I think I may be missing something basic (and possibly trivial) but cannot seem to discover how to make this work. Any help will be appreciated.

答:
Maybe you should check your API Level on the device. The following solution works for me.</p>
```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val windowInsetsController = ViewCompat.getWindowInsetsController(window.decorView) ?: return
            // Configure the behavior of the hidden system bars
            windowInsetsController.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            // Hide both the status bar and the navigation bar
            windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
        }else{
            val flags =
                (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
            window!!.decorView.setSystemUiVisibility(flags)
        }
</code>```

Body:
I'm trying to learn android studio, android, and kotlin. Mostly this has been straightforward but with a few glitches. One such glitch is the following for which I could use some help:

I'm trying to create a phone view in immersive mode. According to the documentation (https://developer.android.com/training/system-ui/immersive) the following function should do the trick.

private fun hideSystemBars() {
    val windowInsetsController =
        ViewCompat.getWindowInsetsController(window.decorView) ?: return
    // Configure the behavior of the hidden system bars
    windowInsetsController.systemBarsBehavior =
        WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
    // Hide both the status bar and the navigation bar
    windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
}// end hideSystemBars function

I set this in the main Activity onCreate function as follows

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

       binding = ActivityMainBinding.inflate(layoutInflater)

        requestWindowFeature(Window.FEATURE_NO_TITLE)
        supportActionBar?.hide()

        setContentView(binding.root)
        hideSystemBars()

    }// end onCreate function

Unfortunately I seem to missing something basic as this always fails because
ViewCompat.getWindowInsetsController(window.decorView) always returns null (I ran several tests to verify this)

I've verified that window.decorView is not null and looks okay. As a precaution I replaced the hideSystemBars() function call with window.decorView.doOnLayout {hideSystemBars()} in case the layout wasn't complete but this doesn't help. In fact, from some addition tests I ran use of the window.decorView.doOnLayout {} doesn't seem to work either no matter what function is used in the brackets (another glitch I don't understand)

I think I may be missing something basic (and possibly trivial) but cannot seem to discover how to make this work. Any help will be appreciated.

Body:
Maybe you should check your API Level on the device. The following solution works for me.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val windowInsetsController = ViewCompat.getWindowInsetsController(window.decorView) ?: return
            // Configure the behavior of the hidden system bars
            windowInsetsController.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            // Hide both the status bar and the navigation bar
            windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
        }else{
            val flags =
                (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
            window!!.decorView.setSystemUiVisibility(flags)
        }


问:
ModX Evolution: ditto + phx code
I am trying to create XML from my pages using ditto snippet. I have ditto snippet with tpl to a chunk and in chunk I have this:

```<code><tour_id>[+tour-terms:get_tourid+]</tour_id>
</code>```

tour-terms is a template variable and get_tourid is php code (in snippet phx:get_tourid) to filter text stored in tv.

All export to xml works only if I have only one page (startID is folder with one page in it). For multiple pages xml page refuse to load (server error 500). I expect some conflict between internal phx of ditto and phx snippet.

Could not find any solution, please help.

答:
Solved. Problem was in functions I had in snippets. They have to be wrap inside a !function_exists conditional block:

```<code>if(!function_exists(rnCountRows)) {
    function rnCountRows() { ... }
}
</code>```

in case they are run more then once on a page

Title: ModX Evolution: ditto + phx code

Body:
I am trying to create XML from my pages using ditto snippet. I have ditto snippet with tpl to a chunk and in chunk I have this:

<tour_id>[+tour-terms:get_tourid+]</tour_id>

tour-terms is a template variable and get_tourid is php code (in snippet phx:get_tourid) to filter text stored in tv.

All export to xml works only if I have only one page (startID is folder with one page in it). For multiple pages xml page refuse to load (server error 500). I expect some conflict between internal phx of ditto and phx snippet.

Could not find any solution, please help.

Body:
Solved. Problem was in functions I had in snippets. They have to be wrap inside a !function_exists conditional block:

if(!function_exists(rnCountRows)) {
    function rnCountRows() { ... }
}

in case they are run more then once on a page


问:
Why would a Select from Tabke1 where FIeldA not in (Select FieldA from Table2) fail if I manually confirm it should work?
I ran

```<code>Select Term from TableA where Term not in (Select Name from TableB)
</code>```

successfully. Yet when I tried another table

```<code>Select Term from TableA where Term not in (Select Name from TableC)
</code>```

It returns a NULL set. I manuallyt confirmed there are literaly 1000s of records in TableA not in TableB and that the fields are correct.

Is there some other consideration I am not taking into account/understanding about what seems to be a simply query?

Update: Interestingly enough this alternative query worked:

```<code> Select Term from TableA where not exist (Select Name from TableB where TableA.Term=TableC.Name)
</code>```

So while I solved the problem at hand I am still curious why the first query worked for both tables but only the second worked on TableC

答:
For a simple example, consider the following query:

```<code>SELECT *
FROM Table
WHERE ID NOT IN (1, 2, NULL);
</code>```

This is semantically equivalent to:

```<code>SELECT *
FROM Table
WHERE ID <> 1 AND ID <> 2 AND ID <> NULL;
</code>```

The issue is with the last predicate (ID <> NULL). Nothing can be equal to null (not even null) and nothing can be not equal to null. The predicate returns neither true nor false, it returns NULL.

e.g.

ID
ID <> 1
ID <> 2
ID <> NULL

1
FALSE
TRUE
NULL

2
TRUE
FALSE
NULL

3
TRUE
TRUE
NULL

Since you need 3 "TRUE"s to satisfy the AND condition, no rows are returned, since none resolve to true for all 3 predicates.

You can get your NOT IN to work by excluding nulls, e.g.

```<code>SELECT Term
FROM TableA
WHERE Term NOT IN (SELECT Name FROM TableC WHERE Name IS NOT NULL);
</code>```

But for this reason, and the potential for name clashes I always use NOT EXISTS.

Body:
I ran

Select Term from TableA where Term not in (Select Name from TableB)

successfully. Yet when I tried another table

Select Term from TableA where Term not in (Select Name from TableC)

It returns a NULL set. I manuallyt confirmed there are literaly 1000s of records in TableA not in TableB and that the fields are correct.

Is there some other consideration I am not taking into account/understanding about what seems to be a simply query?

Update: Interestingly enough this alternative query worked:

 Select Term from TableA where not exist (Select Name from TableB where TableA.Term=TableC.Name)

So while I solved the problem at hand I am still curious why the first query worked for both tables but only the second worked on TableC

Body:
For a simple example, consider the following query:

SELECT *
FROM Table
WHERE ID NOT IN (1, 2, NULL);

This is semantically equivalent to:

SELECT *
FROM Table
WHERE ID <> 1 AND ID <> 2 AND ID <> NULL;

The issue is with the last predicate (ID <> NULL). Nothing can be equal to null (not even null) and nothing can be not equal to null. The predicate returns neither true nor false, it returns NULL.

e.g.

ID
ID <> 1
ID <> 2
ID <> NULL

1
FALSE
TRUE
NULL

2
TRUE
FALSE
NULL

3
TRUE
TRUE
NULL

Since you need 3 "TRUE"s to satisfy the AND condition, no rows are returned, since none resolve to true for all 3 predicates.

You can get your NOT IN to work by excluding nulls, e.g.

SELECT Term
FROM TableA
WHERE Term NOT IN (SELECT Name FROM TableC WHERE Name IS NOT NULL);

But for this reason, and the potential for name clashes I always use NOT EXISTS.


问:
Modal is hidden from other divs
I'm having a small problem with the modal; part of it is hidden by the right div.

I have two splits, one on the left where the table is shown and the other on the right where a form is shown.

On the left split there is also a button, "Open modal", which allows me to open the modal.

The problem is that once the modal is open, it is visible on the left side, while the part of the modal that ends up on the right split is hidden by the right split.

See figure for further clarification.

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.split {
            height: 100%;
            position: fixed;
            z-index: 1;
            top: 30;
            overflow-x: hidden;
            padding-top: 20px;
        }

        .left {
            left: 0;
            width: 40%;
            background-color: whitesmoke;
        }

        .right {
            right: 0;
            width: 60%;
            background-color: ghostwhite;
        }

        .centered {
            position: absolute;
            top: 30%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }

        .centered table {
            width: 300px;
        }

        table,
        th,
        td {
            border: 1px solid black;
        }

        .buttons {
            display: flex;
        }

        .buttons form {
            margin: 0 10px;
        }

        .part {
            width: 200px;
            padding: 5px;
            border: 1px solid gray;
            margin: 0;
            margin-bottom: 20px;
        }

        /* The Modal (background) */
        .modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            padding-top: 100px;
            /* Location of the box */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
        }

        /* Modal Content */
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        /* The Close Button */
        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }</code>```

Parti dell'articolo

                        Numero
                        Tipo
                        Seleziona

                    <form action="creaFrammento.html">
                        <input type="submit" value="Aggiungi parte articolo" />
                    </form>

                    <input type="button" value="Elimina parti articolo" onclick="confirmation()" />

                <button id="myBtn">Open Modal</button>

                        ×

                    <form method="post" id="save" action="javascript:myFunction()" class="formEdit">

Modifica frammento

                            ID :
                            <input type="number" id="id" name="id" />

                            ID Articolo:
                            <input type="text" id="id_a" name="id_a" />

                            Numero Frammento:
                            <input type="number" id="numero" name="numero" />

                            Tipo Frammento:
                            <select name="tipo" id="tipo" form="tipoform">
                                <option value="Titolo">Titolo</option>
                                <option value="Testo">Testo</option>
                                <option value="Immagine">Immagine</option>
                                <option value="Video youtube">Video youtube</option>
                            </select>

                            Valore Frammento:
                            <textarea id="valore" name="valore" rows="5" cols="30"> </textarea>

                            <button type="submit" id="save-btn" class="full">Salva modifiche</button>
                            <input type="button" id="delete-btn" value="Annulla modifiche"

                    </form>

```

答:
The elements with higher value of z-index appear on top of elements with lower value of z-index.

You need to take the div wrapping  the .modal out of the .left div. Also add z-index to the .modal like so:

```<code>.modal {
   z-index: 999;
}
</code>```
```<code><div hr="" class="horiz">

        <div>
                <!-- Trigger/Open The Modal -->
                <button id="myBtn">Open Modal</button>

                <!-- The Modal -->
                <div id="myModal" class="modal" style="display: block;Z-INDEX: 100;">

                    <!-- Modal content -->
                    <div class="modal-content">
                        <span class="close">×</span>

                        <div>
                            <h1 div="" class="title" id="title">
                        </h1></div>

                        <div class="text-container">
                            <p class="txt1" id="txt1"> </p>
                        </div> <br>

                        <div class="img"> <img id="img" src="" onerror="this.onerror=null;" style="width:50%"> </div> <br>

                        <div class="text-container">
                            <p class="txt2" id="txt2"> </p>
                        </div> <br>

                        <div class="video"> <iframe id="idframe" width="600" height="400"> </iframe> </div> <br>

                    </div>

                </div>
            </div><div class="split left">
            <div class="centered">
                <div class="part">
                    <h3>Parti dell'articolo</h3>
                </div>
                <table id="my-table" width="90%">
                    <tbody><tr>
                        <th>Numero</th>
                        <th>Tipo</th>
                        <th>Seleziona</th>
                    </tr>

                </tbody></table>

                <br><br>

                <div class="buttons">
                    <form action="creaFrammento.html">
                        <input type="submit" value="Aggiungi parte articolo">
                    </form>

                    <input type="button" value="Elimina parti articolo" onclick="confirmation()">
                </div>

            </div>

        </div>

        <div class="split right">
            <div class="centered"> <br>
                <div class="form">
                    <form method="post" id="save" action="javascript:myFunction()" class="formEdit">
                        <h1>Modifica frammento</h1>
                        <div class="field">
                            <label for="id">ID :</label>
                            <input type="number" id="id" name="id">
                        </div>
                        <div class="field">
                            <label for="id_a">ID Articolo:</label>
                            <input type="text" id="id_a" name="id_a">
                        </div>
                        <div class="field">
                            <label for="numero">Numero Frammento:</label>
                            <input type="number" id="numero" name="numero">
                        </div>
                        <div class="field">
                            <label for="tipo">Tipo Frammento:</label>
                            <select name="tipo" id="tipo" form="tipoform">
                                <option value="Titolo">Titolo</option>
                                <option value="Testo">Testo</option>
                                <option value="Immagine">Immagine</option>
                                <option value="Video youtube">Video youtube</option>
                            </select>
                        </div>
                        <div class="field">
                            <label for="valore">Valore Frammento:</label>
                            <textarea id="valore" name="valore" rows="5" cols="30"> </textarea>
                        </div>
                        <div class="button">
                            <button type="submit" id="save-btn" class="full">Salva modifiche</button>
                            <input type="button" id="delete-btn" value="Annulla modifiche" <="" div="">

                </div></form>
            </div>
        </div>
   </div>
</div>
</code>```

Title: Modal is hidden from other divs

Body:
I'm having a small problem with the modal; part of it is hidden by the right div.

I have two splits, one on the left where the table is shown and the other on the right where a form is shown.

On the left split there is also a button, "Open modal", which allows me to open the modal.

The problem is that once the modal is open, it is visible on the left side, while the part of the modal that ends up on the right split is hidden by the right split.

See figure for further clarification.

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

.split {
            height: 100%;
            position: fixed;
            z-index: 1;
            top: 30;
            overflow-x: hidden;
            padding-top: 20px;
        }

        .left {
            left: 0;
            width: 40%;
            background-color: whitesmoke;
        }

        .right {
            right: 0;
            width: 60%;
            background-color: ghostwhite;
        }

        .centered {
            position: absolute;
            top: 30%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }

        .centered table {
            width: 300px;
        }

        table,
        th,
        td {
            border: 1px solid black;
        }

        .buttons {
            display: flex;
        }

        .buttons form {
            margin: 0 10px;
        }

        .part {
            width: 200px;
            padding: 5px;
            border: 1px solid gray;
            margin: 0;
            margin-bottom: 20px;
        }

        /* The Modal (background) */
        .modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            padding-top: 100px;
            /* Location of the box */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
        }

        /* Modal Content */
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        /* The Close Button */
        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }

Parti dell'articolo

                        Numero
                        Tipo
                        Seleziona

                    <form action="creaFrammento.html">
                        <input type="submit" value="Aggiungi parte articolo" />
                    </form>

                    <input type="button" value="Elimina parti articolo" onclick="confirmation()" />

                <button id="myBtn">Open Modal</button>

                        ×

                    <form method="post" id="save" action="javascript:myFunction()" class="formEdit">

Modifica frammento

                            ID :
                            <input type="number" id="id" name="id" />

                            ID Articolo:
                            <input type="text" id="id_a" name="id_a" />

                            Numero Frammento:
                            <input type="number" id="numero" name="numero" />

                            Tipo Frammento:
                            <select name="tipo" id="tipo" form="tipoform">
                                <option value="Titolo">Titolo</option>
                                <option value="Testo">Testo</option>
                                <option value="Immagine">Immagine</option>
                                <option value="Video youtube">Video youtube</option>
                            </select>

                            Valore Frammento:
                            <textarea id="valore" name="valore" rows="5" cols="30"> </textarea>

                            <button type="submit" id="save-btn" class="full">Salva modifiche</button>
                            <input type="button" id="delete-btn" value="Annulla modifiche"

                    </form>

Body:
The elements with higher value of z-index appear on top of elements with lower value of z-index.

You need to take the div wrapping  the .modal out of the .left div. Also add z-index to the .modal like so:

.modal {
   z-index: 999;
}

<div hr="" class="horiz">

        <div>
                <!-- Trigger/Open The Modal -->
                <button id="myBtn">Open Modal</button>

                <!-- The Modal -->
                <div id="myModal" class="modal" style="display: block;Z-INDEX: 100;">

                    <!-- Modal content -->
                    <div class="modal-content">
                        <span class="close">×</span>

                        <div>
                            <h1 div="" class="title" id="title">
                        </h1></div>

                        <div class="text-container">
                            <p class="txt1" id="txt1"> </p>
                        </div> <br>

                        <div class="img"> <img id="img" src="" onerror="this.onerror=null;" style="width:50%"> </div> <br>

                        <div class="text-container">
                            <p class="txt2" id="txt2"> </p>
                        </div> <br>

                        <div class="video"> <iframe id="idframe" width="600" height="400"> </iframe> </div> <br>

                    </div>

                </div>
            </div><div class="split left">
            <div class="centered">
                <div class="part">
                    <h3>Parti dell'articolo</h3>
                </div>
                <table id="my-table" width="90%">
                    <tbody><tr>
                        <th>Numero</th>
                        <th>Tipo</th>
                        <th>Seleziona</th>
                    </tr>

                </tbody></table>

                <br><br>

                <div class="buttons">
                    <form action="creaFrammento.html">
                        <input type="submit" value="Aggiungi parte articolo">
                    </form>

                    <input type="button" value="Elimina parti articolo" onclick="confirmation()">
                </div>

            </div>

        </div>

        <div class="split right">
            <div class="centered"> <br>
                <div class="form">
                    <form method="post" id="save" action="javascript:myFunction()" class="formEdit">
                        <h1>Modifica frammento</h1>
                        <div class="field">
                            <label for="id">ID :</label>
                            <input type="number" id="id" name="id">
                        </div>
                        <div class="field">
                            <label for="id_a">ID Articolo:</label>
                            <input type="text" id="id_a" name="id_a">
                        </div>
                        <div class="field">
                            <label for="numero">Numero Frammento:</label>
                            <input type="number" id="numero" name="numero">
                        </div>
                        <div class="field">
                            <label for="tipo">Tipo Frammento:</label>
                            <select name="tipo" id="tipo" form="tipoform">
                                <option value="Titolo">Titolo</option>
                                <option value="Testo">Testo</option>
                                <option value="Immagine">Immagine</option>
                                <option value="Video youtube">Video youtube</option>
                            </select>
                        </div>
                        <div class="field">
                            <label for="valore">Valore Frammento:</label>
                            <textarea id="valore" name="valore" rows="5" cols="30"> </textarea>
                        </div>
                        <div class="button">
                            <button type="submit" id="save-btn" class="full">Salva modifiche</button>
                            <input type="button" id="delete-btn" value="Annulla modifiche" <="" div="">

                </div></form>
            </div>
        </div>
   </div>
</div>


问:
How to parse a stringified HTML and bind it to the DOM with its attributes (angular)
i have this kind of string

"
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sit amet vestibulum eros, ac aliquam magna. Interdum et malesuada fames ac ante ipsum primis in faucibus. In ante urna, dictum sed porta ut, consectetur eu felis. Pellentesque eleifend egestas augue, iaculis ultricies nulla volutpat at. Vivamus sagittis est eu rutrum blandit"

which includes style attributes
i want to bind it to my html
but whatever i try i always lose some styles like the first one

("<div style="text-align: center;" )

any idea how to put this into my html without losing any styles ?
thank you

答:
Well i do assume you've used [innerHtml] directive on your HTML element like this:

```<code>// Your *.html template
<p [innerHTML]="myUnsafeHtmlString"></p>

// Your *.component.ts controller file
myUnsafeHtmlString: string = `<div style="text-align: center;">
<b style="color: rgb(122, 122, 122); font-family: 'Open Sans', Arial, sans-serif; text-align: justify;">Lorem ipsum...</b></div>`;
</code>```

In that case Angular will block some HTML attributes because of safety reasons. You have info about this inside your browser developer tools -> console tab.

More about DomSanitizer in Angular - https://angular.io/api/platform-browser/DomSanitizer

To achieve "unsafe" html in your templates you need to explicitly call it thru DomSanitizer. In my example I've used @Pipe to achieve this, however your can also use it from your components controller.

```<code>// Your *.html template
<p [innerHTML]="myUnsafeHtmlString | safeHtml"></p>

// Your *.pipe.ts
@Pipe({ name: 'safeHtml' })
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

// Your *.component.ts controller file
myUnsafeHtmlString: string = `<div style="text-align: center;">
<b style="color: rgb(122, 122, 122); font-family: 'Open Sans', Arial, sans-serif; text-align: justify;">Lorem ipsum...</b></div>`;
</code>```

Full stackblitz example:

https://stackblitz.com/edit/angular-ivy-yxcwjb?file=src%2Fapp%2Fapp.component.html

Body:
Well i do assume you've used [innerHtml] directive on your HTML element like this:

// Your *.html template
<p [innerHTML]="myUnsafeHtmlString"></p>

// Your *.component.ts controller file
myUnsafeHtmlString: string = `<div style="text-align: center;">
<b style="color: rgb(122, 122, 122); font-family: 'Open Sans', Arial, sans-serif; text-align: justify;">Lorem ipsum...</b></div>`;

In that case Angular will block some HTML attributes because of safety reasons. You have info about this inside your browser developer tools -> console tab.

More about DomSanitizer in Angular - https://angular.io/api/platform-browser/DomSanitizer

To achieve "unsafe" html in your templates you need to explicitly call it thru DomSanitizer. In my example I've used @Pipe to achieve this, however your can also use it from your components controller.

// Your *.html template
<p [innerHTML]="myUnsafeHtmlString | safeHtml"></p>

// Your *.pipe.ts
@Pipe({ name: 'safeHtml' })
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

// Your *.component.ts controller file
myUnsafeHtmlString: string = `<div style="text-align: center;">
<b style="color: rgb(122, 122, 122); font-family: 'Open Sans', Arial, sans-serif; text-align: justify;">Lorem ipsum...</b></div>`;

Full stackblitz example:

https://stackblitz.com/edit/angular-ivy-yxcwjb?file=src%2Fapp%2Fapp.component.html


问:
Retrieving specific key value pairs from URL using Axios API
I am trying to use axios to retrieve data from a url and then print our specific key value pairs from the JSON retrieved. This is what I have written

```<code>const newArr = ["javascript","bootstrap","technology","jquery","node"]
axios.get('http://localhost:5000/api/articles')
      .then((resp) => {
      newArr.forEach((item) => {
        console.log(`headline: ${resp.data.articles[item].headline} id: ${resp.data.articles[item].authorName}` );
    })
  })
</code>```

In a nutshell the URL has the titles; Javascript, Bootstrap, Technology, jQuery and Node.

For each of this I want to print out the associated headline and authorName.

My code returns

```<code>headline: undefined id: undefined
headline: undefined id: undefined
headline: undefined id: undefined
headline: undefined id: undefined
headline: undefined id: undefined
</code>```

I expect to retrieve the values

```<code>headline: 'ES8: The Next Step in the Evolution of Javascript and What it Means For Your Projects' id: 'SIR RUFF'N'STUFF'
headline: 'Type Coercion: Why Does NaN !== NaN? and Other Strange Occurrences' id: 'BONES R. LIFE'
headline: "When to Rest, When to Spread: Why There Are Two Meanings Behind '...'" id: 'PUPPER S. DOGGO'
headline: 'Typescript: Ten Things you Should Know Before Building Your Next Angular Application' id: "SIR RUFF'N'STUFF"
headline: 'Bootstrap 5: Get a Sneak Peak at all the New Features' id: 'FIDO WALKSALOT'
headline: 'UI Frameworks: A Comparison, Which Made Our List? (Hint: Bootstrap is on it)' id: 'MAX GOODBOYE'
headline: 'The Hottest New Bootstrap 4 Components Every Developer Needs to Know About' id: 'MAX GOODBOYE'
headline: 'AI: What Are the Ethical Ramifications of the Future?' id: 'MAX GOODBOYE'
...
</code>```

UPDATE

This is what I get when I do a console.log(resp.data)

```<code>{
  articles: {
    javascript: [ [Object], [Object], [Object], [Object] ],
    bootstrap: [ [Object], [Object], [Object] ],
    technology: [ [Object], [Object], [Object] ],
    jquery: [ [Object], [Object], [Object] ],
    node: [ [Object], [Object] ]
  }
}
{
  articles: {
    javascript: [ [Object], [Object], [Object], [Object] ],
    bootstrap: [ [Object], [Object], [Object] ],
    technology: [ [Object], [Object], [Object] ],
    jquery: [ [Object], [Object], [Object] ],
    node: [ [Object], [Object] ]
  }
}
{
  articles: {
    javascript: [ [Object], [Object], [Object], [Object] ],
    bootstrap: [ [Object], [Object], [Object] ],
    technology: [ [Object], [Object], [Object] ],
    jquery: [ [Object], [Object], [Object] ],
    node: [ [Object], [Object] ]
  }
}
{
  articles: {
    javascript: [ [Object], [Object], [Object], [Object] ],
    bootstrap: [ [Object], [Object], [Object] ],
    technology: [ [Object], [Object], [Object] ],
    jquery: [ [Object], [Object], [Object] ],
    node: [ [Object], [Object] ]
  }
}
{
  articles: {
    javascript: [ [Object], [Object], [Object], [Object] ],
    bootstrap: [ [Object], [Object], [Object] ],
    technology: [ [Object], [Object], [Object] ],
    jquery: [ [Object], [Object], [Object] ],
    node: [ [Object], [Object] ]
  }
}
</code>```

答:
You need a nested loop for this:</p>
```<code>const newArr = ["javascript","bootstrap","technology","jquery","node"]
axios.get('http://localhost:5000/api/articles')
      .then((resp) => {
      newArr.forEach((item) => {
           resp.data.articles[item].forEach((obj)=>{
                console.log(`headline: ${obj.headline} id: ${obj.authorName}` );
           })

    })
  })
</code>```

Body:
I am trying to use axios to retrieve data from a url and then print our specific key value pairs from the JSON retrieved. This is what I have written

const newArr = ["javascript","bootstrap","technology","jquery","node"]
axios.get('http://localhost:5000/api/articles')
      .then((resp) => {
      newArr.forEach((item) => {
        console.log(`headline: ${resp.data.articles[item].headline} id: ${resp.data.articles[item].authorName}` );
    })
  })

In a nutshell the URL has the titles; Javascript, Bootstrap, Technology, jQuery and Node.

For each of this I want to print out the associated headline and authorName.

My code returns

headline: undefined id: undefined
headline: undefined id: undefined
headline: undefined id: undefined
headline: undefined id: undefined
headline: undefined id: undefined

I expect to retrieve the values

headline: 'ES8: The Next Step in the Evolution of Javascript and What it Means For Your Projects' id: 'SIR RUFF'N'STUFF'
headline: 'Type Coercion: Why Does NaN !== NaN? and Other Strange Occurrences' id: 'BONES R. LIFE'
headline: "When to Rest, When to Spread: Why There Are Two Meanings Behind '...'" id: 'PUPPER S. DOGGO'
headline: 'Typescript: Ten Things you Should Know Before Building Your Next Angular Application' id: "SIR RUFF'N'STUFF"
headline: 'Bootstrap 5: Get a Sneak Peak at all the New Features' id: 'FIDO WALKSALOT'
headline: 'UI Frameworks: A Comparison, Which Made Our List? (Hint: Bootstrap is on it)' id: 'MAX GOODBOYE'
headline: 'The Hottest New Bootstrap 4 Components Every Developer Needs to Know About' id: 'MAX GOODBOYE'
headline: 'AI: What Are the Ethical Ramifications of the Future?' id: 'MAX GOODBOYE'
...

UPDATE

This is what I get when I do a console.log(resp.data)

{
  articles: {
    javascript: [ [Object], [Object], [Object], [Object] ],
    bootstrap: [ [Object], [Object], [Object] ],
    technology: [ [Object], [Object], [Object] ],
    jquery: [ [Object], [Object], [Object] ],
    node: [ [Object], [Object] ]
  }
}
{
  articles: {
    javascript: [ [Object], [Object], [Object], [Object] ],
    bootstrap: [ [Object], [Object], [Object] ],
    technology: [ [Object], [Object], [Object] ],
    jquery: [ [Object], [Object], [Object] ],
    node: [ [Object], [Object] ]
  }
}
{
  articles: {
    javascript: [ [Object], [Object], [Object], [Object] ],
    bootstrap: [ [Object], [Object], [Object] ],
    technology: [ [Object], [Object], [Object] ],
    jquery: [ [Object], [Object], [Object] ],
    node: [ [Object], [Object] ]
  }
}
{
  articles: {
    javascript: [ [Object], [Object], [Object], [Object] ],
    bootstrap: [ [Object], [Object], [Object] ],
    technology: [ [Object], [Object], [Object] ],
    jquery: [ [Object], [Object], [Object] ],
    node: [ [Object], [Object] ]
  }
}
{
  articles: {
    javascript: [ [Object], [Object], [Object], [Object] ],
    bootstrap: [ [Object], [Object], [Object] ],
    technology: [ [Object], [Object], [Object] ],
    jquery: [ [Object], [Object], [Object] ],
    node: [ [Object], [Object] ]
  }
}

Body:
You need a nested loop for this:

const newArr = ["javascript","bootstrap","technology","jquery","node"]
axios.get('http://localhost:5000/api/articles')
      .then((resp) => {
      newArr.forEach((item) => {
           resp.data.articles[item].forEach((obj)=>{
                console.log(`headline: ${obj.headline} id: ${obj.authorName}` );
           })

    })
  })


问:
Marking outliers in time series data
I have a df of thousands of entries of particular lab value for patients with each row representing one instance they had the lab taken. I am interested in looking at the change in this value over time after a surgery. If the value rises and falls back to baseline within an acute time period I need to exclude the rise, however if it rises and stays above baseline I need to keep these values. I am able to mark if the value rises past a certain threshold within a time period, but I'm unsure how to code if it returns to baseline within a particular range of time. My ultimate goal is to use a geom_smooth to trend the value over time based on a particular procedure type, but need to exclude these outliers for my graphs to be correct. Any help would be very appreciated!

My data is organized like this:

lab Date
Lab value
study ID
Acutely Past threshold

1/1/2001
2
1
NA

4/1/2001
2.3
1
N

5/2/2002
2.3
1
N

4/8/2018
1
2
NA

4/9/2018
3.8
2
Y

4/15/2018
1
2
N

5/1/2016
1.0
3
NA

5/2/2016
1.2
3
N

4/1/1997
1.0
4
NA

4/4/1997
2.5
4
Y

5/5/1997
2.5
4
N

答:
For further reference, when posting data it is better to use dput in order to provide a reproducible example.
I thinking something like this might work. You would need to identify the "episodes" in which the value went over the threshold.
In this code, the output I think you're looking for is "episode"</p>
```<code>df %>%
  group_by(id) %>%
  mutate(
    potential_episode_grp = (lab_value > normal_level) * data.table::rleid(lab_value > normal_level)
  ) %>%
  group_by(id, potential_episode_grp) %>%
  mutate(episode = as.integer(potential_episode_grp > 0 & any(lab_value > threshold_you_want)))
</code>```

Title: Marking outliers in time series data

Body:
For further reference, when posting data it is better to use dput in order to provide a reproducible example.
I thinking something like this might work. You would need to identify the "episodes" in which the value went over the threshold.
In this code, the output I think you're looking for is "episode"

df %>%
  group_by(id) %>%
  mutate(
    potential_episode_grp = (lab_value > normal_level) * data.table::rleid(lab_value > normal_level)
  ) %>%
  group_by(id, potential_episode_grp) %>%
  mutate(episode = as.integer(potential_episode_grp > 0 & any(lab_value > threshold_you_want)))


问:
How to save current cmd-output
Is there a way to get whats currently displayed on the windows command prompt?

For example:

```<code>print('some text')
print('some different text')

>>> some text
>>> some different text

a = save_whats_on_cmd()
>>> a = 'some text \n some different text'
</code>```

答:
I used @omar's solution to my problem and modified it for it to fit perfectly for my needs. Here is what I wrote:

```<code>def log(text, **kwargs): # possible arguments: colour, end
    logfile = open('log.txt', 'a')
    if kwargs == {}:
        # normal print statement: no colour, no end=''
        print(text)
        logfile.write(text + '\n')
    else:
        if 'colour' in kwargs and 'end' in kwargs:
            # both colour and end=''
            print(f'\x1b[{kwargs["colour"]}m{text}\x1b[0m', end='', flush=True)
            logfile.write(text)
        elif 'colour' in kwargs:
            # only colour
            print(f'\x1b[{kwargs["colour"]}m{text}\x1b[0m')
            logfile.write(text + '\n')
        elif 'end' in kwargs:
            # only end=''
            print(text, end='', flush=True)
            logfile.write(text)
    logfile.close()
</code>```

I didn't want sth like \x1b[1;31;42mSOMETEXT\x1b[0m to appear in the log so I made the colour-stuff be an argument. Result in the log-file is then only SOMETEXT.

For the end argument it's irrelevant what's assigned to it. I just needs to be mentioned.

This makes the log-file like a second command prompt - only colourless.

If anyone has any ideas about how to improve my function, please tell me because I think it looks quite messy.  :P

Thanks for the anwsers :)

Title: How to save current cmd-output

Body:
Is there a way to get whats currently displayed on the windows command prompt?

For example:

print('some text')
print('some different text')

>>> some text
>>> some different text

a = save_whats_on_cmd()
>>> a = 'some text \n some different text'

Body:
I used @omar's solution to my problem and modified it for it to fit perfectly for my needs. Here is what I wrote:

def log(text, **kwargs): # possible arguments: colour, end
    logfile = open('log.txt', 'a')
    if kwargs == {}:
        # normal print statement: no colour, no end=''
        print(text)
        logfile.write(text + '\n')
    else:
        if 'colour' in kwargs and 'end' in kwargs:
            # both colour and end=''
            print(f'\x1b[{kwargs["colour"]}m{text}\x1b[0m', end='', flush=True)
            logfile.write(text)
        elif 'colour' in kwargs:
            # only colour
            print(f'\x1b[{kwargs["colour"]}m{text}\x1b[0m')
            logfile.write(text + '\n')
        elif 'end' in kwargs:
            # only end=''
            print(text, end='', flush=True)
            logfile.write(text)
    logfile.close()

I didn't want sth like \x1b[1;31;42mSOMETEXT\x1b[0m to appear in the log so I made the colour-stuff be an argument. Result in the log-file is then only SOMETEXT.

For the end argument it's irrelevant what's assigned to it. I just needs to be mentioned.

This makes the log-file like a second command prompt - only colourless.

If anyone has any ideas about how to improve my function, please tell me because I think it looks quite messy.  :P

Thanks for the anwsers :)


问:
Error while loading shared libraries: libX11.so.6
I installed authy using the snap install authy command. When I try to open the application, I get the following error message:
/snap/authy/6/authy: error loading shared libraries: libX11.so.6: unable to open shared objects file: No such file or directory

Ubuntu 20.04.3 LTS

答:
Installing libx11-6:i386 worked for me:

```<code>sudo apt-get install libx11-6:i386
</code>```

after that I experienced another error solved by installing libstdc++5:i386:

```<code>sudo apt-get install libstdc++5:i386
</code>```

Body:
Installing libx11-6:i386 worked for me:

sudo apt-get install libx11-6:i386

after that I experienced another error solved by installing libstdc++5:i386:

sudo apt-get install libstdc++5:i386


问:
bootstrap carousel border expands during slide
I'm building a bootstrap5 carousel with a video inside. The video has a fixed width and height and I am using a box-shadow on it.

The problem is that during every slide transition, the box-shadow expands as if the video element had a different height/width.

I need to know how to make the box-shadow stay at the exact same place, so that I don't end up with this messy/buggy transition:

snippet:

.monkey-video {
    /* box-shadow: 0px 0px -60px -40px rgba(255, 255, 255, 0.35) inset; */
    width: 200;
    height: 240;
    box-shadow: rgba(255, 255, 255, 0.35) 0px 5px 15px;
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<body class="bg-dark">
<section id="chars-section" class="position-relative" style="width: 100%;">
                <div class="d-flex flex-column justify-content-evenly align-items-center ">

                    <h3 class="p-1" style="font-family: 'league_spartanbold'; color:   #F8C84A;">MEET THE MONKEYS</h3>

                    <div id="carousel-monkeys" class="carousel slide carousel-fade" data-bs-ride="carousel">
                        <div class="carousel-inner monkey-video">
                          <div id="0" class="carousel-item active">
                            <div class="d-flex justify-content-center w-100">
                                <video width="200" height="240" autoplay muted loop>
                                    <source src="./img/Neandermonkey - Vídeo.mp4" type="video/mp4">
                                    Your browser does not support the video, please use a different browser.
                                </video>
                            </div>
                          </div>
                          <div id="1" class="carousel-item">
                            <div class="d-flex justify-content-center w-100">
                                <video width="200" height="240" autoplay muted loop>
                                    <source src="./img/Medieval - Vídeo.mp4" type="video/mp4">
                                    Your browser does not support the video, please use a different browser.
                                </video>
                            </div>
                          </div>
                          <div id="2" class="carousel-item">
                            <div class="d-flex justify-content-center w-100">
                                <video width="200" height="240" autoplay muted loop>
                                    <source src="./img/Futuro - Vídeo.mp4" type="video/mp4">
                                    Your browser does not support the video, please use a different browser.
                                </video>
                            </div>
                          </div>
                        </div>
                        <button class="carousel-control-prev" type="button" data-bs-target="#carousel-monkeys" data-bs-slide="prev">
                          <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                          <span class="visually-hidden">Previous</span>
                        </button>
                        <button class="carousel-control-next" type="button" data-bs-target="#carousel-monkeys" data-bs-slide="next">
                          <span class="carousel-control-next-icon" aria-hidden="true"></span>
                          <span class="visually-hidden">Next</span>
                        </button>
                    </div>

                </div>
            </section>
            </body></code>```

答:
The problem is the #carousel-monkeys element width expands while the carousel items are in transition.  You should set a fixed with on the #carousel-monkeys element to match the video width.  Try this out:</p>
```<code><html>
   <head>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
      <script defer src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
      <style>
         #carousel-monkeys {
         width: 200px;
         }
      </style>
   </head>
   <body class="bg-dark">
      <section id="chars-section" class="position-relative" style="width: 100%;">
         <div class="d-flex flex-column justify-content-evenly align-items-center ">
            <h3 class="p-1" style="font-family: 'league_spartanbold'; color:   #F8C84A;">MEET THE MONKEYS</h3>
            <div id="carousel-monkeys" class="carousel slide carousel-fade" data-bs-ride="carousel">
               <div class="carousel-inner monkey-video">
                  <div id="0" class="carousel-item active">
                     <div class="d-flex justify-content-center w-100">
                        <video width="200" height="240" autoplay muted loop>
                           <source src="./video.mp4" type="video/mp4">
                           Your browser does not support the video, please use a different browser.
                        </video>
                     </div>
                  </div>
                  <div id="1" class="carousel-item">
                     <div class="d-flex justify-content-center w-100">
                        <video width="200" height="240" autoplay muted loop>
                           <source src="./video.mp4" type="video/mp4">
                           Your browser does not support the video, please use a different browser.
                        </video>
                     </div>
                  </div>
                  <div id="2" class="carousel-item">
                     <div class="d-flex justify-content-center w-100">
                        <video width="200" height="240" autoplay muted loop>
                           <source src="./video.mp4" type="video/mp4">
                           Your browser does not support the video, please use a different browser.
                        </video>
                     </div>
                  </div>
               </div>
               <button class="carousel-control-prev" type="button" data-bs-target="#carousel-monkeys" data-bs-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Previous</span>
               </button>
               <button class="carousel-control-next" type="button" data-bs-target="#carousel-monkeys" data-bs-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Next</span>
               </button>
            </div>
         </div>
      </section>
   </body>
</html>
</code>```

Body:
I'm building a bootstrap5 carousel with a video inside. The video has a fixed width and height and I am using a box-shadow on it.

The problem is that during every slide transition, the box-shadow expands as if the video element had a different height/width.

I need to know how to make the box-shadow stay at the exact same place, so that I don't end up with this messy/buggy transition:

snippet:

.monkey-video {
    /* box-shadow: 0px 0px -60px -40px rgba(255, 255, 255, 0.35) inset; */
    width: 200;
    height: 240;
    box-shadow: rgba(255, 255, 255, 0.35) 0px 5px 15px;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

MEET THE MONKEYS

                                <video width="200" height="240" autoplay muted loop>
                                    <source src="./img/Neandermonkey - Vídeo.mp4" type="video/mp4">
                                    Your browser does not support the video, please use a different browser.
                                </video>

                                <video width="200" height="240" autoplay muted loop>
                                    <source src="./img/Medieval - Vídeo.mp4" type="video/mp4">
                                    Your browser does not support the video, please use a different browser.
                                </video>

                                <video width="200" height="240" autoplay muted loop>
                                    <source src="./img/Futuro - Vídeo.mp4" type="video/mp4">
                                    Your browser does not support the video, please use a different browser.
                                </video>

                        <button class="carousel-control-prev" type="button" data-bs-target="#carousel-monkeys" data-bs-slide="prev">

                          Previous
                        </button>
                        <button class="carousel-control-next" type="button" data-bs-target="#carousel-monkeys" data-bs-slide="next">

                          Next
                        </button>

Body:
The problem is the #carousel-monkeys element width expands while the carousel items are in transition.  You should set a fixed with on the #carousel-monkeys element to match the video width.  Try this out:

<html>
   <head>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
      <script defer src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
      <style>
         #carousel-monkeys {
         width: 200px;
         }
      </style>
   </head>
   <body class="bg-dark">
      <section id="chars-section" class="position-relative" style="width: 100%;">
         <div class="d-flex flex-column justify-content-evenly align-items-center ">
            <h3 class="p-1" style="font-family: 'league_spartanbold'; color:   #F8C84A;">MEET THE MONKEYS</h3>
            <div id="carousel-monkeys" class="carousel slide carousel-fade" data-bs-ride="carousel">
               <div class="carousel-inner monkey-video">
                  <div id="0" class="carousel-item active">
                     <div class="d-flex justify-content-center w-100">
                        <video width="200" height="240" autoplay muted loop>
                           <source src="./video.mp4" type="video/mp4">
                           Your browser does not support the video, please use a different browser.
                        </video>
                     </div>
                  </div>
                  <div id="1" class="carousel-item">
                     <div class="d-flex justify-content-center w-100">
                        <video width="200" height="240" autoplay muted loop>
                           <source src="./video.mp4" type="video/mp4">
                           Your browser does not support the video, please use a different browser.
                        </video>
                     </div>
                  </div>
                  <div id="2" class="carousel-item">
                     <div class="d-flex justify-content-center w-100">
                        <video width="200" height="240" autoplay muted loop>
                           <source src="./video.mp4" type="video/mp4">
                           Your browser does not support the video, please use a different browser.
                        </video>
                     </div>
                  </div>
               </div>
               <button class="carousel-control-prev" type="button" data-bs-target="#carousel-monkeys" data-bs-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Previous</span>
               </button>
               <button class="carousel-control-next" type="button" data-bs-target="#carousel-monkeys" data-bs-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Next</span>
               </button>
            </div>
         </div>
      </section>
   </body>
</html>


问:
Cannot authenticate Azure service
I am creating a Microsoft Teams Bot and have two similar projects. I have two resources in Azure: app service and Azure bot. I believe app service is responsible for running my bot in Azure.

Project A: So: I created new client secret for the Azure bot. Now my bot (already deployed) doesn't work, in the logs I can see an error about wrong client secret. But where do I need to put it? I updated the Authentication Service provider (Test connection gives the Token, so secret value is correct) in Azure bot.

答: The resolution was to publish application with updated values in appsettings.json. Probably even the local Bot Emulator uses authentication settings from Azure.</p>

Title: Cannot authenticate Azure service


问:
jquery selectors and disabled='disabled'
I just noticed that a disabled input text field is not picked up in a selector when it is disabled. Is there a way to say select inputs disabled or not...</p>

```<code><input type="text" name="MYNAME" id="preXXXX" disabled='disabled' value="my Value"  />

$.each($('input[id^="pre"], select[id^="pre"]').serializeArray(), function() {
</code>```

答:
The HTML5 spec specifies that disabled form fields should not be submitted with the form (3.1 bullet #2).

jQuery does it's best to follow the spec as far as expected results.

If you want data to be transmitted with a form, but you want to prevent a user from editing the value, you should use readonly="readonly" instead of disabled="disabled". Read only fields are just that, the user can read them, but not edit them.

As far as selection goes, you just need to use the jQuery factory method for selection:

```<code>$('input[id^="pre"], select[id^="pre"]')
</code>```

And you can iterate over every element using the each function:

```<code>$('input[id^="pre"], select[id^="pre"]').each( function( index, element ){
  ...do stuff...
});
</code>```

Body:
I just noticed that a disabled input text field is not picked up in a selector when it is disabled. Is there a way to say select inputs disabled or not...

<input type="text" name="MYNAME" id="preXXXX" disabled='disabled' value="my Value"  />

$.each($('input[id^="pre"], select[id^="pre"]').serializeArray(), function() {

Body:
The HTML5 spec specifies that disabled form fields should not be submitted with the form (3.1 bullet #2).

jQuery does it's best to follow the spec as far as expected results.

If you want data to be transmitted with a form, but you want to prevent a user from editing the value, you should use readonly="readonly" instead of disabled="disabled". Read only fields are just that, the user can read them, but not edit them.

As far as selection goes, you just need to use the jQuery factory method for selection:

$('input[id^="pre"], select[id^="pre"]')

And you can iterate over every element using the each function:

$('input[id^="pre"], select[id^="pre"]').each( function( index, element ){
  ...do stuff...
});


问:
Office Outlook Add-In resizing taskpane
Is there a way to resize a custom Add-In? I am creating a custom add-in for outlook and would like to make the width bigger. Thanks!</p>

答:
OfficeJS doesn't provide anything for resizing a task pane. The resizeTo method of the window object doesn't work for task panes from web add-ins.

If you need to be able to resize a custom task pane you may consider creating a VSTO based add-in instead.

Title: Office Outlook Add-In resizing taskpane


问:
How to get the values from inside the code when exception occurs?
I have a worker service in .net core 3.1
in my Program.cs i have the below codes

```<code>   public static void Main(string[] args)
    {
        try
        {
            CreateHostBuilder(args).Build().Run();
        }
        catch(Exception ex)
        {
            Handler(ex);
        }

    }

 static void Handler( Exception e)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        List<Test> _Test = new List<Test>()
        {
            new Test()
            {

            }
        };
        LogEventInfo eventInfo = new LogEventInfo
        {
            Level = LogLevel.Error,
            Properties = { { "Application",_Test } }
        };
        logger.Log(eventInfo);
    }

private class Test
{
 public string Name{get;set;}
 public string Place{get;set;}
}
</code>```

In my worker class i have code as below

```<code>public class Worker : BackgroundService
{

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {

        do
        {

           string Name  ="MyName";// These values will be fetched from different file
           string Place="MyPlace";
        //Some Logic where an exception may occur
        }
        while (!stoppingToken.IsCancellationRequested);

    }
}
</code>```

Is there anyway to get the values of Name and Place of worker class to Handler method in program class when an exception arises. Since I'm thinking of a global exception handler I'm thinking of not putting any more try catch blocks. I want to handle all the exception with the try catch in the program.cs file. How can i get the Name and Place values onto my handler on such scenario so that it can be logged?

答:
While a custom exception is a possibility, you could also simply decorate any exception thrown inside your service with those properties using the Data property:

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    do
    {
        string Name = "MyName";
        string Place = "MyPlace";

        try
        {
            //Some Logic where an exception may occur
        }
        catch (Exception e)
        {
            e.Data["Name"] = Name;
            e.Data["Place"] = Place;
            throw;
        }
    }
    while (!stoppingToken.IsCancellationRequested);
}
```

Body:
I have a worker service in .net core 3.1
in my Program.cs i have the below codes

   public static void Main(string[] args)
    {
        try
        {
            CreateHostBuilder(args).Build().Run();
        }
        catch(Exception ex)
        {
            Handler(ex);
        }

    }

 static void Handler( Exception e)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        List<Test> _Test = new List<Test>()
        {
            new Test()
            {

            }
        };
        LogEventInfo eventInfo = new LogEventInfo
        {
            Level = LogLevel.Error,
            Properties = { { "Application",_Test } }
        };
        logger.Log(eventInfo);
    }

private class Test
{
 public string Name{get;set;}
 public string Place{get;set;}
}

In my worker class i have code as below

public class Worker : BackgroundService
{

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {

        do
        {

           string Name  ="MyName";// These values will be fetched from different file
           string Place="MyPlace";
        //Some Logic where an exception may occur
        }
        while (!stoppingToken.IsCancellationRequested);

    }
}

Is there anyway to get the values of Name and Place of worker class to Handler method in program class when an exception arises. Since I'm thinking of a global exception handler I'm thinking of not putting any more try catch blocks. I want to handle all the exception with the try catch in the program.cs file. How can i get the Name and Place values onto my handler on such scenario so that it can be logged?


问:
Check if the element exists in the array, and then replace between two arrays Swift
I have a class "Players", and a class "Team". I created two array of Strings calling player1.name, player2.name, etc.
one array with main players and the other array with secondary players

Class:

```<code>class Players {
    let name: String
    let number: int
    var position:PositionPlayer
    var birth: Date
    let nationality: String
    var height: Double
    var weight: int
    init(name: String, number: Int, position: PositionPlayer, birth: Date, height: Double, weight: Int) {
        self.name = name
        self.number = number
        self.position = position
        self.birth = birth
        self.nationality = nationality
        self.height = height
        self.weight = weight
    }
</code>```

Class Team is empty (just doing the function on it)

Arrays:

```<code>var mainPlayers: [String] = []
var secondaryPlayers: [String] = []
</code>```

add elements in arrays:

```<code>mainPlayers.append("\(player1.name)")
</code>```

How do I make a function in class "Team" that checks the elements of the arrays and does the substitution between the 2 arrays?

e.g. I have 3 main players and 3 secondary players, and I want to put player 4 (secondary player) in place of player 1.

答:
If the order of the collection doesnt matter you should use a set to make sure there is no duplicated players in your collection:

```<code>var mainPlayers: Set = ["player1", "player2", "player3"]
var secondaryPlayers: Set = ["player4", "player5", "player6"]

let oldPlayer = "player1"
let newPlayer = "player4"
if mainPlayers.contains(oldPlayer),
    secondaryPlayers.contains(newPlayer),
    let oldMember = mainPlayers.remove(oldPlayer),
    let newMember = secondaryPlayers.remove(newPlayer),
    mainPlayers.insert(newMember).inserted,
    secondaryPlayers.insert(oldMember).inserted {
    print("oldMember", oldMember)   // player1
    print("newMember", newMember)   // player4
    print(mainPlayers)       // ["player3", "player4", "player2"]
    print(secondaryPlayers)  // ["player1", "player5", "player6"]
}
</code>```

If the order of the collection matters the array approach should look like this:

```<code>var mainPlayers = ["player1", "player2", "player3"]
var secondaryPlayers = ["player4", "player5", "player6"]

if let oldMemberIndex = mainPlayers.firstIndex(of: "player1"),
    let newMemberIndex = secondaryPlayers.firstIndex(of: "player4"),
    case let oldMember = mainPlayers.remove(at: oldMemberIndex),
    case let newMember = secondaryPlayers.remove(at: newMemberIndex) {
    mainPlayers.insert(newMember, at: oldMemberIndex)
    secondaryPlayers.insert(oldMember, at: newMemberIndex)
    print("oldMember", oldMember)   // player1
    print("newMember", newMember)   // player4
    print(mainPlayers)       // ["player4", "player2", "player3"]
    print(secondaryPlayers)  // ["player1", "player5", "player6"]
}
</code>```

Body:
I have a class "Players", and a class "Team". I created two array of Strings calling player1.name, player2.name, etc.
one array with main players and the other array with secondary players

Class:

class Players {
    let name: String
    let number: int
    var position:PositionPlayer
    var birth: Date
    let nationality: String
    var height: Double
    var weight: int
    init(name: String, number: Int, position: PositionPlayer, birth: Date, height: Double, weight: Int) {
        self.name = name
        self.number = number
        self.position = position
        self.birth = birth
        self.nationality = nationality
        self.height = height
        self.weight = weight
    }

Class Team is empty (just doing the function on it)

Arrays:

var mainPlayers: [String] = []
var secondaryPlayers: [String] = []

add elements in arrays:

mainPlayers.append("\(player1.name)")

How do I make a function in class "Team" that checks the elements of the arrays and does the substitution between the 2 arrays?

e.g. I have 3 main players and 3 secondary players, and I want to put player 4 (secondary player) in place of player 1.

Body:
If the order of the collection doesnt matter you should use a set to make sure there is no duplicated players in your collection:

var mainPlayers: Set = ["player1", "player2", "player3"]
var secondaryPlayers: Set = ["player4", "player5", "player6"]

let oldPlayer = "player1"
let newPlayer = "player4"
if mainPlayers.contains(oldPlayer),
    secondaryPlayers.contains(newPlayer),
    let oldMember = mainPlayers.remove(oldPlayer),
    let newMember = secondaryPlayers.remove(newPlayer),
    mainPlayers.insert(newMember).inserted,
    secondaryPlayers.insert(oldMember).inserted {
    print("oldMember", oldMember)   // player1
    print("newMember", newMember)   // player4
    print(mainPlayers)       // ["player3", "player4", "player2"]
    print(secondaryPlayers)  // ["player1", "player5", "player6"]
}

If the order of the collection matters the array approach should look like this:

var mainPlayers = ["player1", "player2", "player3"]
var secondaryPlayers = ["player4", "player5", "player6"]

if let oldMemberIndex = mainPlayers.firstIndex(of: "player1"),
    let newMemberIndex = secondaryPlayers.firstIndex(of: "player4"),
    case let oldMember = mainPlayers.remove(at: oldMemberIndex),
    case let newMember = secondaryPlayers.remove(at: newMemberIndex) {
    mainPlayers.insert(newMember, at: oldMemberIndex)
    secondaryPlayers.insert(oldMember, at: newMemberIndex)
    print("oldMember", oldMember)   // player1
    print("newMember", newMember)   // player4
    print(mainPlayers)       // ["player4", "player2", "player3"]
    print(secondaryPlayers)  // ["player1", "player5", "player6"]
}


问:
Oracle SQL case condition involving one column but changing another
I'm trying to change the sortest_tesc_code of any tuple whose sortest_test_date is greater than 5 years to ZZZ

```<code>select sortest_pidm, sortest_tesc_code
     case sortest_tesc_code
     when extract(year from sysdate)-extract(year from sortest_test_date)>=5 then 'ZZZ'
          else sortest_tesc_code end as sortest_tesc_code
from tempTbl2
</code>```

assuming tempTbl2 (derived) is this:

Sample data:

```<code>MOD7    1   10-JAN-11
MOD9    1   10-JAN-11
MPA3    1   19-JUL-11
C012    3   01-JUL-18
C030    3   01-JUL-17
MPA2    1   12-JUL-18
</code>```

Change to:

```<code>ZZZ     1   10-JAN-11
ZZZ     1   10-JAN-11
ZZZ     1   19-JUL-11
C012    3   01-JUL-18
C030    3   01-JUL-17
MPA2    1   12-JUL-18
</code>```

答:
You merely got a little confused with the CASE syntax.

```<code>select
   case when extract(year from sysdate) - extract(year from sortest_test_date) >= 5
     then 'ZZZ'
     else sortest_tesc_code
  end as new_sortest_tesc_code,
  testscore,
  sortest_test_date
from tempTbl2
order by sortest_test_date, sortest_tesc_code;
</code>```

Body:
I'm trying to change the sortest_tesc_code of any tuple whose sortest_test_date is greater than 5 years to ZZZ

select sortest_pidm, sortest_tesc_code
     case sortest_tesc_code
     when extract(year from sysdate)-extract(year from sortest_test_date)>=5 then 'ZZZ'
          else sortest_tesc_code end as sortest_tesc_code
from tempTbl2

assuming tempTbl2 (derived) is this:

Sample data:

MOD7    1   10-JAN-11
MOD9    1   10-JAN-11
MPA3    1   19-JUL-11
C012    3   01-JUL-18
C030    3   01-JUL-17
MPA2    1   12-JUL-18

Change to:

ZZZ     1   10-JAN-11
ZZZ     1   10-JAN-11
ZZZ     1   19-JUL-11
C012    3   01-JUL-18
C030    3   01-JUL-17
MPA2    1   12-JUL-18

Body:
You merely got a little confused with the CASE syntax.

select
   case when extract(year from sysdate) - extract(year from sortest_test_date) >= 5
     then 'ZZZ'
     else sortest_tesc_code
  end as new_sortest_tesc_code,
  testscore,
  sortest_test_date
from tempTbl2
order by sortest_test_date, sortest_tesc_code;


问:
Time formatting issues with Moment.JS
I have some DB objects coming back from my server as so:

```<code>client_id: 24
created_at: "2022-02-11 17:41:39.330443"
id: 22
report: "sfsf"
report_category: "Client Assigned"
volunteer_id: 23

client_id: 24
created_at: "2022-02-11 17:43:04.837869"
id: 23
report: "one more"
report_category: "Client Assigned"
volunteer_id: 23
</code>```

In my React code I am trying to apply formatting with moment to the created_at field:

```<code>{moment(comment.createdAt).format('DD/MM/YY, h:mm a')}
</code>```

which returns something like:

```<code>11/02/22, 12:46 pm
</code>```

For all the objects the time just seems to default to the current time it is right now and not the time in the created_at field. All the entries show 12:46 pm. Any advice on this issue?

答:
I was thinking maybe the formatting is errored and it just defaults to current time if so.
What does the 'a' do at the end for the format. Maybe try something like this "HH:mm:ss"</p>

Title: Time formatting issues with Moment.JS

Body:
I have some DB objects coming back from my server as so:

client_id: 24
created_at: "2022-02-11 17:41:39.330443"
id: 22
report: "sfsf"
report_category: "Client Assigned"
volunteer_id: 23

client_id: 24
created_at: "2022-02-11 17:43:04.837869"
id: 23
report: "one more"
report_category: "Client Assigned"
volunteer_id: 23

In my React code I am trying to apply formatting with moment to the created_at field:

{moment(comment.createdAt).format('DD/MM/YY, h:mm a')}

which returns something like:

11/02/22, 12:46 pm

For all the objects the time just seems to default to the current time it is right now and not the time in the created_at field. All the entries show 12:46 pm. Any advice on this issue?


问:
Render objects based on zoom level in Azure maps
I want to show a pop up on marker after a certain zoom level is it possible?</p>

答:
Data layers have a min/max zoom option that can be used to specify the zoom level range that layer should appear. Popups however don't have such an option, but such logic can be added by making use of the zoomend event. Here is a code sample.</p>
```<code>var map;

function GetMap() {
    //Initialize a map instance.
    map = new atlas.Map('myMap', {
        view: 'Auto',

        //Add authentication details for connecting to Azure Maps.
        authOptions: {
            authType: 'subscriptionKey',
            subscriptionKey: '<Your Azure Maps Key>'
        }
    });

    //Wait until the map resources are ready.
    map.events.add('ready', function () {

        //Create one or more popups.
        var popup = new atlas.Popup({
            //Set the position.
            position: [-99.213191, 39.507909], //Middle of the USA

            //Add the content.
            content: '<div style="padding:10px;">Hello World</div>',

             //Likely don't want the user closing the popup if the map zoom level is managing this.
             closeButton: false
        });

        //Link some information to the popup that tells us the zoom level range.
        popup.metadata = {
            //In this case the popup will appear when the map is between zoom levels 3 and 8.
            minzoom: 3,
            maxzoom: 8
        };

        //Add the popup to the map.
        map.popups.add(popup);

        //Add an event to monitor the zoomend event.
        //If you are only using a small number of popups in your app you could use the "zoom" event which will fire as the map moves, but can quickly cause performance issues if there is a a couple dozen or more popups.
        map.events.add('zoomend', mapZoomed);
    });
}

function mapZoomed(e){
    //Get the zoom level.
    var zoom = map.getCamera().zoom;

    var popups = map.popups.getPopups();

    for(var i=0, len = popups.length; i < len; i++){
        var popup = popups[i];

        if(popup.metadata) {
            //Open/close the popup based on the zoom level range information.
            if(zoom >= popup.metadata.minzoom && zoom <= popup.metadata.maxzoom) {
                popup.open();
            } else {
                popup.close();
            }
        }
    }
}

</code>```

Body:
Data layers have a min/max zoom option that can be used to specify the zoom level range that layer should appear. Popups however don't have such an option, but such logic can be added by making use of the zoomend event. Here is a code sample.

var map;

function GetMap() {
    //Initialize a map instance.
    map = new atlas.Map('myMap', {
        view: 'Auto',

        //Add authentication details for connecting to Azure Maps.
        authOptions: {
            authType: 'subscriptionKey',
            subscriptionKey: '<Your Azure Maps Key>'
        }
    });

    //Wait until the map resources are ready.
    map.events.add('ready', function () {

        //Create one or more popups.
        var popup = new atlas.Popup({
            //Set the position.
            position: [-99.213191, 39.507909], //Middle of the USA

            //Add the content.
            content: '<div style="padding:10px;">Hello World</div>',

             //Likely don't want the user closing the popup if the map zoom level is managing this.
             closeButton: false
        });

        //Link some information to the popup that tells us the zoom level range.
        popup.metadata = {
            //In this case the popup will appear when the map is between zoom levels 3 and 8.
            minzoom: 3,
            maxzoom: 8
        };

        //Add the popup to the map.
        map.popups.add(popup);

        //Add an event to monitor the zoomend event.
        //If you are only using a small number of popups in your app you could use the "zoom" event which will fire as the map moves, but can quickly cause performance issues if there is a a couple dozen or more popups.
        map.events.add('zoomend', mapZoomed);
    });
}

function mapZoomed(e){
    //Get the zoom level.
    var zoom = map.getCamera().zoom;

    var popups = map.popups.getPopups();

    for(var i=0, len = popups.length; i < len; i++){
        var popup = popups[i];

        if(popup.metadata) {
            //Open/close the popup based on the zoom level range information.
            if(zoom >= popup.metadata.minzoom && zoom <= popup.metadata.maxzoom) {
                popup.open();
            } else {
                popup.close();
            }
        }
    }
}