问:
Is there a good way to display collected data to the user in HTML or javascript and still keep the data?
I am trying to pick up some user data from a HTML page by having the user type it in. I want to retain the data, (they are ID numbers of sorts) display it back to the user on any subsequent section they go to (currently different href sections on one page), collect more data from them and eventually present the data to the user as a review. I thought this would be a little like HTML “Hello World”, but it’s proving to be more than that. . I found out that document.write() is the wrong way to go about it, but no good answer on how to accomplish this. Collecting this data is the first thing I need from the user, and then I will collect more data, so I have to be able to get data and let the user move around.

I have spent a day and a half on this site and others, pulled out two books (yes, paper!) looking for answers, but not reaching a usable solution. Nothing seems to work. When complete, I want to give the user a chance to correct the data before submitting, most likely to post at the moment, but would be a server if implemented.

Here’s how I am collecting, simplified as much as possible:

```<code><form name="getNPIandTIN">
<p> Please enter NPI and TIN</p>
Provider NPI: <input type="number" name="Provider_NPI">
<p>
Provider TIN: <input type="number" name="Provider_TIN">
<input type="submit" value="Submit NPI and TIN">
</form>

...

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

Inner HTML action
<script> document.getElementById"demo").innerHTML=
document.getNPIandTIN.Provider_NPI.value
</script>
</code>```

No error messages; things just don't work. I want to ask the user to enter field 1, have them type it in, click for acceptance, store the data in a variable and echo the information back to them. Sounds pretty simple, but it isn't.

答:
There are many different ways, you can use ajax to save all data to a database and show them to user when ever you want.

Or you could use localStorage to save the data temporarily and save them later in certain circumstances...

Body:
I am trying to pick up some user data from a HTML page by having the user type it in. I want to retain the data, (they are ID numbers of sorts) display it back to the user on any subsequent section they go to (currently different href sections on one page), collect more data from them and eventually present the data to the user as a review. I thought this would be a little like HTML “Hello World”, but it’s proving to be more than that. . I found out that document.write() is the wrong way to go about it, but no good answer on how to accomplish this. Collecting this data is the first thing I need from the user, and then I will collect more data, so I have to be able to get data and let the user move around.

I have spent a day and a half on this site and others, pulled out two books (yes, paper!) looking for answers, but not reaching a usable solution. Nothing seems to work. When complete, I want to give the user a chance to correct the data before submitting, most likely to post at the moment, but would be a server if implemented.

Here’s how I am collecting, simplified as much as possible:

<form name="getNPIandTIN">

 Please enter NPI and TIN

Provider NPI: <input type="number" name="Provider_NPI">

Provider TIN: <input type="number" name="Provider_TIN">
<input type="submit" value="Submit NPI and TIN">
</form>

...

Inner HTML action

No error messages; things just don't work. I want to ask the user to enter field 1, have them type it in, click for acceptance, store the data in a variable and echo the information back to them. Sounds pretty simple, but it isn't.


来源: stackexchange

问:
How to execute a command CREATE USER from mysql inside Spring Project?
I have a Spring project and when i create a register user on table i have to create a database user too.

Now i have:

```<code>user = userRepository.save(user);
</code>```

The command is:

```<code>CREATE USER 'username' IDENTIFIED BY 'password';
</code>```

Is it possible?

答:
You can do it like below:  </p>

```<code>//UserService

@Autowired
private JdbcTemplate jdbcTemplate;

...
user = userRepository.save(user);
jdbcTemplate.execute("CREATE USER \'username\' IDENTIFIED BY \'password\'");
</code>```

<p>Note that your datasource user defined in application properties should have suitable privileges to create user and etc. </p>

ContentLicense: CC BY-SA 4.0

Body:
I have a Spring project and when i create a register user on table i have to create a database user too.

Now i have:

user = userRepository.save(user);

The command is:

CREATE USER 'username' IDENTIFIED BY 'password';

Is it possible?

Body:
You can do it like below:

//UserService

@Autowired
private JdbcTemplate jdbcTemplate;

...
user = userRepository.save(user);
jdbcTemplate.execute("CREATE USER \'username\' IDENTIFIED BY \'password\'");

Note that your datasource user defined in application properties should have suitable privileges to create user and etc.


问:
Unsetting nested descendants of a particular ancestor based on an key and if empty unset the ancestor as well
Let's imagine we have this multidimensional array which contains nested arrays

```<code>$arr = [
    1 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2
            ],
            1 => [
                'id' => 3
            ],
        ]
    ],
    2 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2,
                'products' => [
                    1 => 'John Doe'
                ],
            ],
            1 => [
                'id' => 3,
                'products' => [],
            ],
        ]
    ],
    3 => [
        'id' => 1,
        'products' => [
            1 => 'Hi',
            2 => 'Hello',
        ]
    ],
    4 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2
            ],
            1 => [
                'id' => 3
            ],
        ]
    ],
];
</code>```

I need to keep all ancestors and descendants where there is at least one item in the key "products", all other arrays should be unset.

So, in this particular example, the result should be as follows:

```<code>$arr = [
    2 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2,
                'products' => [
                    1 => 'John Doe'
                ],
            ],
        ]
    ],
    3 => [
        'id' => 1,
        'products' => [
            1 => 'Hi',
            2 => 'Hello',
        ]
    ],
];
</code>```

Basically, what needs to be done is to go from the most inner array up and asking:

1) Is our key "products" empty? Yes

2) Is our key "families" either empty or not set? Yes

3) unset this array

Body:
Let's imagine we have this multidimensional array which contains nested arrays

$arr = [
    1 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2
            ],
            1 => [
                'id' => 3
            ],
        ]
    ],
    2 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2,
                'products' => [
                    1 => 'John Doe'
                ],
            ],
            1 => [
                'id' => 3,
                'products' => [],
            ],
        ]
    ],
    3 => [
        'id' => 1,
        'products' => [
            1 => 'Hi',
            2 => 'Hello',
        ]
    ],
    4 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2
            ],
            1 => [
                'id' => 3
            ],
        ]
    ],
];

I need to keep all ancestors and descendants where there is at least one item in the key "products", all other arrays should be unset.

So, in this particular example, the result should be as follows:

$arr = [
    2 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2,
                'products' => [
                    1 => 'John Doe'
                ],
            ],
        ]
    ],
    3 => [
        'id' => 1,
        'products' => [
            1 => 'Hi',
            2 => 'Hello',
        ]
    ],
];

Basically, what needs to be done is to go from the most inner array up and asking:

1) Is our key "products" empty? Yes

2) Is our key "families" either empty or not set? Yes

3) unset this array

Body:
You can do it like this:

<?php

$arr = [
    1 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2
            ],
            1 => [
                'id' => 3
            ],
        ]
    ],
    2 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2,
                'products' => [
                    1 => 'John Doe'
                ],
            ],
            1 => [
                'id' => 3,
                'products' => [],
            ],
        ]
    ],
    3 => [
        'id' => 1,
        'products' => [
            1 => 'Hi',
            2 => 'Hello',
        ]
    ],
    4 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2
            ],
            1 => [
                'id' => 3
            ],
        ]
    ],
];

foreach($arr as $k => $a) {
    if(strpos(json_encode($a), "products") == 0){
        unset($arr[$k]);
    }
}

var_dump($arr);

https://3v4l.org/tNSqs


问:
Using Python textwrap.shorten for string but with bytes width
I'd like to shorten a string using textwrap.shorten or a function like it. The string can potentially have non-ASCII characters. What's special here is that the maximal width is for the bytes encoding of the string. This problem is motivated by the fact that several database column definitions and some message buses have a bytes based max length.

For example:

>>> import textwrap
>>> s = '☺ Ilsa, le méchant ☺ ☺ gardien ☺'

# Available function that I tried:
>>> textwrap.shorten(s, width=27)
'☺ Ilsa, le méchant ☺ [...]'
>>> len(_.encode())
31  # I want ⩽27

# Desired function:
>>> shorten_to_bytes_width(s, width=27)
'☺ Ilsa, le méchant [...]'
>>> len(_.encode())
27  # I want and get ⩽27
```

It's okay for the implementation to use a width greater than or equal to the length of the whitespace-stripped placeholder [...], i.e. 5.

The text should not be shortened any more than necessary. Some buggy implementations can use optimizations which on occasion result in excessive shortening.

Using textwrap.wrap with bytes count is a similar question but it's different enough from this one since it is about textwrap.wrap, not textwrap.shorten. Only the latter function uses a placeholder ([...]) which makes this question sufficiently unique.

Caution: Do not rely on any of the answers here for shortening a JSON encoded string in a fixed number of bytes. For it, substitute text.encode() with json.dumps(text).

答:
This solution is inefficient, but it does appear to always work correctly and without ever shortening excessively. It serves as a canonical baseline for testing any efficient solutions.

It first shortens pretending that the text is an ASCII string; this can shorten insufficiently but never excessively. It then inefficiently shortens one character at a time, and no more than necessary.

import textwrap

_MIN_WIDTH = 5  # == len(textwrap.shorten(string.ascii_letters, len(string.ascii_letters) - 1)) == len('[...]')

def shorten_to_bytes_width(text: str, width: int) -> str:
    # Ref: https://stackoverflow.com/a/56401167/
    width = max(_MIN_WIDTH, width)  # This prevents ValueError if width < _MIN_WIDTH
    text = textwrap.shorten(text, width)  # After this line, len(text.encode()) >= width
    while len(text.encode()) > width:
        text = textwrap.shorten(text, len(text) - 1)
    assert len(text.encode()) <= width
    return text
```

<p>Credit: Thanks to Sanyash for an improvement.</p>

