问:
embedded jquery script not executing with html
I have a jquery embedded in my html page which takes the value of cgstPct and price fields and calculates the value of the final amount on the change event of cgstPct field.
On the web page this does not work.

I tried running on jsfiddle and it worked there so I assume there might be a problem with how I'm using it in my HTML file.

```<code><html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
    <head>
        <title>Create Product</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
        $('#cgstPct').change(function() {
            var pct = parseFloat($(this).val());
            var price = parseFloat($('#price').val());
            var total = (price) * (pct/100);
            $('#finalAmount').val(total.toFixed(2));
        });
        </script>
    </head>
    <body>
        <div layout:fragment="content" class="row">
            <div class="col-xs-8 col-md-8">
                <h3>
                    <a href="/product" class="btn btn-lg btn-primary"><span class="glyphicon glyphicon-list"></span> Product</a>
                </h3>
                <h2>Create Product</h2>
                <form action="/save">
                    <div class="form-group">
                        <label for="email">Product Name:</label>
                        <input type="text" class="form-control" name="prodName" />
                    </div>
                    <div class="form-group">
                        <label for="email">Product Description</label>
                        <textarea class="form-control" name="prodDesc" cols="60" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="email">Product Price</label>
                        <input type="number" id="price" class="form-control" name="prodPrice" />

                    <label for="cgstPct">CGST PCT</label>
                    <input type="number" id="cgstPct" class="form-control" name="cgstPct" />

                    <label for="finalAmount">Amount after GST</label>
                    <input type="number" readonly="readonly" id="finalAmount" class="form-control" name="finalAmount" />

                    <button type="submit" class="btn btn-success">Save</button>
                </form>
            </div>
        </div>
    </body>
</html>
</code>```

答:
I think you forget to give script tag to your code.Can you please change your code structure as per below.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
        $('#cgstPct').change(function() {
            var pct = parseFloat($(this).val());
            var price = parseFloat($('#price').val());
            var total = (price) * (pct/100);
            $('#finalAmount').val(total.toFixed(2));
        });
 </script>
</code>```

And for better practice always write your jquery or javascript code at bottom of body tag. This might solve your problem .Thank you :)

Body:
I have a jquery embedded in my html page which takes the value of cgstPct and price fields and calculates the value of the final amount on the change event of cgstPct field.
On the web page this does not work.

I tried running on jsfiddle and it worked there so I assume there might be a problem with how I'm using it in my HTML file.

        <title>Create Product</title>

                     Product

Create Product

                <form action="/save">

                        Product Name:
                        <input type="text" class="form-control" name="prodName" />

                        Product Description
                        <textarea class="form-control" name="prodDesc" cols="60" rows="3"></textarea>

                        Product Price
                        <input type="number" id="price" class="form-control" name="prodPrice" />

                    CGST PCT
                    <input type="number" id="cgstPct" class="form-control" name="cgstPct" />

                    Amount after GST
                    <input type="number" readonly="readonly" id="finalAmount" class="form-control" name="finalAmount" />

                    <button type="submit" class="btn btn-success">Save</button>
                </form>

Body:
I think you forget to give script tag to your code.Can you please change your code structure as per below.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
        $('#cgstPct').change(function() {
            var pct = parseFloat($(this).val());
            var price = parseFloat($('#price').val());
            var total = (price) * (pct/100);
            $('#finalAmount').val(total.toFixed(2));
        });
 </script>

And for better practice always write your jquery or javascript code at bottom of body tag. This might solve your problem .Thank you :)


来源: stackexchange

问:
How i prevent to dispose error characters from database?
I´m spanish and we use for example the letter "ñ" and some accent marks. I'm having this problem where I have a database in PhpMyAdmin where there are some data the includes the "ñ" and accent marks. When I use that information on the screen it shows an error character with a question mark. What can i do to prevent that? Not using the letters and accent marks is not an option.

This is an example of what I see: https://ibb.co/NjkRf9D (Not possible to upload the image with IMGur).

答:
This happens because your database is not configured as Unicode

Try this :

```<code>ALTER DATABASE your_database_name charset=utf8;
ALTER TABLE your_table_name charset=utf8;
</code>```

and read  this article on handling Unicode also

Official documentation on Charset

ContentLicense: CC BY-SA 4.0

Body:
This happens because your database is not configured as Unicode

Try this :

ALTER DATABASE your_database_name charset=utf8;
ALTER TABLE your_table_name charset=utf8;

and read  this article on handling Unicode also

Official documentation on Charset


问:
npm csv-parse not reading all rows
I'm trying to read a CSV using csv-parse, but the final line isn't being read.
My code:

```<code>const handleFiles = event => {
  const f = event.target.files[0];
  const parser = CsvParse({delimiter: ',', columns: true});
  parser.on('readable', function(){
    console.log('readable');
    let record;
    // eslint-disable-next-line no-cond-assign
    while (record = parser.read()) {
      console.log(record);
    }
  });
  const reader = new FileReader();
  reader.onload = (function() {
    return function(e) {
      console.log('Writing');
      parser.write(e.target.result);
    };
  })(f);

  reader.readAsText(f);
};
</code>```

The input:

```<code>Letter,Number
A,1
B,2
C,3
</code>```

The output:

```<code>Writing
readable
{Letter: "A", Number: "1"}
readable
{Letter: "B", Number: "2"}
</code>```

Why is C3 not being read?

And why is "readable" being printed twice? I have a feeling I'm not understanding csv-parse correctly.

Thanks

答: I was missing parser.end(); after parser.write(e.target.result); The last row was read correctly after adding that.

Title: npm csv-parse not reading all rows

Body:
I'm trying to read a CSV using csv-parse, but the final line isn't being read.
My code:

const handleFiles = event => {
  const f = event.target.files[0];
  const parser = CsvParse({delimiter: ',', columns: true});
  parser.on('readable', function(){
    console.log('readable');
    let record;
    // eslint-disable-next-line no-cond-assign
    while (record = parser.read()) {
      console.log(record);
    }
  });
  const reader = new FileReader();
  reader.onload = (function() {
    return function(e) {
      console.log('Writing');
      parser.write(e.target.result);
    };
  })(f);

  reader.readAsText(f);
};

The input:

Letter,Number
A,1
B,2
C,3

The output:

Writing
readable
{Letter: "A", Number: "1"}
readable
{Letter: "B", Number: "2"}

Why is C3 not being read?

And why is "readable" being printed twice? I have a feeling I'm not understanding csv-parse correctly.

Thanks


问:
How I can set the index of Datagridview to 0
How I can set the index of DataGridView to 0?

I developed a pharmacy software where I want to add values from TextBoxes into DataGridView with adding a new row. It is working but the problem is when I clear the value of DataGridView by using this code

```<code>dgvSoldMedicineInfo.Rows.Clear()
</code>```

then when I try the previous procedure it show this error in VB.NET

Index was out of range, Must be non-negative and less than the size of the collection. Parameter name:index

Code:

```<code>Dim rowcounter As Integer = 0

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click

    dgvSoldMedicineInfo.Rows.Add()

    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnBarcodeNo").Value = txtBarcodeNo.Text
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnName").Value = dgvSale.CurrentRow.Cells(2).Value
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnQuantity").Value = txtQuantity.Text
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnSalePrice").Value = txtSalePrice.Text
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnAmount").Value = txtTotalAmount.Text
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnReject").Value = "Reject"
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnStockID").Value = dgvSale.CurrentRow.Cells(0).Value
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnStockQuantity").Value = dgvSale.CurrentRow.Cells(3).Value

    System.Math.Max(System.Threading.Interlocked.Increment(rowcounter), rowcounter - 1)
End Sub
</code>```

答:
There's really no point to that rowcounter variable in that context and it's bad form to keep using dgvSoldMedicineInfo.Rows(rowcounter) over and over again.  The proper way to do that would be like so:

```<code>Dim rowIndex = dgvSoldMedicineInfo.Rows.Add()
Dim row = dgvSoldMedicineInfo.Rows(rowIndex)
Dim cells = row.Cells

cells("ColumnBarcodeNo").Value = txtBarcodeNo.Text
cells("ColumnName").Value = dgvSale.CurrentRow.Cells(2).Value
'etc.
</code>```

That said, why do that when the Add method is overloaded and will accept all the cell values up front?

```<code>dgvSoldMedicineInfo.Rows.Add(txtBarcodeNo.Text,
                             dgvSale.CurrentRow.Cells(2).Value,
                             ...)
</code>```

Body:
How I can set the index of DataGridView to 0?

I developed a pharmacy software where I want to add values from TextBoxes into DataGridView with adding a new row. It is working but the problem is when I clear the value of DataGridView by using this code

dgvSoldMedicineInfo.Rows.Clear()

then when I try the previous procedure it show this error in VB.NET

Index was out of range, Must be non-negative and less than the size of the collection. Parameter name:index

Code:

Dim rowcounter As Integer = 0

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click

    dgvSoldMedicineInfo.Rows.Add()

    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnBarcodeNo").Value = txtBarcodeNo.Text
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnName").Value = dgvSale.CurrentRow.Cells(2).Value
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnQuantity").Value = txtQuantity.Text
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnSalePrice").Value = txtSalePrice.Text
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnAmount").Value = txtTotalAmount.Text
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnReject").Value = "Reject"
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnStockID").Value = dgvSale.CurrentRow.Cells(0).Value
    dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnStockQuantity").Value = dgvSale.CurrentRow.Cells(3).Value

    System.Math.Max(System.Threading.Interlocked.Increment(rowcounter), rowcounter - 1)
End Sub

Body:
There's really no point to that rowcounter variable in that context and it's bad form to keep using dgvSoldMedicineInfo.Rows(rowcounter) over and over again.  The proper way to do that would be like so:

Dim rowIndex = dgvSoldMedicineInfo.Rows.Add()
Dim row = dgvSoldMedicineInfo.Rows(rowIndex)
Dim cells = row.Cells

cells("ColumnBarcodeNo").Value = txtBarcodeNo.Text
cells("ColumnName").Value = dgvSale.CurrentRow.Cells(2).Value
'etc.

That said, why do that when the Add method is overloaded and will accept all the cell values up front?

dgvSoldMedicineInfo.Rows.Add(txtBarcodeNo.Text,
                             dgvSale.CurrentRow.Cells(2).Value,
                             ...)


问:
Navigating code using Ctrl-F, and CodeRush Markers
When I use the 'Jump To ...' context menu CodeRush drops a marker before jumping, so that I can navigate back.

When I CTRL-F in Visual Studio it doesn't.

How can I configure CodeRush to add this handy little navigation aide.

答:
Ok simple enough

Create a new Shortcut using instructions found here

Specify Ctrl+F as the Key

Specify MarkerDrop as the Command

Then check the "after executing this command, pass shortcut to IDE for default handling" checkbox.

Ctrl+F should now drop a marker whenever it launches the Find Dialog.

More detail and bonus Marker tips are available here

ContentLicense: CC BY-SA 3.0


问:
Using a play button ('Click Me') over default video poster not working
I have a video . I have placed a text "Click Me" at the center of the video.

My requirement is - on clicking on the "Click Me" or any part of the video , the video should play and "Click Me" disappear.

```<code>.banner-description{
    position: absolute;
    font-weight: bold;
    top : 50%;
    left: 50%;
    background: rebeccapurple;
}
.video-banner{
    position: relative;
}

