问:
How can I set the complete page background for a Word page with Apache POI?
I have already searched all day today, but without success. First I created a new Word document and tried to set the background with

```<code> //Blank Document
    XWPFDocument doc = new XWPFDocument();

    //Write the Document in file system
    FileOutputStream out = new FileOutputStream(new File("test.docx"));

    File backgroundImage = new File("img.png");

doc.getDocument().addNewBackground().addNewDrawing().save(backgroundImage);
</code>```

backgroundImage is the picture I want to set.

答:
Your question seems to be about add, change, or delete the background color in Word.

This consists of two settings.

First, display-background-shape must be enabled in document settings .

Second, the document must have set background having a color. This might be white but must be set.

Then optional a picture reference can be set. That picture then gets used as background tile. Microsoft Word itself still uses VML to set the picture reference to background. This is much simpler than using a drawing. Although using a drawing in CTBackground is possible according Office Open XML specifications, I've never seen this in practical usage until now.

Nothing of that is supported by the high level class layer of apache poi. But it can be solved using the low level org.openxmlformats.schemas.wordprocessingml.x2006.main.* classes.

One more challenge is to get the XWPFSettings. There is not a getter method. So we need using reflection to get it from XWPFDocument. Same for to get CTSettings from XWPFSettings then.

Following complete example shows how to set background color and/or background tile picture. The code is tested and works using current apache po 5.2.0 and poi-ooxml-full-5.2.0.jar.

```<code>import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class CreateWordPageBackground {

 static XWPFSettings getSettings(XWPFDocument document) throws Exception {
  java.lang.reflect.Field settings = XWPFDocument.class.getDeclaredField("settings");
  settings.setAccessible(true);
  return (XWPFSettings)settings.get(document);
 }

 static void setDisplayBackgroundShape(XWPFSettings settings, boolean booleanOnOff) throws Exception {
  java.lang.reflect.Field _ctSettings = XWPFSettings.class.getDeclaredField("ctSettings");
  _ctSettings.setAccessible(true);
  CTSettings ctSettings = (CTSettings )_ctSettings.get(settings);
  CTOnOff onOff = CTOnOff.Factory.newInstance();
  onOff.setVal(booleanOnOff);
  ctSettings.setDisplayBackgroundShape(onOff);
 }

 static void setBackgroundPictureId(CTBackground background, String rId) throws Exception {
  String vmlBackgroundXML = ""
   + "<v:background xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" "
   + "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" "
   + "id=\"_x0000_s1025\" o:bwmode=\"white\" o:targetscreensize=\"1024,768\">"
   + "<v:fill r:id=\"" + rId + "\" recolor=\"t\" type=\"frame\"/>"
   + "</v:background>"
  ;
  org.apache.xmlbeans.XmlObject vmlBackgroundXmlObject = org.apache.xmlbeans.XmlObject.Factory.parse(vmlBackgroundXML);
  background.set(vmlBackgroundXmlObject);
 }

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  // we need document settings to set display-background-shape
  XWPFSettings settings = getSettings(document);
  setDisplayBackgroundShape(settings, true);

  // set a background color
  CTBackground background = document.getDocument().addNewBackground();
  background.setColor("FF0000");

  // crate a picture reference in document
  InputStream is = new FileInputStream("./logo.png");
  String rId = document.addPictureData(is, Document.PICTURE_TYPE_PNG);
  // set a background picture
  setBackgroundPictureId(background, rId);
  background.setColor("FFFFFF");

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();
  run.setText("Text in Body ...");

  paragraph = document.createParagraph();

  FileOutputStream out = new FileOutputStream("./CreateWordPageBackground.docx");
  document.write(out);
  out.close();
  document.close();
 }
}
</code>```

Both, background color as well as background tile picture, only gets visible in Microsoft Word GUI. It not gets printed.

If the need is a printed page background, then this will be resolved by a shape in the page header, also known as watermark. But this is another question then.

Body:
I have already searched all day today, but without success. First I created a new Word document and tried to set the background with

 //Blank Document
    XWPFDocument doc = new XWPFDocument();

    //Write the Document in file system
    FileOutputStream out = new FileOutputStream(new File("test.docx"));

    File backgroundImage = new File("img.png");

doc.getDocument().addNewBackground().addNewDrawing().save(backgroundImage);

backgroundImage is the picture I want to set.

Body:
Your question seems to be about add, change, or delete the background color in Word.

This consists of two settings.

First, display-background-shape must be enabled in document settings .

Second, the document must have set background having a color. This might be white but must be set.

Then optional a picture reference can be set. That picture then gets used as background tile. Microsoft Word itself still uses VML to set the picture reference to background. This is much simpler than using a drawing. Although using a drawing in CTBackground is possible according Office Open XML specifications, I've never seen this in practical usage until now.

Nothing of that is supported by the high level class layer of apache poi. But it can be solved using the low level org.openxmlformats.schemas.wordprocessingml.x2006.main.* classes.

One more challenge is to get the XWPFSettings. There is not a getter method. So we need using reflection to get it from XWPFDocument. Same for to get CTSettings from XWPFSettings then.

Following complete example shows how to set background color and/or background tile picture. The code is tested and works using current apache po 5.2.0 and poi-ooxml-full-5.2.0.jar.

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class CreateWordPageBackground {

 static XWPFSettings getSettings(XWPFDocument document) throws Exception {
  java.lang.reflect.Field settings = XWPFDocument.class.getDeclaredField("settings");
  settings.setAccessible(true);
  return (XWPFSettings)settings.get(document);
 }

 static void setDisplayBackgroundShape(XWPFSettings settings, boolean booleanOnOff) throws Exception {
  java.lang.reflect.Field _ctSettings = XWPFSettings.class.getDeclaredField("ctSettings");
  _ctSettings.setAccessible(true);
  CTSettings ctSettings = (CTSettings )_ctSettings.get(settings);
  CTOnOff onOff = CTOnOff.Factory.newInstance();
  onOff.setVal(booleanOnOff);
  ctSettings.setDisplayBackgroundShape(onOff);
 }

 static void setBackgroundPictureId(CTBackground background, String rId) throws Exception {
  String vmlBackgroundXML = ""
   + "<v:background xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" "
   + "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" "
   + "id=\"_x0000_s1025\" o:bwmode=\"white\" o:targetscreensize=\"1024,768\">"
   + "<v:fill r:id=\"" + rId + "\" recolor=\"t\" type=\"frame\"/>"
   + "</v:background>"
  ;
  org.apache.xmlbeans.XmlObject vmlBackgroundXmlObject = org.apache.xmlbeans.XmlObject.Factory.parse(vmlBackgroundXML);
  background.set(vmlBackgroundXmlObject);
 }

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  // we need document settings to set display-background-shape
  XWPFSettings settings = getSettings(document);
  setDisplayBackgroundShape(settings, true);

  // set a background color
  CTBackground background = document.getDocument().addNewBackground();
  background.setColor("FF0000");

  // crate a picture reference in document
  InputStream is = new FileInputStream("./logo.png");
  String rId = document.addPictureData(is, Document.PICTURE_TYPE_PNG);
  // set a background picture
  setBackgroundPictureId(background, rId);
  background.setColor("FFFFFF");

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();
  run.setText("Text in Body ...");

  paragraph = document.createParagraph();

  FileOutputStream out = new FileOutputStream("./CreateWordPageBackground.docx");
  document.write(out);
  out.close();
  document.close();
 }
}

Both, background color as well as background tile picture, only gets visible in Microsoft Word GUI. It not gets printed.

If the need is a printed page background, then this will be resolved by a shape in the page header, also known as watermark. But this is another question then.


来源: stackexchange

问:
how to create empty parameter in in pytorch tensor variable
```<code>from torch import FloatTensor

def new_parameter(*size): #1024
    out = torch.nn.Parameter(FloatTensor(*size), requires_grad=True)
    torch.nn.init.xavier_normal_(out)
    return out
</code>```

at = new_parameter(1024, 1)

output is

```<code>Parameter containing:
tensor([[ 0.0203],
        [-0.0043],
        [-0.0386],
        ...,
        [-0.0084],
        [-0.0289],
        [-0.0188]], requires_grad=True)
</code>```

similarway we can create

```<code>bt=torch.randn((1024,1),requires_grad=True)
</code>```

output also same

```<code>tensor([[-1.5478],
        [ 1.5060],
        [ 0.1580],
        ...,
        [ 0.9754],
        [ 0.1699],
        [ 0.2062]], requires_grad=True)
</code>```

are there any differences in a tensor variable the above two ways? please explain the above code in simply

答:
The first method will initialize a random float tensor, then wrap it with nn.Parameter. Which is generally used to register than tensor as a parameter to a nn.Module (not seen here). A utility function nn.init.xavier_normal_ is then applied on that parameter to initialize its values.

The second method only initializes a random float tensor.

ContentLicense: CC BY-SA 4.0

Body:
from torch import FloatTensor

def new_parameter(*size): #1024
    out = torch.nn.Parameter(FloatTensor(*size), requires_grad=True)
    torch.nn.init.xavier_normal_(out)
    return out

at = new_parameter(1024, 1)

output is

Parameter containing:
tensor([[ 0.0203],
        [-0.0043],
        [-0.0386],
        ...,
        [-0.0084],
        [-0.0289],
        [-0.0188]], requires_grad=True)

similarway we can create

bt=torch.randn((1024,1),requires_grad=True)

output also same

tensor([[-1.5478],
        [ 1.5060],
        [ 0.1580],
        ...,
        [ 0.9754],
        [ 0.1699],
        [ 0.2062]], requires_grad=True)

are there any differences in a tensor variable the above two ways? please explain the above code in simply


问:
Bootstrap centered header breaks when header wraps
I have a div with a background image and a header that I want centered both horizontally and vertically within the div in front of the image. I have it working on a header that only has one word: Reviews, but when I use the same approach on a header with two words: Custom Slipcovers, it works on medium and up sizes but breaks for mobile: justifying to the left. It seems to only break when the text wraps.