<h2>Test</h2>

<pre class="lang-py prettyprint-override"><code>>>> s = '☺ Ilsa, le méchant ☺ ☺ gardien ☺'
>>> shorten_to_bytes_width(s, 27)
'☺ Ilsa, le méchant [...]'
>>> len(_.encode())
27
</code>```

Testing a candidate answer

Any candidate answer can be tested by comparing its outputs with the outputs of my function for width of range(50, -1, -1) or at minimum range(50, 5, -1). Given a candidate function, the code below implements the unit test:

import unittest

class TestShortener(unittest.TestCase):
    def test_candidate(self):
        text = '☺ Ilsa, le méchant ☺ ☺ gardien ☺'
        for width in range(50, -1, -1):
            with self.subTest(width=width):
                self.assertEqual(shorten_to_bytes_width(text, width), candidate(text, width))
```

Body:
I'd like to shorten a string using textwrap.shorten or a function like it. The string can potentially have non-ASCII characters. What's special here is that the maximal width is for the bytes encoding of the string. This problem is motivated by the fact that several database column definitions and some message buses have a bytes based max length.

For example:

>>> import textwrap
>>> s = '☺ Ilsa, le méchant ☺ ☺ gardien ☺'

# Available function that I tried:
>>> textwrap.shorten(s, width=27)
'☺ Ilsa, le méchant ☺ [...]'
>>> len(_.encode())
31  # I want ⩽27

# Desired function:
>>> shorten_to_bytes_width(s, width=27)
'☺ Ilsa, le méchant [...]'
>>> len(_.encode())
27  # I want and get ⩽27

It's okay for the implementation to use a width greater than or equal to the length of the whitespace-stripped placeholder [...], i.e. 5.

The text should not be shortened any more than necessary. Some buggy implementations can use optimizations which on occasion result in excessive shortening.

Using textwrap.wrap with bytes count is a similar question but it's different enough from this one since it is about textwrap.wrap, not textwrap.shorten. Only the latter function uses a placeholder ([...]) which makes this question sufficiently unique.

Caution: Do not rely on any of the answers here for shortening a JSON encoded string in a fixed number of bytes. For it, substitute text.encode() with json.dumps(text).

Body:
This solution is inefficient, but it does appear to always work correctly and without ever shortening excessively. It serves as a canonical baseline for testing any efficient solutions.

It first shortens pretending that the text is an ASCII string; this can shorten insufficiently but never excessively. It then inefficiently shortens one character at a time, and no more than necessary.

import textwrap

_MIN_WIDTH = 5  # == len(textwrap.shorten(string.ascii_letters, len(string.ascii_letters) - 1)) == len('[...]')

def shorten_to_bytes_width(text: str, width: int) -> str:
    # Ref: https://stackoverflow.com/a/56401167/
    width = max(_MIN_WIDTH, width)  # This prevents ValueError if width < _MIN_WIDTH
    text = textwrap.shorten(text, width)  # After this line, len(text.encode()) >= width
    while len(text.encode()) > width:
        text = textwrap.shorten(text, len(text) - 1)
    assert len(text.encode()) <= width
    return text

Credit: Thanks to Sanyash for an improvement.

Test

>>> s = '☺ Ilsa, le méchant ☺ ☺ gardien ☺'
>>> shorten_to_bytes_width(s, 27)
'☺ Ilsa, le méchant [...]'
>>> len(_.encode())
27

Testing a candidate answer

Any candidate answer can be tested by comparing its outputs with the outputs of my function for width of range(50, -1, -1) or at minimum range(50, 5, -1). Given a candidate function, the code below implements the unit test:

import unittest

class TestShortener(unittest.TestCase):
    def test_candidate(self):
        text = '☺ Ilsa, le méchant ☺ ☺ gardien ☺'
        for width in range(50, -1, -1):
            with self.subTest(width=width):
                self.assertEqual(shorten_to_bytes_width(text, width), candidate(text, width))


问:
React - Unable to setState inside a Promise then
I'm trying to set the state inside a then() of a Promise, but the state value is not getting saved and is not accessible outside of the then().

Below is the UPDATED code:

```<code>handleSelect = location => {
  this.setState({ location });
  geocodeByAddress(
    location
  )
  .then(results => getLatLng(results[0]))
  .then(latLng => {
    this.setState({
      location_latitude: latLng.lat,
      location_longitude: latLng.lng,
    })
    console.log(this.state.location_latitude); // returns the correct value
  })
  console.log(this.state.location_latitude); // returns null (the originally declared value)
}
</code>```

If I console.log(this.state.location_latitude) I get a null value. But if I console.log inside the then() block, I get the correct value. How do I set the state in this case?

UPDATED explanation:

To give a better context to the whole logic here: I'm using a Google Places Autocomplete component which allows the user to select a location from the dropdown. The above method handleSelect is called when the user selects a location from the dropdown. I then extract the latitude and longitude of the place selected by the user using the geocodeByAddress method, which is a promise. I need to then retrieve the latitude and longitude and set the state accordingly, which is later used to send to the database. I can't submit the value to the database yet because there are other form inputs that the user needs to fill (which are also stored in the state) and once he clicks on Submit, I'll be submitting all the state elements in a single call to the backend. So, there is nothing I want to update with componentDidMount() or nothing is getting updated yet to use componentDidUpdate(). In any case, I can only store the state value inside the then of geocodeByAddress (please correct me if I'm wrong here). So, I HAVE to be able to modify the state value inside the then block.

答:
You need to bind the function context to current class/ component. Try something like below. Create a function like "callSetState" bind it with this and while calling in then just pass the values as parameters to it.</p>

```<code>import React, { Component } from 'react';
class Test extends Component{
    constructor() {
        super()
        this.callSetState = this.callSetState.bind(this);
    }

    callSetState(latitude, longitude) {
        this.setState({
            location_latitude: latitude,
            location_longitude: longitude,
        })
    }

/* Call this func in your class and call callSetState which is already bound to your component in constructor */

    // geocodeByAddress(location)
    //     .then(results => getLatLng(results[0]))
    //     .then(latLng => this.callSetState(latLng.lat, latLng.lng));

}
</code>```

Body:
I'm trying to set the state inside a then() of a Promise, but the state value is not getting saved and is not accessible outside of the then().

Below is the UPDATED code:

handleSelect = location => {
  this.setState({ location });
  geocodeByAddress(
    location
  )
  .then(results => getLatLng(results[0]))
  .then(latLng => {
    this.setState({
      location_latitude: latLng.lat,
      location_longitude: latLng.lng,
    })
    console.log(this.state.location_latitude); // returns the correct value
  })
  console.log(this.state.location_latitude); // returns null (the originally declared value)
}

If I console.log(this.state.location_latitude) I get a null value. But if I console.log inside the then() block, I get the correct value. How do I set the state in this case?

UPDATED explanation:

To give a better context to the whole logic here: I'm using a Google Places Autocomplete component which allows the user to select a location from the dropdown. The above method handleSelect is called when the user selects a location from the dropdown. I then extract the latitude and longitude of the place selected by the user using the geocodeByAddress method, which is a promise. I need to then retrieve the latitude and longitude and set the state accordingly, which is later used to send to the database. I can't submit the value to the database yet because there are other form inputs that the user needs to fill (which are also stored in the state) and once he clicks on Submit, I'll be submitting all the state elements in a single call to the backend. So, there is nothing I want to update with componentDidMount() or nothing is getting updated yet to use componentDidUpdate(). In any case, I can only store the state value inside the then of geocodeByAddress (please correct me if I'm wrong here). So, I HAVE to be able to modify the state value inside the then block.

Body:
You need to bind the function context to current class/ component. Try something like below. Create a function like "callSetState" bind it with this and while calling in then just pass the values as parameters to it.

import React, { Component } from 'react';
class Test extends Component{
    constructor() {
        super()
        this.callSetState = this.callSetState.bind(this);
    }

    callSetState(latitude, longitude) {
        this.setState({
            location_latitude: latitude,
            location_longitude: longitude,
        })
    }

/* Call this func in your class and call callSetState which is already bound to your component in constructor */

    // geocodeByAddress(location)
    //     .then(results => getLatLng(results[0]))
    //     .then(latLng => this.callSetState(latLng.lat, latLng.lng));

}


问:
TestFlight push notifications not working
My TestFlight app isn't receiving APNs push notifications, however my development app receives them correctly. This seems to suggest that it's a problem with my Apple certs/profile/etc. There are numerous SO questions on this topic, but none of them helped me.

I'm using Phonegap Build to build the app -- not Xcode.

I tried regenerating all the certs/profiles/.p12 files, all of which are set up for distribution rather than development.

In my config.xml, I've set the "aps-environment" entitlement to "production". I've also confirmed that my provisioning profile contains the aps-environment "production" entitlement, as described here.

```<code><config-file target="*.entitlements" parent="aps-environment">
    <string>production</string>
</config-file>
</code>```

答: I regenerated the cert/profile/.p12 about 3 more times and it finally started working. Not a very satisfying answer, but there you go.</p>

Body:
My TestFlight app isn't receiving APNs push notifications, however my development app receives them correctly. This seems to suggest that it's a problem with my Apple certs/profile/etc. There are numerous SO questions on this topic, but none of them helped me.

I'm using Phonegap Build to build the app -- not Xcode.

I tried regenerating all the certs/profiles/.p12 files, all of which are set up for distribution rather than development.

In my config.xml, I've set the "aps-environment" entitlement to "production". I've also confirmed that my provisioning profile contains the aps-environment "production" entitlement, as described here.

<config-file target="*.entitlements" parent="aps-environment">
    <string>production</string>