<body>

    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis laudantium nobis laboriosam quaerat. Quo, veritatis harum nemo eligendi sed dicta fugiat ad. Voluptas ea maxime qui nostrum blanditiis facere natus!
    </div>

    <div class="video-banner">
        <video controls>
            <source src="011-video-files.mp4">
        </video>
        <div class="banner-description">
            <p>Click Me</p>
        </div>
    </div>

    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde explicabo repellat minima magnam totam, temporibus nemo saepe praesentium ipsam a quidem. Mollitia vero impedit architecto quod ex voluptates neque eveniet!
    </div>

</body>
</code>```

The problem is : while clicking on the "Click Me" , nothing happens . And , while clicking on some other part of the video, though video starts "Click Me" dose not disappear

答:
Sea this one click me button is working there is jquery for that to work check this I think it's useful for you

document.getElementById("banner-description").addEventListener("click", changeBackground);

// OTHER FUN STUFF WE CAN DO:
    function changeBackground() {
      var randomColor = Math.floor(Math.random()*16777215).toString(16);
      document.body.style.background = '#' + randomColor;
    };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#banner-description{
    position: absolute;
    font-weight: bold;
    top : 50%;
    left: 50%;
    background: rebeccapurple;
}
.video-banner{
    position: relative;
}</code>```

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis laudantium nobis laboriosam quaerat. Quo, veritatis harum nemo eligendi sed dicta fugiat ad. Voluptas ea maxime qui nostrum blanditiis facere natus!

        <video controls>
            <source src="011-video-files.mp4">
        </video>

Click Me

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde explicabo repellat minima magnam totam, temporibus nemo saepe praesentium ipsam a quidem. Mollitia vero impedit architecto quod ex voluptates neque eveniet!

```

Body:
I have a video . I have placed a text "Click Me" at the center of the video.

My requirement is - on clicking on the "Click Me" or any part of the video , the video should play and "Click Me" disappear.

.banner-description{
    position: absolute;
    font-weight: bold;
    top : 50%;
    left: 50%;
    background: rebeccapurple;
}
.video-banner{
    position: relative;
}

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis laudantium nobis laboriosam quaerat. Quo, veritatis harum nemo eligendi sed dicta fugiat ad. Voluptas ea maxime qui nostrum blanditiis facere natus!

        <video controls>
            <source src="011-video-files.mp4">
        </video>

Click Me

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde explicabo repellat minima magnam totam, temporibus nemo saepe praesentium ipsam a quidem. Mollitia vero impedit architecto quod ex voluptates neque eveniet!

The problem is : while clicking on the "Click Me" , nothing happens . And , while clicking on some other part of the video, though video starts "Click Me" dose not disappear

Body:
Sea this one click me button is working there is jquery for that to work check this I think it's useful for you

document.getElementById("banner-description").addEventListener("click", changeBackground);

// OTHER FUN STUFF WE CAN DO:
    function changeBackground() {
      var randomColor = Math.floor(Math.random()*16777215).toString(16);
      document.body.style.background = '#' + randomColor;
    };

#banner-description{
    position: absolute;
    font-weight: bold;
    top : 50%;
    left: 50%;
    background: rebeccapurple;
}
.video-banner{
    position: relative;
}

<body>

    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis laudantium nobis laboriosam quaerat. Quo, veritatis harum nemo eligendi sed dicta fugiat ad. Voluptas ea maxime qui nostrum blanditiis facere natus!
    </div>

    <div class="video-banner">
        <video controls>
            <source src="011-video-files.mp4">
        </video>
        <div id="banner-description">
            <p>Click Me</p>
        </div>
    </div>

    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde explicabo repellat minima magnam totam, temporibus nemo saepe praesentium ipsam a quidem. Mollitia vero impedit architecto quod ex voluptates neque eveniet!
    </div>

</body>


问:
Convert 4 level nested JSON file to 1 level nested with Python
I have the 4 level nested JSON file below, that I would like to normalize to a one level nesting:

Input file is like this:

```<code>{
    "@index": "40",
    "row": [
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "text 1"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "text 2"
            }
          },
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "text 3"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "text 4"
            }
          }
        ]
      }
    ]
  }
</code>```

Desired output is like this:

```<code>{
    "@index": "40",
    "row": [
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "Text 1"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "Text 2"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "Text 3"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "Text 4"
          }
    ]
  }
</code>```

The code I have so far is this using pandas is below, but I don´t know how to continue to normalize to one level.

```<code>import json
import pandas as pd
from pandas.io.json import json_normalize #package for flattening json in pandas df

#load json object
with open('D:\Files\JSON\4Level.json') as f:
    d = json.load(f)

nycphil = json_normalize(d['row'])
print (nycphil.head(4))
</code>```

This is the current output tabulated, where shows that column is a nested element:

```<code>                                            column
0  [{'text': {'@fontName': 'Times New Roman', '@f...
1  [{'text': {'@fontName': 'Times New Roman', '@f...
2  [{'text': {'@fontName': 'Times New Roman', '@f...
</code>```

The print with one level nesting would be:

```<code>text.#text   text.@fontName text.@fontSize   ...   text.@width text.@x text.@y
0     Text 1  Times New Roman           12.0   ...        250.01   85.10  663.12
1     Text 2  Times New Roman            8.0   ...        348.98  121.10  675.36
2     Text 3  Times New Roman           12.0   ...         42.47  473.30  676.92
3     Text 4  Times New Roman           12.0   ...        433.61   85.10  690.72
</code>```

The Input/Output comparison is like this:

Maybe someone could help me with this. Thanks for any help.

UPDATE

In order to make a small sample in first sample input I showed, I removed some elements that seems to be are needed in your scripts to work. So now I show exactly the same structure as real file but with this input your scripts don't work. I think they need a little tweak but I've been trying and I don't know how to change them to get the same output with this new input. Maybe you can help me and sorry for not show the correct input from beginning.

```<code>{
   "document":{
      "page":[
         {
            "@index":"0",
            "image":{
               "@data":"ABC",
               "@format":"png",
               "@height":"620.00",
               "@type":"base64encoded",
               "@width":"450.00",
               "@x":"85.00",
               "@y":"85.00"
            }
         },
         {
            "@index":"1",
            "row":[
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text1",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"71.04",
                           "@x":"121.10",
                           "@y":"83.42"
                        }
                     }
                  ]
               },
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text2",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"101.07",
                           "@x":"121.10",
                           "@y":"124.82"
                        }
                     }
                  ]
               }
            ]
         },
         {
            "@index":"2",
            "row":[
               {
                  "column":{
                     "text":{
                        "#text":"Text3",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"363.44",
                        "@x":"85.10",
                        "@y":"69.62"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text4",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"382.36",
                        "@x":"85.10",
                        "@y":"83.42"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text5",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"435.05",
                        "@x":"85.10",
                        "@y":"97.22"
                     }
                  }
               }
            ]
         },
         {
            "@index":"3"
         }
      ]
   }
}
</code>```

答:
As an alternative to json_normalize() you can also use a comprehension.:

```<code>my_dict["row"] = [{k: v for k, v in col_entry["text"].items()} for entry in my_dict["row"] for col_entry in entry["column"]]
</code>```

Edit: fixed code to cover multiple entries in each column list. This does admittedly approach the pain threshold in terms of nesting of comprehensions...

Body:
I have the 4 level nested JSON file below, that I would like to normalize to a one level nesting:

Input file is like this:

{
    "@index": "40",
    "row": [
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "text 1"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "text 2"
            }
          },
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "text 3"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "text 4"
            }
          }
        ]
      }
    ]
  }

Desired output is like this:

{
    "@index": "40",
    "row": [
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "Text 1"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "Text 2"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "Text 3"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "Text 4"
          }
    ]
  }

The code I have so far is this using pandas is below, but I don´t know how to continue to normalize to one level.

import json
import pandas as pd
from pandas.io.json import json_normalize #package for flattening json in pandas df

#load json object
with open('D:\Files\JSON\4Level.json') as f:
    d = json.load(f)

nycphil = json_normalize(d['row'])
print (nycphil.head(4))

This is the current output tabulated, where shows that column is a nested element:

                                            column
0  [{'text': {'@fontName': 'Times New Roman', '@f...
1  [{'text': {'@fontName': 'Times New Roman', '@f...
2  [{'text': {'@fontName': 'Times New Roman', '@f...

The print with one level nesting would be:

text.#text   text.@fontName text.@fontSize   ...   text.@width text.@x text.@y
0     Text 1  Times New Roman           12.0   ...        250.01   85.10  663.12
1     Text 2  Times New Roman            8.0   ...        348.98  121.10  675.36
2     Text 3  Times New Roman           12.0   ...         42.47  473.30  676.92
3     Text 4  Times New Roman           12.0   ...        433.61   85.10  690.72

The Input/Output comparison is like this:

Maybe someone could help me with this. Thanks for any help.

UPDATE

In order to make a small sample in first sample input I showed, I removed some elements that seems to be are needed in your scripts to work. So now I show exactly the same structure as real file but with this input your scripts don't work. I think they need a little tweak but I've been trying and I don't know how to change them to get the same output with this new input. Maybe you can help me and sorry for not show the correct input from beginning.

{
   "document":{
      "page":[
         {
            "@index":"0",
            "image":{
               "@data":"ABC",
               "@format":"png",
               "@height":"620.00",
               "@type":"base64encoded",
               "@width":"450.00",
               "@x":"85.00",
               "@y":"85.00"
            }
         },
         {
            "@index":"1",
            "row":[
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text1",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"71.04",
                           "@x":"121.10",
                           "@y":"83.42"
                        }
                     }
                  ]
               },
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text2",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"101.07",
                           "@x":"121.10",
                           "@y":"124.82"
                        }
                     }
                  ]
               }
            ]
         },
         {
            "@index":"2",
            "row":[
               {
                  "column":{
                     "text":{
                        "#text":"Text3",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"363.44",
                        "@x":"85.10",
                        "@y":"69.62"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text4",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"382.36",
                        "@x":"85.10",
                        "@y":"83.42"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text5",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"435.05",
                        "@x":"85.10",
                        "@y":"97.22"
                     }
                  }
               }
            ]
         },
         {
            "@index":"3"
         }
      ]
   }
}

Body:
As an alternative to json_normalize() you can also use a comprehension.:

my_dict["row"] = [{k: v for k, v in col_entry["text"].items()} for entry in my_dict["row"] for col_entry in entry["column"]]

Edit: fixed code to cover multiple entries in each column list. This does admittedly approach the pain threshold in terms of nesting of comprehensions...


问:
Is it okay to return void to a TapGestureRecogniser initiated method?
I have this XAML for Button.xaml :

```<code><Frame xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:t="clr-namespace:Japanese.Templates"
                  xmlns:local="clr-namespace:Japanese;assembly=Japanese"
                  x:Class="Japanese.Templates.Button" x:Name="this"
                  VerticalOptions="FillAndExpand"
                  HeightRequest="{DynamicResource GridButtonHeight}" >
<Frame.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding TapCommand, Source={x:Reference this}}"
                          CommandParameter="{Binding ., Source={x:Reference this}}" />
    <TapGestureRecognizer Tapped="ChangeTheColours" />