Centered Properly

Broken for mobile

I am using bootstrap 4 and the snippet is of the working code for the Reviews banner. The slipcover banner code is the same on a different page and has the same css just with new class names. Is there a simple fix that I'm missing here? I'd like to avoid making the text smaller in order to keep it on one line as I want to keep the headers uniform in size.

.banner,
.bannerHeader {
    position: relative;
    height: 200px;
}

.banner::before {
    content: "";
    background-image: url(/img/reviews_banner.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    opacity: 0.7;
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
}

.reviewsHeader {
    position: relative;
    font-size: 3rem;
    font-weight: bold;
}

@media (min-width: 768px) {
    .banner,
    .bannerHeader {
        height: 300px;
    }
}
```
<pre class="lang-html prettyprint-override"><code><div class="container-fluid underNav banner">
    <div class="row bannerHeader align-items-center justify-content-center">
        <h1 class="reviewsHeader">Reviews</h2>
    </div>
</div>
</code>```

Here it is working for the shorter header:
Mobile centered

答:
Here you go... As @Cute Code Rob mentioned, you should add text-center. Let me know if this works for you.

.banner,
.bannerHeader {
  position: relative;
  height: 200px;
}

.banner::before {
  content: "";
  background-image: url(/img/reviews_banner.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  opacity: 0.7;
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
}

.reviewsHeader {
  position: relative;
  font-size: 3rem;
  font-weight: bold;
}

@media (min-width: 768px) {
  .banner,
  .bannerHeader {
    height: 300px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang='en'>

<head>

  <meta charset='UTF-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Document</title>
  <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>
  <script src='https://code.jquery.com/jquery-3.2.1.slim.min.js' integrity='sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN' crossorigin='anonymous'></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js' integrity='sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q' crossorigin='anonymous'></script>
  <script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js' integrity='sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl' crossorigin='anonymous'></script>

</head>

<body>

  <div class='container-fluid underNav banner'>
    <div class='row bannerHeader align-items-center justify-content-center'>
      <h1 class='reviewsHeader text-center'>Reviews</h1>
    </div>
  </div>

</body>

</html></code>```

Body:
I have a div with a background image and a header that I want centered both horizontally and vertically within the div in front of the image. I have it working on a header that only has one word: Reviews, but when I use the same approach on a header with two words: Custom Slipcovers, it works on medium and up sizes but breaks for mobile: justifying to the left. It seems to only break when the text wraps.

Centered Properly

Broken for mobile

I am using bootstrap 4 and the snippet is of the working code for the Reviews banner. The slipcover banner code is the same on a different page and has the same css just with new class names. Is there a simple fix that I'm missing here? I'd like to avoid making the text smaller in order to keep it on one line as I want to keep the headers uniform in size.

.banner,
.bannerHeader {
    position: relative;
    height: 200px;
}

.banner::before {
    content: "";
    background-image: url(/img/reviews_banner.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    opacity: 0.7;
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
}

.reviewsHeader {
    position: relative;
    font-size: 3rem;
    font-weight: bold;
}

@media (min-width: 768px) {
    .banner,
    .bannerHeader {
        height: 300px;
    }
}

Reviews

Here it is working for the shorter header:
Mobile centered

Body:
Here you go... As @Cute Code Rob mentioned, you should add text-center. Let me know if this works for you.

.banner,
.bannerHeader {
  position: relative;
  height: 200px;
}

.banner::before {
  content: "";
  background-image: url(/img/reviews_banner.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  opacity: 0.7;
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
}

.reviewsHeader {
  position: relative;
  font-size: 3rem;
  font-weight: bold;
}

@media (min-width: 768px) {
  .banner,
  .bannerHeader {
    height: 300px;
  }
}

<!DOCTYPE html>
<html lang='en'>

<head>

  <meta charset='UTF-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Document</title>
  <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>
  <script src='https://code.jquery.com/jquery-3.2.1.slim.min.js' integrity='sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN' crossorigin='anonymous'></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js' integrity='sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q' crossorigin='anonymous'></script>
  <script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js' integrity='sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl' crossorigin='anonymous'></script>

</head>

<body>

  <div class='container-fluid underNav banner'>
    <div class='row bannerHeader align-items-center justify-content-center'>
      <h1 class='reviewsHeader text-center'>Reviews</h1>
    </div>
  </div>

</body>

</html>


问:
Sequelize raw query update array of objects as replacements
I am using sequelize (postgres) and I need to properly escape a query like this:

`
       UPDATE "Pets"
       SET "name" = CASE LOWER("name")
         ${input.pets
            .map((pet) => `WHEN '${pet.name.toLowerCase()}' THEN '${pet.newName}'`)
            .join('\n')}
          ELSE "name"
          END
        WHERE LOWER("name") IN(${input.pets
          .map((pet) => `'${pet.name.toLowerCase()}'`)
          .join(',')});
`
```
<p>Sample <code>input.pets</code>:</p>
```[{ name: "rocky", newName: "leo" }]
```
<p>Does anyone have an idea how to achieve this with replacements?</p>
<p>I have found a thread on github which suggested something like this:</p>
<pre class="lang-sql prettyprint-override"><code>let data = [ [ 252456, 1, 55, '0' ],
[ 357083, 1, 56, '0' ],
[ 316493, 1, 57, '0' ] ];

db.query(
  `INSERT INTO product (a, b) VALUES ${data.map(a => '(?)').join(',')};`,
  {
     replacements: data,
     type: Sequelize.QueryTypes.INSERT
  }
);
</code>```

However, a 2d array is being used here not an array of objects. Is there a way to access individual properties from the array? When I try something like this

`
       UPDATE "Pets"
       SET "name" = CASE LOWER("name")
         ${input.pets
            .map((_pet) => `WHEN ? THEN ?`)
            .join('\n')}
          ELSE "name"
          END
        WHERE LOWER("name") IN(${input.pets
          .map((_pet) => `?`)
          .join(',')});
`,
    { type: QueryTypes.UPDATE, replacements: input.pets },
```

The first ? turns out to be the whole object. Is there a way to access it's properties?
I also tried transforming input.pets into a 2d array but still couldn't get it to work as in example with insert above.

In advance thanks for your time

答:
    const names = input.pets.map((pet) => pet.name);
    const newNames = input.pets.map((pet) => pet.newName);

`
        UPDATE "Pets"
        SET "name" = CASE LOWER("name")
          ${names.map((_) => `WHEN LOWER(:names) THEN :newNames`).join('\n')}
              ELSE "name"
              END
        WHERE LOWER("name") IN(${names.map((_) => `LOWER(:names)`).join(',')});
`,
      { replacements: { names, newNames } },

```
<p>This works. In cases like this it's better to work with simpler data structures. Another option I found is using <code>sequelize.escape()</code> built-in function, but it's not documented so I decided not to</p>
<p>EDIT:
After some testing, this works but for only one object in the input</p>
<p>If the input looks something like this:</p>
```[
        { name: "rocky", newName: "fafik" }
        { name: "asd", newName: "qwerty" }
]
```
<p>Then in resut I get queries like this:</p>
```WHEN LOWER('rocky', 'asd') THEN 'fafik', 'qwerty'
WHEN LOWER('rocky', 'asd') THEN 'fafik', 'qwerty'
```
<p>So it doesn't loop over arrays. Still the problem remains, how to access individual properties, whether from array or an object?</p>
<p>EDIT2: FINAL ANSWER</p>
<pre class="lang-js prettyprint-override"><code>sequelize.query(
  `
    UPDATE "Pets"
    SET "name" = CASE LOWER("name")
      ${input.pets.map(() => `WHEN ? THEN ?`).join('\n')}
         ELSE "name"
         END
    WHERE LOWER("name") IN(?);
  `,
  {
    replacements: [
      ...input.pets.flatMap((x) => [x.name.toLocaleLowerCase(), x.newName]),
      input.pets.map((x) => x.name.toLocaleLowerCase()),
    ],
  },
</code>```

Body:
I am using sequelize (postgres) and I need to properly escape a query like this:

`
       UPDATE "Pets"
       SET "name" = CASE LOWER("name")
         ${input.pets
            .map((pet) => `WHEN '${pet.name.toLowerCase()}' THEN '${pet.newName}'`)
            .join('\n')}
          ELSE "name"
          END
        WHERE LOWER("name") IN(${input.pets
          .map((pet) => `'${pet.name.toLowerCase()}'`)
          .join(',')});
`

Sample input.pets:

[{ name: "rocky", newName: "leo" }]

Does anyone have an idea how to achieve this with replacements?

I have found a thread on github which suggested something like this:

let data = [ [ 252456, 1, 55, '0' ],
[ 357083, 1, 56, '0' ],
[ 316493, 1, 57, '0' ] ];

db.query(
  `INSERT INTO product (a, b) VALUES ${data.map(a => '(?)').join(',')};`,
  {
     replacements: data,
     type: Sequelize.QueryTypes.INSERT
  }
);

However, a 2d array is being used here not an array of objects. Is there a way to access individual properties from the array? When I try something like this

`
       UPDATE "Pets"
       SET "name" = CASE LOWER("name")
         ${input.pets
            .map((_pet) => `WHEN ? THEN ?`)
            .join('\n')}
          ELSE "name"
          END
        WHERE LOWER("name") IN(${input.pets
          .map((_pet) => `?`)
          .join(',')});
`,
    { type: QueryTypes.UPDATE, replacements: input.pets },

The first ? turns out to be the whole object. Is there a way to access it's properties?
I also tried transforming input.pets into a 2d array but still couldn't get it to work as in example with insert above.

In advance thanks for your time

Body:
    const names = input.pets.map((pet) => pet.name);
    const newNames = input.pets.map((pet) => pet.newName);

`
        UPDATE "Pets"
        SET "name" = CASE LOWER("name")
          ${names.map((_) => `WHEN LOWER(:names) THEN :newNames`).join('\n')}
              ELSE "name"
              END
        WHERE LOWER("name") IN(${names.map((_) => `LOWER(:names)`).join(',')});
`,
      { replacements: { names, newNames } },

This works. In cases like this it's better to work with simpler data structures. Another option I found is using sequelize.escape() built-in function, but it's not documented so I decided not to

EDIT:
After some testing, this works but for only one object in the input

If the input looks something like this:

[
        { name: "rocky", newName: "fafik" }
        { name: "asd", newName: "qwerty" }
]

Then in resut I get queries like this:

WHEN LOWER('rocky', 'asd') THEN 'fafik', 'qwerty'
WHEN LOWER('rocky', 'asd') THEN 'fafik', 'qwerty'

So it doesn't loop over arrays. Still the problem remains, how to access individual properties, whether from array or an object?

EDIT2: FINAL ANSWER

sequelize.query(
  `
    UPDATE "Pets"
    SET "name" = CASE LOWER("name")
      ${input.pets.map(() => `WHEN ? THEN ?`).join('\n')}
         ELSE "name"
         END
    WHERE LOWER("name") IN(?);
  `,
  {
    replacements: [
      ...input.pets.flatMap((x) => [x.name.toLocaleLowerCase(), x.newName]),
      input.pets.map((x) => x.name.toLocaleLowerCase()),
    ],
  },


问:
Flutter Validate DropDownButton without using DropDownButtonFormField
Im trying to use a dropDownButton instead of a dropDownButtonFormField because i run thru alot of bugs that i see in the dropDownButtonFormField widget. One problem is that in dropDownButtonFormField the clickable area to open the items is only over the hint text and not a cm under it, witch in my case created bad ux. The second problem is that in the dropDownButtonFormField, if an item is a long text and the user presses it when it displays on the main part of the dropdown, the text doesnt create a new line so the user can see the text, the same thing doesnt happen to the dropDownButton widget. Im using dropDownButtonFormField only to use the validator. This is with using DropDownButton Widget.

And this is using the dropDownButtonFormField Widget while having a long text.

```<code>Center locationDropDown() {
    return Center(
      child: Container(
        margin: const EdgeInsets.all(10),
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        decoration: BoxDecoration(
          color: Colors.grey.shade200,
          borderRadius: BorderRadius.circular(12),
        ),
        child: DropdownButtonFormField<String>(
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please select a location';
            }
            return null;
          },
          decoration: const InputDecoration(
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.transparent),
            ),
          ),
          value: chooseLocation,
          hint: const Text('Select a location'),
          isExpanded: true,
          items: workingData!.map((some) {
            return DropdownMenuItem(
              child: Text(
                some.name + ' (${some.location})',
              ),
              value: some.id,
            );
          }).toList(),
          onChanged: (String? displayedValue) {
            setState(
              () {
                chooseLocation = displayedValue!;
              },
            );
          },
        ),
      ),
    );
  }
</code>```

答:
```<code>isDense: false,
</code>```

Add isDense value false in DropdownButtonFormField.

Body:
Im trying to use a dropDownButton instead of a dropDownButtonFormField because i run thru alot of bugs that i see in the dropDownButtonFormField widget. One problem is that in dropDownButtonFormField the clickable area to open the items is only over the hint text and not a cm under it, witch in my case created bad ux. The second problem is that in the dropDownButtonFormField, if an item is a long text and the user presses it when it displays on the main part of the dropdown, the text doesnt create a new line so the user can see the text, the same thing doesnt happen to the dropDownButton widget. Im using dropDownButtonFormField only to use the validator. This is with using DropDownButton Widget.

And this is using the dropDownButtonFormField Widget while having a long text.

Center locationDropDown() {
    return Center(
      child: Container(
        margin: const EdgeInsets.all(10),
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        decoration: BoxDecoration(
          color: Colors.grey.shade200,
          borderRadius: BorderRadius.circular(12),
        ),
        child: DropdownButtonFormField<String>(
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please select a location';
            }
            return null;
          },
          decoration: const InputDecoration(
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.transparent),
            ),
          ),
          value: chooseLocation,
          hint: const Text('Select a location'),
          isExpanded: true,
          items: workingData!.map((some) {
            return DropdownMenuItem(
              child: Text(
                some.name + ' (${some.location})',
              ),
              value: some.id,
            );
          }).toList(),
          onChanged: (String? displayedValue) {
            setState(
              () {
                chooseLocation = displayedValue!;
              },
            );
          },
        ),
      ),
    );
  }

Body:
isDense: false,

Add isDense value false in DropdownButtonFormField.


问:
R Shiny/RHandsontable: Trying to read from and update the same RHandsontable in real time
I'm trying to create an RShiny page to help with some fuzzy matches, and allow the user to confirm the matches are correct. The table being displayed has a few columns, most important of which are the names from list A, potential matching names from list B, and a True/False column at the end. Ideally, when a match is confirmed as correct I would like the table to update - not just to mark the row as a correct match, but to look for other rows which contain potential matches for that item and remove them (or, in this case, reduce their height to 0.5). I'm hoping it will look like the options collapse to only show the matching one when the matching one is selected, and, in case of user error, if the selected row is unmatched, the rest of the rows appear.

I currently have it working (in one form or another) aside from the conditional formatting. The script is below.

Any ideas or help would be much appreciated!

```<code>library(tidyverse)
library(rhandsontable)
library(shiny)

test_DF <- data.frame("ID" = 1:10,
                      "list A Code" = c("1001", "1001", "1003", "1003", "1003", "1006", "1006", "1007", "1008", "1010"),
                      "List A Item" = c("Olive Oil", "Olive Oil", "Tomato Sauce", "Tomato Sauce", "Tomato Sauce", "Dried Pasta", "Dried Pasta", "Oregano", "Pesto", "Garlic Bulb"),
                      "List B Code" = c("2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010"),
                      "List B Item" = c("Olive Oil", "Olives", "Tomato", "Tomato Sauce", "Pasta Sauce", "Dried Pasta", "Fresh Pasta", "Oregano", "Pesto", "Garlic Bulb"),
                      "Correct Match" = FALSE)

ui<-(fluidPage(
  fluidRow(
    titlePanel(
      h1("food item potential matches", align = "center")),
    sidebarPanel(
      actionButton("saveBtn", "All matches identified")),
    mainPanel(
      rHandsontableOutput("table", height = "500px"),
      br()

    )
  )
))
server<-(function(input,output,session){

  # returns rhandsontable type object - editable excel type grid data
  output$table <- renderRHandsontable({
    output <- rhandsontable(test_DF) %>%
      hot_col(1:5, readOnly = TRUE) #Outputs the table, and makes it so that only the True/False column is editable

    matched_codes <- output$table[,2][output$table[,6] == TRUE] #Creates a list of list A codes that have been successfully matched

    incorrect_match_rows <- output$table[,1][output$table$list.A.Code %in% matched_codes & output$table$Correct.Match == FALSE]

    if(length(matched_codes>0)) {
      print("matches made") #This is just me trying to test if it gets this far
      for (incorrect_row in incorrect_match_rows) {
        output <- output %>% hot_rows(incorrect_row, rowHeights=0.5) #making the rows to be removed 0.5 in height
      }
    }
    output
    #https://stackoverflow.com/questions/62816744/rhandsontable-using-a-dropdown-to-hide-columns

  })

  # on click of button the file will be saved to the working directory
  observeEvent(input$saveBtn, {
    write.csv(isolate(hot_to_r(input$table)), file = "Fuzzy_matches.csv", row.names = FALSE)
    print("requirements met")
    stopApp()
  })
  # hot_to_r() converts the rhandsontable object to r data object
})

shinyApp(ui, server)
</code>```

答:
OK, I believe I have found a way to solve this now. The full functionality isn't quite what I'd like (i.e. I still haven't found a way to collapse the row heights - instead I've put incorrect matches to the bottom of the list, marked them red, and made the only editable column uneditable).

I hope this helps anyone looking for something similar!

```<code>library(tidyverse)
library(rhandsontable)
library(shiny)

test_DF <- data.frame("ID" = 1:10,
                      "Pseudo_ID" = 1:10,
                      "list A Code" = c("1001", "1001", "1003", "1003", "1003", "1006", "1006", "1007", "1008", "1010"),
                      "List A Item" = c("Olive Oil", "Olive Oil", "Tomato Sauce", "Tomato Sauce", "Tomato Sauce", "Dried Pasta", "Dried Pasta", "Oregano", "Pesto", "Garlic Bulb"),
                      "List B Code" = c("2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010"),
                      "List B Item" = c("Olive Oil", "Olives", "Tomato", "Tomato Sauce", "Pasta Sauce", "Dried Pasta", "Fresh Pasta", "Oregano", "Pesto", "Garlic Bulb"),
                      "Correct Match" = FALSE)

ui<-(fluidPage(
  fluidRow(
    titlePanel(
      h1("food item potential matches", align = "center")),
    sidebarPanel(
      actionButton("saveBtn", "All matches identified")),
    mainPanel(
      rHandsontableOutput("table", height = "500px"),
      br()

    )
  )
))
server<-(function(input,output,session){

  values <- reactiveValues(data = test_DF)
  observeEvent(input$table,{
    values$data<-as.data.frame(hot_to_r(input$table))

    matched_codes <- values$data[,3][values$data[,7] == TRUE] #Creates a list of list A codes that have been successfully matched
    print(matched_codes)
    incorrect_match_rows <- values$data[,1][values$data$list.A.Code %in% matched_codes & values$data$Correct.Match == FALSE]
    print(incorrect_match_rows)
    print(length(incorrect_match_rows)>0)
    print("matches made") #This is just me trying to test if it gets this far
    values$data$Pseudo_ID <- values$data$ID
    values$data$Pseudo_ID[which(values$data$ID %in% incorrect_match_rows)]<-NA
    values$data<-values$data[order(values$data$Pseudo_ID, na.last=TRUE),]
    print(values$data)

    output$table <- renderRHandsontable({
      rhandsontable(values$data)%>%
        hot_col(1:6, readOnly = TRUE) %>% #Outputs the table, and makes it so that only the True/False column is editable
        hot_col(1:2, width = 0.5) %>%
        hot_col(1:6, renderer = "
           function (instance, td, row, col, prop, value, cellProperties) {
             Handsontable.renderers.TextRenderer.apply(this, arguments);
             var ID = instance.getData()[row][0]
             var pseudoID = instance.getData()[row][1]
             if (ID !== pseudoID) {
              td.style.background = 'pink';
              cellProperties.rowheight = '1';
             }
           }") %>%
        hot_col(7, renderer = "
           function (instance, td, row, col, prop, value, cellProperties) {
             Handsontable.renderers.CheckboxRenderer.apply(this, arguments);
             var ID = instance.getData()[row][0]
             var pseudoID = instance.getData()[row][1]
             if (ID !== pseudoID) {
              td.style.background = 'pink';
              cellProperties.rowheight = '1';
              cellProperties.readOnly = true;
             }
           }")

    })
  })
  output$table <- renderRHandsontable({
    rhandsontable(values$data)%>%
      hot_col(1:6, readOnly = TRUE) %>% #Outputs the table, and makes it so that only the True/False column is editable
      hot_col(1:2, width = 0.5)
  })

  observeEvent(input$saveBtn, {
    write.csv(isolate(hot_to_r(input$table)), file = "Fuzzy_matches.csv", row.names = FALSE)
    print("requirements met")
    stopApp()
  })
})

shinyApp(ui, server)
</code>```

Body:
I'm trying to create an RShiny page to help with some fuzzy matches, and allow the user to confirm the matches are correct. The table being displayed has a few columns, most important of which are the names from list A, potential matching names from list B, and a True/False column at the end. Ideally, when a match is confirmed as correct I would like the table to update - not just to mark the row as a correct match, but to look for other rows which contain potential matches for that item and remove them (or, in this case, reduce their height to 0.5). I'm hoping it will look like the options collapse to only show the matching one when the matching one is selected, and, in case of user error, if the selected row is unmatched, the rest of the rows appear.

I currently have it working (in one form or another) aside from the conditional formatting. The script is below.

Any ideas or help would be much appreciated!

library(tidyverse)
library(rhandsontable)
library(shiny)

test_DF <- data.frame("ID" = 1:10,
                      "list A Code" = c("1001", "1001", "1003", "1003", "1003", "1006", "1006", "1007", "1008", "1010"),
                      "List A Item" = c("Olive Oil", "Olive Oil", "Tomato Sauce", "Tomato Sauce", "Tomato Sauce", "Dried Pasta", "Dried Pasta", "Oregano", "Pesto", "Garlic Bulb"),
                      "List B Code" = c("2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010"),
                      "List B Item" = c("Olive Oil", "Olives", "Tomato", "Tomato Sauce", "Pasta Sauce", "Dried Pasta", "Fresh Pasta", "Oregano", "Pesto", "Garlic Bulb"),
                      "Correct Match" = FALSE)

ui<-(fluidPage(
  fluidRow(
    titlePanel(
      h1("food item potential matches", align = "center")),
    sidebarPanel(
      actionButton("saveBtn", "All matches identified")),
    mainPanel(
      rHandsontableOutput("table", height = "500px"),
      br()

    )
  )
))
server<-(function(input,output,session){

  # returns rhandsontable type object - editable excel type grid data
  output$table <- renderRHandsontable({
    output <- rhandsontable(test_DF) %>%
      hot_col(1:5, readOnly = TRUE) #Outputs the table, and makes it so that only the True/False column is editable

    matched_codes <- output$table[,2][output$table[,6] == TRUE] #Creates a list of list A codes that have been successfully matched

    incorrect_match_rows <- output$table[,1][output$table$list.A.Code %in% matched_codes & output$table$Correct.Match == FALSE]

    if(length(matched_codes>0)) {
      print("matches made") #This is just me trying to test if it gets this far
      for (incorrect_row in incorrect_match_rows) {
        output <- output %>% hot_rows(incorrect_row, rowHeights=0.5) #making the rows to be removed 0.5 in height
      }
    }
    output
    #https://stackoverflow.com/questions/62816744/rhandsontable-using-a-dropdown-to-hide-columns

  })

  # on click of button the file will be saved to the working directory
  observeEvent(input$saveBtn, {
    write.csv(isolate(hot_to_r(input$table)), file = "Fuzzy_matches.csv", row.names = FALSE)
    print("requirements met")
    stopApp()
  })
  # hot_to_r() converts the rhandsontable object to r data object
})

shinyApp(ui, server)

Body:
OK, I believe I have found a way to solve this now. The full functionality isn't quite what I'd like (i.e. I still haven't found a way to collapse the row heights - instead I've put incorrect matches to the bottom of the list, marked them red, and made the only editable column uneditable).

I hope this helps anyone looking for something similar!

library(tidyverse)
library(rhandsontable)
library(shiny)

test_DF <- data.frame("ID" = 1:10,
                      "Pseudo_ID" = 1:10,
                      "list A Code" = c("1001", "1001", "1003", "1003", "1003", "1006", "1006", "1007", "1008", "1010"),
                      "List A Item" = c("Olive Oil", "Olive Oil", "Tomato Sauce", "Tomato Sauce", "Tomato Sauce", "Dried Pasta", "Dried Pasta", "Oregano", "Pesto", "Garlic Bulb"),
                      "List B Code" = c("2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010"),
                      "List B Item" = c("Olive Oil", "Olives", "Tomato", "Tomato Sauce", "Pasta Sauce", "Dried Pasta", "Fresh Pasta", "Oregano", "Pesto", "Garlic Bulb"),
                      "Correct Match" = FALSE)

ui<-(fluidPage(
  fluidRow(
    titlePanel(
      h1("food item potential matches", align = "center")),
    sidebarPanel(
      actionButton("saveBtn", "All matches identified")),
    mainPanel(
      rHandsontableOutput("table", height = "500px"),
      br()

    )
  )
))
server<-(function(input,output,session){

  values <- reactiveValues(data = test_DF)
  observeEvent(input$table,{
    values$data<-as.data.frame(hot_to_r(input$table))

    matched_codes <- values$data[,3][values$data[,7] == TRUE] #Creates a list of list A codes that have been successfully matched
    print(matched_codes)
    incorrect_match_rows <- values$data[,1][values$data$list.A.Code %in% matched_codes & values$data$Correct.Match == FALSE]
    print(incorrect_match_rows)
    print(length(incorrect_match_rows)>0)
    print("matches made") #This is just me trying to test if it gets this far
    values$data$Pseudo_ID <- values$data$ID
    values$data$Pseudo_ID[which(values$data$ID %in% incorrect_match_rows)]<-NA
    values$data<-values$data[order(values$data$Pseudo_ID, na.last=TRUE),]
    print(values$data)

    output$table <- renderRHandsontable({
      rhandsontable(values$data)%>%
        hot_col(1:6, readOnly = TRUE) %>% #Outputs the table, and makes it so that only the True/False column is editable
        hot_col(1:2, width = 0.5) %>%
        hot_col(1:6, renderer = "
           function (instance, td, row, col, prop, value, cellProperties) {
             Handsontable.renderers.TextRenderer.apply(this, arguments);
             var ID = instance.getData()[row][0]
             var pseudoID = instance.getData()[row][1]
             if (ID !== pseudoID) {
              td.style.background = 'pink';
              cellProperties.rowheight = '1';
             }
           }") %>%
        hot_col(7, renderer = "
           function (instance, td, row, col, prop, value, cellProperties) {
             Handsontable.renderers.CheckboxRenderer.apply(this, arguments);
             var ID = instance.getData()[row][0]
             var pseudoID = instance.getData()[row][1]
             if (ID !== pseudoID) {
              td.style.background = 'pink';
              cellProperties.rowheight = '1';
              cellProperties.readOnly = true;
             }
           }")

    })
  })
  output$table <- renderRHandsontable({
    rhandsontable(values$data)%>%
      hot_col(1:6, readOnly = TRUE) %>% #Outputs the table, and makes it so that only the True/False column is editable
      hot_col(1:2, width = 0.5)
  })

  observeEvent(input$saveBtn, {
    write.csv(isolate(hot_to_r(input$table)), file = "Fuzzy_matches.csv", row.names = FALSE)
    print("requirements met")
    stopApp()
  })
})

shinyApp(ui, server)


问:
How to load method for struct in Array in Golang
Hello Now I am trying to convert Java to Go.

But I have problem with using method declared for structure.

Before put structure in Array, Method could be loaded and used.

After put it in array, I cannot call method for it.

Can you check below codes?

Result said me that dvdCollection.DVD undefined (type [15]*DVD has no field or method DVD)

```<code>type DVD struct {
    name        string
    releaseYear int
    director    string
}

func (d *DVD) AddDVD(name string, releaseYear int, director string) {
    d.name = name
    d.releaseYear = releaseYear
    d.director = director
}

func main() {
    dvdCollection := [15]DVD{}
    dvdCollection.AddDVD("Terminator1", 1984, "James Cameron")
}
</code>```

答:
dvdCollection is a value of an array type ([15]DVD). The AddDVD() method is defined on the DVD type (more specifically *DVD). You can only call AddDVD() on a *DVD value.

For example:

```<code>dvdCollection[0].AddDVD("Terminator1", 1984, "James Cameron")
// which means (&dvdCollection[0]).AddDVD("Terminator1", 1984, "James Cameron")
fmt.Println(dvdCollection[0])
</code>```

This will output (try it on the Go Playground):

```<code>{Terminator1 1984 James Cameron}
</code>```

Also note that you are using an array ([15]DVD). It's rare to use an array in Go, you should likely want to use a slice. For an introduction and details, see blog post: Arrays, slices (and strings): The mechanics of 'append'

Body:
Hello Now I am trying to convert Java to Go.

But I have problem with using method declared for structure.

Before put structure in Array, Method could be loaded and used.

After put it in array, I cannot call method for it.

Can you check below codes?

Result said me that dvdCollection.DVD undefined (type [15]*DVD has no field or method DVD)

type DVD struct {
    name        string
    releaseYear int
    director    string
}

func (d *DVD) AddDVD(name string, releaseYear int, director string) {
    d.name = name
    d.releaseYear = releaseYear
    d.director = director
}

func main() {
    dvdCollection := [15]DVD{}
    dvdCollection.AddDVD("Terminator1", 1984, "James Cameron")
}

Body:
dvdCollection is a value of an array type ([15]DVD). The AddDVD() method is defined on the DVD type (more specifically *DVD). You can only call AddDVD() on a *DVD value.

For example:

dvdCollection[0].AddDVD("Terminator1", 1984, "James Cameron")
// which means (&dvdCollection[0]).AddDVD("Terminator1", 1984, "James Cameron")
fmt.Println(dvdCollection[0])

This will output (try it on the Go Playground):

{Terminator1 1984 James Cameron}

Also note that you are using an array ([15]DVD). It's rare to use an array in Go, you should likely want to use a slice. For an introduction and details, see blog post: Arrays, slices (and strings): The mechanics of 'append'


问:
How to aggregate and sum list of dictionaries for use in bar plot
I am trying to aggregate data that I query from a database into a specific format for a Grouped Bar Plot (ApexCharts.js).

Starting point:

```<code>all_records= [
  {'fruit': 'Apple', 'var1': 1, 'var2': 2},
  {'fruit': 'Apple', 'var1': 2, 'var2': 1},
  {'fruit': 'Banana', 'var1': 1, 'var2': 3},
  {'fruit': 'Cherry', 'var1': 0, 'var2': 1},
  {'fruit': 'Cherry', 'var1': 4, 'var2': 0}
]
</code>```

The required aggregation looks like this:

```<code> {'fruit': ['Apple', 'Banana', 'Cherry' ], 'var1': [ 3, 1, 4 ], 'var2': [ 3, 3, 1 ]}
</code>```

To get to the desired result, I was trying to use

```<code>from collections import defaultdict

var1_dict = defaultdict(int)
for d in all_records:
    var1_dict [d['fruit']] += d['var1']

print(var1_dict)
defaultdict(<class 'int'>, {'Apple': 3, 'Banana': 1, 'Cherry': 4 })

var2_dict= defaultdict(int)
for d in all_records:
    var2_dict[d['fruit']] += d['var2']

print(var2_dict)
defaultdict(<class 'int'>, {'Apple': 3, 'Banana': 3, 'Cherry': 1 })
</code>```

Then I could use list(var1_dict.keys()) to get ['Apple', 'Banana', 'Cherry'] which is one piece of the aggregation solved.

But from this point I honestly don't know how to proceed.

答:
Here's a solution with pandas dataframes:

import pandas as pd

all_records= [
  {'fruit': 'Apple', 'var1': 1, 'var2': 2},
  {'fruit': 'Apple', 'var1': 2, 'var2': 1},
  {'fruit': 'Banana', 'var1': 1, 'var2': 3},
  {'fruit': 'Cherry', 'var1': 0, 'var2': 1},
  {'fruit': 'Cherry', 'var1': 4, 'var2': 0}
]

df = pd.DataFrame(all_records).groupby('fruit').sum().reset_index()
print(df)

res = df.to_dict('list')
print(res)

```
<p>Output:</p>
```{'fruit': ['Apple', 'Banana', 'Cherry'], 'var1': [3, 1, 4], 'var2': [3, 3, 1]}
```

Body:
I am trying to aggregate data that I query from a database into a specific format for a Grouped Bar Plot (ApexCharts.js).

Starting point:

all_records= [
  {'fruit': 'Apple', 'var1': 1, 'var2': 2},
  {'fruit': 'Apple', 'var1': 2, 'var2': 1},
  {'fruit': 'Banana', 'var1': 1, 'var2': 3},
  {'fruit': 'Cherry', 'var1': 0, 'var2': 1},
  {'fruit': 'Cherry', 'var1': 4, 'var2': 0}
]

The required aggregation looks like this:

 {'fruit': ['Apple', 'Banana', 'Cherry' ], 'var1': [ 3, 1, 4 ], 'var2': [ 3, 3, 1 ]}

To get to the desired result, I was trying to use

from collections import defaultdict

var1_dict = defaultdict(int)
for d in all_records:
    var1_dict [d['fruit']] += d['var1']

print(var1_dict)
defaultdict(<class 'int'>, {'Apple': 3, 'Banana': 1, 'Cherry': 4 })

var2_dict= defaultdict(int)
for d in all_records:
    var2_dict[d['fruit']] += d['var2']

print(var2_dict)
defaultdict(<class 'int'>, {'Apple': 3, 'Banana': 3, 'Cherry': 1 })

Then I could use list(var1_dict.keys()) to get ['Apple', 'Banana', 'Cherry'] which is one piece of the aggregation solved.

But from this point I honestly don't know how to proceed.

Body:
Here's a solution with pandas dataframes:

import pandas as pd

all_records= [
  {'fruit': 'Apple', 'var1': 1, 'var2': 2},
  {'fruit': 'Apple', 'var1': 2, 'var2': 1},
  {'fruit': 'Banana', 'var1': 1, 'var2': 3},
  {'fruit': 'Cherry', 'var1': 0, 'var2': 1},
  {'fruit': 'Cherry', 'var1': 4, 'var2': 0}
]

df = pd.DataFrame(all_records).groupby('fruit').sum().reset_index()
print(df)

res = df.to_dict('list')
print(res)

Output:

{'fruit': ['Apple', 'Banana', 'Cherry'], 'var1': [3, 1, 4], 'var2': [3, 3, 1]}


问:
Vuetify how to add props to v-list-group v-slot:activator template
Im attempting to make a similar menu to the expansion lists example in the documentation . This uses the v-list-group and v-slot:activator components. Each of the child elements have a child list-item, which is easy to add a vue-router link to. The issue is that when one of the parent list items (Dashboard) dont have children items, i wish to add a vue-router :to link instead to this, although these parent list-items use the v-slot:activator template and im unsure how i can add props or events to this.

I read about the v-slot activator here github, but it doesnt seem to mension how I can achieve what i need it to do.

Template

```<code>    <v-list>
        <v-list-group
            v-for="item in items"
            :key="item.name"
            v-model="item.active"
            :prepend-icon="item.icon"
            :append-icon="item.children ? undefined : ''"
            no-action
        >
            //Want this to work with :to or @click
            <template v-slot:activator :to="{name: item.route}">
                <v-list-item-content>
                    <v-list-item-title v-text="item.name"></v-list-item-title>
                </v-list-item-content>
            </template>

            <v-list-item
                v-for="childItem in item.children"
                :key="childItem.name"
                :to="{name:childItem.route}"
            >
                <v-list-item-content>
                    <v-list-item-title v-text="childItem.name"></v-list-item-title>
                </v-list-item-content>
            </v-list-item>
        </v-list-group>
    </v-list>
</code>```

Data

```<code>     items: [
                {
                    name: 'Dashboard',
                    route: 'dashboard',
                    active: false,
                    icon: 'mdi-view-dashboard',
                },
                {
                    name: 'Editor',
                    icon: 'mdi-pencil',
                    active: false,
                    children: [
                        {
                            name: 'General',
                            route: 'general',
                        },
                        {
                            name: 'Designs',
                            route: 'designs',

                        },
                        {
                            name: 'Images',
                            route: 'images',
                        },
                    ],
                },
          ];
</code>```

Update

I hacked together a workaround by adding v-list-item inside the template when the parent element contains a route key. Then using absolute position to extended its size to fit the parent template. Am i missing something...is this the best method of achieving this?

```<code>    <template v-slot:activator>
        <v-list-item v-if="item.route" :to="{name: item.route}" class="item-link"></v-list-item>
        <v-list-item-content>
            <v-list-item-title v-text="item.name"></v-list-item-title>
        </v-list-item-content>
    </template>
</code>```

Style

```<code> .item-link {
   position: absolute;
   top: 0;
   bottom: 0;
   right: 0;
   left: 0;
 }
</code>```

答:
I don't know if you are still looking for an answer, but, I had the same issue and found a workaround using the slot attribute. (NOT THE V-SLOT in the template) - remove the template, here check it out:</p>
```<code><v-list-group v-for="(parentCat, parent_id) in item.parent_cat" :key="`${parent_id}parentCat`" :value="openParent==parent_id" append-icon="" active-class="tagActiveIcon" @click="parentCatChanged(parent_id)" :disabled="true">
    <div slot="activator" class="d-flex justify-space-between maximizeWidth" @click="parentCatChanged(parent_id)">
        <div>Par_{{ parentCat.title}}</div>
        <div><v-icon color="primary">mdi-eye</v-icon></div>
    </div>
...
</code>```

Body:
Im attempting to make a similar menu to the expansion lists example in the documentation . This uses the v-list-group and v-slot:activator components. Each of the child elements have a child list-item, which is easy to add a vue-router link to. The issue is that when one of the parent list items (Dashboard) dont have children items, i wish to add a vue-router :to link instead to this, although these parent list-items use the v-slot:activator template and im unsure how i can add props or events to this.

I read about the v-slot activator here github, but it doesnt seem to mension how I can achieve what i need it to do.

Template

    <v-list>
        <v-list-group
            v-for="item in items"
            :key="item.name"
            v-model="item.active"
            :prepend-icon="item.icon"
            :append-icon="item.children ? undefined : ''"
            no-action
        >
            //Want this to work with :to or @click
            <template v-slot:activator :to="{name: item.route}">
                <v-list-item-content>
                    <v-list-item-title v-text="item.name"></v-list-item-title>
                </v-list-item-content>
            </template>

            <v-list-item
                v-for="childItem in item.children"
                :key="childItem.name"
                :to="{name:childItem.route}"
            >
                <v-list-item-content>
                    <v-list-item-title v-text="childItem.name"></v-list-item-title>
                </v-list-item-content>
            </v-list-item>
        </v-list-group>
    </v-list>

Data

     items: [
                {
                    name: 'Dashboard',
                    route: 'dashboard',
                    active: false,
                    icon: 'mdi-view-dashboard',
                },
                {
                    name: 'Editor',
                    icon: 'mdi-pencil',
                    active: false,
                    children: [
                        {
                            name: 'General',
                            route: 'general',
                        },
                        {
                            name: 'Designs',
                            route: 'designs',

                        },
                        {
                            name: 'Images',
                            route: 'images',
                        },
                    ],
                },
          ];

Update

I hacked together a workaround by adding v-list-item inside the template when the parent element contains a route key. Then using absolute position to extended its size to fit the parent template. Am i missing something...is this the best method of achieving this?

    <template v-slot:activator>
        <v-list-item v-if="item.route" :to="{name: item.route}" class="item-link"></v-list-item>
        <v-list-item-content>
            <v-list-item-title v-text="item.name"></v-list-item-title>
        </v-list-item-content>
    </template>

Style

 .item-link {
   position: absolute;
   top: 0;
   bottom: 0;
   right: 0;
   left: 0;
 }

Body:
I don't know if you are still looking for an answer, but, I had the same issue and found a workaround using the slot attribute. (NOT THE V-SLOT in the template) - remove the template, here check it out:

<v-list-group v-for="(parentCat, parent_id) in item.parent_cat" :key="`${parent_id}parentCat`" :value="openParent==parent_id" append-icon="" active-class="tagActiveIcon" @click="parentCatChanged(parent_id)" :disabled="true">
    <div slot="activator" class="d-flex justify-space-between maximizeWidth" @click="parentCatChanged(parent_id)">
        <div>Par_{{ parentCat.title}}</div>
        <div><v-icon color="primary">mdi-eye</v-icon></div>
    </div>
...


问:
Exporting Sqlite Database to Excel file using Intent.ACITON_CREATE_DOCUMENT
There is very nice library that I am using thanks to programmer which has made exporting very easy, but my concern is since Android 10, the file cannot be exported on internal memory of the device. The file gets exported under the package name. Well no issues there though, what I am trying is, I wan to use Intent.ACTION_CREATE_DOCUMENT, and let the user choose where to save the excel file that is generated from Sqlite Database.

Below is the code to convert sqlite to excel, it converts and automatically saves it to internal memory on Android < 10.

```<code>public void exportDBtoExcel() {
        String folder;
        Context context = getApplicationContext();
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Musajjal Report/";
        File externalFolder = context.getExternalFilesDir(null);

        folder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Musajjal Report/" ;

        File file = new File(folder); // this below 2 lines of code is for Android > 10
        if (externalFolder != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            folder = externalFolder.getAbsolutePath();
        }
        boolean fileCreated = file.exists();
        if ( !fileCreated ) {
            fileCreated = file.mkdirs();
        }
        if ( fileCreated ) {

            // Export SQLite DB as EXCEL FILE
            SQLiteToExcel sqliteToExcel = new SQLiteToExcel(getApplicationContext(), StudentDatabase.DBname,folder);
            sqliteToExcel.exportAllTables("Student.xls", new SQLiteToExcel.ExportListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onCompleted(String filePath) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Report Generated");
                    builder.setMessage(filePath);
                    builder.setCancelable(false);
                    builder.setPositiveButton("Ok", (dialogInterface, i) -> builder.setCancelable(true));
                    builder.show();
                }

                @Override
                public void onError(Exception e) {
                    Toast.makeText(getApplicationContext(), "Export Failed: " + e, Toast.LENGTH_LONG).show();

                }
            });

        }

    }
</code>```

My question is how can I save the excel file using the File Manager , please help, Thank you in advance. I have tried using the below code but it does not seem to work, because the above method is converting and saving before I can use the File Manager to pick a location to save.

```<code>private void createFile() {
        // when you create document, you need to add Intent.ACTION_CREATE_DOCUMENT
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        // filter to only show openable items.
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        // Create a file with the requested Mime type
        intent.setType("text/csv");

        startActivityForResult(intent, WRITE_REQ);
    }

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == WRITE_REQ){
            switch (resultCode){
                case Activity
                        .RESULT_OK:
                    if (data != null && data.getData() != null){
                        exportDBtoExcel();
                    }
                    break;
                case Activity.RESULT_CANCELED:
                    break;
            }
        }
    }
