问:
How to use Service management ecosystem(kafka connector) in gravitee 3.x. Is their any guide or tutorial
Not able to understand how to use kafka connector. do we require our own service to connect to kafka or gravitee will provide.</p>

答: You can find out more about how to use the Kafka Connector on Gravitee here.</p>


来源: stackexchange

问:
Fetch API return json object or response status
I'm a bit stuck with the fetch API.
This is a simple Login function

```<code>export default class LoginService {
    async loginUser(u, p) {
        return fetch(API_URL + '/users/authenticate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 'username': u, 'password': p })
        })
            .then(response => response.json())
            .catch(e => console.log(e))
        }
}
</code>```

When user is not found the in the backend return 400 bad request. How can I return the json object or the response status? Or maybe this practice is wrong?

Thank you!

答:
```<code>    .then(res=>{
    if(res.ok)
    {
       return response.json()
    }
    else{
    // return 400 bad request here
    }
    })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm a bit stuck with the fetch API.
This is a simple Login function

export default class LoginService {
    async loginUser(u, p) {
        return fetch(API_URL + '/users/authenticate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 'username': u, 'password': p })
        })
            .then(response => response.json())
            .catch(e => console.log(e))
        }
}

When user is not found the in the backend return 400 bad request. How can I return the json object or the response status? Or maybe this practice is wrong?

Thank you!


问:
how to convert decimal to binary by using repeated division in python
how to convert decimal to binary by using repeated division in python?

i know i have to use a while loop, and use modulus sign  and others {%} and {//} to do this...but i need some kind of example for me to understand  how its done so i can understand completely.
CORRECT ME, if I'm wrong:

```<code>number = int(input("Enter a numberto convert into binary: "))

result = ""
while number != 0:
    remainder = number % 2 # gives the exact remainder
    times = number // 2
    result = str(remainder) + result
    print("The binary representation is", result)
    break
</code>```

Thank You

答:
```<code>B_Number = 0
cnt = 0
while (N != 0):
    rem = N % 2
    c = pow(10, cnt)
    B_Number += rem * c
    N //= 2

    # Count used to store exponent value
    cnt += 1

return B_Number
</code>```

ContentLicense: CC BY-SA 3.0

Body:
how to convert decimal to binary by using repeated division in python?

i know i have to use a while loop, and use modulus sign  and others {%} and {//} to do this...but i need some kind of example for me to understand  how its done so i can understand completely.
CORRECT ME, if I'm wrong:

number = int(input("Enter a numberto convert into binary: "))

result = ""
while number != 0:
    remainder = number % 2 # gives the exact remainder
    times = number // 2
    result = str(remainder) + result
    print("The binary representation is", result)
    break

Thank You


问:
Shopify Storefront GraphQL filtering products within a collection
According to this documentation:
https://shopify.dev/custom-storefronts/products/filter-products#query-products-by-type

We should be able to filter products within a collection using collectionByHandle.

I have created a very basic test query in the Shopify GraphiQL App explorer tool. When I run the documented query, it returns all products, not filtering at all. See below:

This looks like a bug with the API right? Or am I missing something basic?

答:
I have the same problem, the filters param of products query seem to be ineffective and returning me all the products in the collection.
I can't find the "allowed filters" option.
Currently I'm using the Storefront API as an external app, all works fine except that.

Here the code.

```<code> query (
      $collectionHandle: String, $product_filters: [ProductFilter!], $nQueryElements: Int
    ) {
      collection(handle: $collectionHandle) {
        title
        products(first: $nQueryElements filters: $product_filters) {
          pageInfo {
            hasNextPage
            hasPreviousPage
          }
          edges {
            cursor
            node {
              title
              vendor
              availableForSale
              id
              handle
              productType
              variants(first: 40) {
                edges {
                  node {
                    selectedOptions {
                       name
                      value
                        }
                    title
                    compareAtPriceV2 {
                      amount
                    }
                    image {
                      id
                    }
                  }
                }
              }
              priceRange {
                maxVariantPrice {
                  amount
                }
              }
              images(first: 1) {
                edges {
                  node {
                    id
                    url(transform:  { maxWidth: 500, maxHeight: 700 })
                  }
                }
              }
            }
          }
        }
      }
    }
</code>```

const variables = { collectionHandle: this.pageURL, nQueryElements: this.nQueryElements, lastCursor: this.queryCursor.last, firstCursor: this.queryCursor.first, product__filters: [{ productVendor: "ASPESI", },], };

Thanks to who can help.

Body:
I have the same problem, the filters param of products query seem to be ineffective and returning me all the products in the collection.
I can't find the "allowed filters" option.
Currently I'm using the Storefront API as an external app, all works fine except that.

Here the code.

 query (
      $collectionHandle: String, $product_filters: [ProductFilter!], $nQueryElements: Int
    ) {
      collection(handle: $collectionHandle) {
        title
        products(first: $nQueryElements filters: $product_filters) {
          pageInfo {
            hasNextPage
            hasPreviousPage
          }
          edges {
            cursor
            node {
              title
              vendor
              availableForSale
              id
              handle
              productType
              variants(first: 40) {
                edges {
                  node {
                    selectedOptions {
                       name
                      value
                        }
                    title
                    compareAtPriceV2 {
                      amount
                    }
                    image {
                      id
                    }
                  }
                }
              }
              priceRange {
                maxVariantPrice {
                  amount
                }
              }
              images(first: 1) {
                edges {
                  node {
                    id
                    url(transform:  { maxWidth: 500, maxHeight: 700 })
                  }
                }
              }
            }
          }
        }
      }
    }

const variables = { collectionHandle: this.pageURL, nQueryElements: this.nQueryElements, lastCursor: this.queryCursor.last, firstCursor: this.queryCursor.first, product__filters: [{ productVendor: "ASPESI", },], };

Thanks to who can help.


问:
How to merge two pandas columns into one column?
I merged two data frames together and I want to combine two pandas columns as follows:

df1:

```<code>A   B   C
1   3  NaN
2  Nan  2
3   5  NaN
4  NaN  1
</code>```

I want to get a result like the following:

df1:

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

答:
This is a simple way to do it by converting NaN to 1 and 'B' times 'C', as follows:

import pandas as pd
import numpy as np
df = pd.DataFrame({
    'A': [1, 2, 3, 4],
    'B': [3, np.nan, 5, np.nan],
    'C': [np.nan, 2, np.nan, 1]
})

print(df)
#   A    B    C
#0  1  3.0  NaN
#1  2  NaN  2.0
#2  3  5.0  NaN
#3  4  NaN  1.0

df['B'] = df['B'].fillna(1)
df['C'] = df['C'].fillna(1)
df['BC'] = df['B']*df['C']

df = df[['A', 'BC']]
print(df)
#   A   BC
#0  1  3.0
#1  2  2.0
#2  3  5.0
#3  4  1.0
```

Body:
I merged two data frames together and I want to combine two pandas columns as follows:

df1:

A   B   C
1   3  NaN
2  Nan  2
3   5  NaN
4  NaN  1

I want to get a result like the following:

df1:

A   BC
1   3
2   2
3   5
4   1


问:
Identify specific element of dataframe
I'm trying to extract a pattern from a dataset in order to identify specific element in dataframe.
Here's a sample dataset that I'm using:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([['A', 'B'], ['B', 'C'], ['C', 'D'],['D', 'E'], ['D', 'F'], ['E', 'G'],['F', 'H'], ['Z', 'T'], ['T', 'M'],['V','D']]),
                   columns=['to', 'from'])
</code>```

to
from

A
B

B
C

C
D

D
E

D
F

E
G

F
H

Z
T

T
M

V
D

The table represents a series of links between elements. The meaning is that A is calculated from B, B is calculated from C, C is calculated from D, D is calculated from E and F, etc.

I'm trying to identify all the input elements given a specific element. Here's my try:

```<code>obj = 'A'
target = []
flag = True

while len(df[df['to'] == obj])>0:
    for i in range(0, len(df[df['to'] == obj])):
        for m in range(0, len(df)):
            if obj == df.loc[m,'to']:
                target.append(df.loc[m,'from'])
                obj = df.loc[m,'from']
                print(obj)

target = target[-1]
print(target)
</code>```

With that code, I obtain G as the only input element but i the main problem is that the element D is calculated from 2 elements and i can't manage to obtain G and H as input.

I hope I have been clear and comprehensive and I thank in advance anyone who can help me.

Thank you,

Giammaria

答:
This is a graph problem.  You can implement your own graph traversal algorithms if you want the exercise, but otherwise it's best to use a standard library for such tasks.

The networkx library is very easy to use and has lots of convenient functions for things like this.

```<code>import pandas as pd
import numpy as np
import networkx as nx
df = pd.DataFrame(np.array([['A', 'B'], ['B', 'C'], ['C', 'D'],['D', 'E'], ['D', 'F'], ['E', 'G'],['F', 'H'], ['Z', 'T'], ['T', 'M'],['V','D']]),
                   columns=['to', 'from'])