</Frame.GestureRecognizers>
<Label Text="{Binding Text, Source={x:Reference this}}" x:Name="ButtonLabel" />
</Frame>
</code>```

and this C# in my application for Button.xaml.cs

```<code>    private async void ChangeTheColours(Object sender, EventArgs e)
    {
        try
        {
            if (this.ButtonLabel.Text != null && (string)this.ButtonLabel.Text.Substring(0, 1) != " ")
            {
                ConfigureColors((Button)sender, "C");
                await Task.Delay(200);
                ConfigureColors((Button)sender, State);
            }
        }
        catch (Exception ex)
        {
            Crashes.TrackError(ex,
                new Dictionary<string, string> {
                        {"ChangeTheColours", "Exception"},
                        {"Device Model", DeviceInfo.Model },
                });
        }
    }
</code>```

For this example, is it okay to return void for the async method or is there a requirement that I should return a Task?

答:
Since this is an event it cannot be converted into a Task.

When you check the Microsoft Docs:

An event is a member that enables an object or class to provide notifications. Clients can attach executable code for events by supplying event handlers.

Events are declared using event_declarations

And when you read the last statement it says:

Each accessor corresponds to a method with a single value parameter of the event type, a void return type, and the same modifiers as the containing event.

Body:
I have this XAML for Button.xaml :

<Frame xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:t="clr-namespace:Japanese.Templates"
                  xmlns:local="clr-namespace:Japanese;assembly=Japanese"
                  x:Class="Japanese.Templates.Button" x:Name="this"
                  VerticalOptions="FillAndExpand"
                  HeightRequest="{DynamicResource GridButtonHeight}" >
<Frame.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding TapCommand, Source={x:Reference this}}"
                          CommandParameter="{Binding ., Source={x:Reference this}}" />
    <TapGestureRecognizer Tapped="ChangeTheColours" />
</Frame.GestureRecognizers>

</Frame>

and this C# in my application for Button.xaml.cs

    private async void ChangeTheColours(Object sender, EventArgs e)
    {
        try
        {
            if (this.ButtonLabel.Text != null && (string)this.ButtonLabel.Text.Substring(0, 1) != " ")
            {
                ConfigureColors((Button)sender, "C");
                await Task.Delay(200);
                ConfigureColors((Button)sender, State);
            }
        }
        catch (Exception ex)
        {
            Crashes.TrackError(ex,
                new Dictionary<string, string> {
                        {"ChangeTheColours", "Exception"},
                        {"Device Model", DeviceInfo.Model },
                });
        }
    }

For this example, is it okay to return void for the async method or is there a requirement that I should return a Task?


问:
fromJS with object type file (file upload)

immutable js - fromJS: dealing with file upload (array of file Object) seems like not possible to convert as immutable

fromJS does great job even with nested structures like:

javascript
const nested = [ { id: 1, val1: '1, other: { id: 1, prop1: '0' } }, true ];

BUT

As long as an object is String(MyObject) = [object Object] fromJS will convert it as Map().

But when object is a file String(MyFileObject) = [object File], fromJS will leave it [object File]

Q1: How to (I mean best way) deal with file upload with immutable js?

Q2: Is there some kind FileMap (equivalent to Map but file object mirror) for this case ?

答:
You cannot freeze a file object. However, a File consists of a bunch of readonly fields anyway, so there might be no need to convert it.

If you want to limit the interactions with the object, you could use the wrapper approach, as explained in Is there a way to freeze an ES6 Map?. Pack your object in a wrapper, which limits the access to it. You can then write your own reviver for fromJS to convert these objects specifically:

```<code>function reviver(key, value) {
  if (value instanceof File)  {
    return wrapFile(value);
  }
  return isKeyed(value) ? value.toMap() : value.toList()
}
</code>```

Body:
You cannot freeze a file object. However, a File consists of a bunch of readonly fields anyway, so there might be no need to convert it.

If you want to limit the interactions with the object, you could use the wrapper approach, as explained in Is there a way to freeze an ES6 Map?. Pack your object in a wrapper, which limits the access to it. You can then write your own reviver for fromJS to convert these objects specifically:

function reviver(key, value) {
  if (value instanceof File)  {
    return wrapFile(value);
  }
  return isKeyed(value) ? value.toMap() : value.toList()
}


问:
Convert string to IntPtr
sorry about my English is poor.
I convert string to IntPtr using

```<code>COPYDATASTRUCT cd = new COPYDATASTRUCT();
            cd.dwData = 0;

            cd.lpData = Marshal.StringToHGlobalAuto(Msg).ToInt32();
            cd.cbData = Msg.Length;
  Marshal.StringToHGlobalAuto(Msg);
</code>```

and send it to another window using SendMessage method
When i receive it and read the IntPtr as string using

```<code>COPYDATASTRUCT CD = (COPYDATASTRUCT)Marshal.PtrToStructure(lParam, typeof(COPYDATASTRUCT));
 byte[] B = new byte[CD.cbData];
IntPtr lpData = new IntPtr(CD.lpData);
string temp = Marshal.PtrToStringUni(lpData);
Marshal.Copy(lpData, B, 0, CD.cbData);
string strData = Encoding.Default.GetString(B);
</code>```

i receive this data
M\0S\0G\0!\0@\01\0|\01\0|\0C\0:\0\\0U\0s\0e\0r\0s\0\\0f\0.\0a\0l\0s\0a\0

When i make strData.Replace("\0","")

i receive my message but it is truncated.
MSG!@1|1|C:\Users\f.alsa

original message is MSG!@1|1|C:\Users\f.alsayyed\Desktop\File.ktb

答: To me it looks like your replace function found a zero termination earlier then where string ends, as it seems your received data contains zero's inside the string too.  </p>

Title: Convert string to IntPtr

Body:
sorry about my English is poor.
I convert string to IntPtr using

COPYDATASTRUCT cd = new COPYDATASTRUCT();
            cd.dwData = 0;

            cd.lpData = Marshal.StringToHGlobalAuto(Msg).ToInt32();
            cd.cbData = Msg.Length;
  Marshal.StringToHGlobalAuto(Msg);

and send it to another window using SendMessage method
When i receive it and read the IntPtr as string using

COPYDATASTRUCT CD = (COPYDATASTRUCT)Marshal.PtrToStructure(lParam, typeof(COPYDATASTRUCT));
 byte[] B = new byte[CD.cbData];
IntPtr lpData = new IntPtr(CD.lpData);
string temp = Marshal.PtrToStringUni(lpData);
Marshal.Copy(lpData, B, 0, CD.cbData);
string strData = Encoding.Default.GetString(B);

i receive this data
M\0S\0G\0!\0@\01\0|\01\0|\0C\0:\0\\0U\0s\0e\0r\0s\0\\0f\0.\0a\0l\0s\0a\0

When i make strData.Replace("\0","")

i receive my message but it is truncated.
MSG!@1|1|C:\Users\f.alsa

original message is MSG!@1|1|C:\Users\f.alsayyed\Desktop\File.ktb


问:
Laratable ambiguous colums on search
I'm using Laravel 5's laratables. and in my PartnersVehicles model i have this function

```<code>    public static function laratablesQueryConditions($query)
    {
        $uid = Auth::id(); //user ID
        $pid = Partners::where('uid', $uid)->first(); //get partner ID

        return $query->select('partners_vehicles.id', 'partners_vehicles.year', 'vehicle_makes.make', 'partners_vehicles.model', 'vehicle_colors.color', 'partners_vehicles.created_at')
        ->join('vehicle_makes', 'vehicle_makes.id', '=', 'partners_vehicles.make')
        ->join('vehicle_colors', 'vehicle_colors.id', '=', 'partners_vehicles.color')
        ->where('partners_vehicles.partner_id', $pid->id);

    }
