问:
Within a foreach() expression, is the value defined before or after the key?
In a classic foreach() loop after the word as, is it possible to use the key variable as part of the value variable or vice versa?

* after more than a decade of PHP development, this possibility only just now occurred to me to investigate.

答:
A foreach() always assigns the value variable before assigning the key variable. (Demo)

This seems a little counterintuitive because $v visually appears to be declared after it is access by key declaration.

This means you can safely use:

```<code>$array = ['a', 'b'];
$result = [];
foreach ($array as $result["prefix_$v"] => $v);
var_export($result);
</code>```

to produce:

```<code>array (
  'prefix_a' => 0,
  'prefix_b' => 1,
)
</code>```

The newly generated array has prefixed keys based on the original values and the original indexes become the new values.

Without the prefix_ prepended to the string, the action is effectively the same as array_flip().

Reversing the assignments so that the value variable receives the key does not work as intended. You might hope to generate ["prefix_0", "prefix_1"] but it does not and it also generates Notices/Warnings due to trying to access an undeclared variable. (The complaint is only on the first iteration because after the first iteration, $k is declared -- it is the previous iteration's key.)

```<code>$array = ['a', 'b'];
$result = [];
foreach ($array as $k => $result["prefix_$k"]);
// not defined on first iteration -------^^
var_export($result);
</code>```

Bad Output:

```<code>Warning: Undefined variable $k in /in/iVm1u on line 6
array (
  'prefix_' => 'a',
  'prefix_0' => 'b',
)
</code>```

For additional context, I'll offer one more working example that generates a multi-dimensional array using the value to determine the array keys in the output array. (Demo)

```<code>$array = [2, 3, 5];

$result = [];
foreach ($array as $result[$v * $v][$v] => $v);
var_export($result);
</code>```

Output:

```<code>array (
  4 =>
  array (
    2 => 0,
  ),
  9 =>
  array (
    3 => 1,
  ),
  25 =>
  array (
    5 => 2,
  ),
)
</code>```

Body:
A foreach() always assigns the value variable before assigning the key variable. (Demo)

This seems a little counterintuitive because $v visually appears to be declared after it is access by key declaration.

This means you can safely use:

$array = ['a', 'b'];
$result = [];
foreach ($array as $result["prefix_$v"] => $v);
var_export($result);

to produce:

array (
  'prefix_a' => 0,
  'prefix_b' => 1,
)

The newly generated array has prefixed keys based on the original values and the original indexes become the new values.

Without the prefix_ prepended to the string, the action is effectively the same as array_flip().

Reversing the assignments so that the value variable receives the key does not work as intended. You might hope to generate ["prefix_0", "prefix_1"] but it does not and it also generates Notices/Warnings due to trying to access an undeclared variable. (The complaint is only on the first iteration because after the first iteration, $k is declared -- it is the previous iteration's key.)

$array = ['a', 'b'];
$result = [];
foreach ($array as $k => $result["prefix_$k"]);
// not defined on first iteration -------^^
var_export($result);

Bad Output:

Warning: Undefined variable $k in /in/iVm1u on line 6
array (
  'prefix_' => 'a',
  'prefix_0' => 'b',
)

For additional context, I'll offer one more working example that generates a multi-dimensional array using the value to determine the array keys in the output array. (Demo)

$array = [2, 3, 5];

$result = [];
foreach ($array as $result[$v * $v][$v] => $v);
var_export($result);

Output:

array (
  4 =>
  array (
    2 => 0,
  ),
  9 =>
  array (
    3 => 1,
  ),
  25 =>
  array (
    5 => 2,
  ),
)


来源: stackexchange

问:
python how to use tika with existing jar file without downloading again
I'm using Tika and I realized that each time the jar file is downloaded and placed in Temp folder

```<code>Retrieving http://search.maven.org/remotecontent?filepath=org/apache/tika/tika-server/1.19/tika-server-1.19.jar to C:\Users\asus\AppData\Local\Temp\tika-server.jar.
Retrieving http://search.maven.org/remotecontent?filepath=org/apache/tika/tika-server/1.19/tika-server-1.19.jar.md5 to C:\Users\asus\AppData\Local\Temp\tika-server.jar.md5.
</code>```

The problem is that the jar file size is around 60MB, which takes some time to download.

This is the code I'm using :

```<code>from tika import parser

def get_pdf_text(path):
    parsed = parser.from_file(path):
    return parsed['content']
</code>```

The only workaround I found is this :

1 - Manually running the jar using java -jar tika-server-x.x.jar --port xxxx

2 - Using tika.TikaClientOnly = True

3 - Replacing parser.from_file(path) with parser.from_file(path, '/path/to/server')

But I don't want to run the jar file manually. It would be better if I can use Python to automatically run the jar file and setup tika with it without redownloading.

答: i am wondering how to get the .md5 file of tika-server.jar, since .md5 file is not provided and sha512 signature is provided instead</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm using Tika and I realized that each time the jar file is downloaded and placed in Temp folder

Retrieving http://search.maven.org/remotecontent?filepath=org/apache/tika/tika-server/1.19/tika-server-1.19.jar to C:\Users\asus\AppData\Local\Temp\tika-server.jar.
Retrieving http://search.maven.org/remotecontent?filepath=org/apache/tika/tika-server/1.19/tika-server-1.19.jar.md5 to C:\Users\asus\AppData\Local\Temp\tika-server.jar.md5.

The problem is that the jar file size is around 60MB, which takes some time to download.

This is the code I'm using :

from tika import parser

def get_pdf_text(path):
    parsed = parser.from_file(path):
    return parsed['content']

The only workaround I found is this :

1 - Manually running the jar using java -jar tika-server-x.x.jar --port xxxx

2 - Using tika.TikaClientOnly = True

3 - Replacing parser.from_file(path) with parser.from_file(path, '/path/to/server')

But I don't want to run the jar file manually. It would be better if I can use Python to automatically run the jar file and setup tika with it without redownloading.


问:
How to resize and reshape UIImage without causing any distortion?
I am using the clearbit api to get and display company logos in my app. This works great except that all of the logos are different size, and I want them all to be displayed as a square.

Does anybody know how to take a rectangular image and add extra pixels to it of a given color until it becomes square with the logo at the center?

This question seemed to answer it, but it is outdated. I also thought that the top answer on this question would work, but the code didn't work. Any help would be very much appreciated, thank you!

答:
`    func drawImageOnCanvas(_ useImage: UIImage, canvasColor: UIColor ) -> UIImage {

```<code>let length = max(useImage.size.width, useImage.size.height)
let canvasSize = CGSize.init(width: length, height: length)
let rect = CGRect(origin: .zero, size: canvasSize)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)

// fill the entire image
canvasColor.setFill()
UIRectFill(rect)

// calculate a Rect the size of the image to draw, centered in the canvas rect
let centeredImageRect = CGRect(x: (canvasSize.width - useImage.size.width) / 2,
                               y: (canvasSize.height - useImage.size.height) / 2,
                               width: useImage.size.width,
                               height: useImage.size.height)

// get a drawing context
let context = UIGraphicsGetCurrentContext();

// "cut" a transparent rectanlge in the middle of the "canvas" image
context?.clear(centeredImageRect)

// draw the image into that rect
useImage.draw(in: centeredImageRect)

// get the new "image in the center of a canvas image"
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return image!
</code>```

}`

`   func imageWithColor(color : UIColor,oriImage:UIImage) -> UIImage{

```<code>let length = max(oriImage.size.width, oriImage.size.height)
let size = CGSize.init(width: length, height: length)
let imgView = UIImageView.init(image: oriImage)
imgView.contentMode = UIView.ContentMode.scaleAspectFit
imgView.backgroundColor = color
imgView.bounds = CGRect.init(x: 0, y: 0, width: length, height: length)
print("\(size.width)" + "\(size.height)")

UIGraphicsBeginImageContext(size)
guard let context = UIGraphicsGetCurrentContext() else{
    print("context get Error")
    return oriImage
}
imgView.layer.render(in:context)
let desImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return desImg ?? oriImage
</code>```

}`

Body:
`    func drawImageOnCanvas(_ useImage: UIImage, canvasColor: UIColor ) -> UIImage {

let length = max(useImage.size.width, useImage.size.height)
let canvasSize = CGSize.init(width: length, height: length)
let rect = CGRect(origin: .zero, size: canvasSize)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)

// fill the entire image
canvasColor.setFill()
UIRectFill(rect)

// calculate a Rect the size of the image to draw, centered in the canvas rect
let centeredImageRect = CGRect(x: (canvasSize.width - useImage.size.width) / 2,
                               y: (canvasSize.height - useImage.size.height) / 2,
                               width: useImage.size.width,
                               height: useImage.size.height)

// get a drawing context
let context = UIGraphicsGetCurrentContext();

// "cut" a transparent rectanlge in the middle of the "canvas" image
context?.clear(centeredImageRect)

// draw the image into that rect
useImage.draw(in: centeredImageRect)

// get the new "image in the center of a canvas image"
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return image!

}`

`   func imageWithColor(color : UIColor,oriImage:UIImage) -> UIImage{

let length = max(oriImage.size.width, oriImage.size.height)
let size = CGSize.init(width: length, height: length)
let imgView = UIImageView.init(image: oriImage)
imgView.contentMode = UIView.ContentMode.scaleAspectFit
imgView.backgroundColor = color
imgView.bounds = CGRect.init(x: 0, y: 0, width: length, height: length)
print("\(size.width)" + "\(size.height)")

UIGraphicsBeginImageContext(size)
guard let context = UIGraphicsGetCurrentContext() else{
    print("context get Error")
    return oriImage
}
imgView.layer.render(in:context)
let desImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return desImg ?? oriImage

}`


问:
Where Cache stored in asp.net
I'm using the Cache object to store the Datatable.
like as below

```<code>Cache["dt"]=dtsum;
</code>```

If I store like this where cahce will store either at client side or serverside.
Previoulsy I was storing in Viewstate. But I was thinking of Viewstate that store data in page itself. so I'm storing in Cache. which will be better option.
please suggest me.

答:
Cache is stored in web server memory.

You should understand the differences between Viewstate, Cache and Session

http://www.codeproject.com/KB/aspnet/PTCacheSessionViewState.aspx

ContentLicense: CC BY-SA 3.0

Title: Where Cache stored in asp.net

Body:
I'm using the Cache object to store the Datatable.
like as below

Cache["dt"]=dtsum;

If I store like this where cahce will store either at client side or serverside.
Previoulsy I was storing in Viewstate. But I was thinking of Viewstate that store data in page itself. so I'm storing in Cache. which will be better option.
please suggest me.


问:
how to react in typescript fetch data
I am currently using typescript of React.
I want to use map using fetch.
How to define the type fetchdata in map
Can I ask for your advice?

```<code>interface Root {
  requests: Request[];
}

interface Request {
  id: number;
  title: string;
  client: string;
  due: string;
  count?: number;
  amount: number;
  method: string[];
  material: string[];
  status: string;
  docs?: number;
}

const Board = () => {
  const [cardInfo, setCardInfo] = useState<Root[]>([]);

  useEffect(() => {
    fetch('http://localhost:4000/requests')
      .then(res => res.json())
      .then(res => setCardInfo(res));
  }, []);

  return (
    <div>
      <S.CardWrap>
        {cardInfo.map((Request): Request => {
          return <Card cardInfo={Request} />;
        })}
      </S.CardWrap>
    </div>
  );
};
</code>```

答:
Just do your type annotation inside your parenthesis, like

```<code>cardInfo.map((request: Request) => { ... })
</code>```

Instead of outside

Title: how to react in typescript fetch data

Body:
I am currently using typescript of React.
I want to use map using fetch.
How to define the type fetchdata in map
Can I ask for your advice?

interface Root {
  requests: Request[];
}

interface Request {
  id: number;
  title: string;
  client: string;
  due: string;
  count?: number;
  amount: number;
  method: string[];
  material: string[];
  status: string;
  docs?: number;
}

const Board = () => {
  const [cardInfo, setCardInfo] = useState<Root[]>([]);

  useEffect(() => {
    fetch('http://localhost:4000/requests')
      .then(res => res.json())
      .then(res => setCardInfo(res));
  }, []);

  return (

      <S.CardWrap>
        {cardInfo.map((Request): Request => {
          return <Card cardInfo={Request} />;
        })}
      </S.CardWrap>

  );
};

Body:
Just do your type annotation inside your parenthesis, like

cardInfo.map((request: Request) => { ... })

Instead of outside


问:
Spring MVC - Binding results missing after manually overriding model
I've got some code which looks like this

```<code>@Controller
public class FooController {

@RequestMapping(value = "/foos", method = POST)
public String createFoo(@ModelAttribute("FooDto")
    @Valid FooDto fooDto, BindingResult bindingResult, Model model) {

    var foo = fooMapper.toFooModel(fooDto);

    if (bindingResult.hasErrors()) {
        var fooDto1 = fooMapper.toFooDto(foo);

        model.addAttribute("FooDto", fooDto1); // binding result disappears
        ...
    }

    ...
</code>```

Also some Test for my Controller class which looks like the following:

```<code>@Test
void createFooWithValidationError() throws Exception {

    perform(post("/foos")).andExpect(status().isOk())
        .andExpect(model().attribute("foo", notNullValue()))
        .andExpect(model().errorCount(1)); // this fails, no error/binding result exists!
}
</code>```

The test has not been successfull, because there is no binding result after setting

model.addAttribute("FooDto", fooDto1);.

I know, that i could set

model.addAttribute("FooDto", fooDto);

whereby the binding result does not disappear.

However I wonder why the binding result is disappearing. Is there some spring magic which binds the binding result to the concrete instance of my model attribute? Is there some other workaround to make the above code working?

答:
I'll dived into the spring code and found my answer:

model.addAttribute("FooDto", fooDto1); does call

public ModelMap addAttribute(String attributeName, @Nullable Object attributeValue) {
    Assert.notNull(attributeName, "Model attribute name must not be null");
    put(attributeName, attributeValue); // calls BindingAwareModelMap
    return this;
}
```
<pre class="lang-java prettyprint-override"><code>public class BindingAwareModelMap  {

   public Object put(String key, @Nullable Object value) {
       removeBindingResultIfNecessary(key, value);
       return super.put(key, value);
   }

   private void removeBindingResultIfNecessary(Object key, @Nullable Object value) {
        ...
        if (bindingResult != null && bindingResult.getTarget() != value) {
            remove(bindingResultKey); // Removes the binding result if target refernces to other instance
        }
    }
}
</code>```

As u can see if the binding results references to an other instance the binding result entry in ModelMap is removed.

Body:
I've got some code which looks like this

@Controller
public class FooController {

@RequestMapping(value = "/foos", method = POST)
public String createFoo(@ModelAttribute("FooDto")
    @Valid FooDto fooDto, BindingResult bindingResult, Model model) {

    var foo = fooMapper.toFooModel(fooDto);

    if (bindingResult.hasErrors()) {
        var fooDto1 = fooMapper.toFooDto(foo);

        model.addAttribute("FooDto", fooDto1); // binding result disappears
        ...
    }

    ...

Also some Test for my Controller class which looks like the following:

@Test
void createFooWithValidationError() throws Exception {

    perform(post("/foos")).andExpect(status().isOk())
        .andExpect(model().attribute("foo", notNullValue()))
        .andExpect(model().errorCount(1)); // this fails, no error/binding result exists!
}

The test has not been successfull, because there is no binding result after setting

model.addAttribute("FooDto", fooDto1);.

I know, that i could set

model.addAttribute("FooDto", fooDto);

whereby the binding result does not disappear.

However I wonder why the binding result is disappearing. Is there some spring magic which binds the binding result to the concrete instance of my model attribute? Is there some other workaround to make the above code working?

Body:
I'll dived into the spring code and found my answer:

model.addAttribute("FooDto", fooDto1); does call

public ModelMap addAttribute(String attributeName, @Nullable Object attributeValue) {
    Assert.notNull(attributeName, "Model attribute name must not be null");
    put(attributeName, attributeValue); // calls BindingAwareModelMap
    return this;
}

public class BindingAwareModelMap  {

   public Object put(String key, @Nullable Object value) {
       removeBindingResultIfNecessary(key, value);
       return super.put(key, value);
   }

   private void removeBindingResultIfNecessary(Object key, @Nullable Object value) {
        ...
        if (bindingResult != null && bindingResult.getTarget() != value) {
            remove(bindingResultKey); // Removes the binding result if target refernces to other instance
        }
    }
}

As u can see if the binding results references to an other instance the binding result entry in ModelMap is removed.


问:
Sharing app content between portals using 2Sxc
I need to design a content system similar to the news article 2sxc application. However, in my situation I have a primary subdomain and multiple secondary subdomains each of which is a portal in a single install of DNN.  I need the primary to be able to selectively share articles with the secondary subdomains. I also need the secondary subdomains to be able to have their own articles. I have explored creating a ghost content type on the secondary sites, but this doesn't seem to share the content.  I have used the visual query designer with an App Data Source to pull data from the zone and app of the primary. Using this, I can pull the needed article data, however, it also pulls lots of meta data like the name of each field on the content type etc.  So I assumed I could filter this stream by content type, but when I do that it removes all items in the stream. Additionally, I have tried using razor code to get the correct data, but have been unsuccessful. So:

What is the best way to accomplish sharing the articles as described?

What am I missing on the visual query designer that is causing it to filter all results when filtering by type?

Thanks

答:
There are a few more options to achieve this BTW

You can just show a module of Portal 1 on Portal 2 using Dnn features to share modules

Use the mechanics described by @Jeremy in his answer

2sxc 13.2 will offer a new shared-global-app system which is actually meant for other scenarios, but could also be used here.

You could also provide the data on your primary site as a RSS or WebService, and re-use that on the target site


问:
Need a specific example of U-Matrix in Self Organizing Map
I'm trying to develop an application using SOM in analyzing data. However, after finishing training, I cannot find a way to visualize the result. I know that U-Matrix is one of the method but I cannot understand it properly. Hence, I'm asking for a specific and detail example how to construct U-Matrix.

I also read an answer at U-matrix and self organizing maps but it only refers to 1 row map, how about 3x3 map? I know that for 3x3 map:

```<code>m(1) m(2) m(3)
m(4) m(5) m(6)
m(7) m(8) m(9)
</code>```

a 5x5 matrix must me created:

```<code>u(1)   u(1,2)     u(2)   u(2,3)     u(3)
u(1,4) u(1,2,4,5) u(2,5) u(2,3,5,6) u(3,6)
u(4)   u(4,5)     u(5)   u(5,6)     u(6)
u(4,7) u(4,5,7,8) u(5,8) u(5,6,8,9) u(6,9)
u(7)   u(7,8)     u(8)   u(8,9)     u(9)
</code>```

but I don't know how to calculate u-weight u(1,2,4,5), u(2,3,5,6), u(4,5,7,8) and u(5,6,8,9).

Finally, after constructing U-Matrix, is there any way to visualize it using color, e.g. heat map?

Thank you very much for your time.

Cheers

答:
From the matrix that you create:

```<code>u(1)     u(1,2)     u(2)   u(2,3)    u(3)
u(1,4) u(1,2,4,5) u(2,5) u(2,3,5,6) u(3,6)
u(4)     u(4,5)     u(5)   u(5,6)    u(6)
u(4,7) u(4,5,7,8) u(5,8) u(5,6,8,9) u(6,9)
u(7)   u(7,8)       u(8)   u(8,9)    u(9)
</code>```

The elements with single numbers like u(1), u(2), ..., u(9) as just the elements with more than two numbers like u(1,2,4,5), u(2,3,5,6), ... , u(5,6,8,9) are calculated using something like the mean, median, min or max of the values in the neighborhood.

It's a nice idea calculate the elements with two numbers first, one possible code for that is:

```<code> for i in range(self.h_u_matrix):
  for j in range(self.w_u_matrix):

    nb = (0,0)

    if not (i % 2) and (j % 2):
      nb = (0,1)

    elif (i % 2) and not (j % 2):
      nb = (1,0)

    self.u_matrix[(i,j)] = np.linalg.norm(
        self.weights[i //2, j //2] - self.weights[i //2 +nb[0], j // 2 + nb[1]],
        axis = 0
    )
</code>```

In the code above the self.h_u_matrix = self.weights.shape[0]*2 - 1 and self.w_u_matrix = self.weights.shape[1]*2 - 1 are the dimensions of the U-Matrix. With that said, for calculate the others elements it's necessary obtain a list with they neighboors and apply a mean for example. The following code implements that's idea:

```<code>for i in range(self.h_u_matrix):
  for j in range(self.w_u_matrix):

    if not (i % 2) and not (j % 2):
       nodelist = []
       if i > 0:
           nodelist.append((i-1,j))
       if i < 4:
           nodelist.append((i+1, j))
       if j > 0:
           nodelist.append((i,j -1))
       if j < 4:
           nodelist.append((i,j+1))

       meanlist = [self.u_matrix[u_node] for u_node in nodelist]
       self.u_matrix[(i,j)] = np.mean(meanlist)

     elif (i % 2) and (j % 2):
       meanlist = [
                    (i - 1, j),
                    (i + 1, j),
                    (i, j - 1),
                    (i, j + 1)]
       self.u_matrix[(i,j)] = np.mean(meanlist)

</code>```

Body:
I'm trying to develop an application using SOM in analyzing data. However, after finishing training, I cannot find a way to visualize the result. I know that U-Matrix is one of the method but I cannot understand it properly. Hence, I'm asking for a specific and detail example how to construct U-Matrix.

I also read an answer at U-matrix and self organizing maps but it only refers to 1 row map, how about 3x3 map? I know that for 3x3 map:

m(1) m(2) m(3)
m(4) m(5) m(6)
m(7) m(8) m(9)

a 5x5 matrix must me created:

u(1)   u(1,2)     u(2)   u(2,3)     u(3)
u(1,4) u(1,2,4,5) u(2,5) u(2,3,5,6) u(3,6)
u(4)   u(4,5)     u(5)   u(5,6)     u(6)
u(4,7) u(4,5,7,8) u(5,8) u(5,6,8,9) u(6,9)
u(7)   u(7,8)     u(8)   u(8,9)     u(9)

but I don't know how to calculate u-weight u(1,2,4,5), u(2,3,5,6), u(4,5,7,8) and u(5,6,8,9).

Finally, after constructing U-Matrix, is there any way to visualize it using color, e.g. heat map?

Thank you very much for your time.

Cheers

Body:
From the matrix that you create:

u(1)     u(1,2)     u(2)   u(2,3)    u(3)
u(1,4) u(1,2,4,5) u(2,5) u(2,3,5,6) u(3,6)
u(4)     u(4,5)     u(5)   u(5,6)    u(6)
u(4,7) u(4,5,7,8) u(5,8) u(5,6,8,9) u(6,9)
u(7)   u(7,8)       u(8)   u(8,9)    u(9)

The elements with single numbers like u(1), u(2), ..., u(9) as just the elements with more than two numbers like u(1,2,4,5), u(2,3,5,6), ... , u(5,6,8,9) are calculated using something like the mean, median, min or max of the values in the neighborhood.

It's a nice idea calculate the elements with two numbers first, one possible code for that is:

 for i in range(self.h_u_matrix):
  for j in range(self.w_u_matrix):

    nb = (0,0)

    if not (i % 2) and (j % 2):
      nb = (0,1)

    elif (i % 2) and not (j % 2):
      nb = (1,0)

    self.u_matrix[(i,j)] = np.linalg.norm(
        self.weights[i //2, j //2] - self.weights[i //2 +nb[0], j // 2 + nb[1]],
        axis = 0
    )

In the code above the self.h_u_matrix = self.weights.shape[0]*2 - 1 and self.w_u_matrix = self.weights.shape[1]*2 - 1 are the dimensions of the U-Matrix. With that said, for calculate the others elements it's necessary obtain a list with they neighboors and apply a mean for example. The following code implements that's idea:

for i in range(self.h_u_matrix):
  for j in range(self.w_u_matrix):

    if not (i % 2) and not (j % 2):
       nodelist = []
       if i > 0:
           nodelist.append((i-1,j))
       if i < 4:
           nodelist.append((i+1, j))
       if j > 0:
           nodelist.append((i,j -1))
       if j < 4:
           nodelist.append((i,j+1))

       meanlist = [self.u_matrix[u_node] for u_node in nodelist]
       self.u_matrix[(i,j)] = np.mean(meanlist)

     elif (i % 2) and (j % 2):
       meanlist = [
                    (i - 1, j),
                    (i + 1, j),
                    (i, j - 1),
                    (i, j + 1)]
       self.u_matrix[(i,j)] = np.mean(meanlist)


问:
abort_with_payload : app built with Xcode 13.2.1 crash after launch on iOS12.5 (real device only)
The app crashes when users download from AppStore and try to open the app, it shows launch screen and then crashes.

This happens only with real devices running iOS12.* App was built with Xcode 13.2.1.

Simulators and real devices running iOS13 and above are fine.

This is what the crash log obtained:

```<code>#0  (null) in __abort_with_payload ()
#5  (null) in _dyld_start ()
</code>```

Update: see this thread

答: Some times it happened for target iOS and build iOS(i.e : target 9.0 but build 12.0)version and also change to "Embed & Sign" to "Embed without Signing" under General > Frameworks, Libraries and Embedded Content. You will try to change your target and build ios version in same.

Body:
The app crashes when users download from AppStore and try to open the app, it shows launch screen and then crashes.

This happens only with real devices running iOS12.* App was built with Xcode 13.2.1.

Simulators and real devices running iOS13 and above are fine.

This is what the crash log obtained:

#0  (null) in __abort_with_payload ()
#5  (null) in _dyld_start ()

Update: see this thread


问:
How can I use a string representation of an enum in a Jest test.each case?
When writing a Jest test.each() test using an enum like below

```<code>enum MyEnum {
    FirstValue,
    SecondValue,
    ThirdValue
}

describe('my example', () => {
    test.each([MyEnum.FirstValue, MyEnum.SecondValue, MyEnum.ThirdValue])(
        '%o',
        (input: MyEnum) => {
            expect(input).toBeDefined();
        }
    );
});
</code>```

The output text is:

```<code>my example
  0
  1
  2
</code>```

I would like it to be

```<code>my example
  FirstValue
  SecondValue
  ThirdValue
</code>```

Using other formatting parameters like %p or %j like listed in the Jest docs don't change anything

答:
I just thought of an answer, I could use describe.each in stead:

```<code>describe.each(testcases)('my test', (input: MyEnum) => {
    test(`${MyEnum[input]}`, () => {
        expect(input).toBeDefined();
    });
});
</code>```

Body:
When writing a Jest test.each() test using an enum like below

enum MyEnum {
    FirstValue,
    SecondValue,
    ThirdValue
}

describe('my example', () => {
    test.each([MyEnum.FirstValue, MyEnum.SecondValue, MyEnum.ThirdValue])(
        '%o',
        (input: MyEnum) => {
            expect(input).toBeDefined();
        }
    );
});

The output text is:

my example
  0
  1
  2

I would like it to be

my example
  FirstValue
  SecondValue
  ThirdValue

Using other formatting parameters like %p or %j like listed in the Jest docs don't change anything

Body:
I just thought of an answer, I could use describe.each in stead:

describe.each(testcases)('my test', (input: MyEnum) => {
    test(`${MyEnum[input]}`, () => {
        expect(input).toBeDefined();
    });
});


问:
Spring Cloud Function Composition
I am trying spring cloud function with aws lambda.
Lets say, I have 5 different spring function (A,B,C,D,E) and function composition of like this A|B|C|D|E.

I specify which function to invoke using spring_cloud_function_definition in lambda,
so, spring_cloud_function_definition = A|B|C|D|E

Now, i want to route to other function (lets say F), from function A in certain scenario (lets say, on receive of some error code while executing in A) and not move to next functions in function composition.

What i would like to know:

Is it possible to end execution in this function composition in middle based on certain parameters.? If yes, How do i achieve.

I tried MessgaeRoutingCallback but its not working for me. I created a class  that
implements MessgaeRoutingCallback. I returned "F" in functiondefinition.  I tried to
call this functiondefinition from function "A".

On execution of composition,it goes like this A -> functiondefinition (does not route to F) -> B ->C->D->E

答:
Once again, (as it is explained here and in the previous post here some time back) composed function is not a chain or flow or a pipeline of any kind. It is a single function created using andThen or compose methods of Java Function.
It is as if you wrote a single function yourself combining the functionality of all 5 functions. So the real question should be "how do you stop execution of a single function in the middle of its execution?"

Title: Spring Cloud Function Composition


问:
ImportError: cannot import name namedtuple
I have a python script that produces the following error when run:

```<code>import urllib2
File "C:\Python27\lib\urllib2.py", line 94, in <module>
import httplib
File "C:\Python27\lib\httplib.py", line 73, in <module>
from urlparse import urlsplit
File "C:\Python27\lib\urlparse.py", line 119, in <module>
from collections import namedtuple
ImportError: cannot import name namedtuple
</code>```

I also use the openpyxl package, located in C:\Python27\Lib\site-packages, which contains a collections folder with a __init__.py file. I figured this is what causes the problem, because it may be preventing the python 2.7 collections module from being imported.

What can I do to fix this problem?

答:
I had the same issue but this worked when I changed Collection Package to a simple collection directory.

I just deleted the init.py file from the collections

this can be due to the package name Collections. this can be also resolved by renaming Collection Package to othername.

Body:
I have a python script that produces the following error when run:

import urllib2
File "C:\Python27\lib\urllib2.py", line 94, in <module>
import httplib
File "C:\Python27\lib\httplib.py", line 73, in <module>
from urlparse import urlsplit
File "C:\Python27\lib\urlparse.py", line 119, in <module>
from collections import namedtuple
ImportError: cannot import name namedtuple

I also use the openpyxl package, located in C:\Python27\Lib\site-packages, which contains a collections folder with a __init__.py file. I figured this is what causes the problem, because it may be preventing the python 2.7 collections module from being imported.

What can I do to fix this problem?


问:
Unable to connect from Google Cloud to Bitbucket repository using app password
I'm using GCP build triggers connected to Bitbucket repositories. The connection is made using user credentials. Bitbucket has announced they're ending support for account password usage:

Beginning March 1, 2022, Bitbucket users will no longer be able to use
their Atlassian account password when using Basic authentication with
the Bitbucket API or Git over HTTPS. For security reasons, we require
all users to use Bitbucket app passwords.

Problem is, when trying to connect to a repository in GCP, the only option to supply Bitbucket credentials is via a web login (which to the point of app passwords, you cannot login via the bitbucket.org with an app password).

GCP Bitbucket login prompt via bitbucket.org

Expected behavior: GCP provides an option to submit app password credentials when connecting to a Bitbucket repository.

答:
I have been informed of this change as well. I am trying to understand the scope of the change and its impact. It states that you cannot log in Atlassian account and password. However, besides using app passwords, you can also log in using OAuth2. https://developer.atlassian.com/cloud/bitbucket/oauth-2/

In the case of GCP Build Triggers, when I first set up the Bitbucket repository to connect to, I need to go through the "Authorization Code Grant" flow and acknowledge what access I am granting to Google Cloud Source Repository.  If you check the Bitbucket API endpoints being called, they are URLs that are being used for "Authorization Code Grant" flow.

Based on these findings, am I right to say that there is no necessity to change existing triggers or mirrored repositories on GCP since they are using OAuth2 in the first place instead of Atlassian accounts and passwords?


问:
How to get total sum of nested list's total value in a while loop?
I am trying to get buy and sell orders from binance api(python-binance) which has a limit of 500 values.(500 ask,500 buy). I already can get this with creating 500 variables with index numbers but it seems to me there has to be a better way than to write 500 lines of code.
This is the code I am trying to make it happen.

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-
from binance.client import Client

user_key = ''
secret_key = ''
binance_client = Client(user_key, secret_key)

while True:
    alis = binance_client.futures_order_book(symbol='XRPUSDT')

    binance_buy = alis['bids'][0]
    binance_buy1 = alis['bids'][1]
    binance_buy2 = alis['bids'][2]
    binance_buy3 = alis['bids'][3]
    binance_buy4 = alis['bids'][4]
    binance_buy5 = alis['bids'][5]
    binance_buy6 = alis['bids'][6]
    binance_buy7 = alis['bids'][7]
    binance_buy8 = alis['bids'][8]
    binance_buy9 = alis['bids'][9]
    binance_buy10 = alis['bids'][10]
    binance_buy11 = alis['bids'][11]
    binance_buy12 = alis['bids'][12]
    binance_buy13 = alis['bids'][13]
    binance_buy14 = alis['bids'][14]
    binance_buy15 = alis['bids'][15]
    binance_buy16 = alis['bids'][16]
    binance_buy17 = alis['bids'][17]
    binance_buy18 = alis['bids'][18]
    binance_buy19 = alis['bids'][19]
    binance_buy20 = alis['bids'][20]
    binance_sell = alis['asks'][0]
    binance_sell1 = alis['asks'][1]
    binance_sell2 = alis['asks'][2]
    binance_sell3 = alis['asks'][3]
    binance_sell4 = alis['asks'][4]
    binance_sell5 = alis['asks'][5]
    binance_sell6 = alis['asks'][6]
    binance_sell7 = alis['asks'][7]
    binance_sell8 = alis['asks'][8]
    binance_sell9 = alis['asks'][9]
    binance_sell10 = alis['asks'][10]
    binance_sell11 = alis['asks'][11]
    binance_sell12 = alis['asks'][12]
    binance_sell13 = alis['asks'][13]
    binance_sell14 = alis['asks'][14]
    binance_sell15 = alis['asks'][15]
    binance_sell16 = alis['asks'][16]
    binance_sell17 = alis['asks'][17]
    binance_sell18 = alis['asks'][18]
    binance_sell19 = alis['asks'][19]
    binance_sell20 = alis['asks'][20]

    binance_buy_demand = float(binance_buy[1]) + float(binance_buy1[1]) \
        + float(binance_buy2[1]) + float(binance_buy3[1]) \
        + float(binance_buy4[1]) + float(binance_buy5[1]) \
        + float(binance_buy6[1]) + float(binance_buy7[1]) \
        + float(binance_buy8[1]) + float(binance_buy9[1]) \
        + float(binance_buy10[1]) + float(binance_buy11[1]) \
        + float(binance_buy12[1]) + float(binance_buy13[1]) \
        + float(binance_buy14[1]) + float(binance_buy15[1]) \
        + float(binance_buy16[1]) + float(binance_buy17[1]) \
        + float(binance_buy18[1]) + float(binance_buy19[1]) \
        + float(binance_buy20[1])

    for i in range(0, 500):
        print (alis['asks'][i][0], alis['asks'][i][1])

    binance_sell_demand = float(binance_sell[1]) \
        + float(binance_sell1[1]) + float(binance_sell2[1]) \
        + float(binance_sell3[1]) + float(binance_sell4[1]) \
        + float(binance_sell5[1]) + float(binance_sell6[1]) \
        + float(binance_sell7[1]) + float(binance_sell8[1]) \
        + float(binance_sell9[1]) + float(binance_sell10[1]) \
        + float(binance_sell11[1]) + float(binance_sell12[1]) \
        + float(binance_sell13[1]) + float(binance_sell14[1]) \
        + float(binance_sell15[1]) + float(binance_sell16[1]) \
        + float(binance_sell17[1]) + float(binance_sell18[1]) \
        + float(binance_sell19[1]) + float(binance_sell20[1])
</code>```

there is 500 bids and 500 asks
after getting data I sum bids  ands asks like this

I tried to make for loop but only could print this values cant sum it in for loop this is the code I tried:
sample output:

```<code>0.9315 18328.6
0.9316 18201.2
0.9317 23544.0
0.9318 260.4
0.9319 689.5
0.9320 20410.5
0.9321 47.7
0.9322 294.2
0.9323 446.6
0.9324 104.0
0.9325 3802.3
0.9326 100.1
0.9327 20122.9
0.9328 1410.0
0.9329 7745.1
0.9330 9094.4
0.9331 10389.9
0.9332 248.5
0.9333 71559.7
0.9334 18024.1
0.9335 7404.5
0.9336 1366.6
0.9337 21972.4
0.9338 1224.8
0.9339 49.9
0.9340 17590.5
0.9341 17967.1
0.9342 272.3
0.9343 704.4
0.9344 3581.7
0.9345 3896.8
</code>```

the first items are price second is quantity

I am trying to make a function that sum and divide avg.price and also want to know how many bids total and asks total.

答:
You can sum in a for loop like this:

```<code>total_ask_volume = 0
total_bid_volume = 0
for i  in range(0, 500):
    total_ask_volume += float(alis["asks"][i][1])
    total_bid_volume += float(alis["bids"][i][1])
print(total_ask_volume, total_bid_volume)
</code>```

Another option is to skip the i index, and go through the values directly:

```<code>total_ask_volume = 0
for ask in alis["asks"]:
    total_ask_volume += float(ask[1])

total_bid_volume = 0
for bid in alis["bids"]:
    total_bid_volume += float(bid[1])

print(total_ask_volume, total_bid_volume)
</code>```

This can sometimes be clearer, particularly in situations where you'd otherwise have multiple indexes (i, j, k and so on) which could get confusing.

As a side note, float often rounds in unintuitive ways; it probably doesn't matter in this particular circumstance, but in most situations involving money you probably want to use Decimal instead (or multiply by 100 and count whole numbers of cents).

Body:
I am trying to get buy and sell orders from binance api(python-binance) which has a limit of 500 values.(500 ask,500 buy). I already can get this with creating 500 variables with index numbers but it seems to me there has to be a better way than to write 500 lines of code.
This is the code I am trying to make it happen.

#!/usr/bin/python
# -*- coding: utf-8 -*-
from binance.client import Client

user_key = ''
secret_key = ''
binance_client = Client(user_key, secret_key)

while True:
    alis = binance_client.futures_order_book(symbol='XRPUSDT')

    binance_buy = alis['bids'][0]
    binance_buy1 = alis['bids'][1]
    binance_buy2 = alis['bids'][2]
    binance_buy3 = alis['bids'][3]
    binance_buy4 = alis['bids'][4]
    binance_buy5 = alis['bids'][5]
    binance_buy6 = alis['bids'][6]
    binance_buy7 = alis['bids'][7]
    binance_buy8 = alis['bids'][8]
    binance_buy9 = alis['bids'][9]
    binance_buy10 = alis['bids'][10]
    binance_buy11 = alis['bids'][11]
    binance_buy12 = alis['bids'][12]
    binance_buy13 = alis['bids'][13]
    binance_buy14 = alis['bids'][14]
    binance_buy15 = alis['bids'][15]
    binance_buy16 = alis['bids'][16]
    binance_buy17 = alis['bids'][17]
    binance_buy18 = alis['bids'][18]
    binance_buy19 = alis['bids'][19]
    binance_buy20 = alis['bids'][20]
    binance_sell = alis['asks'][0]
    binance_sell1 = alis['asks'][1]
    binance_sell2 = alis['asks'][2]
    binance_sell3 = alis['asks'][3]
    binance_sell4 = alis['asks'][4]
    binance_sell5 = alis['asks'][5]
    binance_sell6 = alis['asks'][6]
    binance_sell7 = alis['asks'][7]
    binance_sell8 = alis['asks'][8]
    binance_sell9 = alis['asks'][9]
    binance_sell10 = alis['asks'][10]
    binance_sell11 = alis['asks'][11]
    binance_sell12 = alis['asks'][12]
    binance_sell13 = alis['asks'][13]
    binance_sell14 = alis['asks'][14]
    binance_sell15 = alis['asks'][15]
    binance_sell16 = alis['asks'][16]
    binance_sell17 = alis['asks'][17]
    binance_sell18 = alis['asks'][18]
    binance_sell19 = alis['asks'][19]
    binance_sell20 = alis['asks'][20]

    binance_buy_demand = float(binance_buy[1]) + float(binance_buy1[1]) \
        + float(binance_buy2[1]) + float(binance_buy3[1]) \
        + float(binance_buy4[1]) + float(binance_buy5[1]) \
        + float(binance_buy6[1]) + float(binance_buy7[1]) \
        + float(binance_buy8[1]) + float(binance_buy9[1]) \
        + float(binance_buy10[1]) + float(binance_buy11[1]) \
        + float(binance_buy12[1]) + float(binance_buy13[1]) \
        + float(binance_buy14[1]) + float(binance_buy15[1]) \
        + float(binance_buy16[1]) + float(binance_buy17[1]) \
        + float(binance_buy18[1]) + float(binance_buy19[1]) \
        + float(binance_buy20[1])

    for i in range(0, 500):
        print (alis['asks'][i][0], alis['asks'][i][1])

    binance_sell_demand = float(binance_sell[1]) \
        + float(binance_sell1[1]) + float(binance_sell2[1]) \
        + float(binance_sell3[1]) + float(binance_sell4[1]) \
        + float(binance_sell5[1]) + float(binance_sell6[1]) \
        + float(binance_sell7[1]) + float(binance_sell8[1]) \
        + float(binance_sell9[1]) + float(binance_sell10[1]) \
        + float(binance_sell11[1]) + float(binance_sell12[1]) \
        + float(binance_sell13[1]) + float(binance_sell14[1]) \
        + float(binance_sell15[1]) + float(binance_sell16[1]) \
        + float(binance_sell17[1]) + float(binance_sell18[1]) \
        + float(binance_sell19[1]) + float(binance_sell20[1])

there is 500 bids and 500 asks
after getting data I sum bids  ands asks like this

I tried to make for loop but only could print this values cant sum it in for loop this is the code I tried:
sample output:

0.9315 18328.6
0.9316 18201.2
0.9317 23544.0
0.9318 260.4
0.9319 689.5
0.9320 20410.5
0.9321 47.7
0.9322 294.2
0.9323 446.6
0.9324 104.0
0.9325 3802.3
0.9326 100.1
0.9327 20122.9
0.9328 1410.0
0.9329 7745.1
0.9330 9094.4
0.9331 10389.9
0.9332 248.5
0.9333 71559.7
0.9334 18024.1
0.9335 7404.5
0.9336 1366.6
0.9337 21972.4
0.9338 1224.8
0.9339 49.9
0.9340 17590.5
0.9341 17967.1
0.9342 272.3
0.9343 704.4
0.9344 3581.7
0.9345 3896.8

the first items are price second is quantity

I am trying to make a function that sum and divide avg.price and also want to know how many bids total and asks total.

Body:
You can sum in a for loop like this:

total_ask_volume = 0
total_bid_volume = 0
for i  in range(0, 500):
    total_ask_volume += float(alis["asks"][i][1])
    total_bid_volume += float(alis["bids"][i][1])
print(total_ask_volume, total_bid_volume)

Another option is to skip the i index, and go through the values directly:

total_ask_volume = 0
for ask in alis["asks"]:
    total_ask_volume += float(ask[1])

total_bid_volume = 0
for bid in alis["bids"]:
    total_bid_volume += float(bid[1])

print(total_ask_volume, total_bid_volume)

This can sometimes be clearer, particularly in situations where you'd otherwise have multiple indexes (i, j, k and so on) which could get confusing.

As a side note, float often rounds in unintuitive ways; it probably doesn't matter in this particular circumstance, but in most situations involving money you probably want to use Decimal instead (or multiply by 100 and count whole numbers of cents).


问:
Vulkan abort problematic commands?
I have an application where multiple threads would be rendering different parts of a world. However it may occur that one of those threads could submit a highly problematic, or even malicious, command to Vulkan.

Is there anyway to preemptively check for issues with the command that could catch it being problematic? Or let it attempt to be executed, but then by some means determine if it is problematic and abort it? All the while not corrupting or wrecking appropriate commands that were submitted from other threads.

I know obvious solution is "don't submit malicious commands!" but without explaining everything, the jist of this is to try and create a kind graphics sandbox.

答:
The Vulkan run-time assumes well formed input; there isn't any error checking (that's left to layer drivers) so without validation you could get rendering corruption or driver crashes.

You can get some limited protection to GPU-side buffer overruns using robustBufferAccess, but it only catches a tiny subset of the problems.

Beyond that the only real solution is to rely on host process isolation, and put each content provider into a separate process on the host OS with a unique rendering context.

Even with that you can get trivial denial-of-service (shader with a very long running and/or infinite loop), which the API doesn't really give you any means to control. You'd be reliant on the privileged GPU driver timing out the process and killing it.

Title: Vulkan abort problematic commands?


问:
Why is the usage of $this in PHP necessary when referencing methods or variables in the same class?
I was explaining to a Java developer why his method call wasn't working. He just needed to add $this->method_name();

He then asked me, "Why do I need to add $this to the method when it's declared in the same class?"

I didn't really know how to answer. Maybe it's because PHP has a global namespace and it you need to explicitly tell it that the method you are looking for belongs to the current class? But then why doesn't PHP check the current class for the method BEFORE looking at the global namespace?

答:
Seems PHP hasn't been properly OOPed.  In Java and C++, references to the current object ('this') are implicit, ie no explicit mention is needed, leaving the code much cleaner.
Perhaps there is some reason this is difficult with PHP implementation ?</p>


问:
Sorting a vector of objects in C++
say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

```<code>class Information {

private:
int age;
string name;

//etc, etc...
};
</code>```

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

```<code>sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());
</code>```

listOfPeople would be the vector.

Any help would be greatly appreciated.

答:
Others have already shown C++98/03 solutions. In C++11, you might want to use a lambda for your comparison instead:

```<code>// ascending age:
std::sort(people.begin(), people.end(),
          [](person const &a, person const &b) { return a.age < b.age; });

// descending age:
std::sort(people.begin(), people.end(),
          [](person const &a, person const &b) { return b.age < a.age; });
</code>```

And, in case it should happen to arise:

```<code>// ascending name:
std::sort(people.begin(), people.end(),
          [](person const &a, person const &b) { return a.name < b.name; });

// descending name:
std::sort(people.begin(), people.end(),
          [](person const &a, person const &b) { return b.name < a.name; });
</code>```

IMO, Information is too generic a name, so I've changed it to person. Contrariwise, listOfPeople puts too much emphasis on the form rather than the content (and, worse, it's just plain wrong, since you really have a vector of people, not a list at all). IMO, in programming, it's generally better to use list only to refer to a linked list, not to linear data structures in general.

Title: Sorting a vector of objects in C++

Body:
say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

class Information {

private:
int age;
string name;

//etc, etc...
};

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());

listOfPeople would be the vector.

Any help would be greatly appreciated.

Body:
Others have already shown C++98/03 solutions. In C++11, you might want to use a lambda for your comparison instead:

// ascending age:
std::sort(people.begin(), people.end(),
          [](person const &a, person const &b) { return a.age < b.age; });

// descending age:
std::sort(people.begin(), people.end(),
          [](person const &a, person const &b) { return b.age < a.age; });

And, in case it should happen to arise:

// ascending name:
std::sort(people.begin(), people.end(),
          [](person const &a, person const &b) { return a.name < b.name; });

// descending name:
std::sort(people.begin(), people.end(),
          [](person const &a, person const &b) { return b.name < a.name; });

IMO, Information is too generic a name, so I've changed it to person. Contrariwise, listOfPeople puts too much emphasis on the form rather than the content (and, worse, it's just plain wrong, since you really have a vector of people, not a list at all). IMO, in programming, it's generally better to use list only to refer to a linked list, not to linear data structures in general.


问:
How do I get the currently displayed fragment?
I am playing with fragments in Android.

I know I can change a fragment by using the following code:

```<code>FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction fragTrans = fragMgr.beginTransaction();

MyFragment myFragment = new MyFragment(); //my custom fragment

fragTrans.replace(android.R.id.content, myFragment);
fragTrans.addToBackStack(null);
fragTrans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragTrans.commit();
</code>```

My question is, in a Java file, how can I get the currently displayed Fragment instance?

答:
In androidx.fragment:fragment-ktx:1.4 there is a new way how can we get recently added fragment to the container.
If you using FragmentContainerView as a container for yours fragments it will be easy:

```<code>val fragmentContainer: FragmentContainerView = ...
val currentFragment: Fragment = fragmentContainer.getFragment()
</code>```

Body:
I am playing with fragments in Android.

I know I can change a fragment by using the following code:

FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction fragTrans = fragMgr.beginTransaction();

MyFragment myFragment = new MyFragment(); //my custom fragment

fragTrans.replace(android.R.id.content, myFragment);
fragTrans.addToBackStack(null);
fragTrans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragTrans.commit();

My question is, in a Java file, how can I get the currently displayed Fragment instance?

Body:
In androidx.fragment:fragment-ktx:1.4 there is a new way how can we get recently added fragment to the container.
If you using FragmentContainerView as a container for yours fragments it will be easy:

val fragmentContainer: FragmentContainerView = ...
val currentFragment: Fragment = fragmentContainer.getFragment()


问:
nginx: load 404 page if location is not matched with given url
in nginx.conf I have used this

try_files $uri $uri/ /index.php;

so that when user type any url the index.php will load.

but now I have some list of url. like [blog, contact, faq]

so when user hit anything out of that url. for example, /test I want to display the 404 page.

how can I achieve that?

here is the location block

```<code>location / {
             auth_basic "Restricted Content";
             auth_basic_user_file /etc/nginx/.htpasswd;
             try_files $uri $uri/ /index.php;

         }
</code>```

答:
Use the map block, e.g.:

map $uri $correct_route {
    /blog    1;
    /contact 1;
    /faq     1;
    # default value will be an empty string
}
server {
    ...
    auth_basic "Restricted Content";
    auth_basic_user_file /etc/nginx/.htpasswd;
    location / {
        try_files $uri $uri/ @check_route;
    }
    location @check_route {
        if ($correct_route) { rewrite ^ /index.php last; }
        return 404;
    }
    ...
}
```

Body:
in nginx.conf I have used this

try_files $uri $uri/ /index.php;

so that when user type any url the index.php will load.

but now I have some list of url. like [blog, contact, faq]

so when user hit anything out of that url. for example, /test I want to display the 404 page.

how can I achieve that?

here is the location block

location / {
             auth_basic "Restricted Content";
             auth_basic_user_file /etc/nginx/.htpasswd;
             try_files $uri $uri/ /index.php;

         }


问:
How to implement MapTiler server in React Native app
I am building a mobile app that includes a map and some markers, I found that using react-native-maps with Google API will cost a lot.

I started hosting my own map tile server using MapTiler.

My problem is I can't find a library that can display my map in React native component.

This is my MapTiler server:
I don't know how to implement these raster tiles in my react native app.

I am using Expo.

Which library should I use that doesn't have any pricing or commercial license.
If you have a good solution please give me an example.

I tried to use react-native-maps but it didn't show any tiles.

```<code>        <MapView
          region={location}
          rotateEnabled={false}
          style={{ flex: 1 }}
          style={styles.map}
          showsUserLocation
          mapType="none"
        >
          <UrlTile
            tileSize={512}
            urlTemplate="http://localhost:3650/api/maps/satellite-hybrid/{z}/{x}/{y}.png"
            maximumZ={19}
          />
          <Marker
            title="Home"
            coordinate={{
              latitude: location.latitude,
              longitude: location.longitude,
            }}
          />
        </MapView>
</code>```

答:
The problem was that react native doesn't understand what localhost is.
I had to change localhost into my IP address 192.168.1.1

I got it from CMD using command ipconfig

```<code>urlTemplate="http://192.168.1.1:3650/api/maps/satellite-hybrid/{z}/{x}/{y}.png"
</code>```

Body:
I am building a mobile app that includes a map and some markers, I found that using react-native-maps with Google API will cost a lot.

I started hosting my own map tile server using MapTiler.

My problem is I can't find a library that can display my map in React native component.

This is my MapTiler server:
I don't know how to implement these raster tiles in my react native app.

I am using Expo.

Which library should I use that doesn't have any pricing or commercial license.
If you have a good solution please give me an example.

I tried to use react-native-maps but it didn't show any tiles.

        <MapView
          region={location}
          rotateEnabled={false}
          style={{ flex: 1 }}
          style={styles.map}
          showsUserLocation
          mapType="none"
        >
          <UrlTile
            tileSize={512}
            urlTemplate="http://localhost:3650/api/maps/satellite-hybrid/{z}/{x}/{y}.png"
            maximumZ={19}
          />
          <Marker
            title="Home"
            coordinate={{
              latitude: location.latitude,
              longitude: location.longitude,
            }}
          />
        </MapView>

Body:
The problem was that react native doesn't understand what localhost is.
I had to change localhost into my IP address 192.168.1.1

I got it from CMD using command ipconfig

urlTemplate="http://192.168.1.1:3650/api/maps/satellite-hybrid/{z}/{x}/{y}.png"


问:
Use DataTable Compute method for a different locale?
I'm using the Compute method to evaluate an expression. My current locale is de-DE. This is simply done by:

```<code>var dt = new DataTable() {
    Locale = CultureInfo.CurrentCulture,
};

var v = dt.Compute(myExpression);
</code>```

When I enter an expression such as:

30.5 / 2.25

The expression is evaluated correctly.

However, when as my locale is different, I need to enter the above expression as:

30,5 / 2,25

The expression is not evaluated as expected.

How do I get the Compute method to evaluate expression correctly for the given locale?

答:
Easy, crude workaround that works:

```<code>var dt = new DataTable();

var temp = myExpression.Replace(".", string.Empty).Replace(",", ".");
var v = dt.Compute(temp, string.Empty);
</code>```

Won't work when changing locales. Might be expanded to handle locales.

Body:
I'm using the Compute method to evaluate an expression. My current locale is de-DE. This is simply done by:

var dt = new DataTable() {
    Locale = CultureInfo.CurrentCulture,
};

var v = dt.Compute(myExpression);

When I enter an expression such as:

30.5 / 2.25

The expression is evaluated correctly.

However, when as my locale is different, I need to enter the above expression as:

30,5 / 2,25

The expression is not evaluated as expected.

How do I get the Compute method to evaluate expression correctly for the given locale?

Body:
Easy, crude workaround that works:

var dt = new DataTable();

var temp = myExpression.Replace(".", string.Empty).Replace(",", ".");
var v = dt.Compute(temp, string.Empty);

Won't work when changing locales. Might be expanded to handle locales.


问:
ios - background location getting and sending periodically, silent push (Flutter)
The goal is to get iPhone location and send it to the server periodically (like every 15 minutes, the interval is a parameter), when the app is on the screen, or in background. The server expects the phone location at given intervals even if the location did not change.
We are using Flutter. The app is for iOS and Android. We have tried some libraries like background_fetch, but they seem not to guarantee the exact intervals. We are experimenting with silent push notifications but they do not work always, especially when the app is in background. Can anyone point me to the right direction please?

答:
For getting location updates when the app is active, in background or
killed

I have used this package (background_locator) and it works as expected, you could also specify your own intervals as to when you want to receive the location updates (in your case 15 minutes)

You can check the example folder and documentation on the usage of the package

background_locator


问:
Hiding ‘Bottom Navigation Bar’ whilst keyboard is present - Android
I have a small demo chat UI application. This application has a bottom navigation bar. I need the bottom navigation bar to hide when the keyboard appears.

Here is an example of the chat UI

As you can see when you click in the EditText element, the keyboard appears but the bottom navigation bar stays visible. I have tried methods such as this measurement method, but the UI elements flicker like this.

Is there a proper way to hide the bottom navigation bar when the keyboard is visible?

EDIT:
In the below activity you can see where I set the keyboard listener to adjust the position of UI elements when the keyboard is determined as being visible.

This is my activity code, uses setKeyboardListener method from the above link and set it in onCreateView:

```<code>package uk.cal.codename.projectnedry.TeamChatFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.roughike.bottombar.BottomBar;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import uk.cal.codename.projectnedry.R;
import uk.cal.codename.projectnedry.TeamChatFragment.ListAdapter.TeamChatListAdapter;
import uk.demo.cal.genericmodelviewpresenter.GenericMvp.GenericMvpFragment;

import static android.view.View.GONE;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link TeamChatView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link TeamChatView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TeamChatView extends GenericMvpFragment implements TeamChatContract.RequiredViewOps {

    private OnFragmentInteractionListener mListener;
    @BindView(R.id.teamChatList)
    RecyclerView mTeamChatRecyclerView;
    @BindView(R.id.teamChatSendButton)
    ImageButton mTeamChatSendButton;
    @BindView(R.id.messageTextInput)
    EditText mMessageTextInput;
    TeamChatListAdapter mTeamChatListAdapter;
    TeamChatListAdapter.ClickListener mTeamChatListClickListener;
    private ArrayList<String> mTestMessageList;

    public interface OnKeyboardVisibilityListener {
        void onVisibilityChanged(boolean visible);
    }

    public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
        final View activityRootView = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);

        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            private boolean wasOpened;

            private final int DefaultKeyboardDP = 100;

            // From @nathanielwolf answer...  Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
            private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);

            private final Rect r = new Rect();

            @Override
            public void onGlobalLayout() {
                // Convert the dp to pixels.
                int estimatedKeyboardHeight = (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());

                // Conclude whether the keyboard is shown or not.
                activityRootView.getWindowVisibleDisplayFrame(r);
                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                boolean isShown = heightDiff >= estimatedKeyboardHeight;

                if (isShown == wasOpened) {
                    Log.d("Keyboard state", "Ignoring global layout change...");
                    return;
                }

                wasOpened = isShown;
                listener.onVisibilityChanged(isShown);
            }
        });
    }

    public TeamChatView() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment TeamChatView.
     */
    public static TeamChatView newInstance() {
        TeamChatView fragment = new TeamChatView();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(TeamChatPresenter.class, TeamChatModel.class, savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_team_chat_view, container, false);
        this.mUnbinder = ButterKnife.bind(this, view);

        mTestMessageList = new ArrayList<>();
        this.mTeamChatListAdapter = new TeamChatListAdapter(mTestMessageList);
        this.mTeamChatRecyclerView.setAdapter(this.mTeamChatListAdapter);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        this.mTeamChatRecyclerView.setLayoutManager(linearLayoutManager);

        this.mTeamChatSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!String.valueOf(mMessageTextInput.getText()).equals("")) {
                    getSpecificImpOfGenericPresenter().sendMessage(String.valueOf(mMessageTextInput.getText()));
                    mMessageTextInput.setText("");
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                }
            }
        });

        setKeyboardListener(new OnKeyboardVisibilityListener(){
            @Override
            public void onVisibilityChanged(boolean visible) {
                RelativeLayout contentFrame = (RelativeLayout) getActivity().findViewById(R.id.content_company_navigation);
                BottomBar lowerNavigationBar = (BottomBar) getActivity().findViewById(R.id.bottomBar);
                if (visible) { // if more than 100 pixels, its probably a keyboard...
                    lowerNavigationBar.setVisibility(GONE);
                    contentFrame.setPadding(0, 0, 0, 0);
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                } else {
                    contentFrame.setPadding(0, 0, 0, convertDpToPixel(60, getContext()));
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                    lowerNavigationBar.setVisibility(View.VISIBLE);
                }
            }
        });
        return view;
    }

    /**
     * This method converts dp unit to equivalent pixels, depending on device density.
     *
     * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent px equivalent to dp depending on device density
     */
    public static int convertDpToPixel(float dp, Context context){
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        int px = (int) (dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }

    public void addToTestMessageList(String str){
        this.mTestMessageList.add(str);
        this.mTeamChatListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
       // getView().getViewTreeObserver().removeGlobalOnLayoutListener(test);
    }

    @Override
    public TeamChatPresenter getSpecificImpOfGenericPresenter() {
        return (TeamChatPresenter) this.mPresenter;
    }
}
</code>```

This is my XML layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="uk.cal.codename.projectnedry.TeamChatFragment.TeamChatView">

    <android.support.v7.widget.RecyclerView
        android:layout_above="@+id/chatViewMessageEntryLayout"
        android:id="@+id/teamChatList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:isScrollContainer="false"
        android:paddingTop="10dp"
        android:scrollbars="vertical" />

    <RelativeLayout
        android:id="@+id/chatViewMessageEntryLayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <View
            android:id="@+id/chatViewMessageEntrySeperator"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#e3e3e8" />

        <EditText
            android:id="@+id/messageTextInput"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:layout_below="@+id/chatViewMessageEntrySeperator"
            android:layout_toLeftOf="@+id/teamChatSendButton"
            android:background="@android:color/transparent"
            android:hint="Enter message"
            android:inputType="textCapSentences|textMultiLine"
            android:maxLength="1000"
            android:maxLines="4"
            android:paddingLeft="10dp" />

        <ImageButton
            android:id="@+id/teamChatSendButton"
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_gravity="center"
            android:background="#00B9EF"
            android:src="@drawable/ic_send_white_24dp" />

    </RelativeLayout>

</RelativeLayout>
</code>```

答:
Actively listen for the Keyboard(IME) open/close events and show/hide bottom navigation accordingly.

We can make use of the WindowInsetsCompat API which makes this job effortless.

Step 1: Make sure you have migrated to AndroidX

Step 2: In your Fragment inside onCreateView add the listener for Keyboard(IME) events

ViewCompat.setOnApplyWindowInsetsListener(window.decorView.rootView) { _, insets ->

   //This lambda block will be called, every time keyboard is opened or closed

    val imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
    if(imeVisible){
     //Now show-hide bottom navigation accordingly
    }

    insets
}

```

This is all you need

For more info on window insets, you can check out this in-depth article

NOTE:

Earlier detecting Keyboard open/close events was not an easy task. Android Devs resorted to all types of hacks to accomplish this. But after decades of requests, prayers and rants Google finally came up with WindowInsets API. Thank you, Google

Body:
I have a small demo chat UI application. This application has a bottom navigation bar. I need the bottom navigation bar to hide when the keyboard appears.

Here is an example of the chat UI

As you can see when you click in the EditText element, the keyboard appears but the bottom navigation bar stays visible. I have tried methods such as this measurement method, but the UI elements flicker like this.

Is there a proper way to hide the bottom navigation bar when the keyboard is visible?

EDIT:
In the below activity you can see where I set the keyboard listener to adjust the position of UI elements when the keyboard is determined as being visible.

This is my activity code, uses setKeyboardListener method from the above link and set it in onCreateView:

package uk.cal.codename.projectnedry.TeamChatFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.roughike.bottombar.BottomBar;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import uk.cal.codename.projectnedry.R;
import uk.cal.codename.projectnedry.TeamChatFragment.ListAdapter.TeamChatListAdapter;
import uk.demo.cal.genericmodelviewpresenter.GenericMvp.GenericMvpFragment;

import static android.view.View.GONE;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link TeamChatView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link TeamChatView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TeamChatView extends GenericMvpFragment implements TeamChatContract.RequiredViewOps {

    private OnFragmentInteractionListener mListener;
    @BindView(R.id.teamChatList)
    RecyclerView mTeamChatRecyclerView;
    @BindView(R.id.teamChatSendButton)
    ImageButton mTeamChatSendButton;
    @BindView(R.id.messageTextInput)
    EditText mMessageTextInput;
    TeamChatListAdapter mTeamChatListAdapter;
    TeamChatListAdapter.ClickListener mTeamChatListClickListener;
    private ArrayList<String> mTestMessageList;

    public interface OnKeyboardVisibilityListener {
        void onVisibilityChanged(boolean visible);
    }

    public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
        final View activityRootView = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);

        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            private boolean wasOpened;

            private final int DefaultKeyboardDP = 100;

            // From @nathanielwolf answer...  Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
            private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);

            private final Rect r = new Rect();

            @Override
            public void onGlobalLayout() {
                // Convert the dp to pixels.
                int estimatedKeyboardHeight = (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());

                // Conclude whether the keyboard is shown or not.
                activityRootView.getWindowVisibleDisplayFrame(r);
                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                boolean isShown = heightDiff >= estimatedKeyboardHeight;

                if (isShown == wasOpened) {
                    Log.d("Keyboard state", "Ignoring global layout change...");
                    return;
                }

                wasOpened = isShown;
                listener.onVisibilityChanged(isShown);
            }
        });
    }

    public TeamChatView() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment TeamChatView.
     */
    public static TeamChatView newInstance() {
        TeamChatView fragment = new TeamChatView();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(TeamChatPresenter.class, TeamChatModel.class, savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_team_chat_view, container, false);
        this.mUnbinder = ButterKnife.bind(this, view);

        mTestMessageList = new ArrayList<>();
        this.mTeamChatListAdapter = new TeamChatListAdapter(mTestMessageList);
        this.mTeamChatRecyclerView.setAdapter(this.mTeamChatListAdapter);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        this.mTeamChatRecyclerView.setLayoutManager(linearLayoutManager);

        this.mTeamChatSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!String.valueOf(mMessageTextInput.getText()).equals("")) {
                    getSpecificImpOfGenericPresenter().sendMessage(String.valueOf(mMessageTextInput.getText()));
                    mMessageTextInput.setText("");
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                }
            }
        });

        setKeyboardListener(new OnKeyboardVisibilityListener(){
            @Override
            public void onVisibilityChanged(boolean visible) {
                RelativeLayout contentFrame = (RelativeLayout) getActivity().findViewById(R.id.content_company_navigation);
                BottomBar lowerNavigationBar = (BottomBar) getActivity().findViewById(R.id.bottomBar);
                if (visible) { // if more than 100 pixels, its probably a keyboard...
                    lowerNavigationBar.setVisibility(GONE);
                    contentFrame.setPadding(0, 0, 0, 0);
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                } else {
                    contentFrame.setPadding(0, 0, 0, convertDpToPixel(60, getContext()));
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                    lowerNavigationBar.setVisibility(View.VISIBLE);
                }
            }
        });
        return view;
    }

    /**
     * This method converts dp unit to equivalent pixels, depending on device density.
     *
     * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent px equivalent to dp depending on device density
     */
    public static int convertDpToPixel(float dp, Context context){
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        int px = (int) (dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }

    public void addToTestMessageList(String str){
        this.mTestMessageList.add(str);
        this.mTeamChatListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
       // getView().getViewTreeObserver().removeGlobalOnLayoutListener(test);
    }

    @Override
    public TeamChatPresenter getSpecificImpOfGenericPresenter() {
        return (TeamChatPresenter) this.mPresenter;
    }
}