g = nx.DiGraph()
g.add_edges_from(df[['from', 'to']].values)
print(nx.ancestors(g, 'D'))
</code>```

The code above prints:

```<code>{'F', 'G', 'H', 'E'}
</code>```

Title: Identify specific element of dataframe

Body:
I'm trying to extract a pattern from a dataset in order to identify specific element in dataframe.
Here's a sample dataset that I'm using:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([['A', 'B'], ['B', 'C'], ['C', 'D'],['D', 'E'], ['D', 'F'], ['E', 'G'],['F', 'H'], ['Z', 'T'], ['T', 'M'],['V','D']]),
                   columns=['to', 'from'])

to
from

A
B

B
C

C
D

D
E

D
F

E
G

F
H

Z
T

T
M

V
D

The table represents a series of links between elements. The meaning is that A is calculated from B, B is calculated from C, C is calculated from D, D is calculated from E and F, etc.

I'm trying to identify all the input elements given a specific element. Here's my try:

obj = 'A'
target = []
flag = True

while len(df[df['to'] == obj])>0:
    for i in range(0, len(df[df['to'] == obj])):
        for m in range(0, len(df)):
            if obj == df.loc[m,'to']:
                target.append(df.loc[m,'from'])
                obj = df.loc[m,'from']
                print(obj)

target = target[-1]
print(target)

With that code, I obtain G as the only input element but i the main problem is that the element D is calculated from 2 elements and i can't manage to obtain G and H as input.

I hope I have been clear and comprehensive and I thank in advance anyone who can help me.

Thank you,

Giammaria

Body:
This is a graph problem.  You can implement your own graph traversal algorithms if you want the exercise, but otherwise it's best to use a standard library for such tasks.

The networkx library is very easy to use and has lots of convenient functions for things like this.

import pandas as pd
import numpy as np
import networkx as nx
df = pd.DataFrame(np.array([['A', 'B'], ['B', 'C'], ['C', 'D'],['D', 'E'], ['D', 'F'], ['E', 'G'],['F', 'H'], ['Z', 'T'], ['T', 'M'],['V','D']]),
                   columns=['to', 'from'])

g = nx.DiGraph()
g.add_edges_from(df[['from', 'to']].values)
print(nx.ancestors(g, 'D'))

The code above prints:

{'F', 'G', 'H', 'E'}


问:
Valid Parenthesis Problem Index Out of Range (Go)
I was converting code for a problem I previously solved in Python into Go and ran into a runtime error: index out of range [1] with length 1 on this line

```<code> if string(s[i]) == ")" && arr[len(s) - 1] == "("{
</code>```

Here is the code in entirety.

```<code>func isValid(s string) bool {
    arr := make([]string, 0)
    if len(s) < 2 {
        return false
    }

    for i := 0; i < len(s); i++ {

        if string(s[i]) == "(" || string(s[i]) == "[" || string(s[i]) == "{" {
            arr = append(arr, string(s[i]))
        } else if string(s[i]) == ")" || string(s[i]) == "]" || string(s[i]) == "}" {
            if len(arr) >= 1 {
                if string(s[i]) == ")" && arr[len(s) - 1] == "("{
                    arr = arr[:len(arr) -1]
                } else if string(s[i]) == "]" && arr[len(s) - 1] == "[" {
                    arr = arr[:len(arr) -1]
                } else if string(s[i]) == "}" && arr[len(s) - 1] == "{" {
                    arr = arr[:len(arr) -1]
                }  else {
                    return false
                }
            }else {
                return false
            }
    }
    }
    if reflect.DeepEqual(arr, []string{""}) {
        return true
    } else  {
        return false
    }

}

</code>```

What is the cause of the issue?

答:
You've used len(s)-1 to find the last index of arr, but it should be len(arr)-1.

Here's a working version of your code, that fixes some additional bugs, and avoids needless conversion to string for single characters. https://go.dev/play/p/sazf2RguoIr

```<code>package main

import "fmt"

func isValid(s string) bool {
    var arr []rune
    for _, c := range s {
        if c == '(' || c == '[' || c == '{' {
            arr = append(arr, c)
        } else if c == ')' || c == ']' || c == '}' {
            if len(arr) == 0 {
                return false
            }
            var last rune
            arr, last = arr[:len(arr)-1], arr[len(arr)-1]
            if c == ')' && last != '(' || c == ']' && last != '[' || c == '}' && last != '{' {
                return false
            }
        }
    }
    return len(arr) == 0
}

func main() {
    cases := []string{
        "()[({}())]",
        "(]",
        "((())",
        "{{{}}}",
        "{{{[][][]}}}",
    }
    for _, c := range cases {
        fmt.Println(c, isValid(c))
    }
}
</code>```

Body:
I was converting code for a problem I previously solved in Python into Go and ran into a runtime error: index out of range [1] with length 1 on this line

 if string(s[i]) == ")" && arr[len(s) - 1] == "("{

Here is the code in entirety.

func isValid(s string) bool {
    arr := make([]string, 0)
    if len(s) < 2 {
        return false
    }

    for i := 0; i < len(s); i++ {

        if string(s[i]) == "(" || string(s[i]) == "[" || string(s[i]) == "{" {
            arr = append(arr, string(s[i]))
        } else if string(s[i]) == ")" || string(s[i]) == "]" || string(s[i]) == "}" {
            if len(arr) >= 1 {
                if string(s[i]) == ")" && arr[len(s) - 1] == "("{
                    arr = arr[:len(arr) -1]
                } else if string(s[i]) == "]" && arr[len(s) - 1] == "[" {
                    arr = arr[:len(arr) -1]
                } else if string(s[i]) == "}" && arr[len(s) - 1] == "{" {
                    arr = arr[:len(arr) -1]
                }  else {
                    return false
                }
            }else {
                return false
            }
    }
    }
    if reflect.DeepEqual(arr, []string{""}) {
        return true
    } else  {
        return false
    }

}

What is the cause of the issue?

Body:
You've used len(s)-1 to find the last index of arr, but it should be len(arr)-1.

Here's a working version of your code, that fixes some additional bugs, and avoids needless conversion to string for single characters. https://go.dev/play/p/sazf2RguoIr

package main

import "fmt"

func isValid(s string) bool {
    var arr []rune
    for _, c := range s {
        if c == '(' || c == '[' || c == '{' {
            arr = append(arr, c)
        } else if c == ')' || c == ']' || c == '}' {
            if len(arr) == 0 {
                return false
            }
            var last rune
            arr, last = arr[:len(arr)-1], arr[len(arr)-1]
            if c == ')' && last != '(' || c == ']' && last != '[' || c == '}' && last != '{' {
                return false
            }
        }
    }
    return len(arr) == 0
}

func main() {
    cases := []string{
        "()[({}())]",
        "(]",
        "((())",
        "{{{}}}",
        "{{{[][][]}}}",
    }
    for _, c := range cases {
        fmt.Println(c, isValid(c))
    }
}


问:
How can I store a timestamp in a DBM database?
I am implemening simple file-sharing service. Currently I use a file-based database (as it suits my needs).

```<code>   # somewhere in my cgi script
   sub first_run
    {
      my $dbh = DBI->connect('dbi:DBM:');
      $dbh = DBI->connect("dbi:DBM:", "", "",{ AutoCommit => 1, RaiseError => 1, f_dir=>$DATABASE_DIR} );
      unless ($dbh)
      {
        print "<br>Cannot connect: $DBI::errstr";
        return undef;
      }
      $dbh->do("CREATE TABLE uploads( user_name TEXT,
        file_name TEXT,
        upload_date TEXT ) ");
      $dbh->disconnect( );
    }
</code>```

As you can see I propose to store the upload timestamp as a string, since currently I only have to display it (suppose to use localtime() to get timestamp in a human readable format).
But this seems to me somewhat bad. What if later I'll want to show uploads from some period, etc.

What is the common way of storing timestamps in a DBM database without using third-party, CPAN modules? How can I pull them later and show them to the user (in my situation, convert back to string)?

答:
Consider that storing UTC time is less ambiguous than storing local time. If you save a time at your computer in London and send me the file in Hong Kong, will I when I load the file in your program see the time you actually saved?

Consider that in storing UTC time you have (at least) two choices: the formatted time string, or a count of numbers of (seconds/milliseconds/whatever) since a particular time ("the epoch"). Presumably either format is isomorphic with the other, as there is a well-defined bi-directional conversion rom one to the other.

OwnerDisplayName: jonny

ContentLicense: CC BY-SA 2.5

Body:
I am implemening simple file-sharing service. Currently I use a file-based database (as it suits my needs).

   # somewhere in my cgi script
   sub first_run
    {
      my $dbh = DBI->connect('dbi:DBM:');
      $dbh = DBI->connect("dbi:DBM:", "", "",{ AutoCommit => 1, RaiseError => 1, f_dir=>$DATABASE_DIR} );
      unless ($dbh)
      {
        print "
Cannot connect: $DBI::errstr";
        return undef;
      }
      $dbh->do("CREATE TABLE uploads( user_name TEXT,
        file_name TEXT,
        upload_date TEXT ) ");
      $dbh->disconnect( );
    }

As you can see I propose to store the upload timestamp as a string, since currently I only have to display it (suppose to use localtime() to get timestamp in a human readable format).
But this seems to me somewhat bad. What if later I'll want to show uploads from some period, etc.

What is the common way of storing timestamps in a DBM database without using third-party, CPAN modules? How can I pull them later and show them to the user (in my situation, convert back to string)?

LastEditorDisplayName: brian d foy

OwnerDisplayName: tpdi


问:
Html.BeginForm() does not submit if nothing is selected in a Html.Dropdownlist() helper with optional label
```<code>@using (Html.BeginForm("Boxing", "Company",FormMethod.Post))
{
    <div class="box">
        <div>
            <div class="left">
                <div class="topLabel">
                    Id No:</div>
                <div class="input_text_65">
                    @Html.TextBoxFor(m => m.Id)
                </div>
                <div class="botLabel">
                    percentt:
                </div>
                <div>
                    <input type="text" style="width: 50px" name="percent" />%
                </div>
            </div>
            <div class="lastDetailField">
                <div class="topLabel">
                    D/C:
                </div>
                <div class="select_110">
                    @Html.DropDownListFor(m => m.cType, new SelectList((IEnumerable<Model.cType>)ViewData[ViewDataKeys.cTypes]), "----")
                </div>
                <div class="margin_top_45">
                    <input id="submit" type="submit" value="submit" />
                </div>
            </div>
        </div>
    </div>
}
</code>```

If I didn't select any option in the dropdownlist (leaving the optionlabel "----" selected) and I press the submit button, the form will not be posted and the focus will be move to the dropdownlist

if I remove the optional Label, like this:

@Html.DropDownListFor(m => m.cType, new SelectList((IEnumerable)ViewData[ViewDataKeys.cTypes]))

then it will work just fine. I'm thinking if I will put an optional label, does that mean I am required to choose an item? I want the form to be submitted even if I leave the dropdownlist with the optionallabel selected.

thanks in advance!

答: Do you have a required attribute in your model/viewmoden on cType? I think the clientside validation is kicking in, but because you didn't set a validation helper, you're not seeing the message. The form won't submit though if you select the optional label.</p>

Body:
@using (Html.BeginForm("Boxing", "Company",FormMethod.Post))
{

                    Id No:

                    @Html.TextBoxFor(m => m.Id)

                    percentt:

                    <input type="text" style="width: 50px" name="percent" />%

                    D/C:

                    @Html.DropDownListFor(m => m.cType, new SelectList((IEnumerable<Model.cType>)ViewData[ViewDataKeys.cTypes]), "----")

                    <input id="submit" type="submit" value="submit" />

}

If I didn't select any option in the dropdownlist (leaving the optionlabel "----" selected) and I press the submit button, the form will not be posted and the focus will be move to the dropdownlist

if I remove the optional Label, like this:

@Html.DropDownListFor(m => m.cType, new SelectList((IEnumerable)ViewData[ViewDataKeys.cTypes]))

then it will work just fine. I'm thinking if I will put an optional label, does that mean I am required to choose an item? I want the form to be submitted even if I leave the dropdownlist with the optionallabel selected.

thanks in advance!


问:
React Slick dots doesnt show
I using slick slider but even i add dots:true i cant see dots on my screen.

My settings :

```<code> const settings = {
    dots: true,
    customPaging: function (i) {
      return <LazyLoadImage src={productDetails.Images[i]} />; //I want image as a dot. (even i make it simple text its still doesnt show.)
    },
    dotsClass: "slick-dots slick-thumb",
    infinite: true,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1,
  };
</code>```

I installed react-slick and slick-carousel too. I import css and Slider like :

```<code>import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
</code>```

But it doesnt work. What can i do? Thanks for all responses!

Edit: I dont have overflow:hidden

答:
You pass just a string to an src attribute. Add a colon before it

```<code><LazyLoadImage :src={productDetails.Images[i]}
</code>```

Title: React Slick dots doesnt show

Body:
I using slick slider but even i add dots:true i cant see dots on my screen.

My settings :

 const settings = {
    dots: true,
    customPaging: function (i) {
      return <LazyLoadImage src={productDetails.Images[i]} />; //I want image as a dot. (even i make it simple text its still doesnt show.)
    },
    dotsClass: "slick-dots slick-thumb",
    infinite: true,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1,
  };

I installed react-slick and slick-carousel too. I import css and Slider like :

import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";

But it doesnt work. What can i do? Thanks for all responses!

Edit: I dont have overflow:hidden

Body:
You pass just a string to an src attribute. Add a colon before it

<LazyLoadImage :src={productDetails.Images[i]}


问:
SQL query - converting seconds to HH:MM:SS
I have the following query that returns a total seconds value (up to 86400 seconds (1 day))

I want to convert this to an HH:MM:SS value. Any help is appreciated.

```<code>(SELECT FIRST TSS.TotalDrivingTime
 FROM HLG01_TR_TachographShiftSummary TSS
 WHERE TSS.DriverID = TRD.DriverID
   AND (CONVERT(date, TSS.PeriodStart)) = S.LoadDate)
</code>```

答:
you can use this</p>
```<code>(Format(Int(Sum([Seconds])/3600),'00') & ':' & Format(Sum([Seconds]/86400),'nn:ss')) AS [Total Time]
</code>```

Body:
I have the following query that returns a total seconds value (up to 86400 seconds (1 day))

I want to convert this to an HH:MM:SS value. Any help is appreciated.

(SELECT FIRST TSS.TotalDrivingTime
 FROM HLG01_TR_TachographShiftSummary TSS
 WHERE TSS.DriverID = TRD.DriverID
   AND (CONVERT(date, TSS.PeriodStart)) = S.LoadDate)

Body:
you can use this

(Format(Int(Sum([Seconds])/3600),'00') & ':' & Format(Sum([Seconds]/86400),'nn:ss')) AS [Total Time]


问:
Navigating to a new page from a viewmodel
I have used the WP7 DataBound app template for my program which utilises a form of MVVM. I would like to navigate from my mainpage to my settings page but since it is the VM that loads the data, which in turn determines if the settings pages needs to be loaded, I should like to call navigate code from the VM, not the view. However, NavigationService does not show the Navigate method in the VM, only in the view.  Does anyone have any suggesions about how I can/should call the Navigate method in the VM?

Thanks,

Jason.

答:
Implement it as a static method in your App.xaml.cs, like this

```<code>public static void Navigate(Uri source)
{
    Dispatcher.BeginInvoke(() => (App.Current.RootVisual as PhoneApplicationFrame).Navigate(source));
}
</code>```

That way you can simply call App.Navigate(uri) from anywhere.

You might also want to implement GoBack():

```<code>public static void GoBack()
{
    Dispatcher.BeginInvoke(() => (App.Current.RootVisual as PhoneApplicationFrame).GoBack());
}
</code>```

Body:
Implement it as a static method in your App.xaml.cs, like this

public static void Navigate(Uri source)
{
    Dispatcher.BeginInvoke(() => (App.Current.RootVisual as PhoneApplicationFrame).Navigate(source));
}

That way you can simply call App.Navigate(uri) from anywhere.

You might also want to implement GoBack():

public static void GoBack()
{
    Dispatcher.BeginInvoke(() => (App.Current.RootVisual as PhoneApplicationFrame).GoBack());
}


问:
Amending Radio Station Wordpress Plugin - Show pages
I'm still new to wordpress so forgive me if this is a simple question.

I'm using the ['Radio Station' plugin] on my wordpress site, however the 'show' pages do not feature a side-bar. I've tried to create a child theme, and amend the coding of the 'single-show.php' page, but I'm not sure whether the basis of the page is either a post or page.

The only thing i've managed to suceed in is adding the side bar which shows right-aligned under the rest of the 'whole page' content.

Ideally, I'd like the 'show' type pages to look like the 'post' type pages.

答: This question was posted six years ago from the date of my reply. We've taken over the plugin from it's original developer. You can find the latest version at https://wordpress.org/plugins/radio-station. We also have a PRO version at https://radiostation.pro. Both free and PRO resolve the issue noted in this post.</p>


问:
spout sends tuples just to a subset of bolt instances
I'm just starting with storm. I have a simple topology of a spout (1 executor) and a bolt (4 executors). The spout and the bolt are connected via "shuffleGrouping".

From what I can see the spout sends tuples only to a subset of bolt executors - the ones that are running on the same host as the spout.

Is this expected? Is there a way to spread the load across all bolt executors no matter where they run?

答:
Sorry for digging up this old post. I had the same problem with a topology and found this post, so I want to share my research, and a/the solution.

I upgraded a topology from Apache Storm 1.0.2 to 2.2.0. Since, the spout sends tuples only to the local bolt executors despite the SHUFFLE grouping mode.

According to this post, it's seems expected, but there are a workaround :

```<code>topology.disable.loadaware.messaging: true
</code>```

See also org.apache.storm.daemon.GrouperFactory to understand how this configuration is used.

Body:
Sorry for digging up this old post. I had the same problem with a topology and found this post, so I want to share my research, and a/the solution.

I upgraded a topology from Apache Storm 1.0.2 to 2.2.0. Since, the spout sends tuples only to the local bolt executors despite the SHUFFLE grouping mode.

According to this post, it's seems expected, but there are a workaround :

topology.disable.loadaware.messaging: true

See also org.apache.storm.daemon.GrouperFactory to understand how this configuration is used.


问:
Spline interpolation in 3D in python
I am searching the equivalent Matlab command

Vq = interp3(X,Y,Z,V,Xq,Yq,Zq)

in Python. In Matlab I can use the method 'spline' interpolation, which I can not find in python for 3D data. There exists scipy.interpolate.griddata, but it doesn't have the option spline for 3D data.

The data I want to interpolate is a 3D matrix (51x51x51), which is regularly distributed on a 3D grid.

scipy.interpolate.Rbf may be the option, but I don't get it working:

xi = yi = zi = np.linspace(1, 132651, 132651)
interp = scipy.interpolate.Rbf(xi, yi, zi, data, function='cubic')

leads to a memory error.

Edit:
A minimal example of what I want (without interpolation):
Matlab code

```<code>v=rand([51,51,51]);
isosurface (v, 0.3);
</code>```

For simplicity, I use random data in this example. I want to make isosurface plots (in particular, Fermi surface plots). Since some structures are very small, a high grid resolution of 51x51x51 is needed.

A further comment: The data set in the matrix is independent from each other, z (or the 3rd component) is NOT a function of x and y.

Title: Spline interpolation in 3D in python

Body:
I am searching the equivalent Matlab command

Vq = interp3(X,Y,Z,V,Xq,Yq,Zq)

in Python. In Matlab I can use the method 'spline' interpolation, which I can not find in python for 3D data. There exists scipy.interpolate.griddata, but it doesn't have the option spline for 3D data.

The data I want to interpolate is a 3D matrix (51x51x51), which is regularly distributed on a 3D grid.

scipy.interpolate.Rbf may be the option, but I don't get it working:

xi = yi = zi = np.linspace(1, 132651, 132651)
interp = scipy.interpolate.Rbf(xi, yi, zi, data, function='cubic')

leads to a memory error.

Edit:
A minimal example of what I want (without interpolation):
Matlab code

v=rand([51,51,51]);
isosurface (v, 0.3);

For simplicity, I use random data in this example. I want to make isosurface plots (in particular, Fermi surface plots). Since some structures are very small, a high grid resolution of 51x51x51 is needed.

A further comment: The data set in the matrix is independent from each other, z (or the 3rd component) is NOT a function of x and y.

Body:
The mess example worked great.  I want to create a b spline of the data in 3d

data = np.array([[ 41. ,  57. ,  92. ],[ 39. ,  57.  , 92.4],[ 43. ,  57.  , 91.2], [ 23.,   47. , 119.6],
                 [ 27. ,  47. , 115.2], [ 25. ,  45. , 122. ], [ 25. ,  49. , 114. ],[ 29.,   49. , 109.6],
                 [ 29. ,  47. , 114.4], [ 27. ,  49. , 111.2], [ 23. ,  45. , 125.6], [ 31.,   49.,  106.8],
                 [ 25. ,  47. , 117.6], [ 39. ,  55. ,  95.6],[ 37.  , 53.  , 98.4], [ 35. ,  55. ,  96.8],
                 [ 33. ,  53. , 116.8], [ 23. ,  43. , 132.8], [ 25. ,  41. , 145.2],[ 25. ,  43.,  133.6],
                 [ 29. ,  51. , 106.4],[ 31.  , 53. , 121.2],[ 31., 51. , 104.8],[ 41.,   55.,   93.6],
                 [ 33. ,  51. , 103.6],[ 35.  , 53. ,  99.6],[ 37. ,  55. ,  96.4]])

x = data[:,0]
y = data[:,1]
z = data[:,2]

# sort data to avoid plotting problems
x, y, z = zip(*sorted(zip(x, y, z)))

x = np.array(x)
y = np.array(y)
z = np.array(z)

import scipy as sp
import scipy.interpolate
from mpl_toolkits.mplot3d import Axes3D

spline = sp.interpolate.Rbf(x,y,z,function='thin_plate',smooth=5, episilon=5)

x_grid = np.linspace(min(x),max(x), len(x))
y_grid = np.linspace(min(y),max(y), len(y))
B1, B2 = np.meshgrid(x_grid, y_grid, indexing='xy')

Z = spline(B1,B2)
fig = plt.figure(figsize=(10,6))
ax = Axes3D(fig)
ax.plot_wireframe(B1, B2, Z)
ax.plot_surface(B1, B2, Z,alpha=0.2)
ax.scatter3D(x,y,z, c='r')
plt.show()


问:
How to combine 2 or more objects in a list based on certain fields of those objects
I'm sorry if the title sounds vague.

I have an object -

```<code>    public class AccountInfo {
        private String accountId;
        private Double vat;
        private Double totalFee;
        private Date invoiceDate;
    }
</code>```

and there is a list of these objects-

```<code>List<AccountInfo> AccountInfoLst;
</code>```

I want to manipulate this list by combining objects with the same accountId by adding up the vat and totalFee fields, provided they have the same invoiceDate as well.

If two objects have the same accountId but different invoiceDate, they shouldn't be combined.

答:
Iterate over the list which are duplicate combine them to one AccountInfo and remove all the duplicates.

Since Date is deprecated we have used java.time.LocalDate.

Code:

```<code>import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class AccountInfo {
    private String accountId;

    private Double vat;
    private Double totalFee;
    private LocalDate invoiceDate;

    public Double getVat() {
        return vat;
    }

    public void setVat(Double vat) {
        this.vat = vat;
    }

    public Double getTotalFee() {
        return totalFee;
    }

    public void setTotalFee(Double totalFee) {
        this.totalFee = totalFee;
    }

    public LocalDate getInvoiceDate() {
        return invoiceDate;
    }

    public void setInvoiceDate(LocalDate invoiceDate) {
        this.invoiceDate = invoiceDate;
    }

    public AccountInfo(String accountId, Double vat, Double totalFee, LocalDate invoiceDate) {
        this.accountId = accountId;
        this.vat = vat;
        this.totalFee = totalFee;
        this.invoiceDate = invoiceDate;
    }

    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

    public String toString() {
        return accountId + " " + vat + " " + totalFee + " " + invoiceDate;
    }

    public boolean areEquals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        AccountInfo that = (AccountInfo) o;
        var thatInvoiceDate = that.getInvoiceDate();
        var thisInvoiceDate = getInvoiceDate();
        return that.getAccountId().equals(getAccountId()) && thatInvoiceDate.isEqual(thisInvoiceDate);
    }

    @Override
    public int hashCode() {
        return Objects.hash(accountId, vat, totalFee, invoiceDate);
    }
}