</config-file>


问:
macro to generate a word document from data in excel
I want to generate a word document from data in particular column in excel...
such that i will have N page word document for N records in Excel...

I also want to customize the position of that data in the word.....

For example,
say first data from excel should be present on 1st page of word document at position 10cm from top and 5cm from left.

i have tried a macro and it generates a word with data from particular cell of excel.

But was unable to find to next cell data on new page and customize its position..

```<code>Option Explicit

Sub Create_New_WordDoc()
Dim wsApp As Word.Application

Set wsApp = CreateObject("Word.Application")
With wsApp
        .Visible = True
        .Documents.Add
End With

Set wsApp = Nothing
End Sub
</code>```

答:
You could create word "template" with key text to find and replace. Here is the Macro from excel, your word doc would contain the text between << and >> and you would search and replace</p>

```<code>Sub Button5_Click()

Dim wApp As Word.Application
Dim wDoc As Word.Document
Set wApp = CreateObject("Word.Application")
FNameQ = Range("E24").Value
Dim FnameP As String
FnameP = " C OF C"
Dim FName As String
FName = FNameQ & FnameP
wApp.Visible = True

Set wDoc = wApp.Documents.Open("LOCATION OF FILE\XXXX.doc")

With wDoc
    .Application.Selection.Find.Text = "<<CUSTNAME>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E22")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<PONUM>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E23")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<PARTNUM>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E24")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<DRAWNUM>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E25")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<DRAWREV>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E26")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<PARTDESC>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E27")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<MATERIAL>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E28")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<SHIPDATE>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E29")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<NAME>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E31")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<TITLE>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E32")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<SHIPDATE>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E29")
    .Application.Selection.EndOf

    .SaveAs2 Filename:=FName, _
    FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False
End With

End Sub
</code>```

Body:
I want to generate a word document from data in particular column in excel...
such that i will have N page word document for N records in Excel...

I also want to customize the position of that data in the word.....

For example,
say first data from excel should be present on 1st page of word document at position 10cm from top and 5cm from left.

i have tried a macro and it generates a word with data from particular cell of excel.

But was unable to find to next cell data on new page and customize its position..

Option Explicit

Sub Create_New_WordDoc()
Dim wsApp As Word.Application

Set wsApp = CreateObject("Word.Application")
With wsApp
        .Visible = True
        .Documents.Add
End With

Set wsApp = Nothing
End Sub

Body:
You could create word "template" with key text to find and replace. Here is the Macro from excel, your word doc would contain the text between << and >> and you would search and replace

Sub Button5_Click()

Dim wApp As Word.Application
Dim wDoc As Word.Document
Set wApp = CreateObject("Word.Application")
FNameQ = Range("E24").Value
Dim FnameP As String
FnameP = " C OF C"
Dim FName As String
FName = FNameQ & FnameP
wApp.Visible = True

Set wDoc = wApp.Documents.Open("LOCATION OF FILE\XXXX.doc")

With wDoc
    .Application.Selection.Find.Text = "<<CUSTNAME>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E22")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<PONUM>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E23")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<PARTNUM>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E24")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<DRAWNUM>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E25")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<DRAWREV>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E26")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<PARTDESC>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E27")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<MATERIAL>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E28")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<SHIPDATE>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E29")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<NAME>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E31")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<TITLE>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E32")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<SHIPDATE>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("E29")
    .Application.Selection.EndOf

    .SaveAs2 Filename:=FName, _
    FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False
End With

End Sub


问:
Why can I read 3 structs while allocating only 2?
I'm trying to understand why the following code works in C:

```<code>test *liste = NULL;

liste = malloc(sizeof(test)*2);
liste[0].number = 5;
liste[1].number = 10;
liste[2].number = 15;

printf("%d\n", liste[0].number);
printf("%d\n", liste[1].number);
printf("%d\n", liste[2].number);
</code>```

With the struct being:

```<code>typedef struct test {
    int number;
} test;
</code>```

Output:

```<code>5
10
15
</code>```

I thought, creating only 2 elements of "test" and accessing more than 2 (like here 3) will result in a memory access violation? But why is this working then?

Getting more and more confused here ....

答:
Welcome to the wonderful world of undefined behavior, where anything can happen!

The C spec says that in certain cases, the result of performing an operation results in what's called undefined behavior. This means that there are no guarantees whatsoever about what might happen when you perform those operations. The program might immediately crash. It might continue to run but with random memory regions corrupted. It might seem to cause no ill effects whatsoever. It might also cause the computer to gain sentience and compose poetry. (That last one is unlikely, but it's technically possible!)

In your case, if you try to access memory that you don't own (here, by reading off the end of a malloc'ed array), the result is undefined behavior. On your system, it seems like walking off by one step in this particular case coincidentally happens to not cause any problems, but walking further than that does lead to a crash. The reason for this likely has to do with the particulars of your memory allocator and the specific machine you're on. This can be jarring if you're coming from a language like Python or Java where errors are more specified and better-defined.

Body:
I'm trying to understand why the following code works in C:

test *liste = NULL;

liste = malloc(sizeof(test)*2);
liste[0].number = 5;
liste[1].number = 10;
liste[2].number = 15;

printf("%d\n", liste[0].number);
printf("%d\n", liste[1].number);
printf("%d\n", liste[2].number);

With the struct being:

typedef struct test {
    int number;
} test;

Output:

5
10
15

I thought, creating only 2 elements of "test" and accessing more than 2 (like here 3) will result in a memory access violation? But why is this working then?

Getting more and more confused here ....


问:
Help with physics simulation in WPF
I'm studying simple physics for 2d games and I would like a help with a simulation I'm trying to do.

I have a bar that will fall over a fixed ball in the ground, xaml below:

```<code><Canvas Background="CornflowerBlue">
    <Rectangle Name="bar" Width="200" Height="20" Fill="Cornsilk" Canvas.Left="250" Canvas.Top="50" />
    <Ellipse Name="ball" Height="50" Width="50" Fill="PaleGreen" Canvas.Left="380" Canvas.Top="250" />
</Canvas>
</code>```

I have all the calculations done to simulate the bar falling due to gravity but what I really need help with is, once the bar hits the ball, it's gonna have one side in the ground and the other side over the ball, which could be pretty much represented with the xaml:

```<code><Canvas Background="CornflowerBlue">
    <Rectangle Name="bar" Width="200" Height="20" Fill="Cornsilk" Canvas.Left="250" Canvas.Top="246.675" RenderTransformOrigin="0.5,0.5" >
        <Rectangle.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform Angle="-18.897"/>
                <TranslateTransform/>
            </TransformGroup>
        </Rectangle.RenderTransform>
    </Rectangle>
    <Ellipse Name="ball" Height="50" Width="50" Fill="PaleGreen" Canvas.Left="380" Canvas.Top="250" />
</Canvas>
</code>```

And I don't know how to make the left side of the bar hit the ground while the left side will be over the ball in phisics terms.

I know there are awesome physics engine available like Farseen but I just want to understand how it would work in this case.

I know how to get the bar's Y based on time, so I keep checking it until it colides with the ball, but then what after that?

Thanks!

答:
Rigid Body physical simulation is not a simple task Unless you are very interested in the topic I would recommend using a physics library. But if you are interested in doing this I would recommend looking at the Physically Based Modeling SIGGRAPH course notes, Brian Mirtich's thesis on impulse based dynamics and perhaps also Kenny Erleben's thesis on multibody dynamics.

These provide a very in depth description of how rigid body dynamics can be implemented.

ContentLicense: CC BY-SA 3.0

Title: Help with physics simulation in WPF

Body:
I'm studying simple physics for 2d games and I would like a help with a simulation I'm trying to do.

I have a bar that will fall over a fixed ball in the ground, xaml below:

<Canvas Background="CornflowerBlue">
    <Rectangle Name="bar" Width="200" Height="20" Fill="Cornsilk" Canvas.Left="250" Canvas.Top="50" />
    <Ellipse Name="ball" Height="50" Width="50" Fill="PaleGreen" Canvas.Left="380" Canvas.Top="250" />
</Canvas>

I have all the calculations done to simulate the bar falling due to gravity but what I really need help with is, once the bar hits the ball, it's gonna have one side in the ground and the other side over the ball, which could be pretty much represented with the xaml:

<Canvas Background="CornflowerBlue">
    <Rectangle Name="bar" Width="200" Height="20" Fill="Cornsilk" Canvas.Left="250" Canvas.Top="246.675" RenderTransformOrigin="0.5,0.5" >
        <Rectangle.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform Angle="-18.897"/>
                <TranslateTransform/>
            </TransformGroup>
        </Rectangle.RenderTransform>
    </Rectangle>
    <Ellipse Name="ball" Height="50" Width="50" Fill="PaleGreen" Canvas.Left="380" Canvas.Top="250" />
</Canvas>

And I don't know how to make the left side of the bar hit the ground while the left side will be over the ball in phisics terms.

I know there are awesome physics engine available like Farseen but I just want to understand how it would work in this case.

I know how to get the bar's Y based on time, so I keep checking it until it colides with the ball, but then what after that?

Thanks!


问:
Why is my query showing data in mongo shell but not node?
I'm working on a module to manually import data that was lost during a db upgrade.  I created the JSON, and did a mongoimport into a collection named loaddata.

From the mongo shell, running db.loaddata.find() returns all 18 orders just like they should be.

When I attempt to run it from node, I get 0 orders (no error) but I don't get why it isn't returning the results, except that I maybe messed up with the database model?  Here is my code:

```<code>module.exports.lostOrdersGetAll = function(req, res) {
  console.log('GET the lost orders');
  LostData.find({}).exec(function(err, orders) {
    if (err) {
      console.log('Error finding lost orders');
      res.status(500).json(err);
    } else {
      console.log('Found lost orders', orders.length);
      res.json(orders);
    }
  });
};
</code>```

My Model

```<code>var mongoose = require('mongoose');

var lostdataSchema = new mongoose.Schema({
  cart: {
    username: String,
    items: [],
    totalQty: Number,
    totalPrice: Number
  },
  customer: String,
  paymentID: {
    type: String,
    required: true
  },
  paymentNote: String,
  refundedAmt: Number,
  paymentStatus: {
    type: String
  },
  user: String,
  createdOn: {
    type: Date,
    default: Date.now
  },
  updatedOn: {
    type: Date
  },
  active: Boolean
});

mongoose.model('LostData', lostdataSchema);
</code>```

My db.js file, although I doubt the problem is in this file:

```<code>var mongoose = require('mongoose');
var options = {
  useMongoClient: true
};
const dburl = 'mongodb://localhost:27017/rumble';

var retry = null;

mongoose.connect(dburl, options);

//CONNECTION EVENTS
mongoose.connection.on('connected', function() {
  console.log('Mongoose connected to', dburl);
});

mongoose.connection.on('disconnected', function() {
  console.log('Mongoose disconnected', dburl);
});

mongoose.connection.on('error', function(err) {
  console.log('Mongoose connection error', err);
});
//CAPTURE APP TERMINATION / RESTART EVENTS
//To be called when process is restarted or terminated
function gracefulShutdown(msg, callback) {
  mongoose.connection.close(function() {
    console.log('Mongoose disconnected through ' + msg);
    callback();
  });
}

//For nodemon restarts
process.once('SIGUSR2', function() {
  gracefulShutdown('nodemon restart', function() {
    process.kill(process.pid, 'SIGUSR2');
  });
});
//For app termination
process.on('SIGINT', function() {
  gracefulShutdown('App termination (SIGINT)', function() {
    process.exit(0);
  });
});
//For Heroku app termination
process.on('SIGTERM', function() {
  gracefulShutdown('App termination (SIGTERM)', function() {
    process.exit(0);
  });
});

//bring in schemas and models
require('./admins.model.js');
require('./articles.model.js');
require('./orders.model.js');
require('./lostdata.model.js');
require('./fields.model.js');
require('./pages.model.js');
require('./alerts.model.js');
require('./products.model.js');
require('./registrations.model.js');
require('./users.model.js');
require('./volunteers.model.js');
require('./winners.model.js');
require('./stripepayments.model.js');
require('./stripecharges.model.js');
require('./cartstore.model');
require('./waiverrecipients.model');
</code>```

The logged results from the console (to me, this says the code is running correctly and did not return errors) are:

My Mongo Shell results:

答:
for mongoose.model() method

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database.

Mongoose trying to be smart and detect the model name, but you can force it to use the collection you want like this

```<code>new Schema({..}, { collection: 'lostdata' })
</code>```

Or when you create the model, like this

```<code>mongoose.model('LostData', lostdataSchema, 'lostdata')
</code>```

Body:
I'm working on a module to manually import data that was lost during a db upgrade.  I created the JSON, and did a mongoimport into a collection named loaddata.

From the mongo shell, running db.loaddata.find() returns all 18 orders just like they should be.

When I attempt to run it from node, I get 0 orders (no error) but I don't get why it isn't returning the results, except that I maybe messed up with the database model?  Here is my code:

module.exports.lostOrdersGetAll = function(req, res) {
  console.log('GET the lost orders');
  LostData.find({}).exec(function(err, orders) {
    if (err) {
      console.log('Error finding lost orders');
      res.status(500).json(err);
    } else {
      console.log('Found lost orders', orders.length);
      res.json(orders);
    }
  });
};

My Model

var mongoose = require('mongoose');

var lostdataSchema = new mongoose.Schema({
  cart: {
    username: String,
    items: [],
    totalQty: Number,
    totalPrice: Number
  },
  customer: String,
  paymentID: {
    type: String,
    required: true
  },
  paymentNote: String,
  refundedAmt: Number,
  paymentStatus: {
    type: String
  },
  user: String,
  createdOn: {
    type: Date,
    default: Date.now
  },
  updatedOn: {
    type: Date
  },
  active: Boolean
});

mongoose.model('LostData', lostdataSchema);

My db.js file, although I doubt the problem is in this file:

var mongoose = require('mongoose');
var options = {
  useMongoClient: true
};
const dburl = 'mongodb://localhost:27017/rumble';

var retry = null;

mongoose.connect(dburl, options);

//CONNECTION EVENTS
mongoose.connection.on('connected', function() {
  console.log('Mongoose connected to', dburl);
});

mongoose.connection.on('disconnected', function() {
  console.log('Mongoose disconnected', dburl);
});

mongoose.connection.on('error', function(err) {
  console.log('Mongoose connection error', err);
});
//CAPTURE APP TERMINATION / RESTART EVENTS
//To be called when process is restarted or terminated
function gracefulShutdown(msg, callback) {
  mongoose.connection.close(function() {
    console.log('Mongoose disconnected through ' + msg);
    callback();
  });
}

//For nodemon restarts
process.once('SIGUSR2', function() {
  gracefulShutdown('nodemon restart', function() {
    process.kill(process.pid, 'SIGUSR2');
  });
});
//For app termination
process.on('SIGINT', function() {
  gracefulShutdown('App termination (SIGINT)', function() {
    process.exit(0);
  });
});
//For Heroku app termination
process.on('SIGTERM', function() {
  gracefulShutdown('App termination (SIGTERM)', function() {
    process.exit(0);
  });
});

//bring in schemas and models
require('./admins.model.js');
require('./articles.model.js');
require('./orders.model.js');
require('./lostdata.model.js');
require('./fields.model.js');
require('./pages.model.js');
require('./alerts.model.js');
require('./products.model.js');
require('./registrations.model.js');
require('./users.model.js');
require('./volunteers.model.js');
require('./winners.model.js');
require('./stripepayments.model.js');
require('./stripecharges.model.js');
require('./cartstore.model');
require('./waiverrecipients.model');

The logged results from the console (to me, this says the code is running correctly and did not return errors) are:

My Mongo Shell results:

Body:
for mongoose.model() method

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database.

Mongoose trying to be smart and detect the model name, but you can force it to use the collection you want like this

new Schema({..}, { collection: 'lostdata' })

Or when you create the model, like this

mongoose.model('LostData', lostdataSchema, 'lostdata')


问:
Which algorithm and what combination of hyper-parameters will be the best to cluster this data?
I was learning about non-linear clustering algorithms and I came across this 2-D graph. I was wondering which clustering alogirthm and combination of hyper-parameters will cluster this data well.

Just like a human will cluster those 5 spikes. I want my algorithm to do it.
I tried KMeans but it was only clustering horizontly or vertically. I started using GMM but couldn't get the hyper-parameters right for the desired clustering.

答:
DBSCAN or GMM should work well to cluster this type of data.

It is one of the few clustering algorithms that does not classify the data into circular clusters

Clustering with DBSCAN

Clustering with GMM

Also please do give this blog a read. It will explain the different clustering techniques.


问:
Tracing redirects with Headless Chrome Developer Tools
I'm using CDP4J, though I expect this question relates directly to Google Chrome DevTools Protocol.

I want to get a list of the HTTP requests made for a webpage and response codes. So that would include the initial request in the main frame and subsequent requests, either made via 3xx redirects or JavaScript-originated navigation.

It's not clear how to do this reliably.

I have tried the following:

Store io.webfolder.cdp.session.Session.getFrameId

Add callback to session with addEventListener, record every event of type io.webfolder.cdp.event.Event.NetworkResponseReceived

Of these, filter those whose frame ID matches.

Of these filter on type io.webfolder.cdp.type.page.ResourceType.Document

I have a URL that I know returns a HTTP 303. But looking at the Events, don't see the original URL, but instead see only the final destination of the redirects. Every single NetworkResponseReceived has a status of 200.

How can I capture the chain of redirects?

答:
I've been using the ResponseReceived event for this purpose.  This seems to work to get the document URL from the event:</p>

```<code>    if (session.getTargetId().equals(responseReceived.getFrameId()) && ResourceType.Document.equals(responseReceived.getType())) {
        String url = responseReceived.getResponse().getUrl();
        ...
    }
</code>```

Body:
I've been using the ResponseReceived event for this purpose.  This seems to work to get the document URL from the event:

    if (session.getTargetId().equals(responseReceived.getFrameId()) && ResourceType.Document.equals(responseReceived.getType())) {
        String url = responseReceived.getResponse().getUrl();
        ...
    }


问:
Oracle - object order - how does it work?
Oracle doc says as follows: "As with map methods, an order method, if one is defined, is called automatically whenever two objects of that type need to be compared."

So I assume it will sort when using 'order by' clausule.

Lets say, I have following object:

```<code>create or replace type height as object
(
    val number,

    constructor function height return self as result,
    constructor function height (val number) return self as result,

    order member function compare (other height) RETURN INTEGER
);
</code>```

and its body implementation:

```<code>create or replace type body height is
    constructor function height return self as result is
         begin
            self.val := null;
         end;

    constructor function height (val number) return self as result is
         begin
            self.val := val;
            return;
         end;

    order member function compare (other height) return integer is
        begin
            if self.val > self.val then return 1;
            elsif self.val < self.val then return -1;
            else return 0;
            end if;
        end;
end;
</code>```

Then my table looks like this:

```<code>CREATE TABLE people (
    name varchar2(50),
    height height
);
</code>```

And some records ...