</code>```

答:
I solved this problem using the JXL library this way:

exportToExcel() function:

```<code>    private static final int CREATE_FILE_XLS = 2;

    private void exportToExcel() {
    final String fileName = "sample.xls";
    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("application/xls");
    intent.putExtra(Intent.EXTRA_TITLE, fileName);
    startActivityForResult(intent, CREATE_FILE_XLS);
    }
</code>```

onActivityResult :

```<code>    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent
      resultData)
    {
    super.onActivityResult(requestCode, resultCode, resultData);
    if (requestCode == CREATE_FILE_XLS && resultCode == Activity.RESULT_OK) {
        Uri uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            try {
                WriteToExcelFile(uri);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (BiffException e) {
                e.printStackTrace();
            }
        }
    }

}
</code>```

Read Sqlite database and Write to Exle File :

```<code>    public void WriteToExcelFile(Uri uri) throws IOException, BiffException {
        // Read database
        ArrayList<ReportModel> cursor = databaseHelper.getReports();
        OutputStream os = getContentResolver().openOutputStream(uri);
        WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setLocale(new Locale("fa", "FA"));
        WritableWorkbook workbook;
        try {
            workbook = Workbook.createWorkbook(os, wbSettings);
            WritableSheet sheet = workbook.createSheet("Features", 0);
            try {
                sheet.addCell(new jxl.write.Label(0, 0, "id"));
                sheet.addCell(new jxl.write.Label(1, 0, "name"));
                sheet.addCell(new jxl.write.Label(2, 0, "type"));
                int index = 3;
                int position = 1;
                index = 3;
                if (cursor != null) {
                    for (ReportModel data : cursor) {
                        sheet.addCell(new jxl.write.Label(0, position, data.getId() + ""));
                        sheet.addCell(new jxl.write.Label(1, position, data.getName() + ""));
                        sheet.addCell(new jxl.write.Label(2, position, data.getType() + ""));
                        position++;
                    }
                }
            } catch (RowsExceededException e) {
                e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }
        workbook.write();
        try {
            workbook.close();
        } catch (WriteException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Body:
There is very nice library that I am using thanks to programmer which has made exporting very easy, but my concern is since Android 10, the file cannot be exported on internal memory of the device. The file gets exported under the package name. Well no issues there though, what I am trying is, I wan to use Intent.ACTION_CREATE_DOCUMENT, and let the user choose where to save the excel file that is generated from Sqlite Database.

Below is the code to convert sqlite to excel, it converts and automatically saves it to internal memory on Android < 10.

public void exportDBtoExcel() {
        String folder;
        Context context = getApplicationContext();
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Musajjal Report/";
        File externalFolder = context.getExternalFilesDir(null);

        folder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Musajjal Report/" ;

        File file = new File(folder); // this below 2 lines of code is for Android > 10
        if (externalFolder != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            folder = externalFolder.getAbsolutePath();
        }
        boolean fileCreated = file.exists();
        if ( !fileCreated ) {
            fileCreated = file.mkdirs();
        }
        if ( fileCreated ) {

            // Export SQLite DB as EXCEL FILE
            SQLiteToExcel sqliteToExcel = new SQLiteToExcel(getApplicationContext(), StudentDatabase.DBname,folder);
            sqliteToExcel.exportAllTables("Student.xls", new SQLiteToExcel.ExportListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onCompleted(String filePath) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Report Generated");
                    builder.setMessage(filePath);
                    builder.setCancelable(false);
                    builder.setPositiveButton("Ok", (dialogInterface, i) -> builder.setCancelable(true));
                    builder.show();
                }

                @Override
                public void onError(Exception e) {
                    Toast.makeText(getApplicationContext(), "Export Failed: " + e, Toast.LENGTH_LONG).show();

                }
            });

        }

    }

My question is how can I save the excel file using the File Manager , please help, Thank you in advance. I have tried using the below code but it does not seem to work, because the above method is converting and saving before I can use the File Manager to pick a location to save.

private void createFile() {
        // when you create document, you need to add Intent.ACTION_CREATE_DOCUMENT
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        // filter to only show openable items.
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        // Create a file with the requested Mime type
        intent.setType("text/csv");

        startActivityForResult(intent, WRITE_REQ);
    }

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == WRITE_REQ){
            switch (resultCode){
                case Activity
                        .RESULT_OK:
                    if (data != null && data.getData() != null){
                        exportDBtoExcel();
                    }
                    break;
                case Activity.RESULT_CANCELED:
                    break;
            }
        }
    }