public class MainClass {
    public static void main(String... $) {
        var out = System.out;

        List<AccountInfo> accounts = Stream.of(new AccountInfo("A", 20.2, 200.4, LocalDate.of(2022, 11, 3))
                , new AccountInfo("A", 20.2, 200.4, LocalDate.of(2022, 11, 3)),
                new AccountInfo("B", 20.2, 200.4, LocalDate.of(2023, 11, 2)),
                new AccountInfo("B", 20.2, 200.4, LocalDate.of(2023, 11, 2))).collect(Collectors.toList());

        //Iterating over all the accounts
        for (int i = 0; i < accounts.size(); i++) {
            var account = accounts.get(i);
            ArrayList<AccountInfo> duplicates = new ArrayList<>();
            for (int j = i + 1; j < accounts.size(); j++) {
                var acc = accounts.get(j);
                if (acc.areEquals(account))
                    duplicates.add(acc);
            }
//            out.println(i + " " + indices);
            //Merging all duplicates to account
            for (AccountInfo acc : duplicates) {
                account.setTotalFee(acc.getTotalFee() + account.getTotalFee());
                account.setVat(acc.getVat() + account.getVat());
            }
            //Removing all duplicates
            accounts.removeAll(duplicates);
        }
        //printing accounts after removal of duplicates
        out.println(accounts);
    }
}
</code>```

Output:

```<code>[A 40.4 400.8 2022-11-03, B 40.4 400.8 2023-11-02]
</code>```

Body:
I'm sorry if the title sounds vague.

I have an object -

    public class AccountInfo {
        private String accountId;
        private Double vat;
        private Double totalFee;
        private Date invoiceDate;
    }

and there is a list of these objects-

List<AccountInfo> AccountInfoLst;

I want to manipulate this list by combining objects with the same accountId by adding up the vat and totalFee fields, provided they have the same invoiceDate as well.

If two objects have the same accountId but different invoiceDate, they shouldn't be combined.

Body:
Iterate over the list which are duplicate combine them to one AccountInfo and remove all the duplicates.

Since Date is deprecated we have used java.time.LocalDate.

Code:

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class AccountInfo {
    private String accountId;

    private Double vat;
    private Double totalFee;
    private LocalDate invoiceDate;

    public Double getVat() {
        return vat;
    }

    public void setVat(Double vat) {
        this.vat = vat;
    }

    public Double getTotalFee() {
        return totalFee;
    }

    public void setTotalFee(Double totalFee) {
        this.totalFee = totalFee;
    }

    public LocalDate getInvoiceDate() {
        return invoiceDate;
    }

    public void setInvoiceDate(LocalDate invoiceDate) {
        this.invoiceDate = invoiceDate;
    }

    public AccountInfo(String accountId, Double vat, Double totalFee, LocalDate invoiceDate) {
        this.accountId = accountId;
        this.vat = vat;
        this.totalFee = totalFee;
        this.invoiceDate = invoiceDate;
    }

    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

    public String toString() {
        return accountId + " " + vat + " " + totalFee + " " + invoiceDate;
    }

    public boolean areEquals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        AccountInfo that = (AccountInfo) o;
        var thatInvoiceDate = that.getInvoiceDate();
        var thisInvoiceDate = getInvoiceDate();
        return that.getAccountId().equals(getAccountId()) && thatInvoiceDate.isEqual(thisInvoiceDate);
    }

    @Override
    public int hashCode() {
        return Objects.hash(accountId, vat, totalFee, invoiceDate);
    }
}

public class MainClass {
    public static void main(String... $) {
        var out = System.out;

        List<AccountInfo> accounts = Stream.of(new AccountInfo("A", 20.2, 200.4, LocalDate.of(2022, 11, 3))
                , new AccountInfo("A", 20.2, 200.4, LocalDate.of(2022, 11, 3)),
                new AccountInfo("B", 20.2, 200.4, LocalDate.of(2023, 11, 2)),
                new AccountInfo("B", 20.2, 200.4, LocalDate.of(2023, 11, 2))).collect(Collectors.toList());

        //Iterating over all the accounts
        for (int i = 0; i < accounts.size(); i++) {
            var account = accounts.get(i);
            ArrayList<AccountInfo> duplicates = new ArrayList<>();
            for (int j = i + 1; j < accounts.size(); j++) {
                var acc = accounts.get(j);
                if (acc.areEquals(account))
                    duplicates.add(acc);
            }
//            out.println(i + " " + indices);
            //Merging all duplicates to account
            for (AccountInfo acc : duplicates) {
                account.setTotalFee(acc.getTotalFee() + account.getTotalFee());
                account.setVat(acc.getVat() + account.getVat());
            }
            //Removing all duplicates
            accounts.removeAll(duplicates);
        }
        //printing accounts after removal of duplicates
        out.println(accounts);
    }
}

Output:

[A 40.4 400.8 2022-11-03, B 40.4 400.8 2023-11-02]


问:
Trying to read a file and then write a file during a WiX install in a CustomAction
I am having a tough time with this.  There are a lot of SO articles about these settings but I'm still stuck.

My goal is to perform two steps:

Read a file that will be physically shipped with the msi.  In other words, there will be three files setup.exe, test.msi, specialFile.txt

During the install, I want to create a new file in the install path. C:\Program Files\MyCompany\MyApplication\newFile.txt

The file in step 2 is created by reading something out of specialFile.txt from step 1.

My problem is navigating the murky combinations of WiX settings to enable me to read session variables and have high enough privs to write the file out.  This has not been easy.

Here is what I've been doing:

```<code><Binary Id="MyCustomAction.CA.dll" SourceFile="path\to\MyCustomAction.CA.dll" />
<CustomAction Id="MyActionsName"
    Return="check"
    Execute="deferred"
    BinaryKey="MyCustomAction.CA.dll"
    DllEntry="MyCustomAction"
    Impersonate="no"/>

    <CustomAction Id="CustomAction1"
        Property="LookupUnattendedXML"
        Value="INSTALLFOLDER=[I_Can_Get_This_From_The_Directory_Tags];SOURCEDIR=How_To_Get_This???"/>