```<code>insert into people values ('Foo', height(150));
insert into people values ('Bar', height(130));
insert into people valueS ('Baz', height(180));
</code>```

Then I want to sort it:

```<code>select p.height.val from people p order by height ASC;
select p.height.val from people p order by height DESC;
</code>```

But result is the same for 2 queries, no matter if order is asc or desc.

答:
In turned out to be a simple mistake...
Implementation of compare function compares self with self instead with other.

Body:
Oracle doc says as follows: "As with map methods, an order method, if one is defined, is called automatically whenever two objects of that type need to be compared."

So I assume it will sort when using 'order by' clausule.

Lets say, I have following object:

create or replace type height as object
(
    val number,

    constructor function height return self as result,
    constructor function height (val number) return self as result,

    order member function compare (other height) RETURN INTEGER
);

and its body implementation:

create or replace type body height is
    constructor function height return self as result is
         begin
            self.val := null;
         end;

    constructor function height (val number) return self as result is
         begin
            self.val := val;
            return;
         end;

    order member function compare (other height) return integer is
        begin
            if self.val > self.val then return 1;
            elsif self.val < self.val then return -1;
            else return 0;
            end if;
        end;
end;

Then my table looks like this:

CREATE TABLE people (
    name varchar2(50),
    height height
);

And some records ...

insert into people values ('Foo', height(150));
insert into people values ('Bar', height(130));
insert into people valueS ('Baz', height(180));

Then I want to sort it:

select p.height.val from people p order by height ASC;
select p.height.val from people p order by height DESC;

But result is the same for 2 queries, no matter if order is asc or desc.


问:
Embed Fonts in TCPDF
I have read through previous threads on this topic, but all are old, unanswered, and/or about something more specific about creating custom fonts.

In TCPDF:

```<code>$pdf->SetFont('times', '', 10);
</code>```

The pdfs I create look awesome. It is just that BarnesAndNoble says my submitted PDF does not contain "embedded fonts".  Kindle says the same, but that they then embedded them for me.  I'm trying LuLu next, but want to deal with BN.com first.

An example suggests:

```<code>$fontname = $pdf->addTTFfont('/fonts/arial.ttf', '', '', 32);
</code>```

... but does not go on to say what to do with "$fontname". Nor what the "32" specifically stands for, or if there are better options for that "32".  Or, if THAT does embed fonts!

My webhost says my fonts path is:

```<code>/usr/share/fonts/default/Type1
</code>```

... maybe then (case sensitive??):

```<code>/usr/share/fonts/default/Type1/Helvetica
</code>```

I need to properly embed my fonts!

答:
TCPDF will just automatically embed fonts you've added on its own. I'm fairly certain it's presumed that most all OS's have Times, Helvetica and Courier already available and therefore TCPDF does not embed them. So in your case, if you add a TTF font TCPDF should recognize when it is used and embed the font definition automatically.

Also, you should only have to do $fontname = $pdf->addTTFfont('/fonts/arial.ttf', '', '', 32); once, so you could run your script once, and then comment that line out.

Direct From the documentation;

```<code>AddFont( $family, $style = '', $fontfile = '', $subset = 'default' )
</code>```

Imports a TrueType, Type1, core, or CID0 font and makes it available. It is necessary to generate a font definition file first (read /fonts/utils/README.TXT). The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by K_PATH_FONTS if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated.

Parameters

$family -
Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.

$style - Font style. Possible values are (case insensitive):

empty string: regular (default)

B: bold

I: italic

BI or IB: bold italic

$fontfile - The font definition file. By default, the name is built from the family and style, in lower case with no spaces.

$subset - if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.

Returns - array containing the font data, or false in case of error.

Since
1.5
See
TCPDF::SetFont(), TCPDF::setFontSubsetting()
Public

Title: Embed Fonts in TCPDF

Body:
I have read through previous threads on this topic, but all are old, unanswered, and/or about something more specific about creating custom fonts.

In TCPDF:

$pdf->SetFont('times', '', 10);

The pdfs I create look awesome. It is just that BarnesAndNoble says my submitted PDF does not contain "embedded fonts".  Kindle says the same, but that they then embedded them for me.  I'm trying LuLu next, but want to deal with BN.com first.

An example suggests:

$fontname = $pdf->addTTFfont('/fonts/arial.ttf', '', '', 32);

... but does not go on to say what to do with "$fontname". Nor what the "32" specifically stands for, or if there are better options for that "32".  Or, if THAT does embed fonts!

My webhost says my fonts path is:

/usr/share/fonts/default/Type1

... maybe then (case sensitive??):

/usr/share/fonts/default/Type1/Helvetica

I need to properly embed my fonts!

Body:
TCPDF will just automatically embed fonts you've added on its own. I'm fairly certain it's presumed that most all OS's have Times, Helvetica and Courier already available and therefore TCPDF does not embed them. So in your case, if you add a TTF font TCPDF should recognize when it is used and embed the font definition automatically.

Also, you should only have to do $fontname = $pdf->addTTFfont('/fonts/arial.ttf', '', '', 32); once, so you could run your script once, and then comment that line out.

Direct From the documentation;

AddFont( $family, $style = '', $fontfile = '', $subset = 'default' )

Imports a TrueType, Type1, core, or CID0 font and makes it available. It is necessary to generate a font definition file first (read /fonts/utils/README.TXT). The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by K_PATH_FONTS if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated.

Parameters

$family -
Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.

$style - Font style. Possible values are (case insensitive):

empty string: regular (default)

B: bold

I: italic

BI or IB: bold italic

$fontfile - The font definition file. By default, the name is built from the family and style, in lower case with no spaces.

$subset - if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.

Returns - array containing the font data, or false in case of error.

Since
1.5
See
TCPDF::SetFont(), TCPDF::setFontSubsetting()
Public


问:
d3 zoom: pan axis on scroll, pan axis on drag, zoom axis on pinch
I'm hoping to configure the zoom behavior of a plot to have three kinds of interaction:

It should be possible to pan from left to right with the scroll wheel.

It should be possible to pan from left to right with mousedown drag events.

it should be possible to zoom in 1-D with the pinch event (i.e. scroll wheel with control key pressed).

Right now, I can get the latter two to work in this Fiddle: https://jsfiddle.net/s1t7mrpw/6/

The zoomed function looks like this:

```<code>function zoomed() {

  if (d3.event.sourceEvent.ctrlKey || d3.event.sourceEvent.type === 'mousemove') {

    view.attr("transform", d3.event.transform);
    centerline.call(xAxis.scale(d3.event.transform.rescaleX(x)));
    d3.event.transform.y = 0;
    g.attr("transform", d3.event.transform);

  } else {

    current_transform = d3.zoomTransform(view);
    current_transform.x = current_transform.x - d3.event.sourceEvent.deltaY;

    // what do I do here to pan the axis and update `view`'s transform?
    // centerline.call(xAxis.scale(d3.event.transform.rescaleX(x))); ?
    // view.attr('transform', current_transform); ?

    g.attr('transform', current_transform);
  }
}
</code>```

It uses the rescale nomenclature from these blocks:

https://bl.ocks.org/mbostock/db6b4335bf1662b413e7968910104f0f

https://bl.ocks.org/rutgerhofste/5bd5b06f7817f0ff3ba1daa64dee629d

And it uses d3-xyzoom for independent scaling in the x and y directions.

https://bl.ocks.org/etiennecrb/863a08b5be3eafe7f1d61c85d724e6c4

But I can't figure out how to pan the axis in the else bracket, when the user is just scrolling (without pressing the control key).

I had previously used a separate trigger for wheel.zoom but then I need to handle the control key in that other function as well.

I basically want the default zoom behaviors for mousemove and when the control key is pressed, but panning rather than zooming on scroll when the control key is not pressed.

答:
I am using d3-zoom on this answer as it is more common and part of the d3 bundle. d3-xyzoom, as an add-on module, adds some useful functionality using d3-zoom as a base, so this solution should work with xyzoom with minor revisions - but I don't believe its use is necessary

The key challenge lies in using the wheel to apply a translate change not a scale change. Roughly speaking, when a scroll event without control occurs you grab the transform on the selection (this should be the node) and update it by taking the scroll and creating an x offset from it to translate the view rectangle. But, you don't update the zoomTransform to nullify the change in scale caused by the zoom - so when you pan by dragging, the rectangle changes size because you haven't updated the zoomTransform used by the zoom behavior. Likewise, the translate can be off if it doesn't account for scale.

The disassociation between zoom transform applied to an element as a "transform" attribute and the zoom transform tracked by the zoom behavior is the cause of many headaches on SO - but it allows freer implementation options as one not need use an element's transform attribute to apply a zoom behavior (useful in canvas, zooming unorthodox things like color, etc).

I'm going to propose a basic solution here.

First, the zoom transform tracked by the zoom behavior can be updated by modifying the d3.event.transform object itself (or with d3.zoomTransform(selection.node) where selection is the selection that the zoom was called on originally).

Secondly, as the d3.event.transform object registers scrolling as scaling, we need to override this and convert this scaling into translating - when needed. To do so, we need to keep track of the current (pre-event) translate and scale - so we can modify them manually:

```<code>// Keep track of zoom state:
var k = 1;
var tx = 0;

function zoomed() {
  var t = d3.event.transform;

  // If control is not pressed and a wheel was turned, set the scale to last known scale, and modify transform.x by some amount:
  if(!d3.event.sourceEvent.ctrlKey && d3.event.sourceEvent.type == "wheel") {
    t.k > k ? tx += 40/k : tx -= 40/k;
    t.k = k;
    t.x = tx;
  }
  // otherwise, proceed as normal, but track current k and tx:
  else {
    k = t.k;
    tx = t.x;
  }

  // Apply the transform:
  view.attr("transform", "translate("+[t.x,0]+")scale("+[t.k,1]+")");
  axisG.call(xAxis.scale(t.rescaleX(xScale)));

}
</code>```

