问:
Count number of unique occurrences of a key value corresponding to each ID column
I have a table in DB2 as below :

```<code>Key     ID  SubID
Abc123  576  10
Abc123  576  12
Abc124  576  13
Abc125  577  14
Abc126  578  15
Abc127  578  16
Abc128  578  17
</code>```

Want to create a additional count column where it counts number of unique occurrences of key value for each ID and the output should be as below

```<code>Key     ID  SubID Count
Abc123  576  10    2
Abc123  576  12    2
Abc124  576  13    2
Abc125  577  14    1
Abc126  578  15    3
Abc127  578  16    3
Abc128  578  17    3
</code>```

I tried below

```<code>select Key, ID, SubId ,
count(Key) over (partition by Key) as count
from table
</code>```

Appreciate any help!

答:
You cannot use a window function with the DISTINCT qualifier. You can use a scalar subquery to count the rows you want.

For example:

```<code>select *,
  (select count(distinct key) from t x where x.id = t.id) as cnt
from t
</code>```

Result:

```<code> KEY     ID   SUBID  CNT
 ------- ---- ------ ---
 Abc123  576  10     2
 Abc123  576  12     2
 Abc124  576  13     2
 Abc125  577  14     1
 Abc126  578  15     3
 Abc127  578  16     3
 Abc128  578  17     3
</code>```

See running example at db<>fiddle.

Body:
I have a table in DB2 as below :

Key     ID  SubID
Abc123  576  10
Abc123  576  12
Abc124  576  13
Abc125  577  14
Abc126  578  15
Abc127  578  16
Abc128  578  17

Want to create a additional count column where it counts number of unique occurrences of key value for each ID and the output should be as below

Key     ID  SubID Count
Abc123  576  10    2
Abc123  576  12    2
Abc124  576  13    2
Abc125  577  14    1
Abc126  578  15    3
Abc127  578  16    3
Abc128  578  17    3

I tried below

select Key, ID, SubId ,
count(Key) over (partition by Key) as count
from table

Appreciate any help!

Body:
You cannot use a window function with the DISTINCT qualifier. You can use a scalar subquery to count the rows you want.

For example:

select *,
  (select count(distinct key) from t x where x.id = t.id) as cnt
from t

Result:

 KEY     ID   SUBID  CNT
 ------- ---- ------ ---
 Abc123  576  10     2
 Abc123  576  12     2
 Abc124  576  13     2
 Abc125  577  14     1
 Abc126  578  15     3
 Abc127  578  16     3
 Abc128  578  17     3

See running example at db<>fiddle.


来源: stackexchange

问:
How to display HTML page using BrightScript
I would like to display a single HTML web page on a Roku channel. I have no need to follow hyperlinks, but the page does have periodic updates.

Is it possible to write a BrightScript application that uses Gecko to render the page, or would I have to draw the page myself?

I see plenty of information as well as examples in the Roku SDK that describe how to provide user navigation and play video on a Roku box using BrightScript, but I can't find any information about displaying a single HTML page on a Roku channel.

答: You could try to use regex to convert html to simple text. This solution worked for our project.</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
JQUERY load an array of elements into a DIV
I have an array of DIV elements in an array called 'noactiveMsg'.
I want to load these DIV elements into a DIV called $('#chatCenterMembers').

I've tried:

```<code>noactiveMsg.appendTo($('#chatCenterMembers'));
</code>```

But this doesn't work.
Can someone advice on the syntax to load an array of elements/objects into a div?

code to made the array:

```<code>var noactiveMsg=[];
 $('div.chatmember').each(function() {
 if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
 alert('offline');
 noactiveMsg.push($(this));
 }
 });
</code>```

答:
I think this is the code you need.
Assuming noactiveMsg is an array containing jQuery objects.

cnt = noactiveMsg.length();

for(i=0; i<cnt; i++) {

```<code>$('#chatCenterMembers').append(noactiveMsg[i].html());
</code>```

}

Body:
I have an array of DIV elements in an array called 'noactiveMsg'.
I want to load these DIV elements into a DIV called $('#chatCenterMembers').

I've tried:

noactiveMsg.appendTo($('#chatCenterMembers'));

But this doesn't work.
Can someone advice on the syntax to load an array of elements/objects into a div?

code to made the array:

var noactiveMsg=[];
 $('div.chatmember').each(function() {
 if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
 alert('offline');
 noactiveMsg.push($(this));
 }
 });

Body:
I think this is the code you need.
Assuming noactiveMsg is an array containing jQuery objects.

cnt = noactiveMsg.length();

for(i=0; i<cnt; i++) {

$('#chatCenterMembers').append(noactiveMsg[i].html());

}


问:
Why is this not outside of the nav Bar
so I am pretty new to development and come across a problem, I think I am missing somthing but I can't tell. So I am building a nav bar and then a drop down menu. I believe that the li is in the ul so that why it is not coming out of it. So how could I fix this. If you know any website that would be good let me know thank you

Code:
https://codepen.io/Giannilmgc/pen/JjrgZdr?editors=1111
Output:
https://codepen.io/Giannilmgc/full/JjrgZdr

To see what wrong keep your cursor over the to do tab and scroll down

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300&display=swap");

/* Here is the body style where we change the background */
body {
  background: linear-gradient(135deg, #36454f 0%, #ffdd3c 100%);
  margin: 5px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: auto;
  background-color: white;
  border-radius: 50px;
}

li {
  float: left;
  width: 16.667%;
  transition-duration: 1s;
}

li a {
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  transition-duration: 1s;
}
li:hover {
  background-color: black;
}

li a:hover {
  background-color: #36454f;
  color: white;
}
#homepageLink {
  background-color: #cccccc;
}

.dropdown {
  position: relative;
  display: inline-block;
}