<InstallExecuteSequence>
    <Custom Action="CustomAction1" Before="MyActionsName" />
    <Custom Action="MyActionsName" Before="InstallFinalize">NOT Installed AND NOT PATCH</Custom>
</InstallExecuteSequence>
</code>```

impersonate="no" in order to have enough privs to write the file

Execute is "deferred" in order to have enough privs to write the file (I don't understand how this works)

The Custom tag is set to Before="InstallFinalize".  I tried other settings for this.  Before="InstallFinalize" seems to fire after the files have been installed.

Then in the C# code, I appear to need to access session to get what I need.  I ask for session["sourceDir"] to figure out where the .msi was launched from and then search for specialFile.txt  This won't work with "deferred" turned on.  I also access a Directory ID called INSTALLFOLDER which is supposed to refer to the path where the application is installed.  It appears to do that.  session["INSTALLFOLDER"]

The last wrinkle is that when I execute the .msi directly (no bootstrapper) and with deferred changed to immediate, I am able to read the session["sourceDir"] and it's really the location of the .msi as I wanted.  When I use the setup.exe bootstrapper, this same variable points to an internal System directory where it appears that the MSI was copied to.  I would like to let the user have both methods of execution (with and without the setup.exe bootstrapper) and somehow be able to access these paths.

UPDATE:

This article and this article about custom properties in deferred actions have enabled me to read the install folder in the custom action (now I know where to write the file to).  A remaining challenge is figuring out the location of the MSI so I can read the file without using session["SourceDir"] because the Custom Action is deferred.

答:
This would have solved the issue:

```<code><Binary Id="MyCustomAction.CA.dll" SourceFile="path\to\MyCustomAction.CA.dll" />
<CustomAction Id="MyActionsName"
    Return="check"
    Execute="deferred"
    BinaryKey="MyCustomAction.CA.dll"
    DllEntry="MyCustomAction"
    Impersonate="no"/>

    <CustomAction Id="MyActionsName.CustomActionData"
        Property="MyActionsName" <!-- this is important -->
        Value="INSTALLFOLDER=[I_Can_Get_This_From_The_Directory_Tags];SOURCEDIR=[SOURCEDIR];ORIGINALDATABASE=[OriginalDatabase]"/>

<InstallExecuteSequence>
    <Custom Action="MyActionsName.CustomActionData" Before="MyActionsName" />
    <Custom Action="MyActionsName" Before="InstallFinalize">NOT Installed AND NOT PATCH</Custom>
</InstallExecuteSequence>
</code>```

In the custom action you can access the data set in MyActionsName.CustomActionData via session.CustomActionData["propertyname"]

In general you have to pass each variable/property you want to use of the 'normal' installation explicitly to the deferred custom action to show up in CustomActionData.

I've just seen that I'm very late. But maybe someone else will find this helpful.

Body:
I am having a tough time with this.  There are a lot of SO articles about these settings but I'm still stuck.

My goal is to perform two steps:

Read a file that will be physically shipped with the msi.  In other words, there will be three files setup.exe, test.msi, specialFile.txt

During the install, I want to create a new file in the install path. C:\Program Files\MyCompany\MyApplication\newFile.txt

The file in step 2 is created by reading something out of specialFile.txt from step 1.

My problem is navigating the murky combinations of WiX settings to enable me to read session variables and have high enough privs to write the file out.  This has not been easy.

Here is what I've been doing:

<Binary Id="MyCustomAction.CA.dll" SourceFile="path\to\MyCustomAction.CA.dll" />
<CustomAction Id="MyActionsName"
    Return="check"
    Execute="deferred"
    BinaryKey="MyCustomAction.CA.dll"
    DllEntry="MyCustomAction"
    Impersonate="no"/>

    <CustomAction Id="CustomAction1"
        Property="LookupUnattendedXML"
        Value="INSTALLFOLDER=[I_Can_Get_This_From_The_Directory_Tags];SOURCEDIR=How_To_Get_This???"/>

<InstallExecuteSequence>
    <Custom Action="CustomAction1" Before="MyActionsName" />
    <Custom Action="MyActionsName" Before="InstallFinalize">NOT Installed AND NOT PATCH</Custom>
</InstallExecuteSequence>

impersonate="no" in order to have enough privs to write the file

Execute is "deferred" in order to have enough privs to write the file (I don't understand how this works)

The Custom tag is set to Before="InstallFinalize".  I tried other settings for this.  Before="InstallFinalize" seems to fire after the files have been installed.

Then in the C# code, I appear to need to access session to get what I need.  I ask for session["sourceDir"] to figure out where the .msi was launched from and then search for specialFile.txt  This won't work with "deferred" turned on.  I also access a Directory ID called INSTALLFOLDER which is supposed to refer to the path where the application is installed.  It appears to do that.  session["INSTALLFOLDER"]

The last wrinkle is that when I execute the .msi directly (no bootstrapper) and with deferred changed to immediate, I am able to read the session["sourceDir"] and it's really the location of the .msi as I wanted.  When I use the setup.exe bootstrapper, this same variable points to an internal System directory where it appears that the MSI was copied to.  I would like to let the user have both methods of execution (with and without the setup.exe bootstrapper) and somehow be able to access these paths.

UPDATE:

This article and this article about custom properties in deferred actions have enabled me to read the install folder in the custom action (now I know where to write the file to).  A remaining challenge is figuring out the location of the MSI so I can read the file without using session["SourceDir"] because the Custom Action is deferred.

Body:
This would have solved the issue:

<Binary Id="MyCustomAction.CA.dll" SourceFile="path\to\MyCustomAction.CA.dll" />
<CustomAction Id="MyActionsName"
    Return="check"
    Execute="deferred"
    BinaryKey="MyCustomAction.CA.dll"
    DllEntry="MyCustomAction"
    Impersonate="no"/>

    <CustomAction Id="MyActionsName.CustomActionData"
        Property="MyActionsName" <!-- this is important -->
        Value="INSTALLFOLDER=[I_Can_Get_This_From_The_Directory_Tags];SOURCEDIR=[SOURCEDIR];ORIGINALDATABASE=[OriginalDatabase]"/>

<InstallExecuteSequence>
    <Custom Action="MyActionsName.CustomActionData" Before="MyActionsName" />
    <Custom Action="MyActionsName" Before="InstallFinalize">NOT Installed AND NOT PATCH</Custom>
</InstallExecuteSequence>

In the custom action you can access the data set in MyActionsName.CustomActionData via session.CustomActionData["propertyname"]

In general you have to pass each variable/property you want to use of the 'normal' installation explicitly to the deferred custom action to show up in CustomActionData.

I've just seen that I'm very late. But maybe someone else will find this helpful.


问:
How can nomad' job from local docker images
nomad docker image will be fetched from Docker Hub.But I have want use some local images.How can I use theme.(I dont want to use private repo)

Example I want to use local image test

> docker images
REPOSITORY                         TAG                 IMAGE ID            CREATED             SIZE
test                        latest              da795ca8a32f        36 minutes ago      567MB
```