Body:
I solved this problem using the JXL library this way:

exportToExcel() function:

    private static final int CREATE_FILE_XLS = 2;

    private void exportToExcel() {
    final String fileName = "sample.xls";
    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("application/xls");
    intent.putExtra(Intent.EXTRA_TITLE, fileName);
    startActivityForResult(intent, CREATE_FILE_XLS);
    }

onActivityResult :

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent
      resultData)
    {
    super.onActivityResult(requestCode, resultCode, resultData);
    if (requestCode == CREATE_FILE_XLS && resultCode == Activity.RESULT_OK) {
        Uri uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            try {
                WriteToExcelFile(uri);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (BiffException e) {
                e.printStackTrace();
            }
        }
    }

}

Read Sqlite database and Write to Exle File :

    public void WriteToExcelFile(Uri uri) throws IOException, BiffException {
        // Read database
        ArrayList<ReportModel> cursor = databaseHelper.getReports();
        OutputStream os = getContentResolver().openOutputStream(uri);
        WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setLocale(new Locale("fa", "FA"));
        WritableWorkbook workbook;
        try {
            workbook = Workbook.createWorkbook(os, wbSettings);
            WritableSheet sheet = workbook.createSheet("Features", 0);
            try {
                sheet.addCell(new jxl.write.Label(0, 0, "id"));
                sheet.addCell(new jxl.write.Label(1, 0, "name"));
                sheet.addCell(new jxl.write.Label(2, 0, "type"));
                int index = 3;
                int position = 1;
                index = 3;
                if (cursor != null) {
                    for (ReportModel data : cursor) {
                        sheet.addCell(new jxl.write.Label(0, position, data.getId() + ""));
                        sheet.addCell(new jxl.write.Label(1, position, data.getName() + ""));
                        sheet.addCell(new jxl.write.Label(2, position, data.getType() + ""));
                        position++;
                    }
                }
            } catch (RowsExceededException e) {
                e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }
        workbook.write();
        try {
            workbook.close();
        } catch (WriteException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}


问:
Why not show Secure in front of URL in my Chrome browser when I open live server from VS code?
Why not show Secure in front of URL in my Chrome browser when I open live server from VS code?
Please If anyone know my problem solution tell me the reason?

enter image description here
What is the reason of my problem?

答:
The only thing that the Not Secure badge in the address bar indicates is that the webpage doesn't have a valid SSL certificate (or that there is no certificate at all, http:// vs https://).

It is not something you need to worry about while developing a website. When you look to host the site, you should look into getting a certificate from a service like "Let's Encrypt" or using a host that provides a free certificate.

One thing to note is that you should avoid using a self signed certificate (as opposed to getting a signed certificate from an authority) if you plan to publish the site to be accessible to people other than yourself. A self signed certificate will result in the same warning in most browsers unless the user has a copy of the certificate in their certificate store (where certificates are stored). You can make it work on an individual computer or network, but it is easy enough to get a proper certificate. You only need to worry about renewing it if the place you get the certificate from doesn't have an auto renewal system.


问:
How to i chain two parts of an animation together in jetpack compose so the the offset increases then decreases?
Ive recently got into doing animations using jet pack compose and am wondering how you can make it so that when you increase a value in an offset, once the animation reaches that value it then changes the value to another value. So like update transition but instead of at the same time, one after the other.</p>

答:
The correct answer is to use Kotlin coroutines. I managed to get it working fine. You have to use coroutines in order to launch the animations in the correct sequence like this:

animationRoutine.launch {
    coroutineScope {
        launch {
            animate(
                startingValue,
                targetValue,
                animationSpec = whatYouWant,
                block = { value, _ -> whateverYouNeed = value }
            )
        }
        launch {
            animate(
                initialValue,
                targetValue,
                animationSpec = whatYouWant,
                block = { value, _ -> whateverYouNeed = value }
            )
        }
}
```

Each of launch scope launches everything in a non blocking way if you tell it to allowing you to run multiple animations at once at a lower level and to sequence the animations you add another coroutine for the next part of the animation.

Body:
The correct answer is to use Kotlin coroutines. I managed to get it working fine. You have to use coroutines in order to launch the animations in the correct sequence like this:

animationRoutine.launch {
    coroutineScope {
        launch {
            animate(
                startingValue,
                targetValue,
                animationSpec = whatYouWant,
                block = { value, _ -> whateverYouNeed = value }
            )
        }
        launch {
            animate(
                initialValue,
                targetValue,
                animationSpec = whatYouWant,
                block = { value, _ -> whateverYouNeed = value }
            )
        }
}

Each of launch scope launches everything in a non blocking way if you tell it to allowing you to run multiple animations at once at a lower level and to sequence the animations you add another coroutine for the next part of the animation.


问:
Laravel, search exact same substring in eloquent query
I have a table like this

Teacher Table

What I am trying to do is to get the row which contains the subjects 1(or any other number like 7,8 etc.)

This is what I have tried in my controller.

```<code>public function allTeachers($sub_id) //receiving $sub_id(to be searched)
  {
        $teachers_all=Teacher::where('subjects','like','%'.','.$sub_id.'%')->latest()->paginate(50);
        dd($teachers_all);
    }
</code>```

The problem here is that, I am getting all the rows which contains subjects as '1',e.g. if it is '3,11,22' or '41,5' it gets selected.
But what I am trying to achieve is it should only return where subjects string contains '1' followed by any other number after ',' or '1,2,44,31,23' etc.
I am using laravel, I hope I made the question clear.

答:
The solution to your question would be either to use find_in_set or concat to fill some missing commas and then search for the value:

```<code>Teacher::whereRaw('find_in_set("' . $sub_id . '", subjects) <> 0')
    ->latest()
    ->paginate(50);
</code>```

or

```<code>Teacher::whereRaw('concat(",", colors, ",") like "%,' . $sub_id . ',%"')
    ->latest()
    ->paginate(50);
</code>```

That being said, @bromeer's comments hold true in any case. MySQL isn't around comma-separated values in fields. Both examples shown above aren't an ideal solution. You should look into relationships a bit more.

I suggest using a many-to-many relationship in your case. For that, create a pivot table called teacher_subject and add the relation to your Teacher model:

```<code>public function subjects()
{
    return $this->belongsToMany(Subject::class);
}
</code>```

To find any teachers teaching a specific subject, use whereHas like this:

```<code>Teacher::whereHas('subjects', function (Builder $query) use ($sub_id) {
    $query->where('id', $sub_id);
})->latest()->paginate(50);
</code>```

Body:
I have a table like this

Teacher Table

What I am trying to do is to get the row which contains the subjects 1(or any other number like 7,8 etc.)

This is what I have tried in my controller.

public function allTeachers($sub_id) //receiving $sub_id(to be searched)
  {
        $teachers_all=Teacher::where('subjects','like','%'.','.$sub_id.'%')->latest()->paginate(50);
        dd($teachers_all);
    }

The problem here is that, I am getting all the rows which contains subjects as '1',e.g. if it is '3,11,22' or '41,5' it gets selected.
But what I am trying to achieve is it should only return where subjects string contains '1' followed by any other number after ',' or '1,2,44,31,23' etc.
I am using laravel, I hope I made the question clear.

Body:
The solution to your question would be either to use find_in_set or concat to fill some missing commas and then search for the value:

Teacher::whereRaw('find_in_set("' . $sub_id . '", subjects) <> 0')
    ->latest()
    ->paginate(50);

or

Teacher::whereRaw('concat(",", colors, ",") like "%,' . $sub_id . ',%"')
    ->latest()
    ->paginate(50);

That being said, @bromeer's comments hold true in any case. MySQL isn't around comma-separated values in fields. Both examples shown above aren't an ideal solution. You should look into relationships a bit more.

I suggest using a many-to-many relationship in your case. For that, create a pivot table called teacher_subject and add the relation to your Teacher model:

public function subjects()
{
    return $this->belongsToMany(Subject::class);
}

To find any teachers teaching a specific subject, use whereHas like this:

Teacher::whereHas('subjects', function (Builder $query) use ($sub_id) {
    $query->where('id', $sub_id);
})->latest()->paginate(50);


问:
Not able to run on android 9+ devices
Manifest:-     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

ListView listView;
String[] items;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = findViewById(R.id.listview);
    runtimePermission();
}

public void runtimePermission(){

    Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
            .withListener(new PermissionListener() {
                @Override
                public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
                    displaySongs();
                }

                @Override
                public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {

                }

                @Override
                public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
                    permissionToken.continuePermissionRequest();
                }
            }).check();
}

public ArrayList<File> findSongs(File file){

    ArrayList<File> arrayList = new ArrayList<>();

    File[] files = file.listFiles();

    for (File singlefile : files){
        if (singlefile.isDirectory() && !singlefile.isHidden()) {
            arrayList.addAll(findSongs(singlefile));
        } else {
            if (singlefile.getName().endsWith(".mp3") || singlefile.getName().endsWith(".wav")){
                arrayList.add(singlefile);
            }
        }
    }
    return arrayList;
}

public void displaySongs(){
    final ArrayList<File> mysongs = findSongs(Environment.getExternalStorageDirectory());
    items = new String[mysongs.size()];
    for (int i = 0; i < mysongs.size(); i++) {
        items[i] = mysongs.get(i).getName().replace(".mp3", "").replace(".wav", "");
    }
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items );
    listView.setAdapter(adapter);
    }
}
</code>```

activity_main.xml

```<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"
tools:context=".MainActivity">

<ListView
    android:id="@+id/listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="10.0sp"
    android:padding="8dp" />
</RelativeLayout>
</code>```

Logcat :-

2022-02-08 14:56:52.834 9348-9348/com.example.mymusic E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mymusic, PID: 9348
java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=42, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.example.mymusic/com.karumi.dexter.DexterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4977)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5018)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2073)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:225)
at android.app.ActivityThread.main(ActivityThread.java:7563)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:994)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.mymusic.MainActivity.displaySongs(MainActivity.java:79)
at com.example.mymusic.MainActivity$1.onPermissionGranted(MainActivity.java:39)
at com.karumi.dexter.MultiplePermissionsListenerToPermissionListenerAdapter.onPermissionsChecked(Unknown Source:35)
at com.karumi.dexter.MultiplePermissionListenerThreadDecorator$1.run(Unknown Source:8)
at com.karumi.dexter.MainThread.execute(Unknown Source:6)
at com.karumi.dexter.MultiplePermissionListenerThreadDecorator.onPermissionsChecked(Unknown Source:7)
at com.karumi.dexter.DexterInstance.onPermissionsChecked(Unknown Source:56)
at com.karumi.dexter.DexterInstance.updatePermissionsAsGranted(Unknown Source:26)
at com.karumi.dexter.DexterInstance.onPermissionRequestGranted(Unknown Source:0)
at com.karumi.dexter.Dexter.onPermissionsRequested(Unknown Source:4)
at com.karumi.dexter.DexterActivity.onRequestPermissionsResult(Unknown Source:51)
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:8408)
at android.app.Activity.dispatchActivityResult(Activity.java:8253)