</code>```

the table loads fine, but when I try and do an ajax search in the search box, i get this error below

Integrity constraint violation: 1052 Column 'make' in where clause is ambiguous (SQL: select count(*) as aggregate from partners_vehicles inner join vehicle_makes on vehicle_makes.id = partners_vehicles.make inner join vehicle_colors on vehicle_colors.id = partners_vehicles.color where partners_vehicles.partner_id = 7 and (year like %2% or make like %2% or model like %2% or color like %2%))

i tried changing my select to this, but still no luck

```<code>select('partners_vehicles.id', 'partners_vehicles.year', 'vehicle_makes.make AS `make`', 'partners_vehicles.model', 'vehicle_colors.color', 'partners_vehicles.created_at')
</code>```

any idea how to fix this? what am i missing? Thanks

答:
Try this code</p>

```<code>public static function laratablesQueryConditions($query)
{
    $uid = Auth::id(); //user ID
    $pid = Partners::where('uid', $uid)->first(); //get partner ID
    $res=DB::table('partners_vehicles')
         ->select('partners_vehicles.id', 'partners_vehicles.year', 'vehicle_makes.make', 'partners_vehicles.model', 'vehicle_colors.color', 'partners_vehicles.created_at')
         ->join('vehicle_makes', 'vehicle_makes.id', '=', 'partners_vehicles.make')
         ->join('vehicle_colors', 'vehicle_colors.id', '=', 'partners_vehicles.color')
         ->where('partners_vehicles.partner_id','=', $pid->id)
         ->get();
   return $res;
}
</code>```

Title: Laratable ambiguous colums on search

Body:
I'm using Laravel 5's laratables. and in my PartnersVehicles model i have this function

    public static function laratablesQueryConditions($query)
    {
        $uid = Auth::id(); //user ID
        $pid = Partners::where('uid', $uid)->first(); //get partner ID

        return $query->select('partners_vehicles.id', 'partners_vehicles.year', 'vehicle_makes.make', 'partners_vehicles.model', 'vehicle_colors.color', 'partners_vehicles.created_at')
        ->join('vehicle_makes', 'vehicle_makes.id', '=', 'partners_vehicles.make')
        ->join('vehicle_colors', 'vehicle_colors.id', '=', 'partners_vehicles.color')
        ->where('partners_vehicles.partner_id', $pid->id);

    }

the table loads fine, but when I try and do an ajax search in the search box, i get this error below

Integrity constraint violation: 1052 Column 'make' in where clause is ambiguous (SQL: select count(*) as aggregate from partners_vehicles inner join vehicle_makes on vehicle_makes.id = partners_vehicles.make inner join vehicle_colors on vehicle_colors.id = partners_vehicles.color where partners_vehicles.partner_id = 7 and (year like %2% or make like %2% or model like %2% or color like %2%))

i tried changing my select to this, but still no luck

select('partners_vehicles.id', 'partners_vehicles.year', 'vehicle_makes.make AS `make`', 'partners_vehicles.model', 'vehicle_colors.color', 'partners_vehicles.created_at')

any idea how to fix this? what am i missing? Thanks

Body:
Try this code

public static function laratablesQueryConditions($query)
{
    $uid = Auth::id(); //user ID
    $pid = Partners::where('uid', $uid)->first(); //get partner ID
    $res=DB::table('partners_vehicles')
         ->select('partners_vehicles.id', 'partners_vehicles.year', 'vehicle_makes.make', 'partners_vehicles.model', 'vehicle_colors.color', 'partners_vehicles.created_at')
         ->join('vehicle_makes', 'vehicle_makes.id', '=', 'partners_vehicles.make')
         ->join('vehicle_colors', 'vehicle_colors.id', '=', 'partners_vehicles.color')
         ->where('partners_vehicles.partner_id','=', $pid->id)
         ->get();
   return $res;
}


问:
SVG animated icon make bigger size with css
In my project I use svg icon. but this icon is very small. I am needed to increase the size of the display.

Below I inserted image for the references. I am trying to big this icon. in this  tag also present in the code.
I am needed to increase the size of the display.
So can I use css to bigger this svg. I am use many ways and seen many example for increasing the size of the svg but all are not working in a right way.
I     Symbol definition is

```<code>     <symbol id="saturnGif">
            <g style="transform-origin: 50px 50px 0px;">
                <g style="transform-origin: 50px 50px 0px; transform: scale(0.6);">
                    <g class="ld ld-swim-px" style="transform-origin: 50px 50px 0px; animation-duration: 1s; animation-delay: 4.23412s; animation-direction: normal;">
                        <g>
                            <g style="transform-origin: 50px 50px 0px;">
                                <path class="st10" d="M50,40.6c-23.5,0-42.5,4.2-42.5,9.4h14.2c0-3.5,12.7-6.3,28.3-6.3s28.3,2.8,28.3,6.3h14.2 C92.5,44.8,73.5,40.6,50,40.6z" fill="#f36c00" style="fill: rgb(243, 108, 0);"></path>
                            </g>
                            <g style="transform-origin: 50px 50px 0px;"><circle class="st1" cx="50" cy="50" r="25.7" fill="rgb(248, 178, 106)" style="fill: rgb(248, 178, 106);"></circle></g>
                            <g style="transform-origin: 50px 50px 0px;">
                                <path class="st28" d="M50,56.3c15.6,0,28.3-2.8,28.3-6.3H21.7C21.7,53.5,34.4,56.3,50,56.3z">
                                </path>
                            </g>
                            <g style="transform-origin: 50px 50px 0px;">
                                <path class="st10" d="M50,56.3c-15.6,0-28.3-2.8-28.3-6.3H7.5c0,5.2,19,9.4,42.5,9.4s42.5-4.2,42.5-9.4H78.3 C78.3,53.5,65.6,56.3,50,56.3z" fill="#f36c00" style="fill: rgb(243, 108, 0);"></path>
                            </g>
                            <metadata xmlns:d="https://loading.io/stock/" style="transform-origin: 50px 50px 0px;">
                                <d:name style="transform-origin: 50px 50px 0px;">saturn</d:name>
                                <d:tags style="transform-origin: 50px 50px 0px;">star,solar system,planet,saturn,astrology</d:tags>
                                <d:license style="transform-origin: 50px 50px 0px;">rf</d:license>
                                <d:slug style="transform-origin: 50px 50px 0px;">2ez0ua</d:slug>
                            </metadata>
                        </g>
                    </g>
                </g>
            </g>
        </symbol>

and **Style :**

    <style type="text/css" style="transform-origin: 50px 50px 0px;">
    @@keyframes ld-swim-px {
        0% {
            -webkit-transform: translate(0, 0) rotate(0deg);
            transform: translate(0, 0) rotate(0deg);
        }

        12.5% {
            -webkit-transform: translate(1px, -2px) rotate(3deg);
            transform: translate(1px, -2px) rotate(3deg);
        }

        25% {
            -webkit-transform: translate(0, -3px) rotate(6deg);
            transform: translate(0, -3px) rotate(6deg);
        }

        37.5% {
            -webkit-transform: translate(-1px, -2px) rotate(3deg);
            transform: translate(-1px, -2px) rotate(3deg);
        }

        50% {
            -webkit-transform: translate(0, 0) rotate(0deg);
            transform: translate(0, 0) rotate(0deg);
        }

        62.5% {
            -webkit-transform: translate(1px, 2px) rotate(-3deg);
            transform: translate(1px, 2px) rotate(-3deg);
        }

        75% {
            -webkit-transform: translate(0, 3px) rotate(-6deg);
            transform: translate(0, 3px) rotate(-6deg);
        }

        87.5% {
            -webkit-transform: translate(-1px, 2px) rotate(-3deg);
            transform: translate(-1px, 2px) rotate(-3deg);
        }

        100% {
            -webkit-transform: translate(0, 0) rotate(0deg);
            transform: translate(0, 0) rotate(0deg);
        }
    }

    @@-webkit-keyframes ld-swim-px {
        0% {
            -webkit-transform: translate(0, 0) rotate(0deg);
            transform: translate(0, 0) rotate(0deg);
        }

        12.5% {
            -webkit-transform: translate(1px, -2px) rotate(3deg);
            transform: translate(1px, -2px) rotate(3deg);
        }

        25% {
            -webkit-transform: translate(0, -3px) rotate(6deg);
            transform: translate(0, -3px) rotate(6deg);
        }

        37.5% {
            -webkit-transform: translate(-1px, -2px) rotate(3deg);
            transform: translate(-1px, -2px) rotate(3deg);
        }

        50% {
            -webkit-transform: translate(0, 0) rotate(0deg);
            transform: translate(0, 0) rotate(0deg);
        }

        62.5% {
            -webkit-transform: translate(1px, 2px) rotate(-3deg);
            transform: translate(1px, 2px) rotate(-3deg);
        }

        75% {
            -webkit-transform: translate(0, 3px) rotate(-6deg);
            transform: translate(0, 3px) rotate(-6deg);
        }

        87.5% {
            -webkit-transform: translate(-1px, 2px) rotate(-3deg);
            transform: translate(-1px, 2px) rotate(-3deg);
        }

        100% {
            -webkit-transform: translate(0, 0) rotate(0deg);
            transform: translate(0, 0) rotate(0deg);
        }
    }

    .ld.ld-swim-px {
        -webkit-animation: ld-swim-px 3s infinite linear;
        animation: ld-swim-px 3s infinite linear;
    }