Above, I modify the transform t.k and t.k for events where wheeling/scrolling should translate. By comparing t.k with the stored k value I can determine direction: would it normally be a zoom out or zoom in event, and then I can convert this into a change in the current translate value. By setting t.k back to the original k value, I can stop the change in scaling that would otherwise occur.

For other zoom events it is business as usual, except, I store the t.x and t.k values for later, for when wheel events should translate rather than scale.

Note: I've set the y scaling and translate in the transform to a hard coded zero, so we don't need to worry about the y component at all.

var width = 500;
var height = 120;

// Keep track of zoom state:
var k = 1;
var tx = 0;

// Some text to show the transform parameters:
var p = d3.select("body")
  .append("p");

// Nothing unordinary here:
var svg = d3.select("body")
   .append("svg")
   .attr("width",width)
   .attr("height",height);

var xScale = d3.scaleLinear()
  .domain([0,100])
  .range([20,width-20])

var xAxis = d3.axisTop(xScale);

var axisG = svg.append("g")
  .attr("transform","translate(0,50)")
  .call(xAxis);

var view = svg.append("rect")
  .attr("width", 20)
  .attr("height",20)
  .attr("x", width/2)
  .attr("y", 60)

var zoom = d3.zoom()
  .on("zoom",zoomed);

svg.call(zoom)