This is my XML layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="uk.cal.codename.projectnedry.TeamChatFragment.TeamChatView">

    <android.support.v7.widget.RecyclerView
        android:layout_above="@+id/chatViewMessageEntryLayout"
        android:id="@+id/teamChatList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:isScrollContainer="false"
        android:paddingTop="10dp"
        android:scrollbars="vertical" />

    <RelativeLayout
        android:id="@+id/chatViewMessageEntryLayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <View
            android:id="@+id/chatViewMessageEntrySeperator"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#e3e3e8" />

        <EditText
            android:id="@+id/messageTextInput"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:layout_below="@+id/chatViewMessageEntrySeperator"
            android:layout_toLeftOf="@+id/teamChatSendButton"
            android:background="@android:color/transparent"
            android:hint="Enter message"
            android:inputType="textCapSentences|textMultiLine"
            android:maxLength="1000"
            android:maxLines="4"
            android:paddingLeft="10dp" />

        <ImageButton
            android:id="@+id/teamChatSendButton"
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_gravity="center"
            android:background="#00B9EF"
            android:src="@drawable/ic_send_white_24dp" />

    </RelativeLayout>

</RelativeLayout>

Body:
Actively listen for the Keyboard(IME) open/close events and show/hide bottom navigation accordingly.

We can make use of the WindowInsetsCompat API which makes this job effortless.