答:
The variable listView in MainActivity is never initialized. The call listView.setAdapter(adapter); results in a NullPointerException.

In onCreate() you need to do something like this (after calling setContentView():

```<code>listView = (ListView)findViewById(R.id.listview);
</code>```

Title: Not able to run on android 9+ devices

Body:
Manifest:-     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

MainActivity.java

public class MainActivity extends AppCompatActivity {

ListView listView;
String[] items;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = findViewById(R.id.listview);
    runtimePermission();
}

public void runtimePermission(){

    Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
            .withListener(new PermissionListener() {
                @Override
                public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
                    displaySongs();
                }

                @Override
                public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {

                }

                @Override
                public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
                    permissionToken.continuePermissionRequest();
                }
            }).check();
}

public ArrayList<File> findSongs(File file){

    ArrayList<File> arrayList = new ArrayList<>();

    File[] files = file.listFiles();

    for (File singlefile : files){
        if (singlefile.isDirectory() && !singlefile.isHidden()) {
            arrayList.addAll(findSongs(singlefile));
        } else {
            if (singlefile.getName().endsWith(".mp3") || singlefile.getName().endsWith(".wav")){
                arrayList.add(singlefile);
            }
        }
    }
    return arrayList;
}

public void displaySongs(){
    final ArrayList<File> mysongs = findSongs(Environment.getExternalStorageDirectory());
    items = new String[mysongs.size()];
    for (int i = 0; i < mysongs.size(); i++) {
        items[i] = mysongs.get(i).getName().replace(".mp3", "").replace(".wav", "");
    }
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items );
    listView.setAdapter(adapter);
    }
}