</style>
<style type="text/css" style="transform-origin: 50px 50px 0px;">
    .st0 {
        fill: #E0E0E0;
    }

    .st1 {
        fill: #F8B26A;
    }

    .st2 {
        fill: #F5E6C8;
    }

    .st3 {
        fill: #849B87;
    }

    .st4 {
        opacity: 0.2;
        fill: #F8B26A;
    }

    .st5 {
        opacity: 0.2;
        fill: #ABBD81;
    }

    .st6 {
        opacity: 0.5;
        fill: #F8B26A;
    }

    .st7 {
        opacity: 0.5;
        fill: #ABBD81;
    }

    .st8 {
        fill: none;
        stroke: #E0E0E0;
        stroke-width: 4;
        stroke-miterlimit: 10;
    }

    .st9 {
        fill: #666666;
    }

    .st10 {
        fill: #F47E60;
    }

    .st11 {
        fill: #ABBD81;
    }

    .st12 {
        fill: #A0C8D7;
    }

    .st13 {
        fill: #333333;
    }

    .st14 {
        fill: #FFFFFF;
        stroke: #1A1A1A;
        stroke-width: 6;
        stroke-linejoin: round;
        stroke-miterlimit: 10;
    }

    .st15 {
        fill: #666666;
        stroke: #1A1A1A;
        stroke-width: 6;
        stroke-linejoin: round;
        stroke-miterlimit: 10;
    }

    .st16 {
        fill: none;
        stroke: #1A1A1A;
        stroke-width: 6;
        stroke-miterlimit: 10;
    }

    .st17 {
        fill: #1A1A1A;
    }

    .st18 {
        fill: #FFFFFF;
        stroke: #1A1A1A;
        stroke-width: 6;
        stroke-miterlimit: 10;
    }

    .st19 {
        fill: #666666;
        stroke: #1A1A1A;
        stroke-width: 6;
        stroke-miterlimit: 10;
    }

    .st20 {
        fill: none;
        stroke: #FFFFFF;
        stroke-width: 6;
        stroke-miterlimit: 10;
    }

    .st21 {
        fill: none;
        stroke: #FFFFFF;
        stroke-width: 6;
        stroke-linejoin: round;
        stroke-miterlimit: 10;
    }

    .st22 {
        fill: #FFFFFF;
    }

    .st23 {
        fill: #353035;
    }

    .st24 {
        fill: #F5E169;
    }

    .st25 {
        fill: none;
        stroke: #ABBD81;
        stroke-width: 8;
        stroke-linecap: round;
        stroke-miterlimit: 10;
    }

    .st26 {
        fill: none;
        stroke: #E0E0E0;
        stroke-width: 8;
        stroke-linecap: round;
        stroke-miterlimit: 10;
    }

    .st27 {
        fill: #FFDC6C;
    }

    .st28 {
        fill: none;
    }

    .st29 {
        fill: #C59B6D;
    }

    .st30 {
        fill: #E6E6E6;
    }

    .st31 {
        fill: #77A4BD;
    }

    .st32 {
        fill: #6079BD;
    }

    .st33 {
        fill: #405A9E;
    }

    .st34 {
        fill: none;
        stroke: #405A9E;
        stroke-width: 1.1292;
        stroke-miterlimit: 10;
    }

    .st35 {
        fill: #7D5A41;
    }

    .st36 {
        fill: #E6CCAE;
    }

    .st37 {
        fill: #CC632F;
    }

    .st38 {
        fill: #998268;
    }

    .st39 {
        fill: #D4C097;
    }

    .st40 {
        fill: #A8A8A8;
    }

    .st41 {
        fill: #CCCCCC;
    }

    .st42 {
        fill: #999999;
    }

    .st43 {
        stroke: #000000;
        stroke-width: 1.8743;
        stroke-miterlimit: 10;
    }

    .st44 {
        fill: #FFFFFF;
        stroke: #000000;
        stroke-width: 1.1246;
        stroke-miterlimit: 10;
    }

    .st45 {
        fill: #FFDC6D;
    }

    .st46 {
        fill: #A0C8D7;
        stroke: #FFFFFF;
        stroke-width: 4;
        stroke-linecap: round;
        stroke-miterlimit: 10;
    }

    .st47 {
        stroke: #F5E6C8;
        stroke-linecap: round;
        stroke-linejoin: round;
        stroke-miterlimit: 10;
    }

    .st48 {
        fill: none;
        stroke: #F5E6C8;
        stroke-linecap: round;
        stroke-linejoin: round;
        stroke-miterlimit: 10;
    }

    .st49 {
        fill: #FFFFFF;
        stroke: #F5E6C8;
        stroke-linecap: round;
        stroke-linejoin: round;
        stroke-miterlimit: 10;
    }

    .st50 {
        fill: none;
        stroke: #F5E6C8;
        stroke-miterlimit: 10;
    }

    .st51 {
        stroke: #F5E6C8;
        stroke-width: 3;
        stroke-miterlimit: 10;
    }

    .st52 {
        stroke: #F5E6C8;
        stroke-miterlimit: 10;
    }

    .st53 {
        fill: none;
        stroke: #F5E6C8;
        stroke-linecap: round;
        stroke-linejoin: round;
    }

    .st54 {
        fill: none;
        stroke: #F5E169;
        stroke-width: 0.7105;
        stroke-miterlimit: 10;
    }

    .st55 {
        fill: none;
        stroke: #F5E169;
        stroke-width: 0.675;
        stroke-miterlimit: 10;
    }

    .st56 {
        fill: none;
        stroke: #F5E169;
        stroke-width: 0.6594;
        stroke-miterlimit: 10;
    }

    .st57 {
        fill: #1A1A1A;
        stroke: #F5E169;
        stroke-width: 0.8;
        stroke-miterlimit: 10;
    }

    .st58 {
        fill: #FF0000;
    }

    .st59 {
        fill: #D686A5;
    }

    .st60 {
        fill: #AFA5CD;
    }

    .st61 {
        opacity: 0.5;
        fill: none;
    }

    .st62 {
        opacity: 0.2;
        fill: #849B87;
    }

    .st63 {
        opacity: 0.2;
        fill: #A0C8D7;
    }

    .st64 {
        opacity: 0.2;
        fill: #77A4BD;
    }

    .st65 {
        opacity: 0.5;
        fill: #849B87;
    }

    .st66 {
        opacity: 0.5;
        fill: #A0C8D7;
    }

    .st67 {
        opacity: 0.5;
        fill: #77A4BD;
    }

    .st68 {
        fill: none;
        stroke: #333333;
        stroke-width: 4;
        stroke-miterlimit: 10;
    }

    .st69 {
        fill: #F5E6C8;
        stroke: #333333;
        stroke-width: 3;
        stroke-miterlimit: 10;
    }
</style>
</code>```

Image for Reference

答:
You will need to give the symbol a viewBox attribute:

```<code><symbol id="saturnGif" viewBox="24 34 52 32">
</code>```

Then when you use the symbol you give the <use> element a width and a height.

```<code><use xlink:href="#saturnGif" width="104" height="64" />
</code>```

Also you can position the <use> with an x and y attributes.

```<code> <svg viewBox="0 0 52 32">
 <symbol id="saturnGif" viewBox="24 34 52 32">
</code>```

svg{border:1px solid}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 200 200">
 <symbol id="saturnGif" viewBox="7 24 87 53">

                                <path class="st10" d="M50,40.6c-23.5,0-42.5,4.2-42.5,9.4h14.2c0-3.5,12.7-6.3,28.3-6.3s28.3,2.8,28.3,6.3h14.2 C92.5,44.8,73.5,40.6,50,40.6z" fill="#f36c00" stroke="#f36c00" ></path>

                            <circle class="st1" cx="50" cy="50" r="25.7" fill="rgb(248, 178, 106)" ></circle>

                                <path class="st10" d="M50,56.3c-15.6,0-28.3-2.8-28.3-6.3H7.5c0,5.2,19,9.4,42.5,9.4s42.5-4.2,42.5-9.4H78.3 C78.3,53.5,65.6,56.3,50,56.3z" fill="#f36c00" stroke="#f36c00" ></path>

   </symbol>
  <use xlink:href="#saturnGif" x="13" y="48" width="174" height="106"  >

  </use>
 </svg></code>```

If you need to use this symbol alone like an inline icon you may use the same viewBox for both svg and symbol. If you are using an svg element without width and height but with a viewBox attribute the svg element will take the width of the container element.

```<code> <svg viewBox="0 0 52 32">
 <symbol id="saturnGif" viewBox="24 34 52 32">...</symbol>
 </svg>
 .......

 <div class="container">
 <svg viewBox="0 0 52 32"><use xlink:href="#saturnGif" /></svg>
 </div>
</code>```

Next comes an animated version where I'm using SMIL animations. I'm animating the use element: The values attribute represent the stages of the animation. I'm animating the attribute transform: attributeName="transform"  type="rotate" and the animation's duration is 4 seconds: dur="4s". The animation happens around the point {x:100,y:100}:

values="0,100,100; -5,100,100; 0,100,100; 5,100,100; 0,100,100"

svg{border:1px solid;width:90vh}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 200 200">
<symbol id="saturnGif" viewBox="7 24 87 53">
<path class="st10" d="M50,40.6c-23.5,0-42.5,4.2-42.5,9.4h14.2c0-3.5,12.7-6.3,28.3-6.3s28.3,2.8,28.3,6.3h14.2 C92.5,44.8,73.5,40.6,50,40.6z" fill="#f36c00" stroke="#f36c00" ></path>

<circle class="st1" cx="50" cy="50" r="25.7" fill="rgb(248, 178, 106)" ></circle>

<path class="st10" d="M50,56.3c-15.6,0-28.3-2.8-28.3-6.3H7.5c0,5.2,19,9.4,42.5,9.4s42.5-4.2,42.5-9.4H78.3 C78.3,53.5,65.6,56.3,50,56.3z" fill="#f36c00" stroke="#f36c00" ></path>
</symbol>
<use xlink:href="#saturnGif" x="13" y="48" width="174" height="106"  >
     <animateTransform
     attributeType="XML"
        attributeName="transform"
        type="rotate"
        values="0,100,100; -5,100,100; 0,100,100; 5,100,100; 0,100,100"
        dur="4s"
        repeatCount="indefinite" />
</use>
</svg></code>```

Body:
In my project I use svg icon. but this icon is very small. I am needed to increase the size of the display.

Below I inserted image for the references. I am trying to big this icon. in this  tag also present in the code.
I am needed to increase the size of the display.
So can I use css to bigger this svg. I am use many ways and seen many example for increasing the size of the svg but all are not working in a right way.
I     Symbol definition is

     <symbol id="saturnGif">
            <g style="transform-origin: 50px 50px 0px;">
                <g style="transform-origin: 50px 50px 0px; transform: scale(0.6);">
                    <g class="ld ld-swim-px" style="transform-origin: 50px 50px 0px; animation-duration: 1s; animation-delay: 4.23412s; animation-direction: normal;">
                        <g>
                            <g style="transform-origin: 50px 50px 0px;">
                                <path class="st10" d="M50,40.6c-23.5,0-42.5,4.2-42.5,9.4h14.2c0-3.5,12.7-6.3,28.3-6.3s28.3,2.8,28.3,6.3h14.2 C92.5,44.8,73.5,40.6,50,40.6z" fill="#f36c00" style="fill: rgb(243, 108, 0);"></path>
                            </g>
                            <g style="transform-origin: 50px 50px 0px;"><circle class="st1" cx="50" cy="50" r="25.7" fill="rgb(248, 178, 106)" style="fill: rgb(248, 178, 106);"></circle></g>
                            <g style="transform-origin: 50px 50px 0px;">
                                <path class="st28" d="M50,56.3c15.6,0,28.3-2.8,28.3-6.3H21.7C21.7,53.5,34.4,56.3,50,56.3z">
                                </path>
                            </g>
                            <g style="transform-origin: 50px 50px 0px;">
                                <path class="st10" d="M50,56.3c-15.6,0-28.3-2.8-28.3-6.3H7.5c0,5.2,19,9.4,42.5,9.4s42.5-4.2,42.5-9.4H78.3 C78.3,53.5,65.6,56.3,50,56.3z" fill="#f36c00" style="fill: rgb(243, 108, 0);"></path>
                            </g>
                            <metadata xmlns:d="https://loading.io/stock/" style="transform-origin: 50px 50px 0px;">
                                <d:name style="transform-origin: 50px 50px 0px;">saturn</d:name>
                                <d:tags style="transform-origin: 50px 50px 0px;">star,solar system,planet,saturn,astrology</d:tags>
                                <d:license style="transform-origin: 50px 50px 0px;">rf</d:license>
                                <d:slug style="transform-origin: 50px 50px 0px;">2ez0ua</d:slug>
                            </metadata>
                        </g>
                    </g>
                </g>
            </g>
        </symbol>

and **Style :**

Image for Reference

Body:
You will need to give the symbol a viewBox attribute:

<symbol id="saturnGif" viewBox="24 34 52 32">

Then when you use the symbol you give the <use> element a width and a height.

<use xlink:href="#saturnGif" width="104" height="64" />

Also you can position the <use> with an x and y attributes.

 <svg viewBox="0 0 52 32">
 <symbol id="saturnGif" viewBox="24 34 52 32">

svg{border:1px solid}

<svg viewBox="0 0 200 200">
 <symbol id="saturnGif" viewBox="7 24 87 53">

                                <path class="st10" d="M50,40.6c-23.5,0-42.5,4.2-42.5,9.4h14.2c0-3.5,12.7-6.3,28.3-6.3s28.3,2.8,28.3,6.3h14.2 C92.5,44.8,73.5,40.6,50,40.6z" fill="#f36c00" stroke="#f36c00" ></path>

                            <circle class="st1" cx="50" cy="50" r="25.7" fill="rgb(248, 178, 106)" ></circle>

                                <path class="st10" d="M50,56.3c-15.6,0-28.3-2.8-28.3-6.3H7.5c0,5.2,19,9.4,42.5,9.4s42.5-4.2,42.5-9.4H78.3 C78.3,53.5,65.6,56.3,50,56.3z" fill="#f36c00" stroke="#f36c00" ></path>

   </symbol>
  <use xlink:href="#saturnGif" x="13" y="48" width="174" height="106"  >

  </use>
 </svg>

If you need to use this symbol alone like an inline icon you may use the same viewBox for both svg and symbol. If you are using an svg element without width and height but with a viewBox attribute the svg element will take the width of the container element.

 <svg viewBox="0 0 52 32">
 <symbol id="saturnGif" viewBox="24 34 52 32">...</symbol>
 </svg>
 .......

 <div class="container">
 <svg viewBox="0 0 52 32"><use xlink:href="#saturnGif" /></svg>
 </div>

Next comes an animated version where I'm using SMIL animations. I'm animating the use element: The values attribute represent the stages of the animation. I'm animating the attribute transform: attributeName="transform"  type="rotate" and the animation's duration is 4 seconds: dur="4s". The animation happens around the point {x:100,y:100}:

values="0,100,100; -5,100,100; 0,100,100; 5,100,100; 0,100,100"

svg{border:1px solid;width:90vh}

<svg viewBox="0 0 200 200">
<symbol id="saturnGif" viewBox="7 24 87 53">
<path class="st10" d="M50,40.6c-23.5,0-42.5,4.2-42.5,9.4h14.2c0-3.5,12.7-6.3,28.3-6.3s28.3,2.8,28.3,6.3h14.2 C92.5,44.8,73.5,40.6,50,40.6z" fill="#f36c00" stroke="#f36c00" ></path>

<circle class="st1" cx="50" cy="50" r="25.7" fill="rgb(248, 178, 106)" ></circle>

<path class="st10" d="M50,56.3c-15.6,0-28.3-2.8-28.3-6.3H7.5c0,5.2,19,9.4,42.5,9.4s42.5-4.2,42.5-9.4H78.3 C78.3,53.5,65.6,56.3,50,56.3z" fill="#f36c00" stroke="#f36c00" ></path>
</symbol>
<use xlink:href="#saturnGif" x="13" y="48" width="174" height="106"  >
     <animateTransform
     attributeType="XML"
        attributeName="transform"
        type="rotate"
        values="0,100,100; -5,100,100; 0,100,100; 5,100,100; 0,100,100"
        dur="4s"
        repeatCount="indefinite" />
</use>
</svg>


问:
How do I know if the prepared statements are cached?
I am using Hikari with SQL Server 2016 and sqljdbc4-2.0.jar in the tomcat lib folder.

My configuration for db resource is as follows:

```<code><Resource name="jdbc/SQLServerDS" auth="Container" type="javax.sql.DataSource"
              username="uname"
              password="pwd"
              driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
              url="jdbc:sqlserver://server:port;DatabaseName=dbName"
              maxActive="20"
              maxIdle="10"
              validationQuery="select 1" />