Step 1: Make sure you have migrated to AndroidX

Step 2: In your Fragment inside onCreateView add the listener for Keyboard(IME) events

ViewCompat.setOnApplyWindowInsetsListener(window.decorView.rootView) { _, insets ->

   //This lambda block will be called, every time keyboard is opened or closed

    val imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
    if(imeVisible){
     //Now show-hide bottom navigation accordingly
    }

    insets
}

This is all you need

For more info on window insets, you can check out this in-depth article

NOTE:

Earlier detecting Keyboard open/close events was not an easy task. Android Devs resorted to all types of hacks to accomplish this. But after decades of requests, prayers and rants Google finally came up with WindowInsets API. Thank you, Google


问:
Running separate infinite background thread in a python webapp (fastapi/flask/django)
How can i launch an application which does below 2 things:

Expose rest endpoint via FastAPI.

Run a seperate thread infintely (rabbitmq consumer - pika) waiting for request.

Below is the code through which i am launching the fastAPI server. But when i try to run a thread,  before execution of below line, it says coroutine was never awaited.

How can both be run parallely?

答:
Maybe this is not the answer you are looking for.
There is a library called celery that makes multithreading easy to manage in python.

Check it out:
https://docs.celeryproject.org/en/stable/getting-started/introduction.html


问:
I am trying a data visualization using R Studio and need all points in X and Y axis
sample image pic