function zoomed() {
  var t = d3.event.transform;

  // If control is not pressed and a wheel was turned, set the scale to last known scale, and modify transform.x by some amount:
  if(!d3.event.sourceEvent.ctrlKey && d3.event.sourceEvent.type == "wheel") {
 t.k > k ? tx += 40/k : tx -= 40/k;
 t.k = k;
 t.x = tx;
  }
  // otherwise, proceed as normal, but track current k and tx:
  else {
 k = t.k;
 tx = t.x;
  }

  // Apply the transform:
  view.attr("transform", "translate("+[t.x,0]+")scale("+[t.k,1]+")");
  axisG.call(xAxis.scale(t.rescaleX(xScale)));

  // Show current zoom transform:
  p.text("transform.k:" + t.k + ", transform.x: " + t.x);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.6.0/d3.min.js"></script></code>```

Body:
I'm hoping to configure the zoom behavior of a plot to have three kinds of interaction:

It should be possible to pan from left to right with the scroll wheel.

It should be possible to pan from left to right with mousedown drag events.

it should be possible to zoom in 1-D with the pinch event (i.e. scroll wheel with control key pressed).

Right now, I can get the latter two to work in this Fiddle: https://jsfiddle.net/s1t7mrpw/6/

The zoomed function looks like this:

function zoomed() {

  if (d3.event.sourceEvent.ctrlKey || d3.event.sourceEvent.type === 'mousemove') {

    view.attr("transform", d3.event.transform);
    centerline.call(xAxis.scale(d3.event.transform.rescaleX(x)));
    d3.event.transform.y = 0;
    g.attr("transform", d3.event.transform);

  } else {

    current_transform = d3.zoomTransform(view);
    current_transform.x = current_transform.x - d3.event.sourceEvent.deltaY;

    // what do I do here to pan the axis and update `view`'s transform?
    // centerline.call(xAxis.scale(d3.event.transform.rescaleX(x))); ?
    // view.attr('transform', current_transform); ?

    g.attr('transform', current_transform);
  }
}

It uses the rescale nomenclature from these blocks:

https://bl.ocks.org/mbostock/db6b4335bf1662b413e7968910104f0f

https://bl.ocks.org/rutgerhofste/5bd5b06f7817f0ff3ba1daa64dee629d

And it uses d3-xyzoom for independent scaling in the x and y directions.

https://bl.ocks.org/etiennecrb/863a08b5be3eafe7f1d61c85d724e6c4

But I can't figure out how to pan the axis in the else bracket, when the user is just scrolling (without pressing the control key).

I had previously used a separate trigger for wheel.zoom but then I need to handle the control key in that other function as well.

I basically want the default zoom behaviors for mousemove and when the control key is pressed, but panning rather than zooming on scroll when the control key is not pressed.

Body:
I am using d3-zoom on this answer as it is more common and part of the d3 bundle. d3-xyzoom, as an add-on module, adds some useful functionality using d3-zoom as a base, so this solution should work with xyzoom with minor revisions - but I don't believe its use is necessary

The key challenge lies in using the wheel to apply a translate change not a scale change. Roughly speaking, when a scroll event without control occurs you grab the transform on the selection (this should be the node) and update it by taking the scroll and creating an x offset from it to translate the view rectangle. But, you don't update the zoomTransform to nullify the change in scale caused by the zoom - so when you pan by dragging, the rectangle changes size because you haven't updated the zoomTransform used by the zoom behavior. Likewise, the translate can be off if it doesn't account for scale.

The disassociation between zoom transform applied to an element as a "transform" attribute and the zoom transform tracked by the zoom behavior is the cause of many headaches on SO - but it allows freer implementation options as one not need use an element's transform attribute to apply a zoom behavior (useful in canvas, zooming unorthodox things like color, etc).

I'm going to propose a basic solution here.

First, the zoom transform tracked by the zoom behavior can be updated by modifying the d3.event.transform object itself (or with d3.zoomTransform(selection.node) where selection is the selection that the zoom was called on originally).

Secondly, as the d3.event.transform object registers scrolling as scaling, we need to override this and convert this scaling into translating - when needed. To do so, we need to keep track of the current (pre-event) translate and scale - so we can modify them manually:

// Keep track of zoom state:
var k = 1;
var tx = 0;

function zoomed() {
  var t = d3.event.transform;

  // If control is not pressed and a wheel was turned, set the scale to last known scale, and modify transform.x by some amount:
  if(!d3.event.sourceEvent.ctrlKey && d3.event.sourceEvent.type == "wheel") {
    t.k > k ? tx += 40/k : tx -= 40/k;
    t.k = k;
    t.x = tx;
  }
  // otherwise, proceed as normal, but track current k and tx:
  else {
    k = t.k;
    tx = t.x;
  }

  // Apply the transform:
  view.attr("transform", "translate("+[t.x,0]+")scale("+[t.k,1]+")");
  axisG.call(xAxis.scale(t.rescaleX(xScale)));

}

Above, I modify the transform t.k and t.k for events where wheeling/scrolling should translate. By comparing t.k with the stored k value I can determine direction: would it normally be a zoom out or zoom in event, and then I can convert this into a change in the current translate value. By setting t.k back to the original k value, I can stop the change in scaling that would otherwise occur.

For other zoom events it is business as usual, except, I store the t.x and t.k values for later, for when wheel events should translate rather than scale.

Note: I've set the y scaling and translate in the transform to a hard coded zero, so we don't need to worry about the y component at all.

var width = 500;
var height = 120;

// Keep track of zoom state:
var k = 1;
var tx = 0;

// Some text to show the transform parameters:
var p = d3.select("body")
  .append("p");

// Nothing unordinary here:
var svg = d3.select("body")
   .append("svg")
   .attr("width",width)
   .attr("height",height);

var xScale = d3.scaleLinear()
  .domain([0,100])
  .range([20,width-20])

var xAxis = d3.axisTop(xScale);

var axisG = svg.append("g")
  .attr("transform","translate(0,50)")
  .call(xAxis);

var view = svg.append("rect")
  .attr("width", 20)
  .attr("height",20)
  .attr("x", width/2)
  .attr("y", 60)

var zoom = d3.zoom()
  .on("zoom",zoomed);

svg.call(zoom)

function zoomed() {
  var t = d3.event.transform;

  // If control is not pressed and a wheel was turned, set the scale to last known scale, and modify transform.x by some amount:
  if(!d3.event.sourceEvent.ctrlKey && d3.event.sourceEvent.type == "wheel") {
 t.k > k ? tx += 40/k : tx -= 40/k;
 t.k = k;
 t.x = tx;
  }
  // otherwise, proceed as normal, but track current k and tx:
  else {
 k = t.k;
 tx = t.x;
  }

  // Apply the transform:
  view.attr("transform", "translate("+[t.x,0]+")scale("+[t.k,1]+")");
  axisG.call(xAxis.scale(t.rescaleX(xScale)));

  // Show current zoom transform:
  p.text("transform.k:" + t.k + ", transform.x: " + t.x);

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.6.0/d3.min.js"></script>


问:
Replacing deprecated QtSignalMapper class to forward Signals in Qt5
I have this code which makes a mdi window written for Qt 4:

```<code>class MdiWindow : public QMainWindow
{
    Q_OBJECT
public:
    MdiWindow( QWidget *parent = nullptr)

...
private:
    QWorkspace* workspace
    QSignalMapper* mapper
}

MdiWindow::MdiWindow( QWidget *parent ) : QMainWindow( parent )
{
  ...

  workspace = new QWorkspace;
  setCentralWidget( workspace );

  connect( workspace, SIGNAL(windowActivated(QWidget *)), this, SLOT(enableActions()));
  mapper = new QSignalMapper( this );
  connect( mapper, SIGNAL(mapped(QWidget*)), workspace, SLOT(setActiveWindow(QWidget*)) );

  ....
}
</code>```

According to the QT documentation QWorkspace should be replaced with QMdiArea.

I did that and wrote the first connect like this:

```<code>connect(workspace, &QMdiArea::subWindowActivated,
        this, &MdiWindow::enableActions);
</code>```

But what about QSignalMapper also that is also deprecated.

So how can I update this line:

```<code>mapper = new QSignalMapper( this );
connect( mapper, SIGNAL(mapped(QWidget*)), workspace, SLOT(setActiveWindow(QWidget*)) );
</code>```

I read QSignalMapper can be replaced with lamdas but how in this case?
If i understand right mapper forwards all the signals from this to the active window of workspace

答:
Previously you used QSignalMapper::setMapping() to make sure that you'd be sent data you need when the SLOT() was called. Now you can just encapsulate this logic inside a lamba, so if you did (like in Qt example):

     for (int i = 0; i < texts.size(); ++i) {
         QPushButton *button = new QPushButton(texts[i]);
         connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
         signalMapper->setMapping(button, texts[i]);
     }
     connect(signalMapper, SIGNAL(mapped(const QString &)),
             this, SIGNAL(clicked(const QString &)));
```

<p>you can now do (somewhat):</p>

<pre class="lang-cpp prettyprint-override"><code>     for (int i = 0; i < texts.size(); ++i) {
         QPushButton *button = new QPushButton(texts[i]);
         connect(button, &QPushButton::clicked, [=]() {
             emit clicked(texts[i]);
         });
     }
</code>```

If the setMapping() is not being used, then it probably could have been connected directly to a SLOT() already.

Body:
I have this code which makes a mdi window written for Qt 4:

class MdiWindow : public QMainWindow
{
    Q_OBJECT
public:
    MdiWindow( QWidget *parent = nullptr)

...
private:
    QWorkspace* workspace
    QSignalMapper* mapper
}

MdiWindow::MdiWindow( QWidget *parent ) : QMainWindow( parent )
{
  ...

  workspace = new QWorkspace;
  setCentralWidget( workspace );

  connect( workspace, SIGNAL(windowActivated(QWidget *)), this, SLOT(enableActions()));
  mapper = new QSignalMapper( this );
  connect( mapper, SIGNAL(mapped(QWidget*)), workspace, SLOT(setActiveWindow(QWidget*)) );

  ....
}

According to the QT documentation QWorkspace should be replaced with QMdiArea.

I did that and wrote the first connect like this:

connect(workspace, &QMdiArea::subWindowActivated,
        this, &MdiWindow::enableActions);

But what about QSignalMapper also that is also deprecated.

So how can I update this line:

mapper = new QSignalMapper( this );
connect( mapper, SIGNAL(mapped(QWidget*)), workspace, SLOT(setActiveWindow(QWidget*)) );

I read QSignalMapper can be replaced with lamdas but how in this case?
If i understand right mapper forwards all the signals from this to the active window of workspace

Body:
Previously you used QSignalMapper::setMapping() to make sure that you'd be sent data you need when the SLOT() was called. Now you can just encapsulate this logic inside a lamba, so if you did (like in Qt example):

     for (int i = 0; i < texts.size(); ++i) {
         QPushButton *button = new QPushButton(texts[i]);
         connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
         signalMapper->setMapping(button, texts[i]);
     }
     connect(signalMapper, SIGNAL(mapped(const QString &)),
             this, SIGNAL(clicked(const QString &)));

you can now do (somewhat):

     for (int i = 0; i < texts.size(); ++i) {
         QPushButton *button = new QPushButton(texts[i]);
         connect(button, &QPushButton::clicked, [=]() {
             emit clicked(texts[i]);
         });
     }

If the setMapping() is not being used, then it probably could have been connected directly to a SLOT() already.


问:
Print preview using PDFJS and angular 7
I just started using ng2-pdfjs-viewer(https://www.npmjs.com/package/ng2-pdfjs-viewer) and trying to provide a print preview of a pdf document to the user using angular 7. I configured and was able to show the document, but couldn't show the print preview.

Here is the relevant code.

  <ng2-pdfjs-viewer #sampleViewer [externalWindow]="true"
    [print]="true" [page]=2></ng2-pdfjs-viewer>
```

The viewer just shows pdf document, I expect it to invoke print functionality and show a print preview.

答: Have you tried to add [startPrint]="true"? The documentation says "Start print preview of document. This combined with externalWindow could mimic a print preview functionality just like the one in gmail."</p>

Title: Print preview using PDFJS and angular 7

Body:
I just started using ng2-pdfjs-viewer(https://www.npmjs.com/package/ng2-pdfjs-viewer) and trying to provide a print preview of a pdf document to the user using angular 7. I configured and was able to show the document, but couldn't show the print preview.

Here is the relevant code.

  <ng2-pdfjs-viewer #sampleViewer [externalWindow]="true"
    [print]="true" [page]=2></ng2-pdfjs-viewer>

The viewer just shows pdf document, I expect it to invoke print functionality and show a print preview.


问:
MongoDB using an OR clause in mongoengine
I'm using python's mongoengine to query MongoDB, and have loved it for the most part, but I'm having an issue with an advanced query.

Here's my model

```<code>class ContentItem(Document):
    account = ReferenceField(Account)
    creator = ReferenceField(User)
    public = BooleanField(default=False)
    last_used = DateTimeField(default=datetime.now)
</code>```

I would like to make a query for all ContentItem's that are of a particular account, and are either created by the logged in user or are public.  Here's the query I wrote

```<code>query = ContentItem.objects.filter( (Q(account=account) & Q(public=True)) |  (Q(account=account) & Q(creator=logged_in_user)) ).order_by('-last_used')
</code>```

or:

```<code>query = ContentItem.objects.filter( Q(account=account) & ( Q(public=True) |  Q(creator=logged_in_user) ) ).order_by('-last_used')
</code>```

But these seem to be XOR where if either public, or the creator but not both. Is this expected?

Am I overlooking something? Should I do this directly with mongodb instead of mongoengine?

My current workaround is to make two different queries and combine the results,  but as the # of Content Items gets larger the result is taking a long time to come back because I need to get all items before I can order them, thereby losing all the benefit of (django) paginated results.

答: MongoEngine docs say otherwise. Please check this:

Body:
I'm using python's mongoengine to query MongoDB, and have loved it for the most part, but I'm having an issue with an advanced query.

Here's my model

class ContentItem(Document):
    account = ReferenceField(Account)
    creator = ReferenceField(User)
    public = BooleanField(default=False)
    last_used = DateTimeField(default=datetime.now)

I would like to make a query for all ContentItem's that are of a particular account, and are either created by the logged in user or are public.  Here's the query I wrote

query = ContentItem.objects.filter( (Q(account=account) & Q(public=True)) |  (Q(account=account) & Q(creator=logged_in_user)) ).order_by('-last_used')

or:

query = ContentItem.objects.filter( Q(account=account) & ( Q(public=True) |  Q(creator=logged_in_user) ) ).order_by('-last_used')

But these seem to be XOR where if either public, or the creator but not both. Is this expected?

Am I overlooking something? Should I do this directly with mongodb instead of mongoengine?

My current workaround is to make two different queries and combine the results,  but as the # of Content Items gets larger the result is taking a long time to come back because I need to get all items before I can order them, thereby losing all the benefit of (django) paginated results.


问:
How to relocate Moment variables to state from render
I'd like to know how I can better store the variables I am using for moment in my react component.

I've already tried just declaring the variables in the constructor below the setState, but these variables are not changeable. I then tried to store the variables in the state, as key value pairs but since one of the values is dependent on another, it did not work.

Here is my current constructor:

```<code>constructor(props) {
super(props);
this.state = {
  scooter: props.scooter,
  header: props.header,
  reservation: ""
};
}

componentWillReceiveProps(nextProps) {
this.setState({
  scooter: nextProps.scooter,
  header: nextProps.header
});
}
</code>```

Some items will have to be called as well in componentsWillRecieveProps as the item will change with next props.

variables below

```<code>render() {
const reservation = this.state.scooter.state.LastAdminReservation;
var a = moment();
const c = moment(reservation.PendingDate);
const d = moment(reservation.EndDate);
const duration = d.from(c, true);
var timeSince = a.from(d, true);
const date = moment(reservation.DownloadAckDate).format("DD.MM.YYYY
HH:mm");
</code>```

I'd like to be able to call these variables in my return and have var a and var timeSince be updated on next props while not storing them in my render as this is bad practice. Thanks!

答:
Try your best not to derive state from props. However, if you really need to, getDerivedStateFromProps is a safer method introduced in React 16.

componentWillReceiveProps is a deprecated method that you should be avoiding.

Instead, you can create a function that will return the date you need, and call it from your render method. If you are worried with performance, you can memoize that function. Example here

If you are using a state management solution like Redux, you can also move that logic up to a selector and pass down only the data you need into your component.

Body:
I'd like to know how I can better store the variables I am using for moment in my react component.

I've already tried just declaring the variables in the constructor below the setState, but these variables are not changeable. I then tried to store the variables in the state, as key value pairs but since one of the values is dependent on another, it did not work.

Here is my current constructor:

constructor(props) {
super(props);
this.state = {
  scooter: props.scooter,
  header: props.header,
  reservation: ""
};
}

componentWillReceiveProps(nextProps) {
this.setState({
  scooter: nextProps.scooter,
  header: nextProps.header
});
}

Some items will have to be called as well in componentsWillRecieveProps as the item will change with next props.

variables below

render() {
const reservation = this.state.scooter.state.LastAdminReservation;
var a = moment();
const c = moment(reservation.PendingDate);
const d = moment(reservation.EndDate);
const duration = d.from(c, true);
var timeSince = a.from(d, true);
const date = moment(reservation.DownloadAckDate).format("DD.MM.YYYY
HH:mm");

I'd like to be able to call these variables in my return and have var a and var timeSince be updated on next props while not storing them in my render as this is bad practice. Thanks!


问:
Getting back a tuple when trying to normalize training data
I have a training and testing set. I need to normalize them but i can't seem to iterate over them i get this error TypeError: list indices must be integers or slices, not tuple. I will give a small part of the set just so you can see how it is structured. I've tried with enumerate and range but i get the same error.

```<code>training_data = [
    [3.6216, 8.6661, -2.8073, -0.44699, 0],
    [4.5459, 8.1674, -2.4586, -1.4621, 0],
    [3.866, -2.6383, 1.9242, 0.10645, 0],
    [3.4566, 9.5228, -4.0112, -3.5944, 0],
    [0.32924, -4.4552, 4.5718, -0.9888, 0],
    [4.3684, 9.6718, -3.9606, -3.1625, 0],
    [3.5912, 3.0129, 0.72888, 0.56421, 0],
    [2.0922, -6.81, 8.4636, -0.60216, 0],
]
</code>```

Code:

```<code>def minMaxNrom(training_data, testing_data):
    for i in enumerate(training_data):
        for j in enumerate(training_data):
            new_data = training_data[i][j] - min(j) / max(j) - min(j)

    for i in enumerate(testing_data):
        for j in enumerate(testing_data[i]):
            new_testing_data = testing_data[i][j] - min(j) / max(j) - min(j)

    return (new_data, new_testing_data)
</code>```

答:
for i in enumertae(list) generate a tuple, ie (index:value), what you are looking for is index, so use for i,v in enumerate(list)

```<code>def minMaxNrom(training_data, testing_data):
    for i,v1 in enumerate(training_data):
        for j,v2 in enumerate(v1):
            new_data = training_data[i][j] - (min(v1) / max(v1)) - min(v1)

    for i,v1 in enumerate(testing_data):
        for j,v2 in enumerate(v1):
            new_testing_data = testing_data[i][j] - (min(v1) / max(v1)) - min(v1)

    return (new_data, new_testing_data)
</code>```

Body:
I have a training and testing set. I need to normalize them but i can't seem to iterate over them i get this error TypeError: list indices must be integers or slices, not tuple. I will give a small part of the set just so you can see how it is structured. I've tried with enumerate and range but i get the same error.

training_data = [
    [3.6216, 8.6661, -2.8073, -0.44699, 0],
    [4.5459, 8.1674, -2.4586, -1.4621, 0],
    [3.866, -2.6383, 1.9242, 0.10645, 0],
    [3.4566, 9.5228, -4.0112, -3.5944, 0],
    [0.32924, -4.4552, 4.5718, -0.9888, 0],
    [4.3684, 9.6718, -3.9606, -3.1625, 0],
    [3.5912, 3.0129, 0.72888, 0.56421, 0],
    [2.0922, -6.81, 8.4636, -0.60216, 0],
]

Code:

def minMaxNrom(training_data, testing_data):
    for i in enumerate(training_data):
        for j in enumerate(training_data):
            new_data = training_data[i][j] - min(j) / max(j) - min(j)

    for i in enumerate(testing_data):
        for j in enumerate(testing_data[i]):
            new_testing_data = testing_data[i][j] - min(j) / max(j) - min(j)

    return (new_data, new_testing_data)

Body:
for i in enumertae(list) generate a tuple, ie (index:value), what you are looking for is index, so use for i,v in enumerate(list)

def minMaxNrom(training_data, testing_data):
    for i,v1 in enumerate(training_data):
        for j,v2 in enumerate(v1):
            new_data = training_data[i][j] - (min(v1) / max(v1)) - min(v1)

    for i,v1 in enumerate(testing_data):
        for j,v2 in enumerate(v1):
            new_testing_data = testing_data[i][j] - (min(v1) / max(v1)) - min(v1)

    return (new_data, new_testing_data)


问:
White Screen on Fresh New Angular 8/Electron 5 App
I am building and running an Angular 8/Electron 5 desktop app. After what I believe to be proper setup, running the app displays a blank white screen.

Using:

Electron 5.0.2

Angular CLI 8.0.1

Node 10.16.0

macOS Mojave 10.14.5

...

ng new my-app

npm i -D electron

package.json

{
  ...
  "main": "main.js", //<-- ADDED
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "electron": "ng build --baseHref=./ && electron ." //<-- ADDED
  }
  ...
}
```

<p><strong>main.js</strong></p>

<pre class="lang-js prettyprint-override"><code>const { app, BrowserWindow } = require("electron");
const path = require("path");
const url = require("url");

let win;

function createWindow() {
  win = new BrowserWindow({ width: 800, height: 600 });

  win.loadURL(
    url.format({
      pathname: path.join(__dirname, `/dist/index.html`), //<-- CHANGED
      protocol: "file:",
      slashes: true
    })
  );

  win.on("closed", () => {
    win = null;
  });
}

app.on("ready", createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (win === null) {
    createWindow();
  }
});
</code>```

I also changed the outputPath in angular.json to just "dist"

  {
    ...
    "outputPath": "dist"
    ...
  }
```

<p>started the app with <code>npm run electron</code></p>

<p>When the app opens, I see a blank white screen. Upon inspecting, I can see the body, and the <code><app-root></code> element, but all I see on the page is a blank white screen.</p>

<p>When doing <code>ng new my-app</code> I tried both <em>with and without</em> routing enabled flag in CLI.</p>

<p>Getting these errors in the electron app console just before the Electron Security Warning:</p>

```runtime-es2015.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
styles-es2015.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
main-es2015.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
polyfills-es2015.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
vendor-es2015.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
```

答:
I got my electron application to work by changing the target in the tsconfig.json to es5.

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "importHelpers": true,
    "module": "esnext",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5", <-- HERE
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}
</code>```

Prior to this, I was getting the blank (white) screen too after updating the Angular 8. Seems now that Angular does a build in both es5 and es2015, electron doesn't like that. I would guess this will be fixed in the future.

UPDATE 2019-10-24:

Looks like this was fixed in electron@7.0.0. You can target es2015 with that version. Tested with @angular/cli@8.3.14.

Body:
I am building and running an Angular 8/Electron 5 desktop app. After what I believe to be proper setup, running the app displays a blank white screen.

Using:

Electron 5.0.2

Angular CLI 8.0.1

Node 10.16.0

macOS Mojave 10.14.5

...

ng new my-app

npm i -D electron

package.json

{
  ...
  "main": "main.js", //<-- ADDED
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "electron": "ng build --baseHref=./ && electron ." //<-- ADDED
  }
  ...
}

main.js

const { app, BrowserWindow } = require("electron");
const path = require("path");
const url = require("url");

let win;

function createWindow() {
  win = new BrowserWindow({ width: 800, height: 600 });

  win.loadURL(
    url.format({
      pathname: path.join(__dirname, `/dist/index.html`), //<-- CHANGED
      protocol: "file:",
      slashes: true
    })
  );

  win.on("closed", () => {
    win = null;
  });
}

app.on("ready", createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (win === null) {
    createWindow();
  }
});

I also changed the outputPath in angular.json to just "dist"

  {
    ...
    "outputPath": "dist"
    ...
  }

started the app with npm run electron

When the app opens, I see a blank white screen. Upon inspecting, I can see the body, and the <app-root> element, but all I see on the page is a blank white screen.

When doing ng new my-app I tried both with and without routing enabled flag in CLI.

Getting these errors in the electron app console just before the Electron Security Warning:

runtime-es2015.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
styles-es2015.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
main-es2015.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
polyfills-es2015.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
vendor-es2015.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

Body:
I got my electron application to work by changing the target in the tsconfig.json to es5.

{
  "compileOnSave": false,
  "compilerOptions": {
    "importHelpers": true,
    "module": "esnext",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5", <-- HERE
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

Prior to this, I was getting the blank (white) screen too after updating the Angular 8. Seems now that Angular does a build in both es5 and es2015, electron doesn't like that. I would guess this will be fixed in the future.

UPDATE 2019-10-24:

Looks like this was fixed in electron@7.0.0. You can target es2015 with that version. Tested with @angular/cli@8.3.14.


问:
How to make an ASP.Net page with a C# code behind that will work in Sharepoint
I need to develop a page for Sharepoint.

Basically it is a 3 step process that takes some inputs, gets some data and shows a preview of it, then allows the data to be sent off attached to an email.

I know ASP.Net and C#.Net, and the problem should be reasonably easy to solve with an ASP.Net page and a C# code behind.

However I've never had to work with Sharepoint before, and I don't know what is required to make the page 'work in Sharepoint'.

Is there anything special that needs to be done to make it work in Sharepoint? Is an ASPX page the right approach for this sort of problem?

(I'm developing on an XP machine using Visual Studio 2008.)

答:
I wrote an article a couple of days ago that, amongst other things, covers how to make a custom application page in SharePoint using a code-behind C# file. Scroll down to Administration page in the article if you just need to get the page up and running.

Also, the first issue of Understanding SharePoint Journal covers a more elaborate example that is used in the CodePlex SPCurrentUsers project.

.b

OwnerDisplayName: Sophia

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Bjørn Furuknap


问:
Specific cast not valid
I use Linq-to-SQL to insert data in vb.net. When I insert data into SQL Server through a DataGridView it gives error of which column data type is "integer" but when I insert data through textbox it not give any error

So I face problem of datatype "integer" to error of specific cast not valid

答:
Well,

There are a few ways to convert a string to an int. But for a safe conversion I would go int.TryParse(your_string_value, out result_value)

This will give you the chance to handle none int values in a more graceful manner.

Good Luck

Title: Specific cast not valid