</code>```

My Datasource configuration is as follows:

```<code>@Bean(name = "dataSource")
    public DataSource getDataSource() throws NamingException {
        HikariConfig config = new HikariConfig();
        config.setMaximumPoolSize(20);
        config.setDataSourceJNDI("java:comp/env/jdbc/SQLServerDS");
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.addDataSourceProperty("useServerPrepStmts", "true");
        config.addDataSourceProperty("cacheResultSetMetadata", "true");
        config.addDataSourceProperty("useLocalSessionState", "true");
        config.addDataSourceProperty("cacheServerConfiguration", "true");
        config.addDataSourceProperty("elideSetAutoCommits", "true");
        config.addDataSourceProperty("maintainTimeStats", "false");
        return new TransactionAwareDataSourceProxy(
                new LazyConnectionDataSourceProxy(new HikariDataSource(config)));
    }
</code>```

How do I know if the preparedstatement caching is working for different connections?

I am using spring container managed transactions with hibernate v4.3.10.Final.

Also, for the caching to work, do I need to have second-level cache enabled?

答:
HikariCP actually doesn't support PreparedStatement caching

others offer PreparedStatement caching. HikariCP does not. Why?

It's considered wrong implementation

Using a statement cache at the pooling layer is an anti-pattern, and will negatively impact your application performance compared to driver-provided caches.

Explanation:

At the connection pool layer PreparedStatements can only be cached per connection. If your application has 250 commonly executed queries and a pool of 20 connections you are asking your database to hold on to 5000 query execution plans -- and similarly the pool must cache this many PreparedStatements and their related graph of objects.

Most major database JDBC drivers already have a Statement cache that can be configured, including PostgreSQL, Oracle, Derby, MySQL, DB2, and many others. JDBC drivers are in a unique position to exploit database specific features, and nearly all of the caching implementations are capable of sharing execution plans across connections. This means that instead of 5000 statements in memory and associated execution plans, your 250 commonly executed queries result in exactly 250 execution plans in the database. Clever implementations do not even retain PreparedStatement objects in memory at the driver-level but instead merely attach new instances to existing plan IDs.

If you accept it, you shouldn't try\expect to cache PreparedStatement

If you reject it, you can use C3P0 as connection pool

About Second level cache in hibernate, it's mostly not defined in connection pool, but use relevant connection provider:

HikariCP now has a ConnectionProvider for Hibernate 4.x called HikariConnectionProvider

In order to use the HikariConnectionProvider in Hibernate 4.x add the following property to your hibernate.properties configuration file:

```<code>hibernate.connection.provider_class=com.zaxxer.hikari.hibernate.HikariConnectionProvider
</code>```

As of Hibernate 4.3.6 there is an official ConnectionProvider class from Hibernate, which should be used instead of the HikariCP implementation. The class is called org.hibernate.hikaricp.internal.HikariCPConnectionProvider

Body:
I am using Hikari with SQL Server 2016 and sqljdbc4-2.0.jar in the tomcat lib folder.

My configuration for db resource is as follows:

<Resource name="jdbc/SQLServerDS" auth="Container" type="javax.sql.DataSource"
              username="uname"
              password="pwd"
              driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
              url="jdbc:sqlserver://server:port;DatabaseName=dbName"
              maxActive="20"
              maxIdle="10"
              validationQuery="select 1" />

My Datasource configuration is as follows:

@Bean(name = "dataSource")
    public DataSource getDataSource() throws NamingException {
        HikariConfig config = new HikariConfig();
        config.setMaximumPoolSize(20);
        config.setDataSourceJNDI("java:comp/env/jdbc/SQLServerDS");
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.addDataSourceProperty("useServerPrepStmts", "true");
        config.addDataSourceProperty("cacheResultSetMetadata", "true");
        config.addDataSourceProperty("useLocalSessionState", "true");
        config.addDataSourceProperty("cacheServerConfiguration", "true");
        config.addDataSourceProperty("elideSetAutoCommits", "true");
        config.addDataSourceProperty("maintainTimeStats", "false");
        return new TransactionAwareDataSourceProxy(
                new LazyConnectionDataSourceProxy(new HikariDataSource(config)));
    }

How do I know if the preparedstatement caching is working for different connections?

I am using spring container managed transactions with hibernate v4.3.10.Final.

Also, for the caching to work, do I need to have second-level cache enabled?

Body:
HikariCP actually doesn't support PreparedStatement caching

others offer PreparedStatement caching. HikariCP does not. Why?

It's considered wrong implementation

Using a statement cache at the pooling layer is an anti-pattern, and will negatively impact your application performance compared to driver-provided caches.

Explanation:

At the connection pool layer PreparedStatements can only be cached per connection. If your application has 250 commonly executed queries and a pool of 20 connections you are asking your database to hold on to 5000 query execution plans -- and similarly the pool must cache this many PreparedStatements and their related graph of objects.

Most major database JDBC drivers already have a Statement cache that can be configured, including PostgreSQL, Oracle, Derby, MySQL, DB2, and many others. JDBC drivers are in a unique position to exploit database specific features, and nearly all of the caching implementations are capable of sharing execution plans across connections. This means that instead of 5000 statements in memory and associated execution plans, your 250 commonly executed queries result in exactly 250 execution plans in the database. Clever implementations do not even retain PreparedStatement objects in memory at the driver-level but instead merely attach new instances to existing plan IDs.

If you accept it, you shouldn't try\expect to cache PreparedStatement

If you reject it, you can use C3P0 as connection pool

About Second level cache in hibernate, it's mostly not defined in connection pool, but use relevant connection provider:

HikariCP now has a ConnectionProvider for Hibernate 4.x called HikariConnectionProvider

In order to use the HikariConnectionProvider in Hibernate 4.x add the following property to your hibernate.properties configuration file:

hibernate.connection.provider_class=com.zaxxer.hikari.hibernate.HikariConnectionProvider

As of Hibernate 4.3.6 there is an official ConnectionProvider class from Hibernate, which should be used instead of the HikariCP implementation. The class is called org.hibernate.hikaricp.internal.HikariCPConnectionProvider


问:
java.lang.ClassNotFoundException throwing some error
```<code>java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</code>```

I added following jar files:

```<code>commons-fileupload-1.2.1.jar
commons-logging-1.1.1.jar
freemarker-2.3.16.jar
ognl-3.0.jar
servlet-api.jar
struts2-core-2.2.1.jar
xwork-core-2.2.1.jar
</code>```

答:
You said that you'd put the JAR files ...

in web-inf folder and also in build-path>libraries under eclipse dynamic web project

The JAR files need to be in

.../webapps/yourWebapp/WEB-INF/lib

If you put them directly into the WEB-INF directory, the web container won't put them onto the webapp's classpath.

Body:
java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

I added following jar files:

commons-fileupload-1.2.1.jar
commons-logging-1.1.1.jar
freemarker-2.3.16.jar
ognl-3.0.jar
servlet-api.jar
struts2-core-2.2.1.jar
xwork-core-2.2.1.jar


问:
move files that no not contain specific string
I would like to move files using mv that do not contain the letter S in the filename. Could not find anyhting in the mv manual. Maybe combination with find or grep? It has to be case-sensitive.

input:

```<code>  file1
  fileS1
  file2
  fileS2
</code>```

file to move:

```<code>  file1
  file2