```job "test" {
  datacenters = ["dc1"]

  group "example" {
    task "test" {
      driver = "docker"

      config {
        image = "test"
      }

      resources {
        cpu = 500
        memory = 256
      }
    }
  }
}

```

It's wrong !

答:
While @Miao1007 s answer works, you need to be aware of one thing. It seems that you you cannot use the tag latest or omit the tag altogether ( see the discussion here). You need to tag your docker build with some version number like

```<code>sudo docker build --tag dokr:1.0.0 .
sudo docker save dokr:1.0.0 > dokr-1.0.0.tar

then use the following in the job file
artifact {
    source = "http://localhost:8000/dokr-1.0.0.tar"
}
config {
    load = "go-docker-dokr-1.0.0.tar"
    image = "go-docker-dokr:1.0.0"
}
</code>```

Body:
nomad docker image will be fetched from Docker Hub.But I have want use some local images.How can I use theme.(I dont want to use private repo)

Example I want to use local image test

> docker images
REPOSITORY                         TAG                 IMAGE ID            CREATED             SIZE
test                        latest              da795ca8a32f        36 minutes ago      567MB

job "test" {
  datacenters = ["dc1"]

  group "example" {
    task "test" {
      driver = "docker"

      config {
        image = "test"
      }

      resources {
        cpu = 500
        memory = 256
      }
    }
  }
}

It's wrong !

Body:
While @Miao1007 s answer works, you need to be aware of one thing. It seems that you you cannot use the tag latest or omit the tag altogether ( see the discussion here). You need to tag your docker build with some version number like

sudo docker build --tag dokr:1.0.0 .
sudo docker save dokr:1.0.0 > dokr-1.0.0.tar

then use the following in the job file
artifact {
    source = "http://localhost:8000/dokr-1.0.0.tar"
}
config {
    load = "go-docker-dokr-1.0.0.tar"
    image = "go-docker-dokr:1.0.0"
}


问:
How do I work with an array object in PHP?
I have a Laravel site I am modifying, but there are some parts of the PHP code I don't quite understand, which are "array objects" or "object arrays". You see, I don't even know what to call them and so can't find a tutorial or basic data on it. Below is the code that I am dealing with:

```<code> private function parseMetric($result, $view)
    {
        $data = collect([]);

        $result->each(function($item) use ($data, $view) {
            if (isset($item->metric->{$view})) {
                $data->push((object)[
                    'label' => $item->metric->{$view},
                    'value' => $item->metric->count
                ]);
            }
        });
...
</code>```

From what I can tell, this creates an object out of $result. If I json_encode this and echo it out I get this:

```<code> [{"label":"1k-25k","value":14229},
{"label":"1mm+","value":1281},
{"label":"25k-50k","value":398},
{"label":"50k-75k","value":493},
{"label":"75k-100k","value":3848},
{"label":"100k-150k","value":9921},
{"label":"150k-200k","value":4949},
{"label":"200k-250k","value":3883},
{"label":"250k-300k","value":2685},
{"label":"300k-350k","value":2744},
{"label":"350k-500k","value":4526},
{"label":"500k-1mm","value":8690}]

</code>```

Now this is obviously an array of arrays... or is it? Is it an array of objects? Or is it an object containing arrays? But the most important question is, how do I access and move or change the individual objects/arrays in this object? For example, I want to take the second object/array, which is:

```<code>{"label":"1mm+","value":1281}
</code>```

and move it to the end. How do I do that? How do I find it? I used the following piece of code to find it which is pretty clunky:

```<code>$pos = strpos(json_encode($result), '1mm+');
        if($pos){
            Log::debug('Enrich 73, I found it!!!!!!!!!!!!!!!!!!!!!!!!!!!');
        }
</code>```

And once I find it, how do I move that array/object to the end of the whole object?

And finally, where can I find some kind of tutorial, or documentation, that describes this construct and how to work with it?

答:
There is no need to json_encode the data. Since the data is an instance of Laravel Collection, you can manipulate it like so

```<code>$item = $data->firstWhere('label', '1mm+'); // get the item
$data = $data->filter(fn($value, $key) => $value->label !== '1mm+') // remove $item from $data
             ->push($item); // move $item to the end of data
</code>```

Body:
I have a Laravel site I am modifying, but there are some parts of the PHP code I don't quite understand, which are "array objects" or "object arrays". You see, I don't even know what to call them and so can't find a tutorial or basic data on it. Below is the code that I am dealing with:

 private function parseMetric($result, $view)
    {
        $data = collect([]);

        $result->each(function($item) use ($data, $view) {
            if (isset($item->metric->{$view})) {
                $data->push((object)[
                    'label' => $item->metric->{$view},
                    'value' => $item->metric->count
                ]);
            }
        });
...

From what I can tell, this creates an object out of $result. If I json_encode this and echo it out I get this:

 [{"label":"1k-25k","value":14229},
{"label":"1mm+","value":1281},
{"label":"25k-50k","value":398},
{"label":"50k-75k","value":493},
{"label":"75k-100k","value":3848},
{"label":"100k-150k","value":9921},
{"label":"150k-200k","value":4949},
{"label":"200k-250k","value":3883},
{"label":"250k-300k","value":2685},
{"label":"300k-350k","value":2744},
{"label":"350k-500k","value":4526},
{"label":"500k-1mm","value":8690}]

Now this is obviously an array of arrays... or is it? Is it an array of objects? Or is it an object containing arrays? But the most important question is, how do I access and move or change the individual objects/arrays in this object? For example, I want to take the second object/array, which is:

{"label":"1mm+","value":1281}

and move it to the end. How do I do that? How do I find it? I used the following piece of code to find it which is pretty clunky:

$pos = strpos(json_encode($result), '1mm+');
        if($pos){
            Log::debug('Enrich 73, I found it!!!!!!!!!!!!!!!!!!!!!!!!!!!');
        }

And once I find it, how do I move that array/object to the end of the whole object?

And finally, where can I find some kind of tutorial, or documentation, that describes this construct and how to work with it?

Body:
There is no need to json_encode the data. Since the data is an instance of Laravel Collection, you can manipulate it like so

$item = $data->firstWhere('label', '1mm+'); // get the item
$data = $data->filter(fn($value, $key) => $value->label !== '1mm+') // remove $item from $data
             ->push($item); // move $item to the end of data


问:
Check date between two other dates spring data jpa
I have this model:

```<code>public class Event {
    private String name;
    private Date start;
    private Date end;
}
</code>```

and repository as

```<code>@Repository
public interface EventRepository extends JpaRepository<Event, Long> {
    List<Event> findByEventTypeAccount(Account account);
}
</code>```

What I want to do is, I will pass one date and need to check that date is between start and end e.g. (I will pass Sept 30 as date and need to find all entries which have Sept 30 between their start and end)

Something like findDateisBetweenStartAndEnd(Date date)?

答:
You can use JpaRepository</p>
```<code>List<Entity> findByColumnDateBetween(LocalDateTime to, LocalDateTime from);
</code>```

Body:
I have this model:

public class Event {
    private String name;
    private Date start;
    private Date end;
}

and repository as

@Repository
public interface EventRepository extends JpaRepository<Event, Long> {
    List<Event> findByEventTypeAccount(Account account);
}

What I want to do is, I will pass one date and need to check that date is between start and end e.g. (I will pass Sept 30 as date and need to find all entries which have Sept 30 between their start and end)

Something like findDateisBetweenStartAndEnd(Date date)?

Body:
You can use JpaRepository

List<Entity> findByColumnDateBetween(LocalDateTime to, LocalDateTime from);


问:
How to alert via email in Ansible
I have setup a mail task in ansible to send emails if yum update is marked as 'changed'.

Here is my current working code:

```<code>- name: Send mail alert if updated
      community.general.mail:
        to:
        - 'recipient1'
        cc:
        - 'recipient2'
        subject: Update Alert
        body: 'Ansible Tower Updates have been applied on the following system: {{ ansible_hostname }}'
        sender: "ansible.updates@domain.com"
      delegate_to: localhost
      when: yum_update.changed
</code>```

This works great, however, every system that gets updated per host group sends a separate email. Last night for instance I had a group of 20 servers update and received 20 separate emails. I'm aware of why this happens, but my question is how would I script this to add all the systems to one email? Is that even possible or should I just alert that the group was updated and inform teams of what servers are in each group? (I'd prefer not to take the second option)

Edit 1:

I have added the code suggested and am now unable to receive any emails. Here's the error message:

```<code>"msg": "The conditional check '_changed|length > 0' failed. The error was: error while evaluating conditional (_changed|length > 0): {{ hostvars|dict2items| selectattr('value.yum_update.changed')| map(attribute='key')|list }}: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'yum_update'\n\nThe error appears to be in '/tmp/bwrap_1073_o8ibkgrl/awx_1073_0eojw5px/project/yum-update-ent_template_servers.yml': line 22, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - name: Send mail alert if updated\n      ^ here\n",
</code>```

I am also attaching my entire playbook for reference:

```<code>---
- name: Update enterprise template servers
  hosts: ent_template_servers

  tasks:

    - name: Update all packages
      yum:
        name: '*'
        state: latest
      register: yum_update

    - name: Reboot if needed
      import_tasks: /usr/share/ansible/tasks/reboot-if-needed-centos.yml

    - name: Kernel Cleanup
      import_tasks: /usr/share/ansible/tasks/kernel-cleanup.yml

    - debug:
        var: yum_update.changed

    - name: Send mail alert if updated
      community.general.mail:
        to:
        - 'email@domain.com'
        subject: Update Alert
        body: |-
          Updates have been applied on the following system(s):
          {{ _changed }}
        sender: "ansible.updates@domain.com"
      delegate_to: localhost
      run_once: true
      when: _changed|length > 0
      vars:
        _changed: "{{ hostvars|dict2items|
                      selectattr('yum_update.changed')|
                      map(attribute='key')|list }}"

...
</code>```

Ansible version is: 2.9.27
Ansible Tower version is: 3.8.3

Thanks in advance!

答:
For example, the mail task below

    - debug:
        var: yum_update.changed
    - community.general.mail:
        sender: ansible
        to: root
        subject: Update Alert
        body: |-
          Updates have been applied to the following system:
          {{ _changed }}
      delegate_to: localhost
      run_once: true
      when: _changed|length > 0
      vars:
        _changed: "{{ hostvars|dict2items|
                      selectattr('value.yum_update.changed')|
                      map(attribute='key')|list }}"
```
<pre class="lang-yaml prettyprint-override"><code>TASK [debug] ***************************************************************
ok: [host01] =>
  yum_update.changed: true
ok: [host02] =>
  yum_update.changed: false
ok: [host03] =>
  yum_update.changed: true

TASK [community.general.mail] **********************************************
ok: [host01 -> localhost]
</code>```

will send

From: ansible@domain.com
To: root@domain.com
Cc:
Subject: Update Alert
Date: Wed, 09 Feb 2022 16:55:47 +0100
X-Mailer: Ansible mail module

Updates have been applied to the following system:
['host01', 'host03']
```
<p>Remove the condition below if you want to receive also empty lists</p>
<pre class="lang-yaml prettyprint-override"><code>      when: _changed|length > 0
</code>```

Debug

'ansible.vars.hostvars.HostVarsVars object' has no attribute 'yum_update'

Q: "What I could try?"

A: Some of the hosts are missing the variables yum_update. You can test it

    - debug:
        msg: "{{ hostvars|dict2items|
                 selectattr('value.yum_update.changed')|
                 map(attribute='key')|list }}"
      run_once: true
```
<p>Either make sure that the variable is defined on all hosts or use <em>json_query</em>. This filter tolerates missing attributes, e.g.</p>
<pre class="lang-yaml prettyprint-override"><code>    - debug:
        msg: "{{ hostvars|dict2items|
                 json_query('[?value.yum_update.changed].key') }}"
      run_once: true
</code>```

Q: "The 'debug' task prior to the 'mail' task gives me the same output. But it fails when the 'mail' task is executed."

A: Minimize the code and isolate the problem. For example, in the code below you can see

Variable yum_update.changed is missing on host03

The filter json_query ignores this

The filter selectattr fails

    - debug:
        var: yum_update.changed

    - debug:
        msg: "{{ hostvars|dict2items|
                 json_query('[?value.yum_update.changed].key') }}"
      run_once: true

    - debug:
        msg: "{{ hostvars|dict2items|
                 selectattr('value.yum_update.changed')|
                 map(attribute='key')|list }}"
      run_once: true
```
<p>gives</p>
<pre class="lang-yaml prettyprint-override"><code>TASK [debug] **************************************************
ok: [host01] =>
  yum_update.changed: true
ok: [host02] =>
  yum_update.changed: false
ok: [host03] =>
  yum_update.changed: VARIABLE IS NOT DEFINED!

TASK [debug] **************************************************
ok: [host01] =>
  msg:
  - host01

TASK [debug] **************************************************
fatal: [host01]: FAILED! =>
  msg: |-
    The task includes an option with an undefined variable.
    The error was: 'ansible.vars.hostvars.HostVarsVars object'
    has no attribute 'yum_update'
</code>```

Both filters give the same results if all variables are present

TASK [debug] **************************************************
ok: [host01] =>
  yum_update.changed: true
ok: [host02] =>
  yum_update.changed: false
ok: [host03] =>
  yum_update.changed: true

TASK [debug] **************************************************
ok: [host01] =>
  msg:
  - host01
  - host03

TASK [debug] **************************************************
ok: [host01] =>
  msg:
  - host01
  - host03
```

Title: How to alert via email in Ansible

Body:
I have setup a mail task in ansible to send emails if yum update is marked as 'changed'.

Here is my current working code:

- name: Send mail alert if updated
      community.general.mail:
        to:
        - 'recipient1'
        cc:
        - 'recipient2'
        subject: Update Alert
        body: 'Ansible Tower Updates have been applied on the following system: {{ ansible_hostname }}'
        sender: "ansible.updates@domain.com"
      delegate_to: localhost
      when: yum_update.changed

This works great, however, every system that gets updated per host group sends a separate email. Last night for instance I had a group of 20 servers update and received 20 separate emails. I'm aware of why this happens, but my question is how would I script this to add all the systems to one email? Is that even possible or should I just alert that the group was updated and inform teams of what servers are in each group? (I'd prefer not to take the second option)

Edit 1:

I have added the code suggested and am now unable to receive any emails. Here's the error message:

"msg": "The conditional check '_changed|length > 0' failed. The error was: error while evaluating conditional (_changed|length > 0): {{ hostvars|dict2items| selectattr('value.yum_update.changed')| map(attribute='key')|list }}: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'yum_update'\n\nThe error appears to be in '/tmp/bwrap_1073_o8ibkgrl/awx_1073_0eojw5px/project/yum-update-ent_template_servers.yml': line 22, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - name: Send mail alert if updated\n      ^ here\n",

I am also attaching my entire playbook for reference:

---
- name: Update enterprise template servers
  hosts: ent_template_servers

  tasks:

    - name: Update all packages
      yum:
        name: '*'
        state: latest
      register: yum_update

    - name: Reboot if needed
      import_tasks: /usr/share/ansible/tasks/reboot-if-needed-centos.yml

    - name: Kernel Cleanup
      import_tasks: /usr/share/ansible/tasks/kernel-cleanup.yml

    - debug:
        var: yum_update.changed

    - name: Send mail alert if updated
      community.general.mail:
        to:
        - 'email@domain.com'
        subject: Update Alert
        body: |-
          Updates have been applied on the following system(s):
          {{ _changed }}
        sender: "ansible.updates@domain.com"
      delegate_to: localhost
      run_once: true
      when: _changed|length > 0
      vars:
        _changed: "{{ hostvars|dict2items|
                      selectattr('yum_update.changed')|
                      map(attribute='key')|list }}"

...

Ansible version is: 2.9.27
Ansible Tower version is: 3.8.3

Thanks in advance!

Body:
For example, the mail task below

    - debug:
        var: yum_update.changed
    - community.general.mail:
        sender: ansible
        to: root
        subject: Update Alert
        body: |-
          Updates have been applied to the following system:
          {{ _changed }}
      delegate_to: localhost
      run_once: true
      when: _changed|length > 0
      vars:
        _changed: "{{ hostvars|dict2items|
                      selectattr('value.yum_update.changed')|
                      map(attribute='key')|list }}"

TASK [debug] ***************************************************************
ok: [host01] =>
  yum_update.changed: true
ok: [host02] =>
  yum_update.changed: false
ok: [host03] =>
  yum_update.changed: true

TASK [community.general.mail] **********************************************
ok: [host01 -> localhost]

will send

From: ansible@domain.com
To: root@domain.com
Cc:
Subject: Update Alert
Date: Wed, 09 Feb 2022 16:55:47 +0100
X-Mailer: Ansible mail module

Updates have been applied to the following system:
['host01', 'host03']

Remove the condition below if you want to receive also empty lists

      when: _changed|length > 0

Debug

'ansible.vars.hostvars.HostVarsVars object' has no attribute 'yum_update'

Q: "What I could try?"

A: Some of the hosts are missing the variables yum_update. You can test it

    - debug:
        msg: "{{ hostvars|dict2items|
                 selectattr('value.yum_update.changed')|
                 map(attribute='key')|list }}"
      run_once: true

Either make sure that the variable is defined on all hosts or use json_query. This filter tolerates missing attributes, e.g.

    - debug:
        msg: "{{ hostvars|dict2items|
                 json_query('[?value.yum_update.changed].key') }}"
      run_once: true

Q: "The 'debug' task prior to the 'mail' task gives me the same output. But it fails when the 'mail' task is executed."

A: Minimize the code and isolate the problem. For example, in the code below you can see

Variable yum_update.changed is missing on host03

The filter json_query ignores this

The filter selectattr fails

    - debug:
        var: yum_update.changed

    - debug:
        msg: "{{ hostvars|dict2items|
                 json_query('[?value.yum_update.changed].key') }}"
      run_once: true

    - debug:
        msg: "{{ hostvars|dict2items|
                 selectattr('value.yum_update.changed')|
                 map(attribute='key')|list }}"
      run_once: true

gives

TASK [debug] **************************************************
ok: [host01] =>
  yum_update.changed: true
ok: [host02] =>
  yum_update.changed: false
ok: [host03] =>
  yum_update.changed: VARIABLE IS NOT DEFINED!

TASK [debug] **************************************************
ok: [host01] =>
  msg:
  - host01

TASK [debug] **************************************************
fatal: [host01]: FAILED! =>
  msg: |-
    The task includes an option with an undefined variable.
    The error was: 'ansible.vars.hostvars.HostVarsVars object'
    has no attribute 'yum_update'

Both filters give the same results if all variables are present

TASK [debug] **************************************************
ok: [host01] =>
  yum_update.changed: true
ok: [host02] =>
  yum_update.changed: false
ok: [host03] =>
  yum_update.changed: true

TASK [debug] **************************************************
ok: [host01] =>
  msg:
  - host01
  - host03

TASK [debug] **************************************************
ok: [host01] =>
  msg:
  - host01
  - host03


问:
How can I refresh the SwiftUI coreData @FetchRequest result?
I am using coreData and loading my model using the following:

```<code>@FetchRequest(sortDescriptors: [NSSortDescriptor(key: "dateAdded_", ascending: false)], animation: .default)
private var items: FetchedResults<Item>
</code>```

The problem is when I update the one-many relation of an item and saveContext on main thread, the view is not refreshed.  I'm assuming the changes to the relations are not observed.

```<code>item.addToItemRelations(itemRelation)
try? context.save()
</code>```

I don't think I will be able to make this work consistently using toggle's and other hacks.  Just wondering if there is anyway to force the @FetchRequest to fetch the entire result again?

答:
If you want so show the child records then you'll need another @FetchRequest to monitor the changes of the entity of the related records using the inverse relation and parent object in the predicate. You need a child view that you supply parent item and another child view within that you init with a FetchRequest. The reason for the wrapper View is explained in this answer to a different question.

If you just want to show a computation of the child records, e.g. a count or sum, then you can first implement that using a derived attribute in the model editor. Then after the save call context.refresh(item, mergeChanges:true) and it'll reload in the object and since the derived attribute is different the @FetchRequest should detect it and cause body to be invoked.

Body:
I am using coreData and loading my model using the following:

@FetchRequest(sortDescriptors: [NSSortDescriptor(key: "dateAdded_", ascending: false)], animation: .default)
private var items: FetchedResults<Item>

The problem is when I update the one-many relation of an item and saveContext on main thread, the view is not refreshed.  I'm assuming the changes to the relations are not observed.

item.addToItemRelations(itemRelation)
try? context.save()

I don't think I will be able to make this work consistently using toggle's and other hacks.  Just wondering if there is anyway to force the @FetchRequest to fetch the entire result again?


问:
Div overlaps another div
My layout is supposed to unfold the three images when I press the switch, but at the moment it slips out completely and I can't find the error at all.

The Body the big div that encloses everything.

I know this is a lot of of code, but I think it is necessary to see everything that is included. I've played around with float and positions, but so far nothing has really worked and it's still been kicked out.
If necessary, I can also provide the entire file as a zip, which then only needs to be used on Xampp or similar, as the document also contains a lot of PHP.

If anyone knows where exactly the problem lies, I would be very grateful, because at the moment I don't really know.

body.hg {
  background-image: linear-gradient(#00aaff, #ffa64d);
  background-color: orange;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Hauptdivcontainer */

div.haupt {
  background: #F8FCFF;
  max-width: 1000px;
  mix-height: 500px;
  margin: 0 auto;
  border: solid #000000;
  box-shadow: 5px 0px 30px 0px #000000;
}

div.jtzt {
  background: #D8F0FF;
  min-height: 200px;
  max-width: 100%;
  border: 1px thin #290A0A;
  box-shadow: 0px 0px 3px 2px #1E1E1E;
  margin: 40px 0;
}

h3.bewirb {
  text-align: center;
  padding: 10px;
  margin-bottom: 20px;
  font-size: 20px;
  color: #000939;
}

/* Switcher */

.containerino {
  text-align: center;
  justify-content: center;
  align-items: center;
}

.switcher {
  display: inline-block;
  height: 34px;
  position: relative;
  width: 60px;
}

.switcher input {
  display: none;
}

.sliderding {
  background-color: #9B2022;
  bottom: 0;
  cursor: pointer;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  transition: .4s;
}

.sliderding:before {
  background-color: #FFFFFF;
  bottom: 4px;
  content: "";
  height: 26px;
  left: 4px;
  position: absolute;
  z-index: 2;
  transition: .4s;
  width: 26px;
}

input:checked+.sliderding {
  background-color: #66bb6a;
}

input:checked+.sliderding:before {
  background-color: #000000;
  transform: translateX(26px);
}

.sliderding.round {
  border-radius: 34px;
}

.sliderding.round:before {
  border-radius: 50%;
}

div.uploaddiv {
  position: inherit;
  display: none;
  margin-top: 150px;
  justify-content: center;
  float: inherit;
  left: 90%;
}

/* Uploaddinger */

.center {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  border-radius: 3px;
  box-shadow: 8px 10px 15px 0 rgba(0, 0, 0, 0.2);
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  flex-direction: column;
  margin: 30px;
}

.title {
  width: 100%;
  height: 50px;
  border-bottom: 1px solid #999;
  text-align: center;
  margin: 0 auto;
}

h1.upload {
  font-size: 16px;
  font-weight: 300;
  color: #666;
}

.dropzone {
  width: 100px;
  height: 80px;
  border: 1px dashed #999;
  border-radius: 3px;
  text-align: center;
}

.upload-icon {
  margin: 25px 2px 2px 2px;
}

.upload-input {
  position: relative;
  top: -62px;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}

.btn {
  display: block;
  width: 140px;
  height: 40px;
  background: darkmagenta;
  color: #fff;
  border-radius: 3px;
  border: 0;
  box-shadow: 0 3px 0 0 hotpink;
  transition: all 0.3s ease-in-out;
  font-size: 14px;
}

.btn:hover {
  background: rebeccapurple;
  box-shadow: 0 3px 0 0 deeppink;
}

/* default-Zustand */

/* bei gesetztem Haken wird der Inhalt eingeblendet */

input.checkbox:checked~div.uploaddiv {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="jtzt">
  <h3 class="bewirb">Bewirb dich jetzt!</h3>
  <div class="containerino">s
    <label class="switcher" for="checkbox">
        <input class="checkbox" type="checkbox" id="checkbox" />
        <div class="sliderding round"></div>

            <div class="uploaddiv">

                <div class="center">
                    <div class="title">
                        <h1 class="upload">Drop file to upload</h1>
                    </div>

                        <div class="dropzone">
                              <img src="http://100dayscss.com/codepen/upload.svg" class="upload-icon" />
                              <input type="file" class="upload-input" />
                        </div>

                        <button type="button" class="btn" name="uploadbutton">Anschreiben</button>
                </div>

                <div class="center">
                    <div class="title">
                        <h1 class="upload">Drop file to upload</h1>
                    </div>

                        <div class="dropzone">
                              <img src="http://100dayscss.com/codepen/upload.svg" class="upload-icon" />
                              <input type="file" class="upload-input" />
                        </div>

                        <button type="button" class="btn" name="uploadbutton">Lebenslauf</button>
                </div>

                <div class="center">
                    <div class="title">
                        <h1 class="upload">Drop file to upload</h1>
                    </div>

                        <div class="dropzone">
                              <img src="http://100dayscss.com/codepen/upload.svg" class="upload-icon" />
                              <input type="file" class="upload-input" />
                        </div>

                        <button type="button" class="btn" name="uploadbutton">Zeugnisse</button>
                </div>
           </div>
    </label>
  </div>
</div></code>```