activity_main.xml

<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"
tools:context=".MainActivity">

<ListView
    android:id="@+id/listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="10.0sp"
    android:padding="8dp" />
</RelativeLayout>

Logcat :-

2022-02-08 14:56:52.834 9348-9348/com.example.mymusic E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mymusic, PID: 9348
java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=42, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.example.mymusic/com.karumi.dexter.DexterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4977)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5018)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2073)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:225)
at android.app.ActivityThread.main(ActivityThread.java:7563)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:994)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.mymusic.MainActivity.displaySongs(MainActivity.java:79)
at com.example.mymusic.MainActivity$1.onPermissionGranted(MainActivity.java:39)
at com.karumi.dexter.MultiplePermissionsListenerToPermissionListenerAdapter.onPermissionsChecked(Unknown Source:35)
at com.karumi.dexter.MultiplePermissionListenerThreadDecorator$1.run(Unknown Source:8)
at com.karumi.dexter.MainThread.execute(Unknown Source:6)
at com.karumi.dexter.MultiplePermissionListenerThreadDecorator.onPermissionsChecked(Unknown Source:7)
at com.karumi.dexter.DexterInstance.onPermissionsChecked(Unknown Source:56)
at com.karumi.dexter.DexterInstance.updatePermissionsAsGranted(Unknown Source:26)
at com.karumi.dexter.DexterInstance.onPermissionRequestGranted(Unknown Source:0)
at com.karumi.dexter.Dexter.onPermissionsRequested(Unknown Source:4)
at com.karumi.dexter.DexterActivity.onRequestPermissionsResult(Unknown Source:51)
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:8408)
at android.app.Activity.dispatchActivityResult(Activity.java:8253)