</code>```

答:
GREP's -v flag can also be used here. According to the docs,

-v, --invert-match
                Invert the sense of matching, to select non-matching lines.

Just use

```<code>ls | grep -v '*S*' | xargs mv -t target_dir/
</code>```

Also, see this post.

Body:
I would like to move files using mv that do not contain the letter S in the filename. Could not find anyhting in the mv manual. Maybe combination with find or grep? It has to be case-sensitive.

input:

  file1
  fileS1
  file2
  fileS2

file to move:

  file1
  file2

Body:
GREP's -v flag can also be used here. According to the docs,

-v, --invert-match
                Invert the sense of matching, to select non-matching lines.

Just use

ls | grep -v '*S*' | xargs mv -t target_dir/

Also, see this post.


答:
You could also use the Ignore-pattern switch from ls, like:

```<code>mv $(ls -I '*S*') /target/dir
</code>```

Title: move files that no not contain specific string

Body:
You could also use the Ignore-pattern switch from ls, like:

mv $(ls -I '*S*') /target/dir


问:
JavaScript Slot Machine: What Is A Simple Algorithm For Picking A Winner?
I'm developing a slot machine in JavaScript, and this slot machine has 3 reels.

Each reel is identical and contains 4 symbols: A bar, a 7, a bell, and a grape. The bar is displayed on the reel one time, the 7 two times, the bell three times, and the grape four times - for a total of 10 symbols per reel. And each symbol corresponds with a number from 0 - 9:

```<code>| bar | -> 9
|  7  | -> 8
|  7  | -> 7
| bell| -> 6
| bell| -> 5
| bell| -> 4
|grape| -> 3
|grape| -> 2
|grape| -> 1
|grape| -> 0
</code>```

I'm then randomly generating a number from 0 - 999, and based on that number I would like to potentially select a winner. For example, if the number is 999 that is three bars and the first jackpot, if the number is 210 that is three grapes and the fourth jackpot. If the number is 359 that is grape/bell/bar and no jackpot.

I had created an if/else to select the winner but realized it does not take into account the second winning situation of 210:

```<code>if (number == 999) {
    // Jackpot 1
} else if (number == 888) {
    // Jackpot 2
} else if (number == 777) {
    // Jackpot 2
} else if (number == 666) {
    // Jackpot 3
} else if (number == 555) {
    // Jackpot 3
} else if (number == 444) {
    // Jackpot 3
} else if (number == 333) {
    // Jackpot 4
} else if (number == 222) {
    // Jackpot 4
} else if (number == 111) {
    // Jackpot 4
} else if (number == 0) {
    // Jackpot 4
} else {
    // No jackpot
}
</code>```

Does anyone have any ideas for how I might devise a simple algorithm for selecting a winner, as opposed to a bunch of if/else's? Also, there needs to be a total of 10 possible outcomes per reel, as the top jackpot should have a probability of 10^3 => 1 in 1,000.

答:
Create an array of arrays.

```<code>[[9], [7,8], [4,5,6] ,[0,1,2,3]]
</code>```

Then convert number to String and use every() and includes()

Working snippet:

function play(num){
  let number = num || Math.floor(Math.random() * 899) + 100;
  console.log(`Random Number: ${number}`)
  number = number.toString().split('')
  let arr = [[0,1,2,3],[4,5,6],[7,8],[9]];

  let jackpot = arr.findIndex(x => number.every(a => x.includes(+a))) + 1
  console.log(`jackpot:${jackpot}`)

}
play(999)
play(123)
play(446)
play(129)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="play()">click</button></code>```

Body:
I'm developing a slot machine in JavaScript, and this slot machine has 3 reels.

Each reel is identical and contains 4 symbols: A bar, a 7, a bell, and a grape. The bar is displayed on the reel one time, the 7 two times, the bell three times, and the grape four times - for a total of 10 symbols per reel. And each symbol corresponds with a number from 0 - 9:

| bar | -> 9
|  7  | -> 8
|  7  | -> 7
| bell| -> 6
| bell| -> 5
| bell| -> 4
|grape| -> 3
|grape| -> 2
|grape| -> 1
|grape| -> 0

I'm then randomly generating a number from 0 - 999, and based on that number I would like to potentially select a winner. For example, if the number is 999 that is three bars and the first jackpot, if the number is 210 that is three grapes and the fourth jackpot. If the number is 359 that is grape/bell/bar and no jackpot.

I had created an if/else to select the winner but realized it does not take into account the second winning situation of 210:

if (number == 999) {
    // Jackpot 1
} else if (number == 888) {
    // Jackpot 2
} else if (number == 777) {
    // Jackpot 2
} else if (number == 666) {
    // Jackpot 3
} else if (number == 555) {
    // Jackpot 3
} else if (number == 444) {
    // Jackpot 3
} else if (number == 333) {
    // Jackpot 4
} else if (number == 222) {
    // Jackpot 4
} else if (number == 111) {
    // Jackpot 4
} else if (number == 0) {
    // Jackpot 4
} else {
    // No jackpot
}

Does anyone have any ideas for how I might devise a simple algorithm for selecting a winner, as opposed to a bunch of if/else's? Also, there needs to be a total of 10 possible outcomes per reel, as the top jackpot should have a probability of 10^3 => 1 in 1,000.

Body:
Create an array of arrays.

[[9], [7,8], [4,5,6] ,[0,1,2,3]]

Then convert number to String and use every() and includes()

Working snippet:

function play(num){
  let number = num || Math.floor(Math.random() * 899) + 100;
  console.log(`Random Number: ${number}`)
  number = number.toString().split('')
  let arr = [[0,1,2,3],[4,5,6],[7,8],[9]];

  let jackpot = arr.findIndex(x => number.every(a => x.includes(+a))) + 1
  console.log(`jackpot:${jackpot}`)

}
play(999)
play(123)
play(446)
play(129)

<button onclick="play()">click</button>


问:
Initiate image capture using volume button (AVCaptureSession)
Now that this functionality is available in iOS5, is it possible to initiate image capture using one of the volume buttons?

I am using AVFoundation framework for my image capture app.

Thanks!

答:
Take a photo on the volume-up event when using UIImagePickerController with custom camera controls is used and we have set "showsCameraControls" to NO.

Here, the Notification event name was changed for volumeChanged event , @"AVSystemController_SystemVolumeDidChangeNotification" to @"_UIApplicationVolumeUpButtonDownNotification"

You can find an answer from this link:

https://stackoverflow.com/a/27180527/3759546


问:
number input always trigger change event
I have a issue with Angulars change event on numeric input. It doesn't always trigger when i click the increment or decrament buttons, actualy it triggers once then it will trigger only after input losses hover.

My question is if there is some way to prevent this from happening or some replacement for change event.

some ground for testing:
stackblitz

答:
This is working as your expectation: </p>

```<code><input type="number" (mouseup)="changed()"/>
</code>```

Body:
This is working as your expectation:

<input type="number" (mouseup)="changed()"/>


问:
Android room persistent library - TypeConverter error of error: Cannot figure out how to save field to database"
Im not able to create a typeConverter in room due to an error. I seem to be following everything per the docs. I would like to convert a list to a json string.  lets take a look at my entity:

```<code>@Entity(tableName = TABLE_NAME)
public class CountryModel {

    public static final String TABLE_NAME = "Countries";

    @PrimaryKey
    private int idCountry;

    /* I WANT TO CONVERT THIS LIST TO A JSON STRING */
    private List<CountryLang> countryLang = null;

    public int getIdCountry() {
        return idCountry;
    }

    public void setIdCountry(int idCountry) {
        this.idCountry = idCountry;
    }

    public String getIsoCode() {
        return isoCode;
    }

    public void setIsoCode(String isoCode) {
        this.isoCode = isoCode;
    }

    public List<CountryLang> getCountryLang() {
        return countryLang;
    }

    public void setCountryLang(List<CountryLang> countryLang) {
        this.countryLang = countryLang;
    }

}
</code>```

The country_lang is what i would like to convert to a string json. So i created the following converter:
Converters.java:

```<code>public class Converters {

@TypeConverter
public static String countryLangToJson(List<CountryLang> list) {

    if(list == null)
        return null;

        CountryLang lang = list.get(0);

    return list.isEmpty() ? null : new Gson().toJson(lang);
}}
</code>```

then the problem is anywhere i put the @TypeConverters({Converters.class}) i keep getting an error. But officially this is where i have placed the annotation to get the typeConverter registered:

```<code>@Database(entities = {CountryModel.class}, version = 1 ,exportSchema = false)
@TypeConverters({Converters.class})
public abstract class MYDatabase extends RoomDatabase {
    public abstract CountriesDao countriesDao();
}
</code>```

The error i get is:

```<code>Error:(58, 31) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
</code>```

答: Had the same issue. Change the List to ArrayList. The list is an interface and room is unable to store it.

Body:
Im not able to create a typeConverter in room due to an error. I seem to be following everything per the docs. I would like to convert a list to a json string.  lets take a look at my entity:

@Entity(tableName = TABLE_NAME)
public class CountryModel {

    public static final String TABLE_NAME = "Countries";

    @PrimaryKey
    private int idCountry;

    /* I WANT TO CONVERT THIS LIST TO A JSON STRING */
    private List<CountryLang> countryLang = null;

    public int getIdCountry() {
        return idCountry;
    }

    public void setIdCountry(int idCountry) {
        this.idCountry = idCountry;
    }

    public String getIsoCode() {
        return isoCode;
    }

    public void setIsoCode(String isoCode) {
        this.isoCode = isoCode;
    }

    public List<CountryLang> getCountryLang() {
        return countryLang;
    }

    public void setCountryLang(List<CountryLang> countryLang) {
        this.countryLang = countryLang;
    }

}

The country_lang is what i would like to convert to a string json. So i created the following converter:
Converters.java:

public class Converters {

@TypeConverter
public static String countryLangToJson(List<CountryLang> list) {

    if(list == null)
        return null;

        CountryLang lang = list.get(0);

    return list.isEmpty() ? null : new Gson().toJson(lang);
}}

then the problem is anywhere i put the @TypeConverters({Converters.class}) i keep getting an error. But officially this is where i have placed the annotation to get the typeConverter registered:

@Database(entities = {CountryModel.class}, version = 1 ,exportSchema = false)
@TypeConverters({Converters.class})
public abstract class MYDatabase extends RoomDatabase {
    public abstract CountriesDao countriesDao();
}

The error i get is:

Error:(58, 31) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.


问:
Applying loops for get_historical function (from Bomrang)
I'm using get_historical_weather function from Bomrang package.
Instead of specifying manually lat and lon details (e.g. get_historical(latlon=c(-28.016666,153.399994),type="rain")) I need to use lat and lon details from existing list.
I've tried using for loop, without any success. Any help would be greatly appreciated!

Thanks

答:
Another way of doing this is using the purrr package

library(bomrang)
library(purrr)
coords <- structure(list(lat = c(-28.01666, -33.8688),
                         lon = c(153.399994, 151.2093)),
                    row.names = c(NA, -2L),
                    class = c("tbl_df", "tbl", "data.frame"))