ul li ul {
  display: none;
  position: absolute;
  background-color: #cccccc;
  width: 20%;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 10;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #36454f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>

  <title> My Site </title>
  <link rel="stylesheet" href="CSS/Homepage-Css.css" />
</head>

<body>

  <body>

    <div>
      <ul>
        <li>HomePage</li>
        <li>Journal</li>
        <li>Calander </li>
        <li class="dropdown">To do
          <ul class="dropdown-content">
            Latin
            Scince
            Ela

          </ul>
        </li>
        <li>Service</li>
        <li>Contact</li>

      </ul>
    </div>

    <div class="time">
      <span id="display_ct"></span>
  </body>
  <!-- Adding Script to the bottom ... Very Imporantent  -->
  <script src="Javascript/Homepage-Java.js"></script></code>```

Thank you

答:
If you want to create a dropdown menu with pure CSS there is this example from w3schools

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a, .dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1;}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>

<ul>
  <li>Home</li>
  <li>News</li>
  <li class="dropdown">
    Dropdown
    <div class="dropdown-content">
      Link 1
      Link 2
      Link 3
    </div>
  </li>
</ul>

<h3>Dropdown Menu inside a Navigation Bar</h3>
<p>Hover over the "Dropdown" link to see the dropdown menu.</p>

</body>
</html></code>```

Title: Why is this not outside of the nav Bar

Body:
so I am pretty new to development and come across a problem, I think I am missing somthing but I can't tell. So I am building a nav bar and then a drop down menu. I believe that the li is in the ul so that why it is not coming out of it. So how could I fix this. If you know any website that would be good let me know thank you

Code:
https://codepen.io/Giannilmgc/pen/JjrgZdr?editors=1111
Output:
https://codepen.io/Giannilmgc/full/JjrgZdr

To see what wrong keep your cursor over the to do tab and scroll down

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300&display=swap");

/* Here is the body style where we change the background */
body {
  background: linear-gradient(135deg, #36454f 0%, #ffdd3c 100%);
  margin: 5px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: auto;
  background-color: white;
  border-radius: 50px;
}

li {
  float: left;
  width: 16.667%;
  transition-duration: 1s;
}

li a {
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  transition-duration: 1s;
}
li:hover {
  background-color: black;
}

li a:hover {
  background-color: #36454f;
  color: white;
}
#homepageLink {
  background-color: #cccccc;
}

.dropdown {
  position: relative;
  display: inline-block;
}

ul li ul {
  display: none;
  position: absolute;
  background-color: #cccccc;
  width: 20%;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 10;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #36454f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}

  <title> My Site </title>
  <link rel="stylesheet" href="CSS/Homepage-Css.css" />

HomePage

Journal

Calander

To do

            Latin
            Scince
            Ela

Service

Contact

Thank you

Body:
If you want to create a dropdown menu with pure CSS there is this example from w3schools

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a, .dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1;}

.dropdown:hover .dropdown-content {
  display: block;
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Dropdown</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
</ul>

<h3>Dropdown Menu inside a Navigation Bar</h3>
<p>Hover over the "Dropdown" link to see the dropdown menu.</p>

</body>
</html>


问:
How to use func assign(_ object: Any, to store: NSPersistentStore) of a NSManagedObjectContext?
Setup:

My app uses 2 persistent stores managed by a single persistent store coordinator that is used by several managed object contexts. Both persistent stores store the same entities.

It is required that any inserts, updates and deletes of managed objects are only done in one of both persistent stores, and the app can select the persistent store.

Problem:

In order to store a managed object only in one persistent store, I want to use func assign(_ object: Any, to store: NSPersistentStore) of a NSManagedObjectContext. The docs say

Specifies the store in which a newly inserted object will be saved.

Question:

What means „newly inserted“?

Can I assign a persistent store as long as the object has never been saved by its context?

Could I use, e.g., a willSaveObjectsNotification to loop though all registeredObjects of the context and assign the required persistent store?

When the app switches the persistent store, I would then reset the contexts so that all managed objects would be fetched newly, and the required persistent store could be set again in the willSaveObjectsNotification notification.

Is this the right way to go?

答:
That function can only be used for a managed object that does not belong to any managed object context yet. It’s possible to create an instance using an entity description, that’s not part of any context. For example you can use init(entity:,insertInto:) with a nil for the second argument. If you do that, you can later use the `assigns function to insert it into a context.

If a managed object is already associated with a context, you can’t use this function to move it to a different one. You would need to create a new instance in the new context and copy all the property values.


问:
C++: Is it a bad idea to use the value of a function returning shared_ptr directly?
For example:

```<code>boost::shared_ptr<int> test() {
    boost::shared_ptr<int> x(new int(3));
    return x;
}

void function() {
    int y = *test();
    ...
}
</code>```

Is it also a bad idea to use shared_ptr to avoid copying the whole object? Like a vector of matrices/images for example.

答:
I would say that yes, it is a bad idea.

If you're using a pointer there are 2 reasons. 1. Your object might be null, or 2. you have a big object that you don't want to copy.

It's rarely a good idea to use the value directly since you don't know if it's null or not.

Body:
For example:

boost::shared_ptr<int> test() {
    boost::shared_ptr<int> x(new int(3));
    return x;
}

void function() {
    int y = *test();
    ...
}

Is it also a bad idea to use shared_ptr to avoid copying the whole object? Like a vector of matrices/images for example.


问:
Matching integers to ranges
I have n integers and m ranges (think [a, b]) of numbers such that n <= m. An integer and a range may be matched if the integer is in the range, i.e., a <= integer <= b. A range may only be matched with one integer and vice versa.

Here is an example:

Ranges: [0, 5], [3, 6], [9, 21]

Integers: 1, 5

The maximum valid matching is to match 1 to the first range and 5 to the second range.

I want to find a greedy algorithm that maximizes the number of integers matched. My initial thought is to greedily choose the shortest range and match the number which is closest to the shortest range's start point (so the a in a range [a, b]). Howveer, I'm not sure this is right.

答:
Here's an idea: When an interval ends, you can't put an integer greater than the end in that interval. This means that you need to satisfy the ranges that end sooner first, if you intend to fill as many as possible. Now, what do you do when two intervals have equal ends? You fill the one that starts sooner. This way you increase your chances of filling the next range/interval with the same ending but a late start.

Now, suppose we sort the integers none-decreasing and the intervals, first by end then start, none-decreasing and start to fill the intervals greedily. What could happen is that an interval lands at the end of the intervals array, since it has a large end, while it has a very small start. When we go over our integers, if we skipped an integer because the first interval's start is greater than that integers, we run the risk to ignore it while we could have fitted the integer in that later coming interval with the large end and very small start.

To mitigate that, we need to check all the remaining intervals for every integer that we consider, and take the first one where we can fit the integer, if any. This deteriorates our run time complexity into an O(n * m), but I don't see how we could overcome that to make it linearithmic.

Here's the above idea converted into an algorithm:

Sort your ranges/intervals by end then start none-decreasing.

Sort your integers none-decreasing.

Have a set where you keep track of the used intervals, used_intervals.

Have an array for the resulting integers, res.

Run the following nested loop:

```<code>for integer in integers:
  for interval in intervals:
    if interval in used_intervals: continue
    if interval.start <= integer <= interval.end:
      res.push(integer)
      used_intervals.add(interval)
</code>```

Time complexity analysis:

Sorting the intervals is O(m * log m) where m is the number of intervals

Sorting the integers is O(n * log n) where n is the number of integers

The nested loop is O(m * n)
Since n <= m, this reduces the time complexity in terms of Big O to O(max(m * n, m * log m)).

Space complexity analysis:
O(m), sorting, the result array, the set

I'm not sure if we can optimize this, not the time complexity but still an optimization. Any feedback is appreciated.

Title: Matching integers to ranges

Body:
Here's an idea: When an interval ends, you can't put an integer greater than the end in that interval. This means that you need to satisfy the ranges that end sooner first, if you intend to fill as many as possible. Now, what do you do when two intervals have equal ends? You fill the one that starts sooner. This way you increase your chances of filling the next range/interval with the same ending but a late start.

Now, suppose we sort the integers none-decreasing and the intervals, first by end then start, none-decreasing and start to fill the intervals greedily. What could happen is that an interval lands at the end of the intervals array, since it has a large end, while it has a very small start. When we go over our integers, if we skipped an integer because the first interval's start is greater than that integers, we run the risk to ignore it while we could have fitted the integer in that later coming interval with the large end and very small start.

To mitigate that, we need to check all the remaining intervals for every integer that we consider, and take the first one where we can fit the integer, if any. This deteriorates our run time complexity into an O(n * m), but I don't see how we could overcome that to make it linearithmic.

Here's the above idea converted into an algorithm:

Sort your ranges/intervals by end then start none-decreasing.

Sort your integers none-decreasing.

Have a set where you keep track of the used intervals, used_intervals.

Have an array for the resulting integers, res.

Run the following nested loop:

for integer in integers:
  for interval in intervals:
    if interval in used_intervals: continue
    if interval.start <= integer <= interval.end:
      res.push(integer)
      used_intervals.add(interval)

Time complexity analysis:

Sorting the intervals is O(m * log m) where m is the number of intervals

Sorting the integers is O(n * log n) where n is the number of integers

The nested loop is O(m * n)
Since n <= m, this reduces the time complexity in terms of Big O to O(max(m * n, m * log m)).

Space complexity analysis:
O(m), sorting, the result array, the set

I'm not sure if we can optimize this, not the time complexity but still an optimization. Any feedback is appreciated.


问:
How can i slow animation speed and shouldn't delete last value in plotly
i am complete beginner in plotly. I want to reduce the animation speed and for example a value is shown and the next value comes without deleting this value. I searched a lot on google but couldn't find it. This is my code</p>
```<code>fig = px.scatter(x=dbdeads, y=dbyear, color=dbdeads,text=dbnamedate,animation_frame=dbyear,
                range_x=[0,200000000], range_y=[-500,2050],size=dbdeads,
)
fig.update_traces(textposition="bottom right")
</code>```

答:
One way to set the animation speed is through:

```<code>fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = 2000
</code>```

where 2000 is milliseconds. Try it out and see how it works for you.

Without a sample of your data and a fully reproducible code snippet, it's hard to know exactly what you mean by:

and for example a value is shown and the next value comes without
deleting this value.

I can't imagine any other use case for this than a line plot. If that's what you're looking for, I'd be happy to write up a suggestion. If it's not, then I would suggest that you edit your question to only handle the animation speed, and then write up a new question with further descriptions of the latter challenge.

Body:
i am complete beginner in plotly. I want to reduce the animation speed and for example a value is shown and the next value comes without deleting this value. I searched a lot on google but couldn't find it. This is my code

fig = px.scatter(x=dbdeads, y=dbyear, color=dbdeads,text=dbnamedate,animation_frame=dbyear,
                range_x=[0,200000000], range_y=[-500,2050],size=dbdeads,
)
fig.update_traces(textposition="bottom right")

Body:
One way to set the animation speed is through:

fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = 2000

where 2000 is milliseconds. Try it out and see how it works for you.

Without a sample of your data and a fully reproducible code snippet, it's hard to know exactly what you mean by:

and for example a value is shown and the next value comes without
deleting this value.

I can't imagine any other use case for this than a line plot. If that's what you're looking for, I'd be happy to write up a suggestion. If it's not, then I would suggest that you edit your question to only handle the animation speed, and then write up a new question with further descriptions of the latter challenge.


问:
error: <identifier> expecte when setting up binding adapters for two way data binding
I am trying to setup two way binding for TextInputEditText with Float variable.

Here is the entire content of my DataBindingAdapters class.

```<code>object DataBindingAdapters  {
    @BindingAdapter("android:text")
    @JvmStatic
    fun setText(view: TextInputEditText, value: Float) {
        if(value != view.text.toString().toFloat()) {
            view.setText(value.toString())
        }
    }

    @InverseBindingAdapter(attribute = "android:text")
    fun getText(view: TextInputEditText): Float  {

        return view.text.toString().toFloat()
    }

}
</code>```

But I am getting:

```<code>error: <identifier> expected
            float callbackArg_0 = mBindingComponent.null.getText(inputFieldSize);
</code>```

What am i missing?

答:
I had the same issue and was able to solve it by making the inverse binding adapter static like in the official documentation:

```<code>    @InverseBindingAdapter(attribute = "android:text")
    @JvmStatic fun getText(view: TextInputEditText): Float  {

        return view.text.toString().toFloat()
    }
</code>```

Note the @JvmStatic right before fun getText(.... This is the only change from the code in your question.

BTW: Mohru's answer also mentions this in the edit-section, but at least for me it was not obvious enough to be found in the first place ;)

Body:
I am trying to setup two way binding for TextInputEditText with Float variable.

Here is the entire content of my DataBindingAdapters class.

object DataBindingAdapters  {
    @BindingAdapter("android:text")
    @JvmStatic
    fun setText(view: TextInputEditText, value: Float) {
        if(value != view.text.toString().toFloat()) {
            view.setText(value.toString())
        }
    }

    @InverseBindingAdapter(attribute = "android:text")
    fun getText(view: TextInputEditText): Float  {

        return view.text.toString().toFloat()
    }

}

But I am getting:

error: <identifier> expected
            float callbackArg_0 = mBindingComponent.null.getText(inputFieldSize);

What am i missing?

Body:
I had the same issue and was able to solve it by making the inverse binding adapter static like in the official documentation:

    @InverseBindingAdapter(attribute = "android:text")
    @JvmStatic fun getText(view: TextInputEditText): Float  {

        return view.text.toString().toFloat()
    }

Note the @JvmStatic right before fun getText(.... This is the only change from the code in your question.

BTW: Mohru's answer also mentions this in the edit-section, but at least for me it was not obvious enough to be found in the first place ;)


问:
How can I intercept a mouse-click-event in JavaScript
I created a base line navigation with buttons but I dont't have any idea how from Javascript intercept a mouse-click event. How to get the click position I know, but this procedure needs to be activated by the here asked mouse-event.</p>

答:
You can try this code in your browser:</p>
```<code><!DOCTYPE html>
<html>
<body>

<h2 onclick="showCoords(event)">Click this heading to get the x (horizontal) and y (vertical) coordinates of the mouse pointer when it was clicked.</h2>

<p><strong>Tip:</strong> Try to click different places in the heading.</p>

<p id="demo"></p>

<script>
function showCoords(event) {
  var x = event.clientX;
  var y = event.clientY;
  var coords = "X coords: " + x + ", Y coords: " + y;
  document.getElementById("demo").innerHTML = coords;
}
</script>

</body>
</html>
</code>```

Body:
You can try this code in your browser:

<!DOCTYPE html>
<html>
<body>

<h2 onclick="showCoords(event)">Click this heading to get the x (horizontal) and y (vertical) coordinates of the mouse pointer when it was clicked.</h2>

<p><strong>Tip:</strong> Try to click different places in the heading.</p>

<p id="demo"></p>

<script>
function showCoords(event) {
  var x = event.clientX;
  var y = event.clientY;
  var coords = "X coords: " + x + ", Y coords: " + y;
  document.getElementById("demo").innerHTML = coords;
}
</script>

</body>
</html>


问:
Get return on investment (ROI) from two numbers in Javascript?
I'm building an app that tracks stock predictions.

I would like to have a function that takes in two numbers, and calculate the return on investment between the two numbers.

For example with a start price of $50, and a current price of $100, the function should return "100", since the price has increased 100% since the first purchase. With a start price of $100, and a current price of $10, the function should return "-90", since that investment would have lost 90% of its value

答:
function getROI(cost, profit) {
  return (profit - cost) / cost;
}
```


问:
How to convert HTTP Response to JSON in Blazor
I am trying to convert an HTTP response with the following format:

```<code>[
  {
    ID: 1
    ...
  },
  {
    ID: 2
    ...
  }
]
</code>```

Into JSON so it looks like this:

```<code>{
  "data": [
    {
      ID: 1
      ...
    },
    {
      ID: 2
      ...
    }
  ]
}
</code>```

Anyone know how I can do this in C# (so that it can be deserialized by a Blazor application)?

There isn't any way to add an argument to the HTTP request to coerce the response into JSON format, is there?

答:
try this

```<code>var json = await response.Content.ReadAsStringAsync();
json="{\n data:"+json+"\n}";
</code>```

output

```<code>{
 data:[
  {
    "ID": 1
  },
  {
    "ID": 2
  }
]
}
</code>```

Body:
I am trying to convert an HTTP response with the following format:

[
  {
    ID: 1
    ...
  },
  {
    ID: 2
    ...
  }
]

Into JSON so it looks like this:

{
  "data": [
    {
      ID: 1
      ...
    },
    {
      ID: 2
      ...
    }
  ]
}

Anyone know how I can do this in C# (so that it can be deserialized by a Blazor application)?

There isn't any way to add an argument to the HTTP request to coerce the response into JSON format, is there?

Body:
try this

var json = await response.Content.ReadAsStringAsync();
json="{\n data:"+json+"\n}";

output

{
 data:[
  {
    "ID": 1
  },
  {
    "ID": 2
  }
]
}


问:
Extract ggplot from a nested dataframe
I have created a set of ggplots using a grouped dataframe and the map function and I would like to extract the plots to be able to manipulate them individually.

```<code>library(tidyverse)

plot <- function(df, title){
  df %>% ggplot(aes(class)) +
    geom_bar() +
    labs(title = title)
}

plots <- mpg %>% group_by(manufacturer) %>%  nest() %>%
  mutate(plots= map(.x=data, ~plot(.x, manufacturer)))

nissan <- plots %>% filter(manufacturer == "nissan") %>% pull(plots)
nissan

nissan + labs(title = "Nissan")

</code>```

In this case, "nissan" is a list object and I am not able to manipulate it. How do I extract the ggplot?

答:
In terms of data structures, I think retaining a tibble (or data.frame) is suboptimal with respect to the illustrated usage. If you have one plot per manufacturer, and you plan to access them by manufacturer, then I would recommend to transmute and then deframe out to a list object.

That is, I would find it more conceptually clear here to do something like:

```<code>library(tidyverse)

plot <- function(df, title){
  df %>% ggplot(aes(class)) +
    geom_bar() +
    labs(title = title)
}

plots <- mpg %>%
  group_by(manufacturer) %>% nest() %>%
  transmute(plot=map(.x=data, ~plot(.x, manufacturer))) %>%
  deframe()

plots[['nissan']]

plots[['nissan']] + labs(title = "Nissan")
</code>```

Otherwise, if you want to keep the tibble, another option similar to what has been suggested in the comments is to use a first() after the pull.

Title: Extract ggplot from a nested dataframe

Body:
I have created a set of ggplots using a grouped dataframe and the map function and I would like to extract the plots to be able to manipulate them individually.

library(tidyverse)

plot <- function(df, title){
  df %>% ggplot(aes(class)) +
    geom_bar() +
    labs(title = title)
}

plots <- mpg %>% group_by(manufacturer) %>%  nest() %>%
  mutate(plots= map(.x=data, ~plot(.x, manufacturer)))

nissan <- plots %>% filter(manufacturer == "nissan") %>% pull(plots)
nissan

nissan + labs(title = "Nissan")

In this case, "nissan" is a list object and I am not able to manipulate it. How do I extract the ggplot?

Body:
In terms of data structures, I think retaining a tibble (or data.frame) is suboptimal with respect to the illustrated usage. If you have one plot per manufacturer, and you plan to access them by manufacturer, then I would recommend to transmute and then deframe out to a list object.

That is, I would find it more conceptually clear here to do something like:

library(tidyverse)

plot <- function(df, title){
  df %>% ggplot(aes(class)) +
    geom_bar() +
    labs(title = title)
}

plots <- mpg %>%
  group_by(manufacturer) %>% nest() %>%
  transmute(plot=map(.x=data, ~plot(.x, manufacturer))) %>%
  deframe()

plots[['nissan']]

plots[['nissan']] + labs(title = "Nissan")

Otherwise, if you want to keep the tibble, another option similar to what has been suggested in the comments is to use a first() after the pull.


问:
Converting Nested Subqueries into Mini Queries
I have a lot of trouble reading nested subqueries - I personally prefer to write several mini queries and work from there. I understand that more advanced SQL users find it more efficient to write nested subqueries.

For instance, in the following query:

```<code>select distinct b.table_b, a.*
from table_a a
inner join table_c b
on a.id_1 = b.id_1
inner join ( select a.id_1, max(a.var_1) as max_var_1 from table_a a
group by a.id_1) c
on a.id_1 = b.id_1 and a.var_1 = c.max_var_1
</code>```

Problem: I am trying to turn this into several different queries:

#PART 1 :

```<code>create table_1 as select distinct b.table_b, a.*
from table_a a
inner join table_c b
on a.id_1 = b.id_1
</code>```

#PART 2:

```<code> create table_2 as select a.id_1, max(a.var_1) as max_var_1 from table_a a
group by a.id_1
</code>```

#PART 3 (final result: final_table)

```<code>create final_table as select a.*, b.*
from table_1 a
inner join table_2 b
on a.id_1 = b.id_1 and a.var_1 = b.max_var_1
</code>```

My Question: Can someone please tell me if this is correct? Is this how the above nested subquery can be converted into 3 mini queries?

答:
For the performance of your query, you can use only #PART2, and others should not be used. They are unnecessary. But for better performance, I recommended you write your query without inserting, using CTE. For example:</p>
```<code>with sub_query as (
    select
        id_1,
        max(var_1) as max_var_1
    from
        table_a
    group by id_1
)
select distinct b.table_b, a.*
from table_a a
inner join table_c b
on a.id_1 = b.id_1
inner join sub_query c
on a.id_1 = b.id_1 and a.var_1 = c.max_var_1;
</code>```

Body:
I have a lot of trouble reading nested subqueries - I personally prefer to write several mini queries and work from there. I understand that more advanced SQL users find it more efficient to write nested subqueries.

For instance, in the following query:

select distinct b.table_b, a.*
from table_a a
inner join table_c b
on a.id_1 = b.id_1
inner join ( select a.id_1, max(a.var_1) as max_var_1 from table_a a
group by a.id_1) c
on a.id_1 = b.id_1 and a.var_1 = c.max_var_1

Problem: I am trying to turn this into several different queries:

#PART 1 :

create table_1 as select distinct b.table_b, a.*
from table_a a
inner join table_c b
on a.id_1 = b.id_1

#PART 2:

 create table_2 as select a.id_1, max(a.var_1) as max_var_1 from table_a a
group by a.id_1

#PART 3 (final result: final_table)

create final_table as select a.*, b.*
from table_1 a
inner join table_2 b
on a.id_1 = b.id_1 and a.var_1 = b.max_var_1

My Question: Can someone please tell me if this is correct? Is this how the above nested subquery can be converted into 3 mini queries?

Body:
For the performance of your query, you can use only #PART2, and others should not be used. They are unnecessary. But for better performance, I recommended you write your query without inserting, using CTE. For example:

with sub_query as (
    select
        id_1,
        max(var_1) as max_var_1
    from
        table_a
    group by id_1
)
select distinct b.table_b, a.*
from table_a a
inner join table_c b
on a.id_1 = b.id_1
inner join sub_query c
on a.id_1 = b.id_1 and a.var_1 = c.max_var_1;


问:
Sort instead of descending order
I'm having a problem:

I mention:

I want to present the count number of each word in the following input that contains the following text:

"This is one number and is a good number"

The output that I would like to have, with the word count found inside the file.txt should be the following:

{'This': 1, 'is': 2, one': 1, 'number': 2, 'and': 1, 'a': 1, 'good': 1}

How can I put a "sorted" to sort the situation, instead of staying in descending order?

Someone can help me?

Thanks for listening!

答:
In newer Python versions (>=3.6) dicts actually keep their insertion order! So you could either use a normal dict or a collections.defaultdict (subclass of dict just like collections.Counter) to do this for you:

from collections import defaultdict

d = defaultdict(int)
for word in "This is one number and is a good number".split():
    d[word] += 1
```
<pre class="lang-none prettyprint-override"><code>defaultdict(<class 'int'>, {'This': 1, 'is': 2, 'one': 1, 'number': 2, 'and': 1, 'a': 1, 'good': 1})
</code>```

Pure dict method:

d = {}

for word in "This is one number and is a good number".split():
    if word not in d:
        d[word] = 0
    d[word] += 1
```
<pre class="lang-none prettyprint-override"><code>{'This': 1, 'is': 2, 'one': 1, 'number': 2, 'and': 1, 'a': 1, 'good': 1}
</code>```

Title: Sort instead of descending order

Body:
In newer Python versions (>=3.6) dicts actually keep their insertion order! So you could either use a normal dict or a collections.defaultdict (subclass of dict just like collections.Counter) to do this for you:

from collections import defaultdict

d = defaultdict(int)
for word in "This is one number and is a good number".split():
    d[word] += 1

defaultdict(<class 'int'>, {'This': 1, 'is': 2, 'one': 1, 'number': 2, 'and': 1, 'a': 1, 'good': 1})

Pure dict method:

d = {}

for word in "This is one number and is a good number".split():
    if word not in d:
        d[word] = 0
    d[word] += 1

{'This': 1, 'is': 2, 'one': 1, 'number': 2, 'and': 1, 'a': 1, 'good': 1}


问:
Ternary operator python not working on dict assignment
I'm new to python.

Today i'm trying to simplify this:

```<code>        for x in t:
            if x in hash:
                hash[x] += 1
            else:
                hash[x] = 1
</code>```

To this:

```<code>        for x in t:
            hash[x] += 1 if x in hash else hash[x] = 1
</code>```

Then i got an error:

```<code>SyntaxError: invalid syntax
                                           ^
    hash[x] += 1 if x in hash else hash[x] = 1
Line 8  (Solution.py)
</code>```

I thought i'm doing an expression here? as shown in this question

What am i doing wrong?

答:
Try this:

for x in t:
    hash[x] = hash.get(x, 0) + 1

```

Body:
I'm new to python.

Today i'm trying to simplify this:

        for x in t:
            if x in hash:
                hash[x] += 1
            else:
                hash[x] = 1

To this:

        for x in t:
            hash[x] += 1 if x in hash else hash[x] = 1

Then i got an error:

SyntaxError: invalid syntax
                                           ^
    hash[x] += 1 if x in hash else hash[x] = 1
Line 8  (Solution.py)

I thought i'm doing an expression here? as shown in this question

What am i doing wrong?


问:
How to make absolute element in relative element responsive?
I have problem with change size while manipulating browser size. I need to keep one column on another so I use relative + absolute combination.

I'm wondering if there is an option with only CSS to make such element responsive.

```<code><div class="clock">
 <div id="apDiv3" class="opening">

   <div class="clock">

    <img id="apDiv2" class="clock" src="./assets/stoper-01.png" usemap="#image-map">
    <img id="apDiv1" class="clockArrow" src="./assets/stoper-01-arrow.png">

   <map name="image-map">
    <area area settings>
    ...
   </map>

  </div>
 </div>
</div>
</code>```
```<code>div.clock {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
img.clock {
  position: relative;
}
.clockArrow {
  position: absolute;
}

</code>```

答:
I'm wondering if there is an option with only CSS to make such element responsive.

Here's a sample:

.wrapper{
  height: 100vh;
  margin: 0 30%;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: max-content;
}

.circle{
  background-image: url(https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fc1.staticflickr.com%2F1%2F694%2F23104548209_fed5c6d1cd_b.jpg&f=1&nofb=1);
  height: 50vh;
  width: 50vh;
  border-radius: 50%;
  background-size: 100% 100%;
  display: flex;
  align-items: center;
  padding: 1.3vh;
}

.rec{
  flex: 1;
  height: 15vh;
  background-image: url(https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.cameraegg.org%2Fwp-content%2Fuploads%2F2012%2F09%2FSony-DSC-RX1-Sample-Image.jpg&f=1&nofb=1);
  background-size: 100% 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="circle">
    <div class="rec"></div>
  </div>
</div></code>```

You can make use of viewport height and width to make the elements responsive. More on units here.

Body:
I have problem with change size while manipulating browser size. I need to keep one column on another so I use relative + absolute combination.

I'm wondering if there is an option with only CSS to make such element responsive.

   <map name="image-map">
    <area area settings>
    ...
   </map>

div.clock {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
img.clock {
  position: relative;
}
.clockArrow {
  position: absolute;
}

Body:
I'm wondering if there is an option with only CSS to make such element responsive.

Here's a sample:

.wrapper{
  height: 100vh;
  margin: 0 30%;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: max-content;
}

.circle{
  background-image: url(https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fc1.staticflickr.com%2F1%2F694%2F23104548209_fed5c6d1cd_b.jpg&f=1&nofb=1);
  height: 50vh;
  width: 50vh;
  border-radius: 50%;
  background-size: 100% 100%;
  display: flex;
  align-items: center;
  padding: 1.3vh;
}

.rec{
  flex: 1;
  height: 15vh;
  background-image: url(https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.cameraegg.org%2Fwp-content%2Fuploads%2F2012%2F09%2FSony-DSC-RX1-Sample-Image.jpg&f=1&nofb=1);
  background-size: 100% 100%;
}

<div class="wrapper">
  <div class="circle">
    <div class="rec"></div>
  </div>
</div>

You can make use of viewport height and width to make the elements responsive. More on units here.


问:
Is there a way to prioritize MSAccess form validation rules rather than SQL's in a linked table?
I'm creating a program in which I want to catch errors in data formatting on the front end within MS Access however, when I try to create rules within MS Access I get the error Table ' ' is a linked table whose design can't be modified. If you want to add or remove fields or change their properties or data types, you must do so in the source database. This is a problem because I think that MS Access' rules are generally better and catch errors on the front end. Is there a way I can use the MS Access rules but still have it be a linked table to the SQL server and flow data that way?</p>

答:
If you check validation rule properties of the control, then go to expression builder, functions, built in functions, you will see inspection(this is category of functions)

e.g =IsNumeric([searchtext]) ensures only numbers can be entered in the searchtext control.

Look at the image i attached for other inspection functions.


问:
Filtering an array of JSON objects with strange characters
I have an array of objects given in the format below as an input, with odd double backslashes that stop me from parsing each input into JSON. I only want to save some document types, so I'm filtering out these records using Array.prototype.filter().  The problem I'm facing is parsing each record with those backslashes.  One is escaping the other and it's keeping one backslash. Any help would be appreciated.

```<code>const records = [
  {
    messageId: '1',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm1"\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '2',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm3\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '3',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm8\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
];

let output = [];
let message = [];
try {
    output = event.Records.filter((resource) => {
    console.log('resource:', resource);
    const body = resource.body ? JSON.stringify(resource.body) : '';
    message = body.Message ? JSON.stringify(resource.body.Message) : '';
    console.log('message:', message);
    const documentType = message.detail?.documentType?.toLowerCase() || '';
    console.log('decoumentType:', documentType);
    const acceptedDocTypes = ['pm1', 'pm2', 'pm3', 'pm4', 'pm5'];
    return acceptedDocTypes.includes(documentType);
});
</code>```

UPDATED SNIPPET:

```<code>  try {
output = event.Records.filter((resource) => {
  let body = '';
  if (resource.body) {
    resource.body.replace(/(\\+")/gmi, '"');
    resource.body.replace(/\s*"\s*\{/gmi, '{').replace(/\s*\}\s*"/gmi, '}');
    body = JSON.parse(resource.body);
  }
  message = body.Message ? JSON.parse(JSON.stringify(body.Message)) : '';
  console.log(message);
  const { documentType } = body.message.detail;
  console.log('decoumentType:', documentType);
  const acceptedDocTypes = ['pm1', 'pm2', 'pm3', 'pm4', 'pm5'];
  return acceptedDocTypes.includes(documentType);
});
</code>```

答:
You should be using JSON.parse() to parse JSON, since body and Message are JSON strings.

const records = [{
    messageId: '1',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm1"\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '2',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm3\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '3',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm8\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
];

let output = [];
let message = [];
output = records.filter((resource) => {
  console.log('resource:', resource);
  const body = resource.body ? JSON.parse(resource.body) : {};
  message = body.message ? JSON.parse(body.Message) : {};
  console.log('message:', message);
  const documentType = message?.detail?.documentType?.toLowerCase() || '';
  console.log('decoumentType:', documentType);
  const acceptedDocTypes = ['pm1', 'pm2', 'pm3', 'pm4', 'pm5'];
  return acceptedDocTypes.includes(documentType);
});```

Body:
I have an array of objects given in the format below as an input, with odd double backslashes that stop me from parsing each input into JSON. I only want to save some document types, so I'm filtering out these records using Array.prototype.filter().  The problem I'm facing is parsing each record with those backslashes.  One is escaping the other and it's keeping one backslash. Any help would be appreciated.

const records = [
  {
    messageId: '1',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm1"\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '2',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm3\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
  {
    messageId: '3',
    body: '{"Message" : "{\\"detail\\": {\\"documentType\\": \\"pm8\\", \\"documentDate\\": \\"2018-08-27 04:00:00\\"}}"}',
  },
];

let output = [];
let message = [];
try {
    output = event.Records.filter((resource) => {
    console.log('resource:', resource);
    const body = resource.body ? JSON.stringify(resource.body) : '';
    message = body.Message ? JSON.stringify(resource.body.Message) : '';
    console.log('message:', message);
    const documentType = message.detail?.documentType?.toLowerCase() || '';
    console.log('decoumentType:', documentType);
    const acceptedDocTypes = ['pm1', 'pm2', 'pm3', 'pm4', 'pm5'];
    return acceptedDocTypes.includes(documentType);
});

UPDATED SNIPPET:

  try {
output = event.Records.filter((resource) => {
  let body = '';
  if (resource.body) {
    resource.body.replace(/(\\+")/gmi, '"');
    resource.body.replace(/\s*"\s*\{/gmi, '{').replace(/\s*\}\s*"/gmi, '}');
    body = JSON.parse(resource.body);
  }
  message = body.Message ? JSON.parse(JSON.stringify(body.Message)) : '';
  console.log(message);
  const { documentType } = body.message.detail;
  console.log('decoumentType:', documentType);
  const acceptedDocTypes = ['pm1', 'pm2', 'pm3', 'pm4', 'pm5'];
  return acceptedDocTypes.includes(documentType);
});


问:
flutter: type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>'
I get this error while serializing my json.
I am not sure I understand the error, but I have figured out that the code never reaches Prices.fromJson if I try to print something there. As you can see I am using Firebase Cloud Functions to return a data with nested data objects, and I struggle to get them serialized.

Code:

```<code>class Price {
  final DateTime validFrom;
  final DateTime validTo;
  final double nokPerKwh;

  const Price({
    required this.validFrom,
    required this.validTo,
    required this.nokPerKwh,
  });

  factory Price.fromJson(Map<String, dynamic> json) {
    return Price(
      validFrom: DateTime.parse(json['validFrom']),
      validTo: DateTime.parse(json['validTo']),
      nokPerKwh: json['nokPerKwh'],
    );
  }
}

class Prices {
  final double now;
  final Price lowest;
  final Price highest;

  const Prices({
    required this.now,
    required this.lowest,
    required this.highest,
  });

  factory Prices.fromJson(Map<String, dynamic> json) {
    return Prices(
      now: json['now'],
      lowest: Price.fromJson(json['lowest']),
      highest: Price.fromJson(json['highest']),
    );
  }
}

class ShowerCost {
  final DateTime time;
  final int minutes;
  final Prices prices;

  const ShowerCost({
    required this.time,
    required this.minutes,
    required this.prices,
  });

  factory ShowerCost.fromJson(Map<String, dynamic> json) {
    print(json); <--- {minutes: 20, time: 2022-02-07T23:46:41.625Z, prices: {now: 11.848, highest: null, lowest: {nokPerKwh: 1.1848, validFrom: 2022-02-08T00:00:00+01:00, validTo: 2022-02-08T01:00:00+01:00}}}
    return ShowerCost(
      time: DateTime.parse(json['time']),
      minutes: json['minutes'],
      prices: Prices.fromJson(json['prices']),
    );
  }
}

Future<ShowerCost> getShowerCost() async {
  try {
    HttpsCallable callable =
        FirebaseFunctions.instance.httpsCallable('getShowerCost');
    final results = await callable.call(<String, dynamic>{
      'minutes': 20,
      'time': DateTime.now().toIso8601String(),
      'minHour': DateTime(2022, 2, 7, 0).toIso8601String(),
      'maxHour': DateTime(2022, 2, 7, 23).toIso8601String()
    });
    return ShowerCost.fromJson(results.data);
  } catch (error) {
    print(error);
    return Future.error(error);
  }
}
</code>```

答:
You can use json.decode from dart:convert package.

```<code>    final results = await callable.call(<String, dynamic>{
      'minutes': 20,
      'time': DateTime.now().toIso8601String(),
      'minHour': DateTime(2022, 2, 7, 0).toIso8601String(),
      'maxHour': DateTime(2022, 2, 7, 23).toIso8601String()
    });
    // Try
    final data = Map<String, dynamic>.from(results.data) as Map<String, dynamic>
    // or
    final data = results.data.toMap()

    return ShowerCost.fromJson(data);
</code>```

Body:
I get this error while serializing my json.
I am not sure I understand the error, but I have figured out that the code never reaches Prices.fromJson if I try to print something there. As you can see I am using Firebase Cloud Functions to return a data with nested data objects, and I struggle to get them serialized.

Code:

class Price {
  final DateTime validFrom;
  final DateTime validTo;
  final double nokPerKwh;

  const Price({
    required this.validFrom,
    required this.validTo,
    required this.nokPerKwh,
  });

  factory Price.fromJson(Map<String, dynamic> json) {
    return Price(
      validFrom: DateTime.parse(json['validFrom']),
      validTo: DateTime.parse(json['validTo']),
      nokPerKwh: json['nokPerKwh'],
    );
  }
}

class Prices {
  final double now;
  final Price lowest;
  final Price highest;

  const Prices({
    required this.now,
    required this.lowest,
    required this.highest,
  });

  factory Prices.fromJson(Map<String, dynamic> json) {
    return Prices(
      now: json['now'],
      lowest: Price.fromJson(json['lowest']),
      highest: Price.fromJson(json['highest']),
    );
  }
}

class ShowerCost {
  final DateTime time;
  final int minutes;
  final Prices prices;

  const ShowerCost({
    required this.time,
    required this.minutes,
    required this.prices,
  });

  factory ShowerCost.fromJson(Map<String, dynamic> json) {
    print(json); <--- {minutes: 20, time: 2022-02-07T23:46:41.625Z, prices: {now: 11.848, highest: null, lowest: {nokPerKwh: 1.1848, validFrom: 2022-02-08T00:00:00+01:00, validTo: 2022-02-08T01:00:00+01:00}}}
    return ShowerCost(
      time: DateTime.parse(json['time']),
      minutes: json['minutes'],
      prices: Prices.fromJson(json['prices']),
    );
  }
}

Future<ShowerCost> getShowerCost() async {
  try {
    HttpsCallable callable =
        FirebaseFunctions.instance.httpsCallable('getShowerCost');
    final results = await callable.call(<String, dynamic>{
      'minutes': 20,
      'time': DateTime.now().toIso8601String(),
      'minHour': DateTime(2022, 2, 7, 0).toIso8601String(),
      'maxHour': DateTime(2022, 2, 7, 23).toIso8601String()
    });
    return ShowerCost.fromJson(results.data);
  } catch (error) {
    print(error);
    return Future.error(error);
  }
}

Body:
You can use json.decode from dart:convert package.

    final results = await callable.call(<String, dynamic>{
      'minutes': 20,
      'time': DateTime.now().toIso8601String(),
      'minHour': DateTime(2022, 2, 7, 0).toIso8601String(),
      'maxHour': DateTime(2022, 2, 7, 23).toIso8601String()
    });
    // Try
    final data = Map<String, dynamic>.from(results.data) as Map<String, dynamic>
    // or
    final data = results.data.toMap()

    return ShowerCost.fromJson(data);


问:
How can I pass data like a variable to a frame in an iframed page
So I have been using this http://www.facebook.com/connect/prompt_feed.php?api_key=2231777543&message=@[undefined:0:] Facebook API to make posts to my Facebook. but recently the it doesnt seem to be taking 'message' posts. So I figured I could put that API into an Iframe and pass the data from my form to the form in the API.

I Know I can just type in there but I need to be able to do it this way for my project and any future reference

答:
If this is for an iFrame app running on a Facebook page you can pass an app_data field that a backend script can extract that you can use.

Check out this FB blog post:

https://developers.facebook.com/blog/post/462


问:
Different scroll speeds for elements in array
I have different randomly-styled stars in an array and I would like them to each have different scroll speeds between -.2 and -.8. The idea is to have them do a parallax effect, and it'd be cool to have everything a little random.

This was the original scroll speed code using images:

```<code>var starsOne = document.querySelector("#starsOne");
function setTranslate(xPos, yPos, el) {
    el.style.transform = "translate3d(" + xPos + ", " + yPos + "px, 0)";
}
var xScrollPosition;
var yScrollPosition;
function scrollLoop() {
    xScrollPosition = window.scrollX;
    yScrollPosition = window.scrollY;
    setTranslate(0, yScrollPosition * -0.6, starsOne);
    requestAnimationFrame(scrollLoop);
}
window.addEventListener("load", scrollLoop, false);
</code>```

I've been trying to integrate the above code somehow for the array:

```<code>let starScrollMin = 2;
let starScrollMax = 8;
var starScrollSpeed = -Math.abs((Math.floor(Math.random() * (starScrollMax - starScrollMin + 1)) + starScrollMin) / 10);

function starScroll() {
        for (i = 0; i < starDivvyArr.length; i++) {
        yScrollPos = window.scrollY;
        starDivvyArr[i].style.transform = "translate3d(" + 0 + "px, " + yScrollPos * starScrollSpeed + "px, 0)";
        }
        requestAnimationFrame(starScroll);
}
    window.addEventListener("load", starScroll, false);

</code>```

If starScrollSpeed is global, then all the stars move in a big chunk. If it's within the starScroll() function, the values are at least different per star, but it gets crazy as it keeps randomizing and multiplying.

Any ideas on how to randomize the scroll speed for each star so it looks like a parallax effect, without them moving in one single chunk or going crazy? Or is it a safer bet to make a bunch of css lines and then randomly assign classes?

jsfiddle

答:
You could create an array for the randomly created numbers and push a value from a function that returns the randomly created speed into that array with in the loop and then use that array to get a random value for each element.

var starCount = 25;
let starContain = document.getElementById('starContain');

/*Create star divs*/
for (var i = 0; i < starCount; i++) {
  var starDiv = document.createElement("div");
  starDiv.className = 'star';
  starContain.append(starDiv);
}

/*Make an array from the star divs*/
var starDivvy = document.querySelectorAll(".star");
var starDivvyArr = Array.from(starDivvy);

/*Create some possible styles*/
var starColor = ['yellow', 'blue', 'white'];
var starSizeMin = 5;
var starSizeMax = 25;
let starContainWidth = starContain.offsetWidth;
let starContainHeight = starContain.offsetHeight;

/*Give the star array some different styles*/
for (i = 0; i < starDivvyArr.length; i++) {
  /*Change star color*/
  starDivvyArr[i].style.backgroundColor = starColor[Math.floor(Math.random() * starColor.length)];
  /*Change star position within container*/
  starDivvyArr[i].style.left = Math.floor((Math.random() * starContainWidth) + 1) + "px";
  starDivvyArr[i].style.top = Math.floor((Math.random() * starContainHeight) + 1) + "px";
  /*Change star size*/
  starDivvyArr[i].style.width = Math.floor(Math.random() * (starSizeMax - starSizeMin + 1)) + starSizeMin + "px";
  starDivvyArr[i].style.height = starDivvyArr[i].style.width;
}

/*>>>>>>>POINT OF CONFUSION<<<<<<<*/
/*Randomize scroll speed between -0.2 and -0.8*/
let starScrollMin = 2;
let starScrollMax = 8;
//function for creating random scroll speed
const starScrollSpeed = (min,max) => {
  return -Math.abs((Math.floor(Math.random() * (min - max + 1)) + min) / 10);
}
//==> added array
const starArray = [];
/*Give the stars a scrolling function*/
function starScroll() {
  for (i = 0; i < starDivvyArr.length; i++) {
    // array to hold randomly created scroll speeds
    starArray.push(starScrollSpeed(starScrollMin,starScrollMax))
    yScrollPos = window.scrollY;
    starDivvyArr[i].style.transform = "translate3d(" + 0 + "px, " + yScrollPos * starArray[i] + "px, 0)";
  }
  requestAnimationFrame(starScroll);
}

window.addEventListener("load", starScroll, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0 auto;
}

section {
  width: 100vw;
  height: 150vh;
}

.section1 {
  background-color: #000;
}

.section2 {
  background-color: #202;
}

h2 {
  text-align: center;
  color: #ccc;
}

#starContain {
  width: 100vw;
  height: 500px;
  position: absolute;
  top: 50vh;
  z-index: 2;
  background-color: rgba(255, 255, 255, 0.2);
}

.star {
  background-color: green;
  position: absolute;
  z-index: 100;
  border-radius: 50%;
}</code>```

      Section 1

      Section 2

```

Body:
I have different randomly-styled stars in an array and I would like them to each have different scroll speeds between -.2 and -.8. The idea is to have them do a parallax effect, and it'd be cool to have everything a little random.

This was the original scroll speed code using images:

var starsOne = document.querySelector("#starsOne");
function setTranslate(xPos, yPos, el) {
    el.style.transform = "translate3d(" + xPos + ", " + yPos + "px, 0)";
}
var xScrollPosition;
var yScrollPosition;
function scrollLoop() {
    xScrollPosition = window.scrollX;
    yScrollPosition = window.scrollY;
    setTranslate(0, yScrollPosition * -0.6, starsOne);
    requestAnimationFrame(scrollLoop);
}
window.addEventListener("load", scrollLoop, false);

I've been trying to integrate the above code somehow for the array:

let starScrollMin = 2;
let starScrollMax = 8;
var starScrollSpeed = -Math.abs((Math.floor(Math.random() * (starScrollMax - starScrollMin + 1)) + starScrollMin) / 10);

function starScroll() {
        for (i = 0; i < starDivvyArr.length; i++) {
        yScrollPos = window.scrollY;
        starDivvyArr[i].style.transform = "translate3d(" + 0 + "px, " + yScrollPos * starScrollSpeed + "px, 0)";
        }
        requestAnimationFrame(starScroll);
}
    window.addEventListener("load", starScroll, false);

If starScrollSpeed is global, then all the stars move in a big chunk. If it's within the starScroll() function, the values are at least different per star, but it gets crazy as it keeps randomizing and multiplying.

Any ideas on how to randomize the scroll speed for each star so it looks like a parallax effect, without them moving in one single chunk or going crazy? Or is it a safer bet to make a bunch of css lines and then randomly assign classes?

jsfiddle

Body:
You could create an array for the randomly created numbers and push a value from a function that returns the randomly created speed into that array with in the loop and then use that array to get a random value for each element.

var starCount = 25;
let starContain = document.getElementById('starContain');

/*Create star divs*/
for (var i = 0; i < starCount; i++) {
  var starDiv = document.createElement("div");
  starDiv.className = 'star';
  starContain.append(starDiv);
}

/*Make an array from the star divs*/
var starDivvy = document.querySelectorAll(".star");
var starDivvyArr = Array.from(starDivvy);

/*Create some possible styles*/
var starColor = ['yellow', 'blue', 'white'];
var starSizeMin = 5;
var starSizeMax = 25;
let starContainWidth = starContain.offsetWidth;
let starContainHeight = starContain.offsetHeight;

/*Give the star array some different styles*/
for (i = 0; i < starDivvyArr.length; i++) {
  /*Change star color*/
  starDivvyArr[i].style.backgroundColor = starColor[Math.floor(Math.random() * starColor.length)];
  /*Change star position within container*/
  starDivvyArr[i].style.left = Math.floor((Math.random() * starContainWidth) + 1) + "px";
  starDivvyArr[i].style.top = Math.floor((Math.random() * starContainHeight) + 1) + "px";
  /*Change star size*/
  starDivvyArr[i].style.width = Math.floor(Math.random() * (starSizeMax - starSizeMin + 1)) + starSizeMin + "px";
  starDivvyArr[i].style.height = starDivvyArr[i].style.width;
}

/*>>>>>>>POINT OF CONFUSION<<<<<<<*/
/*Randomize scroll speed between -0.2 and -0.8*/
let starScrollMin = 2;
let starScrollMax = 8;
//function for creating random scroll speed
const starScrollSpeed = (min,max) => {
  return -Math.abs((Math.floor(Math.random() * (min - max + 1)) + min) / 10);
}
//==> added array
const starArray = [];
/*Give the stars a scrolling function*/
function starScroll() {
  for (i = 0; i < starDivvyArr.length; i++) {
    // array to hold randomly created scroll speeds
    starArray.push(starScrollSpeed(starScrollMin,starScrollMax))
    yScrollPos = window.scrollY;
    starDivvyArr[i].style.transform = "translate3d(" + 0 + "px, " + yScrollPos * starArray[i] + "px, 0)";
  }
  requestAnimationFrame(starScroll);
}

window.addEventListener("load", starScroll, false);

* {
  margin: 0 auto;
}

section {
  width: 100vw;
  height: 150vh;
}

.section1 {
  background-color: #000;
}

.section2 {
  background-color: #202;
}

h2 {
  text-align: center;
  color: #ccc;
}

#starContain {
  width: 100vw;
  height: 500px;
  position: absolute;
  top: 50vh;
  z-index: 2;
  background-color: rgba(255, 255, 255, 0.2);
}

.star {
  background-color: green;
  position: absolute;
  z-index: 100;
  border-radius: 50%;
}

<main>
  <section class="section1">
    <h2>
      Section 1
    </h2>
  </section>

  <div id="starContain">

  </div>

  <section class="section2">
    <h2>
      Section 2
    </h2>
  </section>
</main>


问:
How to hide a button if the user is logged in using Elementor
I'm using Elementor to build a Wordpress website, I want to hide a button (Register) if the user is logged in.

I don't know how to test if the user session is opened or not to hide this button

Please help!

答:
you can try this plugin, it will do the trick:

https://wordpress.org/plugins/visibility-logic-elementor/

Edit Button > Show if all Conditions met and User Roll is Guest


问:
Replace a set of html br elements with another in jQuery -- parsing HTML with jQuery
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

```<code><br><br clear=all><br>
</code>```

with

```<code><br />
</code>```

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

答:
You better do this with regexps not with jquery. Simplest example:</p>

```<code>string.replace('<br><br clear=all><br>', '<br />')
</code>```

Body:
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

with

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

Body:
You better do this with regexps not with jquery. Simplest example:

string.replace('<br><br clear=all><br>', '<br />')


问:
Access Denied to amazon AWS SQS through CLI or API
I am getting access denied when I try to access the Amazon SQS through CLI or API. This is the node.js code:

```<code>// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'eu-west-1'});

var credentials = new AWS.SharedIniFileCredentials({profile: 'default'});
AWS.config.credentials = credentials;

// Create the SQS service object
var sqs = new AWS.SQS({apiVersion: 'latest'});

var params = {
  MaxResults: 10
};

sqs.listQueues(params, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
</code>```

The sqs policy is the following:

```<code>{
  "Version": "2012-10-17",
  "Id": "__default_policy_ID",
  "Statement": [
    {
      "Sid": "__owner_statement",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::437568002678:root",
          "arn:aws:iam::ACCOUNTID:role/MyRole",
          "arn:aws:iam::ACCOUNTID:user/username"
        ]
      },
      "Action": [
        "sqs:GetQueueAttributes",
        "sqs:SendMessage",
        "sqs:ListQueues"
      ],
      "Resource": "arn:aws:sqs:eu-west-1:ACCOUNTID:NAME"
    }
  ]
}
</code>```

The complete error is:

```<code>Error AccessDenied: Access to the resource https://sqs.eu-west-1.amazonaws.com/ is denied.
</code>```

The credentials file is set at /home/user/.aws/credentials.

I am using one account for AWS services.

答:
To reproduce your situation I did the following:

Created an IAM User with no permissions

Configured the AWS CLI to use credentials associated with the new IAM User

Created a standard (non-FIFO) Amazon SQS queue

Attached your policy to the queue, but with an updated Resource and Principal

Used the AWS CLI to send a message to the SQS queue:

```<code>aws sqs send-message --queue-url https://sqs.ap-southeast-2.amazonaws.com/123456789012/queuename --message-body foo
</code>```

The message was successfully sent to the queue. This means that the Access Policy on the SQS queue was sufficient to grant permission to send the message, without requiring any additional permissions on the IAM User.

Therefore, either your AWS CLI is not using the IAM User referenced in your Access Policy or there are some permissions on the IAM User or Account SCP that is specifically denying the ability to use SendMessage().

Body:
I am getting access denied when I try to access the Amazon SQS through CLI or API. This is the node.js code:

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'eu-west-1'});

var credentials = new AWS.SharedIniFileCredentials({profile: 'default'});
AWS.config.credentials = credentials;

// Create the SQS service object
var sqs = new AWS.SQS({apiVersion: 'latest'});

var params = {
  MaxResults: 10
};

sqs.listQueues(params, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});

The sqs policy is the following:

{
  "Version": "2012-10-17",
  "Id": "__default_policy_ID",
  "Statement": [
    {
      "Sid": "__owner_statement",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::437568002678:root",
          "arn:aws:iam::ACCOUNTID:role/MyRole",
          "arn:aws:iam::ACCOUNTID:user/username"
        ]
      },
      "Action": [
        "sqs:GetQueueAttributes",
        "sqs:SendMessage",
        "sqs:ListQueues"
      ],
      "Resource": "arn:aws:sqs:eu-west-1:ACCOUNTID:NAME"
    }
  ]
}

The complete error is:

Error AccessDenied: Access to the resource https://sqs.eu-west-1.amazonaws.com/ is denied.

The credentials file is set at /home/user/.aws/credentials.

I am using one account for AWS services.

Body:
To reproduce your situation I did the following:

Created an IAM User with no permissions

Configured the AWS CLI to use credentials associated with the new IAM User

Created a standard (non-FIFO) Amazon SQS queue

Attached your policy to the queue, but with an updated Resource and Principal

Used the AWS CLI to send a message to the SQS queue:

aws sqs send-message --queue-url https://sqs.ap-southeast-2.amazonaws.com/123456789012/queuename --message-body foo

The message was successfully sent to the queue. This means that the Access Policy on the SQS queue was sufficient to grant permission to send the message, without requiring any additional permissions on the IAM User.

Therefore, either your AWS CLI is not using the IAM User referenced in your Access Policy or there are some permissions on the IAM User or Account SCP that is specifically denying the ability to use SendMessage().


问:
WorkManager CoroutineWorker's stream cancellation
I have the following setup:

```<code>override suspend fun doWork(): Result = coroutineScope {
    flowOfEvents
        .onEach(eventChannel::send)
        .launchIn(this)

    if (isQueueEmpty()) return@coroutineScope Result.success()

    ...
}
</code>```

What I'm seeing is the following: when isQueueEmpty() is true, I return Result.success() and I'd expect the flowOfEvents...launchIn(this) stream to be disposed/cancelled as well, but I keep receiving events from that stream.

Am I doing something wrong?

Capturing the Job from launchIn(this) and explicitly calling job.cancel() before each return statement works, but feels unnecessary/wrong.

答:
After a bit of research, it was made clear that this is a Kotlin coroutines behavior and isn't related to WorkManager at all.

Listening to a Flow<Event> is a never-ending job

By definition, parent coroutines wait for the child coroutines to finish

Given these 2 points, it is now apparent why I kept receiving Events even after I returned from the parent coroutine.

The solution: call coroutineContext[Job]?.cancelChildren() before returning from the parent coroutine.

```<code>override suspend fun doWork(): Result = coroutineScope {
    flowOfEvents
        .onEach(eventChannel::send)
        .launchIn(this)

    if (isQueueEmpty()) {
        coroutineContext[Job]?.cancelChildren()
        return@coroutineScope Result.success()
    }

    ...
}
</code>```

Note: calling parent's cancel() throws a CancellationException, which in the context of a WorkManager meant that the Worker#doWork method would actually result in a failed job.

Body:
I have the following setup:

override suspend fun doWork(): Result = coroutineScope {
    flowOfEvents
        .onEach(eventChannel::send)
        .launchIn(this)

    if (isQueueEmpty()) return@coroutineScope Result.success()

    ...
}

What I'm seeing is the following: when isQueueEmpty() is true, I return Result.success() and I'd expect the flowOfEvents...launchIn(this) stream to be disposed/cancelled as well, but I keep receiving events from that stream.

Am I doing something wrong?

Capturing the Job from launchIn(this) and explicitly calling job.cancel() before each return statement works, but feels unnecessary/wrong.

Body:
After a bit of research, it was made clear that this is a Kotlin coroutines behavior and isn't related to WorkManager at all.

Listening to a Flow<Event> is a never-ending job

By definition, parent coroutines wait for the child coroutines to finish

Given these 2 points, it is now apparent why I kept receiving Events even after I returned from the parent coroutine.

The solution: call coroutineContext[Job]?.cancelChildren() before returning from the parent coroutine.

override suspend fun doWork(): Result = coroutineScope {
    flowOfEvents
        .onEach(eventChannel::send)
        .launchIn(this)

    if (isQueueEmpty()) {
        coroutineContext[Job]?.cancelChildren()
        return@coroutineScope Result.success()
    }

    ...
}

Note: calling parent's cancel() throws a CancellationException, which in the context of a WorkManager meant that the Worker#doWork method would actually result in a failed job.


问:
Variable inconsistency in Python?
I've run into a strange inconsistency. This is a simplified version of the problem:

```<code>func1={
    'flist':[12,13,14],
    'fnum':10
}

dlist=func1['flist']
dnum=func1['fnum']

dlist+=[16]
dnum+=1

print(func1)
print(dnum)
</code>```

The output is:

```<code>{'flist': [12, 13, 14, 16], 'fnum': 10}

11
</code>```

Why is that the changes to the variable dlist are carried over to flist in func1, but changes in dnum are not carried over to fnum in func1?

flist has changed, fnum has not.

答:
This has to do with the mutability of the underlying objects. Since func1['flist'] refers to a list, when you do dlist=func1['flist'] you are actually getting a reference to the memory address of func1['flist'] and then when you add another value, you are modifying the same object in memory. This is because lists are mutable objects and referred to by reference.

On the other hand when you do dnum+=1, what is happening in memory is that 10+1=11 is being created as a new object in memory and then dnum is set to point to the new memory address. This has no effect on the memory address and therefore the value of func1['fnum']. This is the behaviour that happens for immutable types.

Title: Variable inconsistency in Python?

Body:
I've run into a strange inconsistency. This is a simplified version of the problem:

func1={
    'flist':[12,13,14],
    'fnum':10
}

dlist=func1['flist']
dnum=func1['fnum']

dlist+=[16]
dnum+=1

print(func1)
print(dnum)

The output is:

{'flist': [12, 13, 14, 16], 'fnum': 10}

11

Why is that the changes to the variable dlist are carried over to flist in func1, but changes in dnum are not carried over to fnum in func1?

flist has changed, fnum has not.


答:
The ternary operator returns a value, it does not support an assignment as a value (otherwise it would be a regular if/then/else)

You can use it like this:

```<code>hash[x] = hash[x] + 1 if x in hash else 1
</code>```

BTW hash is a Python built-in function, you should not use that as a variable name.

Note that there are other data structures in Python that might be  better suited to your purpose.  (e.g. collections.Counter, collections.defaultdict)

Title: Ternary operator python not working on dict assignment

Body:
The ternary operator returns a value, it does not support an assignment as a value (otherwise it would be a regular if/then/else)

You can use it like this:

hash[x] = hash[x] + 1 if x in hash else 1

BTW hash is a Python built-in function, you should not use that as a variable name.

Note that there are other data structures in Python that might be  better suited to your purpose.  (e.g. collections.Counter, collections.defaultdict)


问:
Getting max values from pandas multiindex dataframe
Im trying to retrieve only the max values (including the multi index values) from a pandas dataframe that has multiple indexes. The dataframe I have is generated via a groupby and column selection ('tOfmAJyI') like this:

```<code>df.groupby('id')['tOfmAJyI'].value_counts()

Out[4]:
id     tOfmAJyI
3      mlNXN       4
       SSvEP       2
       hCIpw       2
5      SSvEP       2
       hCIpw       1
       mlNXN       1
11     mlNXN       2
       SSvEP       1
...
</code>```

What I would like to achieve is to get the max values including their corresponding index values. So something like:

```<code>id     tOfmAJyI
3      mlNXN       4
5      SSvEP       2
11     mlNXN       2
...
</code>```

Any ideas how I can achieve this? I was able to get the id and max value but I'm still trying to get the corresponding value of 'tOfmAJyI'.

答:
I had a similar question and I don't think currently this question has a good answer.

My solution was this, I think it's cleaner:

```<code>df.groupby(level=0).nlargest(1)
</code>```

this keeps the multiindex object and doesn't need a lambda function

Body:
Im trying to retrieve only the max values (including the multi index values) from a pandas dataframe that has multiple indexes. The dataframe I have is generated via a groupby and column selection ('tOfmAJyI') like this:

df.groupby('id')['tOfmAJyI'].value_counts()

Out[4]:
id     tOfmAJyI
3      mlNXN       4
       SSvEP       2
       hCIpw       2
5      SSvEP       2
       hCIpw       1
       mlNXN       1
11     mlNXN       2
       SSvEP       1
...

What I would like to achieve is to get the max values including their corresponding index values. So something like:

id     tOfmAJyI
3      mlNXN       4
5      SSvEP       2
11     mlNXN       2
...

Any ideas how I can achieve this? I was able to get the id and max value but I'm still trying to get the corresponding value of 'tOfmAJyI'.

Body:
I had a similar question and I don't think currently this question has a good answer.

My solution was this, I think it's cleaner:

df.groupby(level=0).nlargest(1)

this keeps the multiindex object and doesn't need a lambda function


问:
Error in chisq.posthoc.test : All entries of 'x' must be nonnegative and finite?
I'm getting this error message even though I don't have any NA's, negative counts, etc.

I'm trying to do a post-hoc chi-square test on this data:

```<code>df <- structure(list(Zone = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("Crocodile",
"Rankin", "West", "Whipray"), class = "factor"), Year = structure(c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("2016",
"2017", "2018", "2019"), class = "factor"), empty_num_sum = c(0L,
8L, 2L, 0L, 3L, 17L, 8L, 19L, 7L, 31L, 17L, 17L, 4L, 4L, 0L,
3L)), row.names = c(NA, -16L), groups = structure(list(Zone = structure(1:4, .Label = c("Crocodile",
"Rankin", "West", "Whipray"), class = "factor"), .rows = structure(list(
    1:4, 5:8, 9:12, 13:16), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
</code>```

But it keeps giving me this error...

```<code>chisq.posthoc.test(df, method = "bonferroni")

    Error in chisq.test(x, ...) :
      all entries of 'x' must be nonnegative and finite
</code>```

答:
You need to pass your counts as a matrix / contingency table. You can easily convert your data frame to this format using the xtabs function:

xtab <- xtabs(empty_num_sum ~ Zone + Year, data = df)

xtab
#>            Year
#> Zone        2016 2017 2018 2019
#>   Crocodile    0    8    2    0
#>   Rankin       3   17    8   19
#>   West         7   31   17   17
#>   Whipray      4    4    0    3
```
<p>So now you can do:</p>
<pre class="lang-r prettyprint-override"><code>library(chisq.posthoc.test)

chisq.posthoc.test(xtab)
#> Warning in chisq.test(x, ...): Chi-squared approximation may be incorrect
#>   Dimension     Value       2016        2017       2018        2019
#> 1 Crocodile Residuals -1.0938835  2.46306043  0.0594116 -2.03921942
#> 2 Crocodile  p values  1.0000000  0.22041100  1.0000000  0.66285000
#> 3    Rankin Residuals -1.0141479 -1.13659482 -0.4827683  2.35822986
#> 4    Rankin  p values  1.0000000  1.00000000  1.0000000  0.29379700
#> 5      West Residuals -0.1127333  0.04881493  1.3347770 -1.15317201
#> 6      West  p values  1.0000000  1.00000000  1.0000000  1.00000000
#> 7   Whipray Residuals  3.0363341 -0.45336940 -1.6889164 -0.04504248
#> 8   Whipray  p values  0.0383160  1.00000000  1.0000000  1.00000000
</code>```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
I'm getting this error message even though I don't have any NA's, negative counts, etc.

I'm trying to do a post-hoc chi-square test on this data:

df <- structure(list(Zone = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("Crocodile",
"Rankin", "West", "Whipray"), class = "factor"), Year = structure(c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("2016",
"2017", "2018", "2019"), class = "factor"), empty_num_sum = c(0L,
8L, 2L, 0L, 3L, 17L, 8L, 19L, 7L, 31L, 17L, 17L, 4L, 4L, 0L,
3L)), row.names = c(NA, -16L), groups = structure(list(Zone = structure(1:4, .Label = c("Crocodile",
"Rankin", "West", "Whipray"), class = "factor"), .rows = structure(list(
    1:4, 5:8, 9:12, 13:16), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))

But it keeps giving me this error...

chisq.posthoc.test(df, method = "bonferroni")

    Error in chisq.test(x, ...) :
      all entries of 'x' must be nonnegative and finite

Body:
You need to pass your counts as a matrix / contingency table. You can easily convert your data frame to this format using the xtabs function:

xtab <- xtabs(empty_num_sum ~ Zone + Year, data = df)

xtab
#>            Year
#> Zone        2016 2017 2018 2019
#>   Crocodile    0    8    2    0
#>   Rankin       3   17    8   19
#>   West         7   31   17   17
#>   Whipray      4    4    0    3

So now you can do:

library(chisq.posthoc.test)

chisq.posthoc.test(xtab)
#> Warning in chisq.test(x, ...): Chi-squared approximation may be incorrect
#>   Dimension     Value       2016        2017       2018        2019
#> 1 Crocodile Residuals -1.0938835  2.46306043  0.0594116 -2.03921942
#> 2 Crocodile  p values  1.0000000  0.22041100  1.0000000  0.66285000
#> 3    Rankin Residuals -1.0141479 -1.13659482 -0.4827683  2.35822986
#> 4    Rankin  p values  1.0000000  1.00000000  1.0000000  0.29379700
#> 5      West Residuals -0.1127333  0.04881493  1.3347770 -1.15317201
#> 6      West  p values  1.0000000  1.00000000  1.0000000  1.00000000
#> 7   Whipray Residuals  3.0363341 -0.45336940 -1.6889164 -0.04504248
#> 8   Whipray  p values  0.0383160  1.00000000  1.0000000  1.00000000

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
Image hiding under nav bar
I have a navbar with an image below it. The issue is the top of the image is being cut off. I want the image to start at the bottom of the navbar. You can see part of the cats head is cut off. It gets worse the smaller the screen size. I was adding a margin top to the image but its not constant as it varies with screen sizeFIDDLE

:root {
    --primary-color: #FF0000;
    --main-color: #FF0000;
    --dark-main: #FF0000;
}

body {

    min-height: 400px;
    margin-bottom: 300px;
    clear: both;
}
html {
    height: 100%;

}

.hero-image {
    background-image: url("https://www.purina.co.uk/sites/default/files/2020-12/8-Large-Domestic-Cat-BreedsHERO.jpg");
    height: 50%;
    padding: 0;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
    margin-bottom: 2em;

}

.body-no-margin {
    height: 100%;
    background: #F6F6F6;
    color: #333333;

}

ul {
    margin: 0;
}

.bg-steel {
    background-color: var(--main-color);
}

.navigation-items{
    display: block;
    padding: .5rem 0.3rem;
    color: #eeeeee;
    text-decoration: none;
    transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out;
    font-family: 'Montserrat', sans-serif;
    font-size: 18px;
}```
<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">

<body class="body-no-margin">
  <header class="site-header">
    <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
      <div class="container-fluid">

          <div class=nav-bar-logo></div>

        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mynavbar">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="mynavbar">
          <ul class="navbar-nav me-auto">
            <li class="nav-item">
              Home
            </li>
            <li class="nav-item">
              Browse
            </li>
          </ul>
          <div class="d-flex">
            <ul class="navbar-nav me-auto">

              <li class="nav-item">
                Profile
              </li>
              <li class="nav-item">
                New
              </li>
              <li class="nav-item">
                Logout
              </li>
            </ul>
          </div>
        </div>
      </div>
    </nav>
  </header>
  <div class="hero-image">
  </div>

  <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  <script src="{% static 'js/lightbox.js' %}"></script>

</body></code>```

答: I added padding-top: 25px; to my main body

Title: Image hiding under nav bar

Body:
I have a navbar with an image below it. The issue is the top of the image is being cut off. I want the image to start at the bottom of the navbar. You can see part of the cats head is cut off. It gets worse the smaller the screen size. I was adding a margin top to the image but its not constant as it varies with screen sizeFIDDLE

:root {
    --primary-color: #FF0000;
    --main-color: #FF0000;
    --dark-main: #FF0000;
}

body {

    min-height: 400px;
    margin-bottom: 300px;
    clear: both;
}
html {
    height: 100%;

}

.hero-image {
    background-image: url("https://www.purina.co.uk/sites/default/files/2020-12/8-Large-Domestic-Cat-BreedsHERO.jpg");
    height: 50%;
    padding: 0;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
    margin-bottom: 2em;

}

.body-no-margin {
    height: 100%;
    background: #F6F6F6;
    color: #333333;

}

ul {
    margin: 0;
}

.bg-steel {
    background-color: var(--main-color);
}

.navigation-items{
    display: block;
    padding: .5rem 0.3rem;
    color: #eeeeee;
    text-decoration: none;
    transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out;
    font-family: 'Montserrat', sans-serif;
    font-size: 18px;
}

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

        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mynavbar">

        </button>

              Home

              Browse

                Profile

                New

                Logout


问:
How to find the most left point in a Triangle?
I have this problem:
I have this class named Point:

```<code>class Point {
private double x;
private double y;

public Point(final double x, final double y) {
    this.x = x;
    this.y = y;
}

public double getX() {
    return x;
}

public double getY() {
    return y;
}
</code>```

}

I have a class Triangle:

```<code>class Triangle {
private Point a;
private Point b;
private Point c;

public Triangle(Point a, Point b , Point c){
    this.a = a;
    this.b = b;
    this.c = c;
}

@Override
public double area() {
    double area = (a.getX() * (b.getY()- c.getY()) +
            b.getX() * (c.getY() - a.getY()) + c.getX() * (a.getY() - b.getY())) / 2.0;
    return Math.abs(area);
}

@Override
public String pointsToString() {
    return "("+a.getX()+","+a.getY()+")"+"("+b.getX()+","+b.getY()+")"+"("+c.getX()+","+c.getY()+")";
}

public String toString() {
    return this.getClass().getSimpleName() + "[" + pointsToString() + "]";
}

@Override
public Point leftmostPoint() {
    return null;
}
</code>```

}

The question is how to find the leftmost point in the Triangle ?

I should realize the method leftmostPoint(). The method leftmostPoint() should return leftmost point of the Triangle: the one having the least X coordinate and if there are many leftmost points, return any of them.

答: the least X coordinate of a Triangle will work</p>

Body:
I have this problem:
I have this class named Point:

class Point {
private double x;
private double y;

public Point(final double x, final double y) {
    this.x = x;
    this.y = y;
}

public double getX() {
    return x;
}

public double getY() {
    return y;
}

}

I have a class Triangle:

class Triangle {
private Point a;
private Point b;
private Point c;

public Triangle(Point a, Point b , Point c){
    this.a = a;
    this.b = b;
    this.c = c;
}

@Override
public double area() {
    double area = (a.getX() * (b.getY()- c.getY()) +
            b.getX() * (c.getY() - a.getY()) + c.getX() * (a.getY() - b.getY())) / 2.0;
    return Math.abs(area);
}

@Override
public String pointsToString() {
    return "("+a.getX()+","+a.getY()+")"+"("+b.getX()+","+b.getY()+")"+"("+c.getX()+","+c.getY()+")";
}

public String toString() {
    return this.getClass().getSimpleName() + "[" + pointsToString() + "]";
}

@Override
public Point leftmostPoint() {
    return null;
}

}

The question is how to find the leftmost point in the Triangle ?

I should realize the method leftmostPoint(). The method leftmostPoint() should return leftmost point of the Triangle: the one having the least X coordinate and if there are many leftmost points, return any of them.


问:
C# comparing 2 lists of objects while ignoring the key field
I am trying to compare 2 lists of objects for equality, but I want to ignore the key field.
How can I do this?

Here is an example:

```<code>public class myProduct
{
    int ID {get; set;}
    int field1 {get; set;}
    int field2 {get; set;}
}

<List>myProduct greenProducts = new <List>myProduct();
<List>myProduct purpleProducts = new <List>myProduct();

greenProducts.Add(new myProduct { ID = 1, field1 = 5, field2 = 8});
greenProducts.Add(new myProduct { ID = 2, field1 = 9, field2 = 12});
greenProducts.Add(new myProduct { ID = 3, field1 = 7, field2 = 7});

purpleProducts.Add(new myProduct { ID = 8, field1 = 5, field2 = 8});
purpleProducts.Add(new myProduct { ID = 9, field1 = 9, field2 = 12});
purpleProducts.Add(new myProduct { ID = 10, field1 = 7, field2 = 7});
</code>```

If you ignore the key field (aka the ID field), these lists are exactly the same.

So I want my code to do something like this:

```<code>if (purpleProducts == greenProducts) //I WANT THE ID FIELD IGNORED FOR THE COMPARISON SO RESULT WITH ABOVE DATA WOULD BE TRUE
{
  //DO ACTION HERE
}
</code>```

答:
```<code>green.Zip(purple, (l,r)=>(l.field1 == r.field1) && (l.field2 == r.field2)).All(x=>x);
</code>```

Body:
I am trying to compare 2 lists of objects for equality, but I want to ignore the key field.
How can I do this?

Here is an example:

public class myProduct
{
    int ID {get; set;}
    int field1 {get; set;}
    int field2 {get; set;}
}

<List>myProduct greenProducts = new <List>myProduct();
<List>myProduct purpleProducts = new <List>myProduct();

greenProducts.Add(new myProduct { ID = 1, field1 = 5, field2 = 8});
greenProducts.Add(new myProduct { ID = 2, field1 = 9, field2 = 12});
greenProducts.Add(new myProduct { ID = 3, field1 = 7, field2 = 7});

purpleProducts.Add(new myProduct { ID = 8, field1 = 5, field2 = 8});
purpleProducts.Add(new myProduct { ID = 9, field1 = 9, field2 = 12});
purpleProducts.Add(new myProduct { ID = 10, field1 = 7, field2 = 7});

If you ignore the key field (aka the ID field), these lists are exactly the same.

So I want my code to do something like this:

if (purpleProducts == greenProducts) //I WANT THE ID FIELD IGNORED FOR THE COMPARISON SO RESULT WITH ABOVE DATA WOULD BE TRUE
{
  //DO ACTION HERE
}


问:
How can create a nested directory?
What is to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p>
```<code>import os

file_path = "/downloads/text.txt"
directory = os.path.dirname(file_path)

try:
    os.stat(directory)
except:
    os.mkdir(directory)
</code>```

答:
Try this one for directory:

os.path.isdir(file_path)
```
<p>To check if a file exist, try this:</p>
<pre class="lang-py prettyprint-override"><code>os.path.isfile(file_path)
</code>```

Title: How can create a nested directory?

Body:
What is to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:

import os

file_path = "/downloads/text.txt"
directory = os.path.dirname(file_path)

try:
    os.stat(directory)
except:
    os.mkdir(directory)

Body:
Try this one for directory:

os.path.isdir(file_path)

To check if a file exist, try this:

os.path.isfile(file_path)