I am new to R programming and trying a simple data visualization using ggplot2. I am trying to display night price distribution of Airbnb hotels on X axis. 'Price' is on X-axis and I am trying to display all prices in that column(instead of just 0,100,200,300) like 0,10,20,30,.....Can someone please help.

Body:
With ggplot2, you can use geom_density, then to show every 10 along the x-axis, you can use scale_x_continuous.

library(ggplot2)

ggplot(df, aes(x=price)) +
  geom_density(alpha=0.4) +
  scale_x_continuous(breaks = seq(0, max(df$price), 10))

Output

Data (thanks @danlooo for the data)

df <- structure(list(id = 1:100, price = c(109.624595324253, 27.6649096833247,
                                           83.8409732976183, 181.114805826247, 65.5487938201821, 202.106111130748,
                                           147.188955595147, 204.096343939955, 195.855863939165, 79.2593880203536,
                                           151.642674971707, 16.0715203902367, 107.877484517272, 174.456805822279,
                                           96.210521872544, 163.589047207947, 132.083670383609, 140.038062746858,
                                           193.132961283141, 72.7321986615563, 130.963890537559, 106.132021275504,
                                           60.4507917286959, 75.0114164907217, 18.2423993103795, 189.228365966262,
                                           114.943913606508, 137.625244706715, 46.2698928281852, 103.213687214262,
                                           163.132473955447, 154.997464810468, 43.8222435603852, 272.303942631828,
                                           64.0138914012169, 83.6572951230969, 73.5113015030196, 126.207637222461,
                                           46.0195176447721, 97.244449039937, 209.934209220287, 11.3045335692197,
                                           103.251611324842, 132.748519111359, 64.3565445507629, 151.028376981832,
                                           131.580735955202, 122.371667635779, 123.326853205371, 65.0869696099348,
                                           98.1772722505436, 155.898308483086, 64.9958736705616, 43.7975911576335,
                                           69.3466360115026, 150.62213539352, 17.193508112824, 129.513154538279,
                                           115.956716797703, 135.080322322307, 31.1271434940532, 115.632293916597,
                                           156.042378896312, 123.591544480071, 156.384266079119, 133.88615684784,
                                           175.511995898008, 203.051717486004, 67.4842044143933, 33.7881163386762,
                                           132.973565300411, 88.9287426485258, 51.8920445993446, 109.373009595098,
                                           100.612231498194, 135.614186933111, 62.3137096206145, 101.909496555451,
                                           158.921053166486, 92.3398075387043, 91.9151233455572, 173.013105599786,
                                           200.472921822109, 96.1030891096855, 167.717103863236, 48.6408103817855,
                                           47.9412339814337, 56.4688492407377, 142.656510914191, 68.861990329901,
                                           160.785493322116, 18.9295625344691, 96.5712335603303, 96.8508537720102,
                                           153.785385539535, 156.455037629072, 122.507336310327, 102.529322114613,
                                           93.7834890773161, 145.600572946958)), class = c("tbl_df", "tbl",
                                                                                "data.frame"), row.names = c(NA, -100L))