x <- purrr::map2(.x = coords$lat, .y = coords$lon, .f = ~get_historical(latlon = c(.x, .y), type = "rain"))
#> Closest station: 040764 (GOLD COAST SEAWAY)
#> Data saved as /tmp/RtmpJkn04r/IDCJAC0009_040764_1800_Data.csv
#> Closest station: 066062 (SYDNEY (OBSERVATORY HILL))
#> Data saved as /tmp/RtmpJkn04r/IDCJAC0009_066062_1800_Data.csv
```

Created on 2019-05-28 by the reprex package (v0.2.1)

Body:
Another way of doing this is using the purrr package

library(bomrang)
library(purrr)
coords <- structure(list(lat = c(-28.01666, -33.8688),
                         lon = c(153.399994, 151.2093)),
                    row.names = c(NA, -2L),
                    class = c("tbl_df", "tbl", "data.frame"))

x <- purrr::map2(.x = coords$lat, .y = coords$lon, .f = ~get_historical(latlon = c(.x, .y), type = "rain"))
#> Closest station: 040764 (GOLD COAST SEAWAY)
#> Data saved as /tmp/RtmpJkn04r/IDCJAC0009_040764_1800_Data.csv
#> Closest station: 066062 (SYDNEY (OBSERVATORY HILL))
#> Data saved as /tmp/RtmpJkn04r/IDCJAC0009_066062_1800_Data.csv

Created on 2019-05-28 by the reprex package (v0.2.1)


问:
Login app using fingerprint instead of password
I am working on Flutter login screen but I want to register app using a fingerprint instead of the password. We have local_auth in Flutter but that is fore unlocking app using a fingerprint or touch id. What are the available methods to do that?</p>

答:
What you can do is to refer the plugin local_auth available on Pub and authenticate with local authentication. It is the fastest way to handle it. The package is maintained by the official flutter team, so no need to worry about the updates.

Check the repository and examples here:

https://github.com/flutter/plugins/tree/master/packages/local_auth

Thanks.


问:
What is the most efficient way to make random label location adjust to window size?
I have a label centered by the X coordinate on a form, and I'm trying to make it adjust its location on form resize.
So, I'm handling the Resize event to update label Location property.

```<code>private void SecondaryWindow_Resize(object sender, EventArgs e)
{
    lblStartPointX = this.Width / 2 - lblSecondary1.Width / 2;
    lblStartPointY = lblSecondary1.Location.Y;
    lblSecondary1.Location = new Point(lblStartPointX, lblStartPointY);
}
</code>```

It seems I can't directly assign some value to lblSecondary1.Location.X property (compiler considers it a mistake), so I came up with this code.

But it strikes me as not very efficient way to do the task... Just how much Point objects are created if you constantly resize the window, I wonder?

答:
There are multiply ways. I would recommend using WPF instead for responsive design.

When the Label is the only control, you can turn of Autosize, set the anchors to all sides, set the TextAlgin to Center and resize your Label, so it takes the whole space.

An other way would be to work with TableLayoutPanels. Takes some time to get used to it, but it comes near the Grid of WPF.

Body:
I have a label centered by the X coordinate on a form, and I'm trying to make it adjust its location on form resize.
So, I'm handling the Resize event to update label Location property.

private void SecondaryWindow_Resize(object sender, EventArgs e)
{
    lblStartPointX = this.Width / 2 - lblSecondary1.Width / 2;
    lblStartPointY = lblSecondary1.Location.Y;
    lblSecondary1.Location = new Point(lblStartPointX, lblStartPointY);
}

It seems I can't directly assign some value to lblSecondary1.Location.X property (compiler considers it a mistake), so I came up with this code.

But it strikes me as not very efficient way to do the task... Just how much Point objects are created if you constantly resize the window, I wonder?


问:
Woocommerce add image after add to cart button
It seems weird,  but am trying to add a background image after an element(button) but for some reason, the image does not show.

    .single_add_to_cart_button:after {
        content: '';
        width: 50px;
        height: 9px;
        display: inline-block;
        background: url(/images/arrow.png);
        background-position: 50%;
        background-size: cover;
        background-repeat: no-repeat;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="submit" class="single_add_to_cart_button button alt disabled wc-variation-selection-needed">Place order</button></code>```

For some reason, the image does not show and I even tried using a live URL

Note: If I try using a paragraph it works as you can see in my pen here

How can I add an image from the template directory after my add to cart button?

In a simpler solution, I tried using a hook but I am also struggling to access the image using bloginfo:

```<code>add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart_button_func' );

function add_content_after_addtocart_button_func() {
    echo '<img src="<?php bloginfo("template_directory")/images/logo/logo.png">';
}
</code>```

答:
Works just fine here (I added some additional styling)

.single_add_to_cart_button {
  background-color: #ededed;
  border: none;
  padding: 2rem;
  display: flex;
  align-items: center;
  font-size: 1rem;
  border-radius: 3px;
}

.single_add_to_cart_button:after {
  content: '';
  width: 4rem;
  height: 2rem;
  margin-left: 1rem;
  display: inline-block;
  background: url(http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png);
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="submit" class="single_add_to_cart_button button alt disabled wc-variation-selection-needed">Place order</button></code>```

Body:
It seems weird,  but am trying to add a background image after an element(button) but for some reason, the image does not show.

    .single_add_to_cart_button:after {
        content: '';
        width: 50px;
        height: 9px;
        display: inline-block;
        background: url(/images/arrow.png);
        background-position: 50%;
        background-size: cover;
        background-repeat: no-repeat;
    }

<button type="submit" class="single_add_to_cart_button button alt disabled wc-variation-selection-needed">Place order</button>

For some reason, the image does not show and I even tried using a live URL

Note: If I try using a paragraph it works as you can see in my pen here

How can I add an image from the template directory after my add to cart button?

In a simpler solution, I tried using a hook but I am also struggling to access the image using bloginfo:

add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart_button_func' );

function add_content_after_addtocart_button_func() {
    echo '<img src="<?php bloginfo("template_directory")/images/logo/logo.png">';
}

Body:
Works just fine here (I added some additional styling)

.single_add_to_cart_button {
  background-color: #ededed;
  border: none;
  padding: 2rem;
  display: flex;
  align-items: center;
  font-size: 1rem;
  border-radius: 3px;
}

.single_add_to_cart_button:after {
  content: '';
  width: 4rem;
  height: 2rem;
  margin-left: 1rem;
  display: inline-block;
  background: url(http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png);
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

<button type="submit" class="single_add_to_cart_button button alt disabled wc-variation-selection-needed">Place order</button>


问:
Pandas resample to monthly, is giving incorrect output?
I am trying to resample data from daily to monthly

This is what I am doing

```<code>i = 'NSE/CHENNPETRO'
df = pdr.DataReader(i, 'quandl', start, end)
df_monthly = df['Close'].resample('M').ohlc()
</code>```

output:

```<code>Date         open    high     low   close

2017-07-31  353.55  400.10  353.55  387.00
2017-08-31  414.30  448.35  378.05  448.35
2017-09-30  460.80  460.80  391.10  402.95
2017-10-31  405.70  468.80  403.10  468.80
2017-11-30  464.55  470.65  427.45  427.45
</code>```

I checked it against the data for the 10th month.

```<code>Open: 410
High: 478
Low: 400
Close: 468.8
</code>```

I am not sure what I may be doing wrong. Very new to pandas

答:
You can use this</p>

```<code>df_monthly = df['Close'].resample('M').apply(lambda x: x[-1])
</code>```

Body:
I am trying to resample data from daily to monthly

This is what I am doing

i = 'NSE/CHENNPETRO'
df = pdr.DataReader(i, 'quandl', start, end)
df_monthly = df['Close'].resample('M').ohlc()

output:

Date         open    high     low   close

2017-07-31  353.55  400.10  353.55  387.00
2017-08-31  414.30  448.35  378.05  448.35
2017-09-30  460.80  460.80  391.10  402.95
2017-10-31  405.70  468.80  403.10  468.80
2017-11-30  464.55  470.65  427.45  427.45

I checked it against the data for the 10th month.

Open: 410
High: 478
Low: 400
Close: 468.8

I am not sure what I may be doing wrong. Very new to pandas

Body:
You can use this

df_monthly = df['Close'].resample('M').apply(lambda x: x[-1])


问:
Could not find a version that satisfies the requirement torch>=1.0.0?
Could not find a version that satisfies the requirement torch>=1.0.0
No matching distribution found for torch>=1.0.0 (from stanfordnlp)</p>

答:
I had this same issue while installing standfordnlp in my windows 10 system.
Installing torch before installing stanfordnlp worked out for me.
I have installed torch from pytorch official website.</p>


问:
what I need to change in my code to get my output like this [None, 2, None, 4,None].I am using lambd function to do this
I am trying to do this :

```<code>evenList = ((lambda x : x if x%2==0 else None), [1,2,3,4,5,6])
</code>```

Expected output :

```<code>[None,2,None,4,None,6]
</code>```

I am getting :

```<code>(<function __main__.<lambda>>, [1,2,3,4,5,6])
</code>```

答:
You just created a tuple, Not using that lambda,

Change your code like this,

```<code>In [10]: list(map((lambda x : x if x%2==0 else None), [1,2,3,4,5,6]))
Out[10]: [None, 2, None, 4, None, 6]
</code>```

Better use list comprehension,

```<code>In [11]: [i if i%2==0 else None for i in [1,2,3,4,5,6]]
Out[11]: [None, 2, None, 4, None, 6]
</code>```

Body:
I am trying to do this :

evenList = ((lambda x : x if x%2==0 else None), [1,2,3,4,5,6])

Expected output :

[None,2,None,4,None,6]

I am getting :

(<function __main__.<lambda>>, [1,2,3,4,5,6])

Body:
You just created a tuple, Not using that lambda,

Change your code like this,

In [10]: list(map((lambda x : x if x%2==0 else None), [1,2,3,4,5,6]))
Out[10]: [None, 2, None, 4, None, 6]

Better use list comprehension,

In [11]: [i if i%2==0 else None for i in [1,2,3,4,5,6]]
Out[11]: [None, 2, None, 4, None, 6]


问:
Where to store html code for jQuery?
In some scripts long html blocks are added to selector. For example

```<code>$("#test").prepend($('<div id="tester">..long html tags..</div>').hide().fadeIn(2000));
</code>```

Where it would be better to store that large html blocks? Directly, in variable, in html code, text file or other.

Thank you.

答: If they are static I think it would be better to have them as separate XML files and get them with an AJAX call to let them be cached.

Title: Where to store html code for jQuery?

Body:
In some scripts long html blocks are added to selector. For example

$("#test").prepend($('
..long html tags..
').hide().fadeIn(2000));

Where it would be better to store that large html blocks? Directly, in variable, in html code, text file or other.

Thank you.