Body:
The variable listView in MainActivity is never initialized. The call listView.setAdapter(adapter); results in a NullPointerException.

In onCreate() you need to do something like this (after calling setContentView():

listView = (ListView)findViewById(R.id.listview);


问:
How should I document my C# code?
I am building the documentation for our C# API containing:

A general overview and description of the current state as a doc/pdf file.

A class library API in a .chm file using Sandcastle.

Questions:

Should I merge these two into the same .chm file? What is a good way to merge them?

I need to exclude certain classes/packages. How can I specify that in SandCastle?

It generates documentation for the VB code and the Visual C++ code. How can I change this? Or should I leave it, knowing that I am only using safe code?

Where can I find HTML Help 2.x Viewer Path on my system?

Edit:

The comments I make above methods, fields and classes are not generated in the documentation.

What should I do?

答:
I recommend that you use Sandcastle Help File Builder from Codeplex.  You can easily include and exclude namespaces, but I am unsure how to go about excluding a single class.  You can set the option to only generate documentation for public/protected classes, but I do not know if that will fit your scenario.

You can also target a specific language in SHFB, as to your second question.

Additionally, you can use MAML within SHFB for conceptual documentation, such as you mention as being in the doc/pdf file.  You should be able to use Doc2Maml for to migrate your existing documentation.  Doc2Maml is a part of DocProject, but it appears that you might be able to run it standalone.

Edit in response to comment:

Directions are for SHFB 1.8.0.1.  I do not remember the exact way to do it in 1.7, but I believe it is similar:

Under "Comments" group in the Project Properties tab, click the ellipsis to the right of "NamespaceSummaries".

In the checkbox list in the top left, uncheck any namespace you want to exclude.

This is also the screen where you put namespace summaries in.

OwnerDisplayName: Sasha

LastEditorDisplayName: Rich B

ContentLicense: CC BY-SA 2.5

Title: How should I document my C# code?


问:
R combine month names with strings
I would like to combine each month name with three strings: 'min', 'max', 'mean'

I tried this:

paste(month.name,rep(c('min','max','mean'),12))
```

but, instead of "January min", "January max", "January mean",... I get a wrong sequence "January min"    "February max"   "March mean" ...

Do you have any suggestions? Thank you

bioglp

答:
We can loop apply a vectorized function like paste to a vector of months

```<code>library(purrr)

month <- c("January", "February", "March")
value <- c("min", "max", "mean")

map(month, ~paste(.x, value, sep = ' ')) %>%
        unlist

[1] "January min"   "January max"   "January mean"  "February min"  "February max"  "February mean"
[7] "March min"     "March max"     "March mean"
</code>```

Title: R combine month names with strings

Body:
I would like to combine each month name with three strings: 'min', 'max', 'mean'

I tried this:

paste(month.name,rep(c('min','max','mean'),12))

but, instead of "January min", "January max", "January mean",... I get a wrong sequence "January min"    "February max"   "March mean" ...

Do you have any suggestions? Thank you

bioglp

Body:
We can loop apply a vectorized function like paste to a vector of months

library(purrr)

month <- c("January", "February", "March")
value <- c("min", "max", "mean")

map(month, ~paste(.x, value, sep = ' ')) %>%
        unlist

[1] "January min"   "January max"   "January mean"  "February min"  "February max"  "February mean"
[7] "March min"     "March max"     "March mean"


问:
Calculating trend per customer level in Python dataframe
I have 4 columns in dataset which are cid(customer level), month, spending and transaction (max.cid=10000). As seen below, df.head().

```<code>    cid month   spending    transaction
0   1   3         61.94        28
1   1   4         73.02        23
2   1   7         59.34        25
3   1   8         48.69        24
4   1   9         121.79       26
</code>```

I use the following function to calculate the trend (slope)in the outflow spending per customer. However, I get the identical number as a result for the whole dataset.  Expected to calculate trend of spendings on customer level. (trend value for each customer).

Is there a way to iterate over each customer level in the dataset and obtain individual trends per customer? Thanks in advance!

```<code>df = pd.read_csv("/content/case_data.csv")

import numpy as np

def trendline(df, order=1):

    coeffs = np.polyfit(df.index.values, list(df), order)
    slope = coeffs[-2]
    return float(slope)

outflow = df['spending']
cid = df['cid']

df_ = pd.DataFrame({'cid': cid, 'outflow': outflow})
slope_outflow = trendline(df_['cid'])
slope_outflow
</code>```

Output : 0.13377820413729283

Expected Output: (Trend1), (Trend2), (Trend3), ......, (Trend10000)

答:
```<code>def trendline(x, y, order=1):
    return np.polyfit(x, y, order)[-2]

df.groupby('cid').apply(lambda subdf: trendline(subdf['month'].values, subdf['spending'].values))
</code>```

You can use groupby to calculate the trend by each cid value. In the above example it is for the trend of spending.

Body:
I have 4 columns in dataset which are cid(customer level), month, spending and transaction (max.cid=10000). As seen below, df.head().

    cid month   spending    transaction
0   1   3         61.94        28
1   1   4         73.02        23
2   1   7         59.34        25
3   1   8         48.69        24
4   1   9         121.79       26

I use the following function to calculate the trend (slope)in the outflow spending per customer. However, I get the identical number as a result for the whole dataset.  Expected to calculate trend of spendings on customer level. (trend value for each customer).

Is there a way to iterate over each customer level in the dataset and obtain individual trends per customer? Thanks in advance!

df = pd.read_csv("/content/case_data.csv")

import numpy as np

def trendline(df, order=1):

    coeffs = np.polyfit(df.index.values, list(df), order)
    slope = coeffs[-2]
    return float(slope)

outflow = df['spending']
cid = df['cid']

df_ = pd.DataFrame({'cid': cid, 'outflow': outflow})
slope_outflow = trendline(df_['cid'])
slope_outflow

Output : 0.13377820413729283

Expected Output: (Trend1), (Trend2), (Trend3), ......, (Trend10000)

Body:
def trendline(x, y, order=1):
    return np.polyfit(x, y, order)[-2]

df.groupby('cid').apply(lambda subdf: trendline(subdf['month'].values, subdf['spending'].values))

You can use groupby to calculate the trend by each cid value. In the above example it is for the trend of spending.