问:
Quarkus testing in Gradle - How to deal with test and native-test
I have a Quarkus project that has both a test sources folder and a native-test folder. The guidance seems to be that I would have a lot of the same tests (specifically @QuarkusIntegrationTests) in the native-test folder. Is there a way to specify to use the same source set in test as native-test?

It makes sense that one might want to have different tests in the other source-set, but it seems tedious to me to have to keep track of the same tests between the two source-sets. Is there a way to tell the nativeTest task to use the tests from the test source set? Is that what I want? Am I visuallizing the purposes of these tests correctly?

I have assumed I could set up in Gradle a bit of script to copy in relevant tests to the native-test directories when testNative runs but this feels quite hacky.

答:
The nativeTest task inherits from the Test task, so you should be able to configure it as the test task.

A problem you may face is that gradle test will run @QuarkusIntegrationTest with the default packaging (this may take time).
gradle nativeTest will run all tests event the @QuarkusTest.

Using include / exclude in task configuration may lead to what you want:

```<code>nativeTest {
  testClassesDirs = project.sourceSets.nativeTest.output.classesDirs
  include '**/it/*'
}

test {
  exclude '**/it/*'
}
</code>```

gradle test will run all tests from src/test/java excepts tests in the it package.
gradle nativeTest will only run test from src/test/java located in the it package.

Body:
The nativeTest task inherits from the Test task, so you should be able to configure it as the test task.

A problem you may face is that gradle test will run @QuarkusIntegrationTest with the default packaging (this may take time).
gradle nativeTest will run all tests event the @QuarkusTest.

Using include / exclude in task configuration may lead to what you want:

nativeTest {
  testClassesDirs = project.sourceSets.nativeTest.output.classesDirs
  include '**/it/*'
}

test {
  exclude '**/it/*'
}

gradle test will run all tests from src/test/java excepts tests in the it package.
gradle nativeTest will only run test from src/test/java located in the it package.