答:
It works now.

input[type=checkbox] {
  height: 0;
  width: 0;
  visibility: hidden;
}

label {
  cursor: pointer;
  text-indent: -9999px;
  width: 70px;
  height: 30px;
  background: #8B0000;
  display: block;
  border-radius: 100px;
  position: relative;
  margin-left: 450px;
}

label:after {
  content: '';
  position: absolute;
  top: 1px;
  left: 2px;
  width: 28px;
  height: 28px;
  background: #000;
  border-radius: 90px;
  transition: 0.3s;
}

input:checked+label {
  background: #bada55;
}

input:checked+label:after {
  left: calc(100% - 2px);
  transform: translateX(-100%);
  background: #fff;
}

div.uploaddiv {
  position: inherit;
  display: none;
  margin-top: 150px;
  margin-left: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="jtzt">
  <h3 class="bewirb">Bewirb dich jetzt!</h3>

  <input type="checkbox" id="switch" style="padding-left: 10000px" />
  <label for="switch">Toggle</label>

  <div class="uploaddiv">
    <div class="center">
      <div class="title">
        <h1 class="upload">Drop file to upload</h1>
      </div>

      <div class="dropzone">
        <img src="http://100dayscss.com/codepen/upload.svg" class="upload-icon" />
        <input type="file" class="upload-input" />
      </div>

      <button type="button" class="btn" name="uploadbutton">Anschreiben</button>
    </div>

    <div class="center">
      <div class="title">
        <h1 class="upload">Drop file to upload</h1>
      </div>

      <div class="dropzone">
        <img src="http://100dayscss.com/codepen/upload.svg" class="upload-icon" />
        <input type="file" class="upload-input" />
      </div>

      <button type="button" class="btn" name="uploadbutton">Lebenslauf</button>
    </div>

    <div class="center">
      <div class="title">
        <h1 class="upload">Drop file to upload</h1>
      </div>

      <div class="dropzone">
        <img src="http://100dayscss.com/codepen/upload.svg" class="upload-icon" />
        <input type="file" class="upload-input" />
      </div>

      <button type="button" class="btn" name="uploadbutton">Zeugnisse</button>
    </div>
  </div>
</div></code>```

Title: Div overlaps another div

Body:
My layout is supposed to unfold the three images when I press the switch, but at the moment it slips out completely and I can't find the error at all.

The Body the big div that encloses everything.

I know this is a lot of of code, but I think it is necessary to see everything that is included. I've played around with float and positions, but so far nothing has really worked and it's still been kicked out.
If necessary, I can also provide the entire file as a zip, which then only needs to be used on Xampp or similar, as the document also contains a lot of PHP.

If anyone knows where exactly the problem lies, I would be very grateful, because at the moment I don't really know.

body.hg {
  background-image: linear-gradient(#00aaff, #ffa64d);
  background-color: orange;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Hauptdivcontainer */

div.haupt {
  background: #F8FCFF;
  max-width: 1000px;
  mix-height: 500px;
  margin: 0 auto;
  border: solid #000000;
  box-shadow: 5px 0px 30px 0px #000000;
}

div.jtzt {
  background: #D8F0FF;
  min-height: 200px;
  max-width: 100%;
  border: 1px thin #290A0A;
  box-shadow: 0px 0px 3px 2px #1E1E1E;
  margin: 40px 0;
}

h3.bewirb {
  text-align: center;
  padding: 10px;
  margin-bottom: 20px;
  font-size: 20px;
  color: #000939;
}

/* Switcher */

.containerino {
  text-align: center;
  justify-content: center;
  align-items: center;
}

.switcher {
  display: inline-block;
  height: 34px;
  position: relative;
  width: 60px;
}

.switcher input {
  display: none;
}

.sliderding {
  background-color: #9B2022;
  bottom: 0;
  cursor: pointer;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  transition: .4s;
}

.sliderding:before {
  background-color: #FFFFFF;
  bottom: 4px;
  content: "";
  height: 26px;
  left: 4px;
  position: absolute;
  z-index: 2;
  transition: .4s;
  width: 26px;
}

input:checked+.sliderding {
  background-color: #66bb6a;
}

input:checked+.sliderding:before {
  background-color: #000000;
  transform: translateX(26px);
}

.sliderding.round {
  border-radius: 34px;
}

.sliderding.round:before {
  border-radius: 50%;
}

div.uploaddiv {
  position: inherit;
  display: none;
  margin-top: 150px;
  justify-content: center;
  float: inherit;
  left: 90%;
}

/* Uploaddinger */

.center {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  border-radius: 3px;
  box-shadow: 8px 10px 15px 0 rgba(0, 0, 0, 0.2);
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  flex-direction: column;
  margin: 30px;
}

.title {
  width: 100%;
  height: 50px;
  border-bottom: 1px solid #999;
  text-align: center;
  margin: 0 auto;
}

h1.upload {
  font-size: 16px;
  font-weight: 300;
  color: #666;
}

.dropzone {
  width: 100px;
  height: 80px;
  border: 1px dashed #999;
  border-radius: 3px;
  text-align: center;
}

.upload-icon {
  margin: 25px 2px 2px 2px;
}

.upload-input {
  position: relative;
  top: -62px;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}

.btn {
  display: block;
  width: 140px;
  height: 40px;
  background: darkmagenta;
  color: #fff;
  border-radius: 3px;
  border: 0;
  box-shadow: 0 3px 0 0 hotpink;
  transition: all 0.3s ease-in-out;
  font-size: 14px;
}

.btn:hover {
  background: rebeccapurple;
  box-shadow: 0 3px 0 0 deeppink;
}

/* default-Zustand */

/* bei gesetztem Haken wird der Inhalt eingeblendet */

input.checkbox:checked~div.uploaddiv {
  display: flex;
}

Bewirb dich jetzt!

s

        <input class="checkbox" type="checkbox" id="checkbox" />

Drop file to upload

                              <input type="file" class="upload-input" />

                        <button type="button" class="btn" name="uploadbutton">Anschreiben</button>

Drop file to upload

                              <input type="file" class="upload-input" />

                        <button type="button" class="btn" name="uploadbutton">Lebenslauf</button>

Drop file to upload

                              <input type="file" class="upload-input" />

                        <button type="button" class="btn" name="uploadbutton">Zeugnisse</button>

Body:
It works now.

input[type=checkbox] {
  height: 0;
  width: 0;
  visibility: hidden;
}

label {
  cursor: pointer;
  text-indent: -9999px;
  width: 70px;
  height: 30px;
  background: #8B0000;
  display: block;
  border-radius: 100px;
  position: relative;
  margin-left: 450px;
}

label:after {
  content: '';
  position: absolute;
  top: 1px;
  left: 2px;
  width: 28px;
  height: 28px;
  background: #000;
  border-radius: 90px;
  transition: 0.3s;
}

input:checked+label {
  background: #bada55;
}

input:checked+label:after {
  left: calc(100% - 2px);
  transform: translateX(-100%);
  background: #fff;
}

div.uploaddiv {
  position: inherit;
  display: none;
  margin-top: 150px;
  margin-left: 200px;
}

<div class="jtzt">
  <h3 class="bewirb">Bewirb dich jetzt!</h3>

  <input type="checkbox" id="switch" style="padding-left: 10000px" />
  <label for="switch">Toggle</label>

  <div class="uploaddiv">
    <div class="center">
      <div class="title">
        <h1 class="upload">Drop file to upload</h1>
      </div>

      <div class="dropzone">
        <img src="http://100dayscss.com/codepen/upload.svg" class="upload-icon" />
        <input type="file" class="upload-input" />
      </div>

      <button type="button" class="btn" name="uploadbutton">Anschreiben</button>
    </div>

    <div class="center">
      <div class="title">
        <h1 class="upload">Drop file to upload</h1>
      </div>

      <div class="dropzone">
        <img src="http://100dayscss.com/codepen/upload.svg" class="upload-icon" />
        <input type="file" class="upload-input" />
      </div>

      <button type="button" class="btn" name="uploadbutton">Lebenslauf</button>
    </div>

    <div class="center">
      <div class="title">
        <h1 class="upload">Drop file to upload</h1>
      </div>

      <div class="dropzone">
        <img src="http://100dayscss.com/codepen/upload.svg" class="upload-icon" />
        <input type="file" class="upload-input" />
      </div>

      <button type="button" class="btn" name="uploadbutton">Zeugnisse</button>
    </div>
  </div>
</div>


问:
Import packages works in idle.exe but not in IDE (python)
Please note that I am a complete beginner and installed python simply by going to the website and clicking "install". It used to work fine.

Now suddenly I have this frustrating situation where I can run just about anything in the idle.exe found in the scripts section of arcgispro, but cannot run the same .py file in an IDE. As a beginner this is obviously a headache as I would like auto code formatting, suggestions, etc. Literally any IDE would be fine (spyder, pycharm). The problem is that every single time there is some kind of error with the package imports. e.g. from pycharm:

import shapefile ModuleNotFoundError: No module named 'shapefile'

It's not just shapefile... this is happened at random times with numpy and also matplotlib.

When I look at "Installed Apps" on windows, it just says Python 3.10.0 and Python Launcher.
No, there is no file that I created called "shapefile.py"
A lot of solutions suggest things with pip... I have absolutely no idea what pip is...is it installed program? where do I find that?

EDIT: I just found out that the system paths of the two are different so this explains why one works but the other doesn't... but how can I make it so that the IDE would work?

答:
Ok, simple answer:

In Pycharm, go to the bottom  and click on Python Console. Then type pip install pyshp. Voila! Assuming it works for other packages as well. Still do not know where to make pycharm work with the other environment...


问:
Expect an array to contain a string using webdriver.io
How can I write my test so that it expects my array to contain a specific string? I've tried what I have below and some other methods such as using array.includes but can't get it to work properly.

```<code>let value = "test4";
let dropdownValues = ["test1", "test2", "test3", "test4"];

expect(dropdownValues).toHaveTextContaining(value);
</code>```

答:
The way to go about this is to set a variable that checks if the array contains a certain string and use that variable in the expect statement:</p>
```<code>let value = "test4";
let dropdownValues = ["test1", "test2", "test3", "test4"];
let valueExist = dropdownValues.includes(value);

expect(valueExist).toEqual(true);
</code>```

Body:
How can I write my test so that it expects my array to contain a specific string? I've tried what I have below and some other methods such as using array.includes but can't get it to work properly.

let value = "test4";
let dropdownValues = ["test1", "test2", "test3", "test4"];

expect(dropdownValues).toHaveTextContaining(value);

Body:
The way to go about this is to set a variable that checks if the array contains a certain string and use that variable in the expect statement:

let value = "test4";
let dropdownValues = ["test1", "test2", "test3", "test4"];
let valueExist = dropdownValues.includes(value);

expect(valueExist).toEqual(true);


问:
React: how to get Material UI's grid spacing to work?
I am using Material UI's Grid (https://material-ui.com/api/grid) for my layout, however while the columns and rows are working fine, the spacing attribute doesn't seem to work.

I have imported Grid as such: import Grid from '@material-ui/core/Grid'

```<code>  <Grid container spacing={10}>
    <Grid item xs={12} sm={6}>
      CONTENT
    </Grid>
    <Grid item xs={12} sm={6}>
      CONTENT
    </Grid>
  </Grid>
</code>```

But no padding appears.

Would anyone know how to I can include spacing in the grid?

答: I ran into this issue when using the sx prop on the Grid components. Be sure to place any custom styling only on children of the Grid components.

Body:
I am using Material UI's Grid (https://material-ui.com/api/grid) for my layout, however while the columns and rows are working fine, the spacing attribute doesn't seem to work.

I have imported Grid as such: import Grid from '@material-ui/core/Grid'

  <Grid container spacing={10}>
    <Grid item xs={12} sm={6}>
      CONTENT
    </Grid>
    <Grid item xs={12} sm={6}>
      CONTENT
    </Grid>
  </Grid>

But no padding appears.

Would anyone know how to I can include spacing in the grid?


问:
End play if database does not exits
I have created the following playbook, to check if a database exists:

- name: Check database exits
  shell: |
    mysql -hmysqlhost -uroot -ppassword -e "show databases" | egrep db"
  register: mysql_exist

- name: Show database
  debug:
    msg: "{{ mysql_exist.stdout }}"
```
<p>My idea is to finish the playbook if the database does not exist and show a message, I tried this but it does not work, otherwise I should continue to the next task.</p>
<pre class="lang-yaml prettyprint-override"><code>- name: Check database exits
  shell: |
    mysql -hmysqlhost -uroot -ppassword -e "show databases" | egrep db"
  register: mysql_exist

- name: End Playbook If database not exits.
   meta: end_play
   when: mysql_exist == 0

- name: Show database
  debug:
    msg: "{{ mysql_exist.stdout }}"

## other tasks
</code>```

How can I create a playbook to check if a database exists and if it does not exist, it must display the message The database does not exist and finish the playbook without running other tasks?

Title: End play if database does not exits

Body:
I have created the following playbook, to check if a database exists:

- name: Check database exits
  shell: |
    mysql -hmysqlhost -uroot -ppassword -e "show databases" | egrep db"
  register: mysql_exist

- name: Show database
  debug:
    msg: "{{ mysql_exist.stdout }}"

My idea is to finish the playbook if the database does not exist and show a message, I tried this but it does not work, otherwise I should continue to the next task.

- name: Check database exits
  shell: |
    mysql -hmysqlhost -uroot -ppassword -e "show databases" | egrep db"
  register: mysql_exist

- name: End Playbook If database not exits.
   meta: end_play
   when: mysql_exist == 0

- name: Show database
  debug:
    msg: "{{ mysql_exist.stdout }}"

## other tasks

How can I create a playbook to check if a database exists and if it does not exist, it must display the message The database does not exist and finish the playbook without running other tasks?

Body:
Do you need to show the message? Stopping the playbook already happens automatically if egrep does not find anything, because it exits with a non-0 code.

Playbook:

---
- hosts: srv1
  become: True
  tasks:
    - name: x
      shell: "echo nope | egrep dbname"
    - name: good
      shell: "echo very much"

Output (notice how "good" is not executed):

PLAY [srv1] *******************************************************************************************************************************

TASK [x] **********************************************************************************************************************************
fatal: [srv1]: FAILED! => {"changed": true, "cmd": "echo nope | egrep dbname", "delta": "0:00:00.005942", "end": "2022-02-09 15:56:56.726828", "msg": "non-zero return code", "rc": 1, "start": "2022-02-09 15:56:56.720886", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

PLAY RECAP ********************************************************************************************************************************
srv1                       : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

It could be approximated with something like this:

    - name: x
      shell: "echo nope | egrep dbname || { echo Database not found && false; }"

Which gives:

TASK [x] ***********************************************************************************************************************************
fatal: [srv1]: FAILED! => {"changed": true, "cmd": "echo nope | egrep dbname || { echo Database not found && false; }", "delta": "0:00:00.006159", "end": "2022-02-09 15:59:26.176704", "msg": "non-zero return code", "rc": 1, "start": "2022-02-09 15:59:26.170545", "stderr": "", "stderr_lines": [], "stdout": "Database not found", "stdout_lines": ["Database not found"]}


问:
GC.AddMemoryPressure equivalent in Java
Project: Java, JNI (C++), Android.

I'm going to manage native C++ object's lifetime by creating a managed wrapper class, which will hold a pointer to the native object (as a long member) and will delete the native object in it's overridden finalize() method. See this question for details.

The C++ object does not consume other types of resources, only memory. The memory footprint of the object is not extremely high, but it is essentially higher than 64 bit of a long in Java. Is there any way to tell Java's GC, that my wrapper is responsible for more than just a long value, and it's not a good idea to create millions of such objects before running garbage collection? In .NET there is a GC's AddMemoryPressure() method, which is there for exactly this purpose. Is there an equivalent in Java?

答:
After some more googling, I've found a good article from IBM Research Center.

Briefly, they recommend using Java heap instead of native heap for native objects. This way memory pressure on JVM garbage collector is more realistic for the native objects, referenced from Java code through handles.

To achieve this, one needs to override the default C++ heap allocation and deallocation functions: operator new and operator delete. In the operator new, if JVM is available (JNI_OnLoad has been already called), then the one calls NewByteArray and GetByteArrayElements, which returns the allocated memory needed. To protect the created ByteArray from being garbage collected, the one also need to create a NewGlobalRef to it, and store it e.g. in the same allocated memory block. In this case, we need to allocate as much memory as requested, plus the memory for the references. In the operator delete, the one needs to DeleteGlobalRef and ReleaseByteArrayElements. In case JVM is not available, the one uses native malloc and free functions instead.

Title: GC.AddMemoryPressure equivalent in Java