问:
Receiving Location even when app is not running in Swift
Still very new to Swift. I have come from an Android background where there is BroadcastReceiver that can deliver location info to a service even though the app isn't running.

So I was looking for something similar in iOS/Swift and it appears that before this wasn't possible but it may be now. I am developing for iOS 10 but would be great if it was backwards compatible.

I found

```<code>startMonitoringSignificantLocationChanges
</code>```

which I can execute to start delivering location updates, although this raises a few questions. Once I call this and my app is NOT running, are the updates still being sent ? And how would the app wake up to respond ?

Also restarting the phone and when it return, does this mean I still need call startMonitoringSignificantLocationChanges again meaning that I would have to wait for the user to execute my app. Or does it remember the setting after reboot ?

Still a little confused how to get around this, here's a brief explanation of what I am trying to do.

I would like to update the location of the phone even though the app is not running, this would be sent to a rest service every so often.

This way on the backend services I could determine if somebody is within X meters of somebody also and send them a push notification.

答:
It may or may not be a good solution but if I were you I would have used both startMonitoringSignificantLocationChanges and regionMonitoring.

Here is the sample I made which worked well with iOS 13.

Lets take regionMonitoring first. We have certainly no problems when the app is in foreground state and we can use the CLLocationManager's didUpdate delegate to get the location and send it to the server.

Keep latest current location in AppDelegate's property, lets say:

```<code>var lastLocation:CLLocation?

//And a location manager
var locationManager = CLLocationManager()
</code>```

We have two UIApplicationDelegates

```<code>func applicationDidEnterBackground(_ application: UIApplication) {
    //Create a region
}

func applicationWillTerminate(_ application: UIApplication) {
    //Create a region
}
</code>```

So whenever the user kills the app or makes the app go to background, we can certainly create a region around the latest current location fetched. Here is an example to create a region.

```<code>func createRegion(location:CLLocation?) {

    if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
            let coordinate = CLLocationCoordinate2DMake((location?.coordinate.latitude)!, (location?.coordinate.longitude)!)
            let regionRadius = 50.0

            let region = CLCircularRegion(center: CLLocationCoordinate2D(
                latitude: coordinate.latitude,
                longitude: coordinate.longitude),
                                          radius: regionRadius,
                                          identifier: "aabb")

            region.notifyOnExit = true
            region.notifyOnEntry = true

            //Send your fetched location to server

            //Stop your location manager for updating location and start regionMonitoring
            self.locationManager?.stopUpdatingLocation()
            self.locationManager?.startMonitoring(for: region)
        }
        else {
            print("System can't track regions")
        }
    }
</code>```

Make use of RegionDelegates

```<code>func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
    print("Entered Region")
}

func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
    print("Exited Region")

    locationManager?.stopMonitoring(for: region)

    //Start location manager and fetch current location
    locationManager?.startUpdatingLocation()
}
</code>```

Grab the location from didUpdate method

```<code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if UIApplication.shared.applicationState == .active {
    } else {
        //App is in BG/ Killed or suspended state
        //send location to server
        // create a New Region with current fetched location
        let location = locations.last
        lastLocation = location

        //Make region and again the same cycle continues.
        self.createRegion(location: lastLocation)
    }
}
</code>```

Here I have made a 50m region radius circle. I have tested this and it is called generally after crossing 100m from your center point.

Now the second approach can me using significantLocationChanges

On making the app go background or terminated, we can just stop location manager for further updating locations and can call the startMonitoringSignificantLocationChanges

```<code>self.locationManager?.stopUpdatingLocation()
self.locationManager?.startMonitoringSignificantLocationChanges()
</code>```

When the app is killed, the location is grabbed from didFinishLaunching method's launchOptions?[UIApplicationLaunchOptionsKey.location]

```<code>if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {
    //You have a location when app is in killed/ not running state
}
</code>```

Make sure to keep BackgroundModes On for Location Updates

Also make sure to ask for locationManager?.requestAlwaysAuthorization() by using the key

```<code><key>NSLocationAlwaysUsageDescription</key>
    <string>Allow location</string>
</code>```

in your Info.plist

There can be a third solution by taking 2 LocationManagers simultaneously.

For region

Significant Location Changes

As using significantLocationChanges

Apps can expect a notification as soon as the device moves 500 meters
  or more from its previous notification. It should not expect
  notifications more frequently than once every five minutes. If the
  device is able to retrieve data from the network, the location manager
  is much more likely to deliver notifications in a timely manner.

as per the give Apple Doc

So it totally depends on your requirements as the location fetching depends on many factors like the number of apps opened, battery power, signal strength etc when the app is not running.

Also keep in mind to always setup a region with good accuracy.

I know that this will not solve your problem completely but you will get an idea to move forward as per your requirements.

Body:
Still very new to Swift. I have come from an Android background where there is BroadcastReceiver that can deliver location info to a service even though the app isn't running.

So I was looking for something similar in iOS/Swift and it appears that before this wasn't possible but it may be now. I am developing for iOS 10 but would be great if it was backwards compatible.

I found

startMonitoringSignificantLocationChanges

which I can execute to start delivering location updates, although this raises a few questions. Once I call this and my app is NOT running, are the updates still being sent ? And how would the app wake up to respond ?

Also restarting the phone and when it return, does this mean I still need call startMonitoringSignificantLocationChanges again meaning that I would have to wait for the user to execute my app. Or does it remember the setting after reboot ?

Still a little confused how to get around this, here's a brief explanation of what I am trying to do.

I would like to update the location of the phone even though the app is not running, this would be sent to a rest service every so often.

This way on the backend services I could determine if somebody is within X meters of somebody also and send them a push notification.

Body:
It may or may not be a good solution but if I were you I would have used both startMonitoringSignificantLocationChanges and regionMonitoring.

Here is the sample I made which worked well with iOS 13.

Lets take regionMonitoring first. We have certainly no problems when the app is in foreground state and we can use the CLLocationManager's didUpdate delegate to get the location and send it to the server.

Keep latest current location in AppDelegate's property, lets say:

var lastLocation:CLLocation?

//And a location manager
var locationManager = CLLocationManager()

We have two UIApplicationDelegates

func applicationDidEnterBackground(_ application: UIApplication) {
    //Create a region
}

func applicationWillTerminate(_ application: UIApplication) {
    //Create a region
}

So whenever the user kills the app or makes the app go to background, we can certainly create a region around the latest current location fetched. Here is an example to create a region.

func createRegion(location:CLLocation?) {

    if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
            let coordinate = CLLocationCoordinate2DMake((location?.coordinate.latitude)!, (location?.coordinate.longitude)!)
            let regionRadius = 50.0

            let region = CLCircularRegion(center: CLLocationCoordinate2D(
                latitude: coordinate.latitude,
                longitude: coordinate.longitude),
                                          radius: regionRadius,
                                          identifier: "aabb")

            region.notifyOnExit = true
            region.notifyOnEntry = true

            //Send your fetched location to server

            //Stop your location manager for updating location and start regionMonitoring
            self.locationManager?.stopUpdatingLocation()
            self.locationManager?.startMonitoring(for: region)
        }
        else {
            print("System can't track regions")
        }
    }

Make use of RegionDelegates

func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
    print("Entered Region")
}

func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
    print("Exited Region")

    locationManager?.stopMonitoring(for: region)

    //Start location manager and fetch current location
    locationManager?.startUpdatingLocation()
}

Grab the location from didUpdate method

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if UIApplication.shared.applicationState == .active {
    } else {
        //App is in BG/ Killed or suspended state
        //send location to server
        // create a New Region with current fetched location
        let location = locations.last
        lastLocation = location

        //Make region and again the same cycle continues.
        self.createRegion(location: lastLocation)
    }
}

Here I have made a 50m region radius circle. I have tested this and it is called generally after crossing 100m from your center point.

Now the second approach can me using significantLocationChanges

On making the app go background or terminated, we can just stop location manager for further updating locations and can call the startMonitoringSignificantLocationChanges

self.locationManager?.stopUpdatingLocation()
self.locationManager?.startMonitoringSignificantLocationChanges()

When the app is killed, the location is grabbed from didFinishLaunching method's launchOptions?[UIApplicationLaunchOptionsKey.location]

if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {
    //You have a location when app is in killed/ not running state
}

Make sure to keep BackgroundModes On for Location Updates

Also make sure to ask for locationManager?.requestAlwaysAuthorization() by using the key

<key>NSLocationAlwaysUsageDescription</key>
    <string>Allow location</string>

in your Info.plist

There can be a third solution by taking 2 LocationManagers simultaneously.

For region

Significant Location Changes

As using significantLocationChanges

Apps can expect a notification as soon as the device moves 500 meters
  or more from its previous notification. It should not expect
  notifications more frequently than once every five minutes. If the
  device is able to retrieve data from the network, the location manager
  is much more likely to deliver notifications in a timely manner.

as per the give Apple Doc

So it totally depends on your requirements as the location fetching depends on many factors like the number of apps opened, battery power, signal strength etc when the app is not running.

Also keep in mind to always setup a region with good accuracy.

I know that this will not solve your problem completely but you will get an idea to move forward as per your requirements.


来源: stackexchange

问:
HTML extend height of div

div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div></code>```

I use the above code to display a big div with two divs in it. For the first one I use position: absolute to place it on bottom left of the div.

How can I extend the height of the second gray one so that it's 5 pixels above the first, but without having to measure its exact height in pixel (like the pic below)? I can set height: 50px; for example but is there another way?

答:
There's this rather new, hip CSS property called 'flex' which you're now going to love because it does it exactly that without the need of positioning absolute etc. I did something similar yesterday where I had a vertical nav bar and I wanted one menu at the top and one at the bottom. In a responsive environment; using your approach of positioning absolute it would've resulted in a nasty mess of working out heights to stop the content from overlapping. Flex prevented this! Yeyyyyy

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

In your example you want to do something like this:

```<code>.div1 {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: space-around;
}
.div2 {
    align-self: flex-start;
    flex-grow:1;
    width:100%;
}
.div3 {
    align-self: flex-end;
    width:100%;
}
</code>```

Now your div 3 will always be at the bottom. Although now .div3 will extend the entire width so within the div insert your content and BOOM done.

ContentLicense: CC BY-SA 3.0

Title: HTML extend height of div

Body:
div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}

Test 123

A

I use the above code to display a big div with two divs in it. For the first one I use position: absolute to place it on bottom left of the div.

How can I extend the height of the second gray one so that it's 5 pixels above the first, but without having to measure its exact height in pixel (like the pic below)? I can set height: 50px; for example but is there another way?

Body:
There's this rather new, hip CSS property called 'flex' which you're now going to love because it does it exactly that without the need of positioning absolute etc. I did something similar yesterday where I had a vertical nav bar and I wanted one menu at the top and one at the bottom. In a responsive environment; using your approach of positioning absolute it would've resulted in a nasty mess of working out heights to stop the content from overlapping. Flex prevented this! Yeyyyyy

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

In your example you want to do something like this:

.div1 {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: space-around;
}
.div2 {
    align-self: flex-start;
    flex-grow:1;
    width:100%;
}
.div3 {
    align-self: flex-end;
    width:100%;
}

Now your div 3 will always be at the bottom. Although now .div3 will extend the entire width so within the div insert your content and BOOM done.


问:
Prevent user to add same product twice in a cart of woocommerce
I want to prevent user to add same product twice in cart of Woocommerce in a same transaction, means once transaction is complete user can add that product into cart but at a same time user can add only one unit of that product into cart.</p>

答:
Unfortunately there is no 'action' hook before WooCommerce adds an item to the cart. But they have a 'filter' hook before adding to cart. That is how I use it:</p>

```<code>add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );
function woo_custom_add_to_cart( $cart_item_data ) {
    global $woocommerce;
    $woocommerce->cart->empty_cart();
    // Do nothing with the data and return
    return $cart_item_data;
}
</code>```

Body:
Unfortunately there is no 'action' hook before WooCommerce adds an item to the cart. But they have a 'filter' hook before adding to cart. That is how I use it:

add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );
function woo_custom_add_to_cart( $cart_item_data ) {
    global $woocommerce;
    $woocommerce->cart->empty_cart();
    // Do nothing with the data and return
    return $cart_item_data;
}


问:
Cut JS string present in an array at every occurrance of a particular substring and append to same array
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

```<code>var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]
</code>```

What I need:

```<code>["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]
</code>```

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

```<code>difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation
</code>```

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

```<code>for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);
</code>```

答:
You can use reduce as follows:</p>

```<code> const dat = ["authentication.$.order", "difference.$.user.$.otherinformation"];

 const ret = dat.reduce((acc, val) => {
    const props = val.split('.');
    let concat = '';
    return acc.concat(props.reduce((acc1, prop) => {
      concat+= (concat ? '.'+ prop : prop);
      acc1.push(concat);
      return acc1;
    }, []));
 }, [])

 console.log(ret);
</code>```

Body:
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]

What I need:

["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);

Body:
You can use reduce as follows:

 const dat = ["authentication.$.order", "difference.$.user.$.otherinformation"];

 const ret = dat.reduce((acc, val) => {
    const props = val.split('.');
    let concat = '';
    return acc.concat(props.reduce((acc1, prop) => {
      concat+= (concat ? '.'+ prop : prop);
      acc1.push(concat);
      return acc1;
    }, []));
 }, [])

 console.log(ret);


问:
SQL Server adds empty spaces to value (char) when trying to set null
I am pulling data from SQL Server to my c# project. I have some textboxes that update from page-to-page. I have one textbox in particular that is set up to only accept two characters, which is setup in the database as char(2). If I were to delete those two characters and click my button to update the database and go to the next page, it stores two empty spaces. I need it to just be empty with no spaces. In my other textboxes, this issue does not occur. The database allows the data to be null. I am able to manually enter "null" in the database, but I need it to be done when erasing the two chars and updating it.

答:
A column declared as CHAR(2) may contain one of the following:

2 characters

NULL.

A column declared as CHAR(2) may not contain any of the following:

0 characters

1 character

3 characters

etc.

When you try to store anything other than either 2 characters or NULL in the column, your database will troll you in the name of some ill-conceived notion of convenience: instead of generating an error, it will store something other than what you gave it to store.

(Amusingly enough, receiving an error when doing something wrong is, and historically has been, regarded as an inconvenience by a surprisingly large portion of programmers. But that's okay, that's how we get stackoverflow questions to answer.)

Specifically, your database will pad the value you are storing with spaces, to match the length of the column.  So, if you try to store just one character, it will add one space.  If you try to store zero characters, it will add two spaces.

Possible Solutions:

If you have the freedom to change the type of the column:

Declare it as VARCHAR instead of CHAR(2), so that it will contain exactly what you store in it.

If you do not have the freedom to change the type of the column:

You have to always be manually checking whether you are about to store an empty string into it, and if so, store NULL instead.

Note about Oracle

The Oracle RDBMS before version 11g (and perhaps also in more recent versions, I am not sure, if someone knows, please leave a comment) will do that last conversion for you: if you try to store an empty string, it will store NULL instead.  This is extremely treacherous due to the following reasons:

It is yet one more example of the database system trolling you by storing something very different from what you gave it to store.

They apply the same rule to all types of character columns, even VARCHAR, which means that you cannot have an empty string even in columns that could accommodate one; you store either NULL or an empty string, you always get NULL back.

This behavior is completely different from the behavior of any other RDBMS.

The behavior is fixed, there is no way to configure Oracle to quit doing that.

ContentLicense: CC BY-SA 4.0


问:
What is the best way to cast from ArrayList to List in .Net 2.0
I have a ArrayList of type BookingData to List<BookingData> ?

I am using .net 2.0 so i cannot use arrayList.Cast<int>().ToList() , and I dont want to make here foreach loop , do you have better ideas ?

Thanks.

答:
Let's keep it simple:</p>

```<code>// untested
List<T> ConvertArrayList<T>(ArrayList data)
{
    List<T>  result = new List<T> (data.Count);
    foreach (T item in data)
      result.Add(item);
    return result;
}

...

List<BookingData> newList = ConvertArrayList<BookingData>(oldList);
</code>```

Body:
Let's keep it simple:

// untested
List<T> ConvertArrayList<T>(ArrayList data)
{
    List<T>  result = new List<T> (data.Count);
    foreach (T item in data)
      result.Add(item);
    return result;
}

...

List<BookingData> newList = ConvertArrayList<BookingData>(oldList);

ContentLicense: CC BY-SA 2.5


问:
Loading HTTP content within HTTPS with iframe
I have this code in a site over HTTPS, which works fine:

```<code>if(window.location.href == 'https:// example . com/'){
    $('body').append('<iframe id="iframe" src="//URL.000webhost.com"></iframe>');
}
</code>```

With //URL . 000webhost . com (free subdomain, HTTP) works fine, but I bought another hosting with domain (HTTP) to load in iframe and now with new URL
(//NEW DOMAIN . net) I see this error :

vendor.js:2 GET https:// NEW DOMAIN . net/ net::ERR_INSECURE_RESPONSE

Why in the free hosting works fine, but in new one doesn't and is there way if I make some domain settings to work ?

答:
Use the full path in the iframe (https:// instead of just //)
because the // will default use http and not https</p>

Body:
I have this code in a site over HTTPS, which works fine:

if(window.location.href == 'https:// example . com/'){
    $('body').append('');
}

With //URL . 000webhost . com (free subdomain, HTTP) works fine, but I bought another hosting with domain (HTTP) to load in iframe and now with new URL
(//NEW DOMAIN . net) I see this error :

vendor.js:2 GET https:// NEW DOMAIN . net/ net::ERR_INSECURE_RESPONSE

Why in the free hosting works fine, but in new one doesn't and is there way if I make some domain settings to work ?


问:
Div with horizontal scrolling only
I have a fixed width DIV containing a table with many columns, and need to allow the user to scroll the table horizontally within the DIV.

This needs to work on IE6 and IE7 only (internal client application).

The following works in IE7:

```<code>overflow-x: scroll;
</code>```

Can anyone help with a solution that works in IE6 as well?

答:
The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:

.container {
    width: 30em;
    overflow-x: auto;
    white-space: nowrap;
}
```

You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y to hidden. But understand that is also an option.

OwnerDisplayName: Richard E

Title: Div with horizontal scrolling only

Body:
I have a fixed width DIV containing a table with many columns, and need to allow the user to scroll the table horizontally within the DIV.

This needs to work on IE6 and IE7 only (internal client application).

The following works in IE7:

overflow-x: scroll;

Can anyone help with a solution that works in IE6 as well?

Body:
The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:

.container {
    width: 30em;
    overflow-x: auto;
    white-space: nowrap;
}

You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y to hidden. But understand that is also an option.

OwnerDisplayName: Jonathan Sampson


问:
What does "somevar >> 0" mean?

What does the notation somevar >> 0 mean in javascript?

Thanks

答:
It's a bitwise operator.
In this case, for shifting the first operand in binary representation the number of bits to the right specified in the second operand, discarding bits shifted off.

With a 0 as second operand, I guess it has no effect (shifting 0 bits, is getting the same value?).

I was wrong with this last. As explained at this @Gumbo's comment.

Title: What does "somevar >> 0" mean?


问:
Convert all HTML Tags to lowercase
I have this code, but PHP gives me an Unknown modifier '?' error.

Anyone knows what I did wrong? (I found the code on the internet, because I'm not familiar with regex)

```<code>$old = "<FONT></FONT><P></P><TR></TR>";
$newString = preg_replace("/</?\w+/e/", "strtolower('\\0')", $old);
echo $newString ."<br/>";
</code>```

答:
Here's a solution that handles attribute names as well as tags. Note this still isn't completely correct; it assumes the character > will never be found in an attribute value such as the alt text for an image. To do this correctly, use the DOMDocument class (but be aware that the parser will have problems with invalid input).</p>

```<code><?php

function lowercase_tag_name_callback(array $m) {
  return strtolower($m[1]) . lowercase_attribute_name($m[2]);
}
function lowercase_attribute_name_callback(array $m) {
  return ' ' . strtolower($m[1]) . $m[2];
}
// change each attribute name to lowercase
function lowercase_attribute_name($input) {
  $output = $input;
  $output = preg_replace_callback('# ([a-zA-Z]+)(="[^"]+")#', 'lowercase_attribute_name_callback', $output);
  $output = preg_replace_callback("# ([a-zA-Z]+)(='[^']+')#", 'lowercase_attribute_name_callback', $output);
  $output = preg_replace_callback('# ([a-zA-Z]+)(=[^"\']+[ >])#', 'lowercase_attribute_name_callback', $output);
  return $output;
}

$input = <<<'EOD'
<FONT></FONT><P id="P1"></P><TR></TR><IMG SRC="FourFive.jpg" ID='AnIDHere' ALT="FOUR five" CLASS=FourFive><!-- A Comment Here --><![CDATA[ CDATA Text Here ]]>

EOD;

$output = preg_replace_callback("#(</?\w+)(.*?>)#", 'lowercase_tag_name_callback', $input);
print "BEFORE: $input";
print " AFTER: $output";
</code>```

Title: Convert all HTML Tags to lowercase

Body:
I have this code, but PHP gives me an Unknown modifier '?' error.

Anyone knows what I did wrong? (I found the code on the internet, because I'm not familiar with regex)

$old = "

";
$newString = preg_replace("/</?\w+/e/", "strtolower('\\0')", $old);
echo $newString ."
";

Body:
Here's a solution that handles attribute names as well as tags. Note this still isn't completely correct; it assumes the character > will never be found in an attribute value such as the alt text for an image. To do this correctly, use the DOMDocument class (but be aware that the parser will have problems with invalid input).

<?php

function lowercase_tag_name_callback(array $m) {
  return strtolower($m[1]) . lowercase_attribute_name($m[2]);
}
function lowercase_attribute_name_callback(array $m) {
  return ' ' . strtolower($m[1]) . $m[2];
}
// change each attribute name to lowercase
function lowercase_attribute_name($input) {
  $output = $input;
  $output = preg_replace_callback('# ([a-zA-Z]+)(="[^"]+")#', 'lowercase_attribute_name_callback', $output);
  $output = preg_replace_callback("# ([a-zA-Z]+)(='[^']+')#", 'lowercase_attribute_name_callback', $output);
  $output = preg_replace_callback('# ([a-zA-Z]+)(=[^"\']+[ >])#', 'lowercase_attribute_name_callback', $output);
  return $output;
}

$input = <<<'EOD'
<FONT></FONT><P id="P1"></P><TR></TR><IMG SRC="FourFive.jpg" ID='AnIDHere' ALT="FOUR five" CLASS=FourFive><!-- A Comment Here --><![CDATA[ CDATA Text Here ]]>

EOD;

$output = preg_replace_callback("#(</?\w+)(.*?>)#", 'lowercase_tag_name_callback', $input);
print "BEFORE: $input";
print " AFTER: $output";


问:
How to debug a Gulp task?
How do I debug a gulp task defined in my gulpfile.js with a debugger such as the Google Chrome debugger, stepping through the task's code line by line?

答: If you are using webstorm you can right click the task in the gulp panel and select debug.

Title: How to debug a Gulp task?


问:
Regex: replace all numbers and "number-like" strings except for years in range
I have the following string:

```<code>s = '2014 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'
</code>```

I want to replace with '' every part of this string which contains a number, except for those parts of the string that are in the year range 1950 to 2025. The resultant string would look like this (don't worry about the extraneous whitespace):

```<code>'2014          keep this text      2015 2025 '
</code>```

So, effectively I want the brute-force removal of anything and everything remotely "numerical," except for something standalone (i.e. not part of another string, and of length 4 excluding whitespace) that resembles a year.

I know I can use this to remove everything containing digits:

```<code>re.sub('\w*[0-9]\w*', '', s)
</code>```

But that doesn't return what I want:

```<code>'           keep this text        '
</code>```

Here's my attempt at replacing anything that doesn't match the patterns listed below:

```<code>re.sub(r'^([A-Za-z]+|19[5-9]\d|20[0-1]\d|202[0-5])', '*', s)
</code>```

Which returns:

```<code>'* 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'
</code>```

I've been here and here, but wasn't able to find what I was looking for.

答:
Regex isn't good at working with numbers. I would ditch regex and use a generator expression:</p>

```<code>predicate= lambda w: (w.isdigit() and 1950<=int(w)<=2025) or not any(char.isdigit() for char in w)
print(' '.join(w for w in s.split() if predicate(w)))
</code>```

Body:
I have the following string:

s = '2014 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'

I want to replace with '' every part of this string which contains a number, except for those parts of the string that are in the year range 1950 to 2025. The resultant string would look like this (don't worry about the extraneous whitespace):

'2014          keep this text      2015 2025 '

So, effectively I want the brute-force removal of anything and everything remotely "numerical," except for something standalone (i.e. not part of another string, and of length 4 excluding whitespace) that resembles a year.

I know I can use this to remove everything containing digits:

re.sub('\w*[0-9]\w*', '', s)

But that doesn't return what I want:

'           keep this text        '

Here's my attempt at replacing anything that doesn't match the patterns listed below:

re.sub(r'^([A-Za-z]+|19[5-9]\d|20[0-1]\d|202[0-5])', '*', s)

Which returns:

'* 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'

I've been here and here, but wasn't able to find what I was looking for.

Body:
Regex isn't good at working with numbers. I would ditch regex and use a generator expression:

predicate= lambda w: (w.isdigit() and 1950<=int(w)<=2025) or not any(char.isdigit() for char in w)
print(' '.join(w for w in s.split() if predicate(w)))


问:
count unique combinations of values
My dataframe looks like this:

```<code>ID | value 1 | value 2 | value 3 | value 4
1  |    M    |    D    |    F    |   A
2  |    F    |    M    |    G    |   B
3  |    M    |    D    |    F    |   A
4  |    L    |    D    |    E    |   B
</code>```

I want to get something like this.

```<code>value 1 | value 2 | value 3 | value 4|  Number of combinations
  M     |    D    |    F    |   A    |     2
  F     |    M    |    G    |   B    |     1
  L     |    D    |    E    |   B    |     1
</code>```

e.g. to count the number of unique combinations of the columns value 1 - value 4.

Title: count unique combinations of values

Body:
My dataframe looks like this:

ID | value 1 | value 2 | value 3 | value 4
1  |    M    |    D    |    F    |   A
2  |    F    |    M    |    G    |   B
3  |    M    |    D    |    F    |   A
4  |    L    |    D    |    E    |   B

I want to get something like this.

value 1 | value 2 | value 3 | value 4|  Number of combinations
  M     |    D    |    F    |   A    |     2
  F     |    M    |    G    |   B    |     1
  L     |    D    |    E    |   B    |     1

e.g. to count the number of unique combinations of the columns value 1 - value 4.

Body:
N <- 10000

d <- data.frame(
  ID=seq(1, N),
  v1=sample(c("M","F", "M", "L"), N, replace = TRUE),
  v2=sample(c("D","M","D","D"), N, replace = TRUE),
  v3=sample(c("F","G","F","E"), N, replace = TRUE),
  v4=sample(c("A","B","A","B"), N, replace = TRUE)
)

With data.table (fastest)

dt <- data.table::as.data.table(d)
dt[, .N, by = c('v1','v2','v3','v4')]

With dplyr

dplyr::count_(d, vars = c('v1','v2','v3','v4'))

With plyr

plyr::count(d, vars = c('v1','v2','v3','v4'))
plyr::ddply(d, .variables = c('v1','v2','v3','v4'), nrow)

With aggregate (slowest)

aggregate(ID ~ ., d, FUN = length)

Benchmark

microbenchmark::microbenchmark(dt[, .N, by = c('v1','v2','v3','v4')],
                               plyr::count(d, vars = c('v1','v2','v3','v4')),
                               plyr::ddply(d, .variables = c('v1','v2','v3','v4'), nrow),
                               dplyr::count_(d, vars = c('v1','v2','v3','v4')),
                               aggregate(ID ~ ., d, FUN = length),
                               times = 1000)

Unit: microseconds
                                                         expr      min       lq      mean   median        uq        max neval  cld
                     dt[, .N, by = c("v1", "v2", "v3", "v4")]  887.807 1107.543  1263.777 1174.258  1289.724   4263.156  1000 a
             plyr::count(d, vars = c("v1", "v2", "v3", "v4")) 3912.791 4270.387  5379.080 4498.053  5791.743 157146.103  1000   c
 plyr::ddply(d, .variables = c("v1", "v2", "v3", "v4"), nrow) 7737.874 8553.370 10630.849 9018.266 11126.517 187301.696  1000    d
           dplyr::count_(d, vars = c("v1", "v2", "v3", "v4")) 2126.913 2432.957  2763.499 2568.251  2789.386  12549.669  1000  b
                           aggregate(ID ~ ., d, FUN = length) 7395.440 8121.828 10546.659 8776.371 10858.263 210139.759  1000    d

It seems best to simply use data.table instead of the data.frame as it is fastest and doesn't need an other function or library to count. Note also that aggregate function performs much slower on large data sets.

Final note: feel free to update with new methods.


问:
Menu toggle breaks with multiple IDs
I have a menu that is responsive with some media queries that adjusts the menu so it looks good regardless of screen size. The menu uses some JavaScript to create a toggle button, people can click the toggle to see the navigation on smaller screens.

Everything is wrapped in a DIV, if the DIV has a class, I have no problems...if the DIV has an id the JavaScript doesn't work.

I don't know that much about JavaScript, but it looks like it's declaring a variable. The variable is getting the id of the UL, so there should be no conflicts. Is there something I am missing?

The JavaScript:

```<code>function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}
</code>```

The HTML (I tweaked the URLS and classes on the links a bit to condense things here):

```<code><div id="nav">
    <ul class="topnav" id="myTopnav">
        <li><a href="http://url.com/">Home</a></li>
        <li>
            <a href="http://url.com/">Pictures</a>
            <ul class="children">
                <li><a href="http://url.com/">Beaver</a></li>
                <li>
                    <a href="http://url.com/">Duck</a>
                    <ul class="children">
                        <li><a href="http://url.com/">Fever</a></li>
                    </ul>
                </li>
                <li><a href="http://url.com/">Frog</a></li>
            </ul>
        </li>
       <li><a href="http://url.com/">Nominations</a></li>
       <li><a href="http://url.com/">Contact</a></li>
       <li class="icon">
           <a href="javascript:void(0);" onclick="myFunction()">☰</a>
       </li>
   </ul>
</div>
</code>```

I don't think the CSS is important, because I'm pretty sure this is a JS issue...especially because if I change the outer ID to a class everything works :-)

Live example: http://joshrodg.com/site/

Any help is appreciated!

Thanks,

Josh

答: I basically just ended up using the class since that worked. It would have been nice to use an ID, but since it's working with the class, it's not a huge deal.</p>

Title: Menu toggle breaks with multiple IDs

Body:
I have a menu that is responsive with some media queries that adjusts the menu so it looks good regardless of screen size. The menu uses some JavaScript to create a toggle button, people can click the toggle to see the navigation on smaller screens.

Everything is wrapped in a DIV, if the DIV has a class, I have no problems...if the DIV has an id the JavaScript doesn't work.

I don't know that much about JavaScript, but it looks like it's declaring a variable. The variable is getting the id of the UL, so there should be no conflicts. Is there something I am missing?

The JavaScript:

function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}

The HTML (I tweaked the URLS and classes on the links a bit to condense things here):

Home

            Pictures

Beaver

                    Duck

Fever

Frog

Nominations

Contact

           ☰

I don't think the CSS is important, because I'm pretty sure this is a JS issue...especially because if I change the outer ID to a class everything works :-)

Live example: http://joshrodg.com/site/

Any help is appreciated!

Thanks,

Josh


问:
Google App Maker - Using properties in SQL data sources
There is something (probably simple) I am missing here.  I am trying to create a Data Source in Google App Maker that queries an SQL database.  I want to have a WHERE clause that uses an email address.  I have set up the email property but, for the life of me, I can't figure out where you assign a value to that property.  Do you do it in a server side script? The Data Source loads when the page loads - so it needs to assign this value on load.

Interface screenshot:

答:
Try using datasource query filters instead, I was looking to do the same thing via SQL queries.

The cleanest way to do this is probably query filtering.

Datasource query filtering works like SQL queries (but simplified, and works with SQL databases)

I am using a Google Cloud SQL database, but I believe the same method will work for any datasource.

-
Write an appmaker query

-
Bind the query parameter

You can make a custom property or bind the query to any value on a page and reload the datasource if needed to update programmatically.

Set the datasource of a table or another widget to your queried datasource to get the results.

That's how I know to create search functions within appmaker.

Hope that helps


问:
Static partial-order reduction on a given state space
Most papers about partial-order reduction assume that the system to be analyzed is given as a set of processes with some composition operator. This makes much sense, since you do not want to compute the state space first, and then to reduce it using partial-order reduction.

But, assuming that you already given a flat state space, can you still reduce it using partial-order reduction? I was thinking that this should be possible using a modified DFS. Some properties can be checked locally, and the cycle condition can be taken into account by using the information you have about states on the stack.

Is there any paper or other reference where such an algorithm is presented?

答:
Yes, this is possible. As you described, the algorithm is very similar to the traditional approach. The only difference is the way information about independence of actions is gathered. Conceptually this is all pretty straightforward. Therefore, I don't think there are any papers on such an algorithm.

For you use-case, bisimulation minimisation is more useful. Baier and Katoen give a great introduction in their book "Principles of Model Checking". The state-of-the-art is described in "Paige and Tarjan - Three partition refinement algorithms" for strong bisimulation and "Groote and Wijs - An O(m log n) Algorithm for Stuttering Equivalence and Branching Bisimulation" for branching bisimulation.


问:
How to fetch only continuous records from mysql?
I have a database table like below

```<code>___________
id |  speed
-----------
1  |   3
2  |   2
3  |   0
4  |   0
5  |   0
6  |   2
7  |   0
8  |   0
9  |   2
10 |   0
</code>```

Now I want to get the records where speed is 0 but only from 3 to 5 which are continuous and greater than any other continuous records. I don't want 7,8 records or the 10th record. How can I achieve this?

答:
Probably the fastest method is to use MySQL session variables to increment the "group" each time the speed changes, as you scan through the rows.

```<code>select n.*, @groupid:=IF(@prev_speed=speed,@groupid,@groupid+1) as groupid, @prev_speed:=speed
from (select @groupid:=0, @prev_speed=-1) _init
cross join n
order by id;

+----+-------+---------+--------------------+
| id | speed | groupid | @prev_speed:=speed |
+----+-------+---------+--------------------+
|  1 |     3 | 1       |                  3 |
|  2 |     2 | 2       |                  2 |
|  3 |     0 | 3       |                  0 |
|  4 |     0 | 3       |                  0 |
|  5 |     0 | 3       |                  0 |
|  6 |     2 | 4       |                  2 |
|  7 |     0 | 5       |                  0 |
|  8 |     0 | 5       |                  0 |
|  9 |     2 | 6       |                  2 |
| 10 |     0 | 7       |                  0 |
+----+-------+---------+--------------------+
</code>```

Then using the above query as a derived table, calculate the lowest and highest id per group, and the count of rows. Sort the groups by the count of rows.

```<code>select min(id) as minid, max(id) as maxid, count(*) as count
from (
    select n.*, @groupid:=IF(@prev_speed=speed,@groupid,@groupid+1) as groupid, @prev_speed:=speed
    from (select @groupid:=0, @prev_speed=-1) _init
    cross join n
    order by id
) as t1
group by t1.groupid
order by count desc;

+-------+-------+-------+
| minid | maxid | count |
+-------+-------+-------+
|     3 |     5 |     3 |
|     7 |     8 |     2 |
|     1 |     1 |     1 |
|     2 |     2 |     1 |
|     6 |     6 |     1 |
|     9 |     9 |     1 |
|    10 |    10 |     1 |
+-------+-------+-------+
</code>```

Then using the first row from the above as another derived table, join to the original table for the rows in the range from the min to max id.

```<code>select n.*
from (
        select min(id) as minid, max(id) as maxid, count(*) as count
        from (
                select n.*, @groupid:=IF(@prev_speed=speed,@groupid,@groupid+1) as groupid, @prev_speed:=speed
                from (select @groupid:=0, @prev_speed=-1) _init
                cross join n
                order by id
        ) as t1
        group by t1.groupid
        order by count desc limit 1
) as t2
inner join n on n.id between t2.minid and t2.maxid

+----+-------+
| id | speed |
+----+-------+
|  3 |     0 |
|  4 |     0 |
|  5 |     0 |
+----+-------+
</code>```

Body:
I have a database table like below

___________
id |  speed
-----------
1  |   3
2  |   2
3  |   0
4  |   0
5  |   0
6  |   2
7  |   0
8  |   0
9  |   2
10 |   0

Now I want to get the records where speed is 0 but only from 3 to 5 which are continuous and greater than any other continuous records. I don't want 7,8 records or the 10th record. How can I achieve this?

Body:
Probably the fastest method is to use MySQL session variables to increment the "group" each time the speed changes, as you scan through the rows.

select n.*, @groupid:=IF(@prev_speed=speed,@groupid,@groupid+1) as groupid, @prev_speed:=speed
from (select @groupid:=0, @prev_speed=-1) _init
cross join n
order by id;

+----+-------+---------+--------------------+
| id | speed | groupid | @prev_speed:=speed |
+----+-------+---------+--------------------+
|  1 |     3 | 1       |                  3 |
|  2 |     2 | 2       |                  2 |
|  3 |     0 | 3       |                  0 |
|  4 |     0 | 3       |                  0 |
|  5 |     0 | 3       |                  0 |
|  6 |     2 | 4       |                  2 |
|  7 |     0 | 5       |                  0 |
|  8 |     0 | 5       |                  0 |
|  9 |     2 | 6       |                  2 |
| 10 |     0 | 7       |                  0 |
+----+-------+---------+--------------------+

Then using the above query as a derived table, calculate the lowest and highest id per group, and the count of rows. Sort the groups by the count of rows.

select min(id) as minid, max(id) as maxid, count(*) as count
from (
    select n.*, @groupid:=IF(@prev_speed=speed,@groupid,@groupid+1) as groupid, @prev_speed:=speed
    from (select @groupid:=0, @prev_speed=-1) _init
    cross join n
    order by id
) as t1
group by t1.groupid
order by count desc;

+-------+-------+-------+
| minid | maxid | count |
+-------+-------+-------+
|     3 |     5 |     3 |
|     7 |     8 |     2 |
|     1 |     1 |     1 |
|     2 |     2 |     1 |
|     6 |     6 |     1 |
|     9 |     9 |     1 |
|    10 |    10 |     1 |
+-------+-------+-------+

Then using the first row from the above as another derived table, join to the original table for the rows in the range from the min to max id.

select n.*
from (
        select min(id) as minid, max(id) as maxid, count(*) as count
        from (
                select n.*, @groupid:=IF(@prev_speed=speed,@groupid,@groupid+1) as groupid, @prev_speed:=speed
                from (select @groupid:=0, @prev_speed=-1) _init
                cross join n
                order by id
        ) as t1
        group by t1.groupid
        order by count desc limit 1
) as t2
inner join n on n.id between t2.minid and t2.maxid

+----+-------+
| id | speed |
+----+-------+
|  3 |     0 |
|  4 |     0 |
|  5 |     0 |
+----+-------+


问:
Rails 5, How to name two models with an associated table?
Given the following two models:

```<code>ChefPosition (Executive, Sous, etc...)
Skills (Creativity, speed, quality)
</code>```

I'm working to create a table that defines what skills are defined per ChefPosition. So far I have:

```<code>ChefPositionSkill (chef_position_id, skill_id)
</code>```

In the Rails 5 world, am I naming the models correctly? If so, what would be the right way to name a controller that returns the skills per ChefPosition, something like:

```<code>ChefPositionSkillController < ApplicationController

  def index
    @ChefPositionSkills = Skill.where(:chef_position => params[:chef_position_id]
    render json: @ChefPositionSkills, status: status
  end
end
</code>```

Is this right?

答: First thing that jumps out to me is the "ChefPositionSkillController" should be pluralized to follow Rails conventions so should be "ChefPositionSkillsController".  Also, if you're just planning on relating a many-to-many with ChefPositions and Skills you're fine naming the join table ChefPositionSkill (Just remember you can change this but the join table must be the combined names of the two tables in lexical order which is what you have here).  Most people however, now use a "has_many through" relationship in that you can add additional details to your join table and not be limited to just the id columns.  This would benefit you if you ever decide that a chef, with a certain skillset, should also have a rank or priority etc.

Body:
Given the following two models:

ChefPosition (Executive, Sous, etc...)
Skills (Creativity, speed, quality)

I'm working to create a table that defines what skills are defined per ChefPosition. So far I have:

ChefPositionSkill (chef_position_id, skill_id)

In the Rails 5 world, am I naming the models correctly? If so, what would be the right way to name a controller that returns the skills per ChefPosition, something like:

ChefPositionSkillController < ApplicationController

  def index
    @ChefPositionSkills = Skill.where(:chef_position => params[:chef_position_id]
    render json: @ChefPositionSkills, status: status
  end
end

Is this right?


问:
EME Key ID different in session request vs. message (ClearKey)

What is the relationship between the kid supplied to MediaKeySession.generateRequest() and the one provided via MediaKeyMessageEvent?

If they are supposed to be the same - why are they different in the code below? note, this won't run here due to security restrictions

navigator.requestMediaKeySystemAccess("org.w3.clearkey", [{
    initDataTypes: ['webm'],
    audioCapabilities: [{
        contentType: 'audio/webm; codecs="opus"'
    }],
    videoCapabilities: [{
        contentType: 'video/webm; codecs="vp8"'
    },
    {
        contentType: 'video/webm; codecs="vp9"'
    }
    ],
}]).then((keySystemAccess) => {
    return keySystemAccess.createMediaKeys();
}).then((mediaKeys) => {
    var session = mediaKeys.createSession("temporary");
    var keyId = "VHM2iIMGiSg";
    var initData = '{"kids":["' + keyId + '"]}';
    console.log(keyId);

    session.addEventListener('message', (evt) => {
        var requestJson = new TextDecoder().decode(evt.message);
        var request = JSON.parse(requestJson);
        console.log(request.kids[0]);
    });

    this.session.generateRequest("webm", new TextEncoder().encode(initData));
});```

output:

VHM2iIMGiSg

eyJraWRzIjpbIlZITTJpSU1HaVNnIl19

expected output is for second line to also be VHM2iIMGiSg

答:
eyJraWRzIjpbIlZITTJpSU1HaVNnIl19 is the base64url encoded value of initData that was passed to generateRequest.

The reason that request.kids[0] is the full value of initData and not the value of keyId is because generateRequest was invoked with the initDataType parameter set to webm. Had the initDataType parameter been set to keyids then request.kids[0] would be the value of keyId.

When the initDataType parameter is set to webm the initData parameter is expected to be a single key ID of one or more bytes. Whereas when the initDataType parameter is set to keyids the initData parameter is expected to be a JSON object encoded as UTF-8, containing a single member kids which is an array of base64url encoded Key ID(s).

Body:
What is the relationship between the kid supplied to MediaKeySession.generateRequest() and the one provided via MediaKeyMessageEvent?

If they are supposed to be the same - why are they different in the code below? note, this won't run here due to security restrictions

navigator.requestMediaKeySystemAccess("org.w3.clearkey", [{
    initDataTypes: ['webm'],
    audioCapabilities: [{
        contentType: 'audio/webm; codecs="opus"'
    }],
    videoCapabilities: [{
        contentType: 'video/webm; codecs="vp8"'
    },
    {
        contentType: 'video/webm; codecs="vp9"'
    }
    ],
}]).then((keySystemAccess) => {
    return keySystemAccess.createMediaKeys();
}).then((mediaKeys) => {
    var session = mediaKeys.createSession("temporary");
    var keyId = "VHM2iIMGiSg";
    var initData = '{"kids":["' + keyId + '"]}';
    console.log(keyId);

    session.addEventListener('message', (evt) => {
        var requestJson = new TextDecoder().decode(evt.message);
        var request = JSON.parse(requestJson);
        console.log(request.kids[0]);
    });

    this.session.generateRequest("webm", new TextEncoder().encode(initData));
});

output:

VHM2iIMGiSg

eyJraWRzIjpbIlZITTJpSU1HaVNnIl19

expected output is for second line to also be VHM2iIMGiSg


问:
Does values capturing of closure in swift means creating static variable?
In Capturing Values section of swift documentation:

... It does this by capturing a reference to runningTotal and amount from the surrounding function and using them within its own function body. ...

and

If you create a second incrementer, it will have its own stored reference to a new, separate runningTotal variable.

So I try the following testing and get a conclusion that since each incrementer made by the makeIncrementer(forIncrementer:) has its own runningTotal and the value of runningTotal is remembered by each incrementer, what values-capturing does is equivalent to creating some static variable(s) for a closure. But I'm not sure whether my statement is correct.

```<code>func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }

    return incrementer
}

let by10Incrementer = makeIncrementer(forIncrement: 10)
let by20Incrementer = makeIncrementer(forIncrement: 20)

for i in 0..<5 {
    print(by10Incrementer())
}

print("---")

for j in 0..<5 {
    print(by20Incrementer())
}
</code>```

output:

```<code>10
20
30
40
50
---
20
40
60
80
100
</code>```

I originally thought that the output of by20Incrementer() would start from 50, but it starts from 0. So the runningTotal of each incrementer refers to different one.

答:
Captures do not become static in a closure, in the sense that each instance of the closure gets its own copy of the variable.

I originally thought that the output of by20Incrementer() would start from 50, but it starts from 0

It starts from the value of runningTotal at the time the closure is created, which is always zero. No matter how many times you increment runningTotal in by10Incrementer, it wouldn't change the value of runningTotal captured in by20Incrementer, because it is a different instance with its own capture of runningTotal.

Effectively, runningTotal becomes a var on the object that represents the closure. Swift syntax makes this capture implicit, but internally the variable is there.

Body:
In Capturing Values section of swift documentation:

... It does this by capturing a reference to runningTotal and amount from the surrounding function and using them within its own function body. ...

and

If you create a second incrementer, it will have its own stored reference to a new, separate runningTotal variable.

So I try the following testing and get a conclusion that since each incrementer made by the makeIncrementer(forIncrementer:) has its own runningTotal and the value of runningTotal is remembered by each incrementer, what values-capturing does is equivalent to creating some static variable(s) for a closure. But I'm not sure whether my statement is correct.

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }

    return incrementer
}

let by10Incrementer = makeIncrementer(forIncrement: 10)
let by20Incrementer = makeIncrementer(forIncrement: 20)

for i in 0..<5 {
    print(by10Incrementer())
}

print("---")

for j in 0..<5 {
    print(by20Incrementer())
}

output:

10
20
30
40
50
---
20
40
60
80
100

I originally thought that the output of by20Incrementer() would start from 50, but it starts from 0. So the runningTotal of each incrementer refers to different one.


问:
Trigger standard HTML validation (form) without using submit button?
Anyone who know how I can trigger the standard HTML5 validation in a form without using a submit button? (JavaScript or jQuery).

I do not want to send POST/GET request, only do the validation.

答:
I think its simpler:

```<code>$('submit').click(function(e){
if (e.isValid())
   e.preventDefault();
//your code.
}
</code>```

this will stop the submit until form is valid.

Body:
I think its simpler:

$('submit').click(function(e){
if (e.isValid())
   e.preventDefault();
//your code.
}

this will stop the submit until form is valid.


问:
Getting runtime error 1004 after putting error handler?
Why does this not suppress errors?

```<code>For i = 1 To Last_row

    On Error GoTo errorhandler1
    Set wkb = Workbooks.Open(Filename:=l)

    '' my code

errorhandler1:

next I
</code>```

This is what I get:

答:
On Error GoTo is more than just some kind of conditional GoTo jump.

When the runtime encounters an error, it is in an error state that you need to clear up.

An error-handling subroutine isn't just a label code jumps to in case of error - it's where you handle runtime errors.

By jumping to the Next statement you make that next iteration occur in a runtime error state, because you didn't Clear the error state ...so execution resumes and all the while, as far as VBA runtime is concerned, the loop body itself becomes the error-handling subroutine: VBA is waiting for Err.Clear, or Resume Next, or any other statement that tells it "all good, error is handled, move along, nothing to see here".

```<code>errorhandler1:
        Err.Clear
        On Error GoTo 0
    next i
</code>```

That would fix the immediate problem, but still leave you with a quite convoluted spaghettish piece of code. Best extract the error-handling clean out of the "happy path".

Body:
Why does this not suppress errors?

For i = 1 To Last_row

    On Error GoTo errorhandler1
    Set wkb = Workbooks.Open(Filename:=l)

    '' my code

errorhandler1:

next I

This is what I get:

Body:
On Error GoTo is more than just some kind of conditional GoTo jump.

When the runtime encounters an error, it is in an error state that you need to clear up.

An error-handling subroutine isn't just a label code jumps to in case of error - it's where you handle runtime errors.

By jumping to the Next statement you make that next iteration occur in a runtime error state, because you didn't Clear the error state ...so execution resumes and all the while, as far as VBA runtime is concerned, the loop body itself becomes the error-handling subroutine: VBA is waiting for Err.Clear, or Resume Next, or any other statement that tells it "all good, error is handled, move along, nothing to see here".

errorhandler1:
        Err.Clear
        On Error GoTo 0
    next i

That would fix the immediate problem, but still leave you with a quite convoluted spaghettish piece of code. Best extract the error-handling clean out of the "happy path".


问:
C# - Getting the current day of the month without month/year
Is there any way to get the day of the month as an int/string? E.G it's the 5th of June, I want the system to return 5 to me.</p>

答:
Easily you can get the day of month by returning</p>

```<code>DateTime.Today.Day
</code>```

Body:
Easily you can get the day of month by returning

DateTime.Today.Day


问:
How to obtain results of an indexedDB cursor in reverse order
I've written the below code to iterate the rows of an object stored in an indexedDB. I'm using Google Chrome browser.

```<code>'use strict';
    var openRequest = indexedDB.open('Library', 1);
    var db;

    openRequest.onupgradeneeded = function(response)
    {
        console.debug(1);
        response.currentTarget.result.createObjectStore("authors",{ keypath: 'id', autoIncrement: true });
    }

    openRequest.onsuccess = function(response) {
        console.debug('success opening indexeddb');
        db = openRequest.result;
       findAuthors();
    };

    function findAuthors() {
        var trans = db.transaction('authors', 'readonly');
        var authors = trans.objectStore("authors");
        var request = authors.openCursor();
        request.PREV = true;
        request.onsuccess = function(response) {
        var cursor = response.target.result;
        if (!cursor) {
        alert('No records found.');
        return;
        }
        alert('Id: ' + cursor.key + ' Last name: ' + cursor.value.lastName);
        cursor.continue();
        };
        request.onerror = function(response) { // display error
        };
    }
</code>```

Records in my DB are as below:

Currently the iteration happens in order of keys 2,3 and then 4. What I want is that when I start iterating the cursor I get the rows with key 4, 3, and then 2 i.e. in reverse order. I tried using a PREV boolean attribute on the cursor object but it doesn't seem to be working:

```<code>request.PREV = true;
</code>```

答:
Try authors.openCursor(null, 'prev');

Also check out https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/openCursor for some documentation.

Body:
I've written the below code to iterate the rows of an object stored in an indexedDB. I'm using Google Chrome browser.

'use strict';
    var openRequest = indexedDB.open('Library', 1);
    var db;

    openRequest.onupgradeneeded = function(response)
    {
        console.debug(1);
        response.currentTarget.result.createObjectStore("authors",{ keypath: 'id', autoIncrement: true });
    }

    openRequest.onsuccess = function(response) {
        console.debug('success opening indexeddb');
        db = openRequest.result;
       findAuthors();
    };

    function findAuthors() {
        var trans = db.transaction('authors', 'readonly');
        var authors = trans.objectStore("authors");
        var request = authors.openCursor();
        request.PREV = true;
        request.onsuccess = function(response) {
        var cursor = response.target.result;
        if (!cursor) {
        alert('No records found.');
        return;
        }
        alert('Id: ' + cursor.key + ' Last name: ' + cursor.value.lastName);
        cursor.continue();
        };
        request.onerror = function(response) { // display error
        };
    }

Records in my DB are as below:

Currently the iteration happens in order of keys 2,3 and then 4. What I want is that when I start iterating the cursor I get the rows with key 4, 3, and then 2 i.e. in reverse order. I tried using a PREV boolean attribute on the cursor object but it doesn't seem to be working:

request.PREV = true;


问:
Unable to attach Threejs EventDispatcher to custom objects
This seems really straightforward but I'm a bit new to JavaScript and struggling. The docs give this example:

```<code>// Adding events to a custom object

var Car = function () {

    this.start = function () {

        this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
    };
};

// Mixin the EventDispatcher.prototype with the custom object prototype
Object.assign( Car.prototype, EventDispatcher.prototype );

// Using events with the custom object
var car = new Car();

car.addEventListener( 'start', function ( event ) {

    alert( event.message );
});

car.start();
</code>```

In the header of my main page I include three.js, which implements EventDispatcher. In the body I load in my app.js, which is where I stick the example code. At this point it throws EventDispatcher is not defined. If I pull in EventDispatcher.js separately before this, it all works.

I guess this is a simple loading / execution order thing, and I'd like to know how to resolve this without needing the extra EventDispatcher.js bit. Cheers!

答:
This should work:

```<code>var Car = function () {

    this.start = function () {

        this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
    };
};

Object.assign( Car.prototype, THREE.EventDispatcher.prototype );

var car = new Car();

car.addEventListener( 'start', function ( event ) {

    alert( event.message );

});

car.start();
</code>```

three.js r.85

Body:
This seems really straightforward but I'm a bit new to JavaScript and struggling. The docs give this example:

// Adding events to a custom object

var Car = function () {

    this.start = function () {

        this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
    };
};

// Mixin the EventDispatcher.prototype with the custom object prototype
Object.assign( Car.prototype, EventDispatcher.prototype );

// Using events with the custom object
var car = new Car();

car.addEventListener( 'start', function ( event ) {

    alert( event.message );
});

car.start();

In the header of my main page I include three.js, which implements EventDispatcher. In the body I load in my app.js, which is where I stick the example code. At this point it throws EventDispatcher is not defined. If I pull in EventDispatcher.js separately before this, it all works.

I guess this is a simple loading / execution order thing, and I'd like to know how to resolve this without needing the extra EventDispatcher.js bit. Cheers!

Body:
This should work:

var Car = function () {

    this.start = function () {

        this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
    };
};

Object.assign( Car.prototype, THREE.EventDispatcher.prototype );

var car = new Car();

car.addEventListener( 'start', function ( event ) {

    alert( event.message );

});

car.start();

three.js r.85


问:
Trying to load local json file with createjs
I'm trying to load animations from Adobe Animate and it works fine when loading from a web server.  But when loading from a local folder, I get "Access denied".  The offending line is

```<code>loader.loadFile({ src: "images/1170_atlas_.json", type: "spritesheet", id: "1170_atlas_" }, true);
</code>```

I should be able to simply include the contents of the file in a variable on the page and load the data directly.  But I'm having problems finding the createjs function I need to call to load the spritesheet.

Any ideas on how to do this?

答:
You can not load JSON locally without doing some things like forcing Chrome to allow file access.

You can also get around it using JSONP, which loads the content as JavaScript.

If you want to manually load the contents, and embed your JSON in your page, you just have to make a new SpriteSheet manually. The EaselJS SpriteSheet docs have examples of this.

Cheers.

Body:
I'm trying to load animations from Adobe Animate and it works fine when loading from a web server.  But when loading from a local folder, I get "Access denied".  The offending line is

loader.loadFile({ src: "images/1170_atlas_.json", type: "spritesheet", id: "1170_atlas_" }, true);

I should be able to simply include the contents of the file in a variable on the page and load the data directly.  But I'm having problems finding the createjs function I need to call to load the spritesheet.

Any ideas on how to do this?


问:
Not getting output for simple java program to find greatest prime factor
```<code>class LargestPrimeFactor{
    public static void main(String args[]){
        long p=0L;
        long n=600851475143L;
        for(long i=2L;i<(n/2);i++){
            if((BigInteger.valueOf(i)).isProbablePrime(1)){
                if(n%i==0){
                    p=i;
                }
            }
        }
        System.out.println(p);
    }
}
</code>```

It's problem 3 from Project Euler. I compiled it and no errors showed up. But am not getting any output. Whats the reason?

答:
It is working (just add a print method inside the loop to check i for example).

You are currently using the Brute-Force method:

http://www.mathblog.dk/project-euler-problem-3/

If you visit the link the guy tells you an alternative solution for it.

The problem I see without having much knowledge about this is

that the operations you currently do are way too many.

You got the value "600851475143" stored in a long datatype and you try to

reach the half (300425737571,5) using the int i (counter in your for-loop).

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#MAX_VALUE

This tells us: "A constant holding the maximum value an int can have,

```<code>2^(31)-1." = 2147483647
</code>```

This is just 0,00715 (0,7%) of what you actually need.

So this leads us to an "Overflow".

Think of using the alternative method (first link)

and change the counter of your for-loop to type "long".

Body:
class LargestPrimeFactor{
    public static void main(String args[]){
        long p=0L;
        long n=600851475143L;
        for(long i=2L;i<(n/2);i++){
            if((BigInteger.valueOf(i)).isProbablePrime(1)){
                if(n%i==0){
                    p=i;
                }
            }
        }
        System.out.println(p);
    }
}

It's problem 3 from Project Euler. I compiled it and no errors showed up. But am not getting any output. Whats the reason?

Body:
It is working (just add a print method inside the loop to check i for example).

You are currently using the Brute-Force method:

http://www.mathblog.dk/project-euler-problem-3/

If you visit the link the guy tells you an alternative solution for it.

The problem I see without having much knowledge about this is

that the operations you currently do are way too many.

You got the value "600851475143" stored in a long datatype and you try to

reach the half (300425737571,5) using the int i (counter in your for-loop).

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#MAX_VALUE

This tells us: "A constant holding the maximum value an int can have,

2^(31)-1." = 2147483647

This is just 0,00715 (0,7%) of what you actually need.

So this leads us to an "Overflow".

Think of using the alternative method (first link)

and change the counter of your for-loop to type "long".


问:
Get a unique ID for worker in python multiprocessing pool
Is there a way to assign each worker in a python multiprocessing pool a unique ID in a way that a job being run by a particular worker in the pool could know which worker is running it? According to the docs, a Process has a name but

The name is a string used for identification purposes only. It has no
  semantics. Multiple processes may be given the same name.

For my particular use-case, I want to run a bunch of jobs on a group of four GPUs, and need to set the device number for the GPU that the job should run on. Because the jobs are of non-uniform length, I want to be sure that I don't have a collision on a GPU of a job trying to run on it before the previous one completes (so this precludes pre-assigning an ID to the unit of work ahead of time).

答:
I did this with threading and ended up using a queue to handle job management.  Here is the baseline.  My complete version has a bunch of try-catches (particularly in the worker, to make sure that q.task_done() is called even on failure).

```<code>from threading import Thread
from queue import Queue
import time
import random

def run(idx, *args):
    time.sleep(random.random() * 1)
    print idx, ':', args

def run_jobs(jobs, workers=1):
    q = Queue()
    def worker(idx):
        while True:
            args = q.get()
            run(idx, *args)
            q.task_done()

    for job in jobs:
        q.put(job)

    for i in range(0, workers):
        t = Thread(target=worker, args=[i])
        t.daemon = True
        t.start()

    q.join()

if __name__ == "__main__":
    run_jobs([('job', i) for i in range(0,10)], workers=5)
</code>```

I didn't need to use multiprocessing (my workers are just for calling an external process), but this could be extended.  The API for multiprocessing changes it a touch, here's how you could adapt:

```<code>from multiprocessing import Process, Queue
from Queue import Empty
import time
import random

def run(idx, *args):
    time.sleep(random.random() * i)
    print idx, ':', args

def run_jobs(jobs, workers=1):
    q = Queue()
    def worker(idx):
        try:
            while True:
                args = q.get(timeout=1)
                run(idx, *args)
        except Empty:
            return

    for job in jobs:
        q.put(job)

    processes = []
    for i in range(0, workers):
        p = Process(target=worker, args=[i])
        p.daemon = True
        p.start()
        processes.append(p)

    for p in processes:
        p.join()

if __name__ == "__main__":
    run_jobs([('job', i) for i in range(0,10)], workers=5)
</code>```

Both versions will output something like:

```<code>0 : ('job', 0)
1 : ('job', 2)
1 : ('job', 6)
3 : ('job', 3)
0 : ('job', 5)
1 : ('job', 7)
2 : ('job', 1)
4 : ('job', 4)
3 : ('job', 8)
0 : ('job', 9)
</code>```

Body:
I did this with threading and ended up using a queue to handle job management.  Here is the baseline.  My complete version has a bunch of try-catches (particularly in the worker, to make sure that q.task_done() is called even on failure).

from threading import Thread
from queue import Queue
import time
import random

def run(idx, *args):
    time.sleep(random.random() * 1)
    print idx, ':', args

def run_jobs(jobs, workers=1):
    q = Queue()
    def worker(idx):
        while True:
            args = q.get()
            run(idx, *args)
            q.task_done()

    for job in jobs:
        q.put(job)

    for i in range(0, workers):
        t = Thread(target=worker, args=[i])
        t.daemon = True
        t.start()

    q.join()

if __name__ == "__main__":
    run_jobs([('job', i) for i in range(0,10)], workers=5)

I didn't need to use multiprocessing (my workers are just for calling an external process), but this could be extended.  The API for multiprocessing changes it a touch, here's how you could adapt:

from multiprocessing import Process, Queue
from Queue import Empty
import time
import random

def run(idx, *args):
    time.sleep(random.random() * i)
    print idx, ':', args

def run_jobs(jobs, workers=1):
    q = Queue()
    def worker(idx):
        try:
            while True:
                args = q.get(timeout=1)
                run(idx, *args)
        except Empty:
            return

    for job in jobs:
        q.put(job)

    processes = []
    for i in range(0, workers):
        p = Process(target=worker, args=[i])
        p.daemon = True
        p.start()
        processes.append(p)

    for p in processes:
        p.join()

if __name__ == "__main__":
    run_jobs([('job', i) for i in range(0,10)], workers=5)

Both versions will output something like:

0 : ('job', 0)
1 : ('job', 2)
1 : ('job', 6)
3 : ('job', 3)
0 : ('job', 5)
1 : ('job', 7)
2 : ('job', 1)
4 : ('job', 4)
3 : ('job', 8)
0 : ('job', 9)


答:
Use the DateTime.Day property.

```<code>var dt = DateTime.Now;
var day = dt.Day;
</code>```

Title: C# - Getting the current day of the month without month/year

Body: Is there any way to get the day of the month as an int/string? E.G it's the 5th of June, I want the system to return 5 to me.

Body:
Use the DateTime.Day property.

var dt = DateTime.Now;
var day = dt.Day;


问:
XML parsing google app script
I have a problem with function XmlService.parse in Google App Script. I am trying to create script, and I need to parse emails which I have in inbox. I tried to send several tests email which have this format

```<code><div dir="ltr">test 1<div><br></div></div>
</code>```

but if I use this line

var doc = XmlService.parse(messages[j].getBody());

I get this error

Error on line 1: The element type "br" must be terminated by the matching end-tag "". (line 18, file "Code")

What is recognizably beacuse there is only
 in message. Is there any solution how to solve this problem? Or I have to use another way how to parse it? Thank you in advance.

edit: I have the same problem with img tag

Error Occured: Error on line 38: The element type "img" must be terminated by the matching end-tag "".

I need to parse the text which is in the red frame email to parse

In old script there was a function

Xml.parse(messag.getBody(),true)

however this function is deprecated. I tried to use

```<code>XmlService.parse(messages.getBody());
</code>```

which I mentioned but I get errors with unpaired html tags. The message which I get by function .getBody() is here getbody email

Could someone help me? Thanks once more.

答:
XmlService can not parse HTML. It can only parse Canonical XML. But there are html parsing libraries for node JS.  So you can take one of those modules run it through browserify, make a minor modification to the generated source, and get a Apps Script library that parses html.

https://github.com/fb55/htmlparser2

My generated library:

1TLbGgQBCztnB0lOhcTYKg2UpXtpdDwocvfcx44w1tqFnHDJC5ZXy_BDo

  https://github.com/Spencer-Easton/Apps-Script-htmlparser2-library

Example code modified from htmlparser2 readme:

```<code>function myFunction() {
  var htmlparser = htmlparser2.init();
  var parser = new htmlparser.Parser({
    onopentag: function(name, attribs){
      if(name === "div"){
        Logger.log("found div");
      }
    },
    ontext: function(text){
      Logger.log("-->" + text);
    },
    onclosetag: function(tagname){
      if(tagname === "div"){
        Logger.log("End Div");
      }
    }
  }, {decodeEntities: true});
  parser.write('<div dir="ltr">test 1<div><br></div></div>');
  parser.end();
}
</code>```

Title: XML parsing google app script

Body:
I have a problem with function XmlService.parse in Google App Script. I am trying to create script, and I need to parse emails which I have in inbox. I tried to send several tests email which have this format

test 1

but if I use this line

var doc = XmlService.parse(messages[j].getBody());

I get this error

Error on line 1: The element type "br" must be terminated by the matching end-tag "". (line 18, file "Code")

What is recognizably beacuse there is only
 in message. Is there any solution how to solve this problem? Or I have to use another way how to parse it? Thank you in advance.

edit: I have the same problem with img tag

Error Occured: Error on line 38: The element type "img" must be terminated by the matching end-tag "".

I need to parse the text which is in the red frame email to parse

In old script there was a function

Xml.parse(messag.getBody(),true)

however this function is deprecated. I tried to use

XmlService.parse(messages.getBody());

which I mentioned but I get errors with unpaired html tags. The message which I get by function .getBody() is here getbody email

Could someone help me? Thanks once more.

Body:
XmlService can not parse HTML. It can only parse Canonical XML. But there are html parsing libraries for node JS.  So you can take one of those modules run it through browserify, make a minor modification to the generated source, and get a Apps Script library that parses html.

https://github.com/fb55/htmlparser2

My generated library:

1TLbGgQBCztnB0lOhcTYKg2UpXtpdDwocvfcx44w1tqFnHDJC5ZXy_BDo

  https://github.com/Spencer-Easton/Apps-Script-htmlparser2-library

Example code modified from htmlparser2 readme:

function myFunction() {
  var htmlparser = htmlparser2.init();
  var parser = new htmlparser.Parser({
    onopentag: function(name, attribs){
      if(name === "div"){
        Logger.log("found div");
      }
    },
    ontext: function(text){
      Logger.log("-->" + text);
    },
    onclosetag: function(tagname){
      if(tagname === "div"){
        Logger.log("End Div");
      }
    }
  }, {decodeEntities: true});
  parser.write('<div dir="ltr">test 1<div><br></div></div>');
  parser.end();
}


问:
SpriteKit Neighboring Hex Tiles
I am trying to build a hex based game using Apple's SpriteKit. I'm currently stuck trying to figure out how to get the surrounding hexes of a given radius, 'N', centered around a selected tile using a SKTileMapNode. I tried using the algorithm from http://www.redblobgames.com/grids/hexagons/#range-coordinate, but was unsuccessfully due to the opaqueness of the SKTileMapNode coordinate system when using a Hex tiled map.

This is what I have tried so far:

for dx -N ... N
     max = max(-N, -dx-N)
     min = min(N, -dx+N)
     for dy max ... min
          // place sprite at (selectedTile.col + dx, selectedTile.row + dy)

where 'N' is the radius of the range. This is not working as intended, and I think it's cause I'm not using the dz coordinate that is mentioned in the site.

Does anyone know if this is possible to do using SpriteKit? I would love to stay using this engine if I can. If there are any questions, please let me know.

答:
So I was able to eventually figure it out. There was nothing wrong with the link I posted, I just didn't realize that the coordinate system that SpriteKit uses is the 'odd-r' coordinate system that is mentioned in the link, while the author uses the cubic coordinate system. What I eventually did was follow the conversion algorithms that the author supplied, and converted back and forth from cubic to 'odd-r' coordinates. Then, using the algorithm for finding the hex range supplied, I was able to implement the correct functionality.

To sum things up...always read the whole article and not just what you're interested in!

Sources:

http://www.redblobgames.com/grids/hexagons/#conversions-offset

Title: SpriteKit Neighboring Hex Tiles


问:
Will PDF 2.0 compatible with PDF 1.x
Will a valid PDF 1.x document be a valid PDF 2.0 document? Will PDF 1.x readers gracefully accept PDF 2.0 documents?</p>

答:
No, a PDF 1.x document is not a valid PDF 2.0 document.

A PDF 1.x document could be a valid PDF 2.0 document if at the very least the only changed required was the version number in the PDF. There are a number of other changes required for PDF 2.0 though like appearances for annotations being defined in the PDF (in 1.x they were optional and viewers would generate them on the fly if not found or simply not display anything) and the deprecation of XFA.

Some PDF 1.x readers may accept PDF 2.0 documents. It will be up to the vendor though to determine what level of support they offer for PDF 2.0 .

Title: Will PDF 2.0 compatible with PDF 1.x


问:
fit_generator input dimensions error when using ImageDataGenerator (Keras)
I am using Keras 2.04 with tensorflow backend. I am trying to train a simple model with ImageDataGenerator on MNIST images. However, I keep getting the following error from fit_generator:

ValueError: Error when checking input: expected input_1 to have 2
  dimensions, but got array with shape (8, 28, 28, 1).

This is the code:

```<code>#loading data & reshaping
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], 28, 28,1)

#building the model
input_img = Input(shape=(784,))
encoded = Dense(30, activation='relu')(input_img)
decoded = Dense(784, activation='sigmoid')(encoded)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='mse')

#creating ImageDataGenerator
datagen = ImageDataGenerator(featurewise_center=True, featurewise_std_normalization=True)
datagen.fit(x_train)

autoencoder.fit_generator(
        #x_train, x_train because the target is to reconstruct the input
        datagen.flow(x_train, x_train, batch_size=8),
        steps_per_epoch=int(len(x_train)/8),
        epochs=64,
       )
</code>```

As far as I understand ImageDataGenerator should generate a batch of training examples each iteration, as it actually does (in this case, batch_size=8) but from the error it seems as if it expects a single training example.

Thanks!

答:
Solved - it should have been: </p>

```<code>autoencoder = Sequential()
autoencoder.add(Reshape((784,), input_shape=(28,28,1)))
autoencoder.add(Dense(30, activation='relu'))
autoencoder.add(Dense(784, activation='relu'))
.
.
.

autoencoder.fit_generator(
        datagen.flow(x_train, x_train.reshape(len(x_train),784,), batch_size=8),
        steps_per_epoch=int(len(x_train)/8),
        epochs=64,
       )
</code>```

Body:
I am using Keras 2.04 with tensorflow backend. I am trying to train a simple model with ImageDataGenerator on MNIST images. However, I keep getting the following error from fit_generator:

ValueError: Error when checking input: expected input_1 to have 2
  dimensions, but got array with shape (8, 28, 28, 1).

This is the code:

#loading data & reshaping
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], 28, 28,1)

#building the model
input_img = Input(shape=(784,))
encoded = Dense(30, activation='relu')(input_img)
decoded = Dense(784, activation='sigmoid')(encoded)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='mse')

#creating ImageDataGenerator
datagen = ImageDataGenerator(featurewise_center=True, featurewise_std_normalization=True)
datagen.fit(x_train)

autoencoder.fit_generator(
        #x_train, x_train because the target is to reconstruct the input
        datagen.flow(x_train, x_train, batch_size=8),
        steps_per_epoch=int(len(x_train)/8),
        epochs=64,
       )

As far as I understand ImageDataGenerator should generate a batch of training examples each iteration, as it actually does (in this case, batch_size=8) but from the error it seems as if it expects a single training example.

Thanks!

Body:
Solved - it should have been:

autoencoder = Sequential()
autoencoder.add(Reshape((784,), input_shape=(28,28,1)))
autoencoder.add(Dense(30, activation='relu'))
autoencoder.add(Dense(784, activation='relu'))
.
.
.

autoencoder.fit_generator(
        datagen.flow(x_train, x_train.reshape(len(x_train),784,), batch_size=8),
        steps_per_epoch=int(len(x_train)/8),
        epochs=64,
       )


问:
Get Statement from JDBCTemplate
I have this code,

```<code>SimpleJdbcCall sql = new SimpleJdbcCall(dataSource).withProcedureName(procName);
sql.execute(parameters);
</code>```

And I believe that under the hood this uses a JDBC Statement. How can I get to that object from here? (I need to call the .getWarnings() method on the statement).

In other words how can I get SQLWarnings AND named parameters?

答:
It took a lot of digging, but here is how you can get SQLWarnings (or Print statements) AND named parameters. I extended JdbcTemplate and overrode the handleWarnings() method, and then passed that into my SimpleJdbcCall.

```<code>  public class JdbcTemplateLoggable extends JdbcTemplate{

    List<String> warnings;

    public JdbcTemplateLoggable(DataSource dataSource){
        super(dataSource);
        warnings = new ArrayList<String>();
    }

    protected void handleWarnings(Statement stmt){
        try {
            SQLWarning warning = stmt.getWarnings();
            while(warning != null){
                warnings.add(warning.getMessage());
                warning = warning.getNextWarning();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public List<String> getWarnings(){
        return warnings;
    }
}
</code>```

Then in my main program

```<code>JdbcTemplateLoggable template = new JdbcTemplateLoggable(dataSource);
        SimpleJdbcCall sql = new SimpleJdbcCall(template).withProcedureName(procName);
        sql.execute(parameters);
        for(String s : template.getWarnings()){
            log.info(s);
        }
</code>```

Title: Get Statement from JDBCTemplate

Body:
I have this code,

SimpleJdbcCall sql = new SimpleJdbcCall(dataSource).withProcedureName(procName);
sql.execute(parameters);

And I believe that under the hood this uses a JDBC Statement. How can I get to that object from here? (I need to call the .getWarnings() method on the statement).

In other words how can I get SQLWarnings AND named parameters?

Body:
It took a lot of digging, but here is how you can get SQLWarnings (or Print statements) AND named parameters. I extended JdbcTemplate and overrode the handleWarnings() method, and then passed that into my SimpleJdbcCall.

  public class JdbcTemplateLoggable extends JdbcTemplate{

    List<String> warnings;

    public JdbcTemplateLoggable(DataSource dataSource){
        super(dataSource);
        warnings = new ArrayList<String>();
    }

    protected void handleWarnings(Statement stmt){
        try {
            SQLWarning warning = stmt.getWarnings();
            while(warning != null){
                warnings.add(warning.getMessage());
                warning = warning.getNextWarning();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public List<String> getWarnings(){
        return warnings;
    }
}

Then in my main program

JdbcTemplateLoggable template = new JdbcTemplateLoggable(dataSource);
        SimpleJdbcCall sql = new SimpleJdbcCall(template).withProcedureName(procName);
        sql.execute(parameters);
        for(String s : template.getWarnings()){
            log.info(s);
        }


问:
Copy list of files to specific paths with Makefile
Scratching my head for a while now, but I would like to copy an arbitrary list of files with paths to under specified path in system.

File layout:

```<code>data/a/file1.ext1
data/b/randomfile.ext2
data/c/file3.ext3
data/c/subdir/randomfile.2
</code>```

Running make -f Makefile deploy DESTDIR=/path/to/somewhere copies those files to:

```<code>$(DESTDIR)/a/file1.ext1
$(DESTDIR)/b/randomfile.ext2
$(DESTDIR)/c/file3.ext3
$(DESTDIR)/c/subdir/randomfile.2
</code>```

Makefile:

```<code>$FILES = \
    a/file1.ext1 \
    b/randomfile.ext2 \
    c/file3.ext3 \
    c/subdir/randomfile.2

ifneq ($(filter env_check,$(MAKECMDGOALS)),$())
  ifndef DESTDIR
    $(error DESTDIR not defined)
  endif
endif

# lots of currently broken rules :(
# check whether target directory has certain structure
# check whether all the files listed in $(FILES) are in repository
</code>```

答:
Are you looking for something like this?

```<code>FILES := ...
DST_FILES := $(addprefix $(DESTDIR)/,$(FILES))

ifneq ($(filter env_check,$(MAKECMDGOALS)),$())
  ifndef DESTDIR
    $(error DESTDIR not defined)
  endif
endif

all: $(DST_FILES)

$(DST_FILES) : ${DESTDIR}/% : %
    @echo "$< ==> $@"
    @[[ -e $< ]] || (echo "some error for $<" && false)
    @mkdir -p $(dir $@)
    @cp  $< $@
</code>```

[Edit]:
Although the version somewhat worked, I still needed to do following adjustments:

Files in source repository are stored under data directory - fixed by using $addprefix call

When file in $(DESTDIR) already existed, it was never copied - used the .FORCE target. (Another option would be --always-make commandline option).

Eventually, the working Makefile looks like that:

```<code># File are stored under data/
FILES= \
    foo/file1.ext \
    bar/file2.txe \
    bar/dir/file3.txt

ifneq ($(filter env_check,$(MAKECMDGOALS)),$())
  ifndef DESTDIR
    $(error DESTDIR not defined)
  endif
endif

.PHONY: deploy help

help:
    @echo "Deploy stuff"

# Check whether certain directories in the output are present
env_check:
    @test -d $(DESTDIR)/WEB-INF -a -d $(DESTDIR)/META-INF || \
        ( echo "DESTDIR: \"$(DESTDIR)\" is not proper deployment path" && exit 1 )

DST_FILES := $(addprefix $(DESTDIR)/, $(FILES))

# We need to add our path prefix to local files and FORCE to always do the copying
$(DST_FILES) : $(addprefix $(DESTDIR), %) : $(addprefix data,%) .FORCE
    @cp -pv $< $@

.FORCE:

deploy: env_check $(DST_FILES)
    @echo "Deployment done..."
</code>```

Body:
Scratching my head for a while now, but I would like to copy an arbitrary list of files with paths to under specified path in system.

File layout:

data/a/file1.ext1
data/b/randomfile.ext2
data/c/file3.ext3
data/c/subdir/randomfile.2

Running make -f Makefile deploy DESTDIR=/path/to/somewhere copies those files to:

$(DESTDIR)/a/file1.ext1
$(DESTDIR)/b/randomfile.ext2
$(DESTDIR)/c/file3.ext3
$(DESTDIR)/c/subdir/randomfile.2

Makefile:

$FILES = \
    a/file1.ext1 \
    b/randomfile.ext2 \
    c/file3.ext3 \
    c/subdir/randomfile.2

ifneq ($(filter env_check,$(MAKECMDGOALS)),$())
  ifndef DESTDIR
    $(error DESTDIR not defined)
  endif
endif

# lots of currently broken rules :(
# check whether target directory has certain structure
# check whether all the files listed in $(FILES) are in repository

Body:
Are you looking for something like this?

FILES := ...
DST_FILES := $(addprefix $(DESTDIR)/,$(FILES))

ifneq ($(filter env_check,$(MAKECMDGOALS)),$())
  ifndef DESTDIR
    $(error DESTDIR not defined)
  endif
endif

all: $(DST_FILES)

$(DST_FILES) : ${DESTDIR}/% : %
    @echo "$< ==> $@"
    @[[ -e $< ]] || (echo "some error for $<" && false)
    @mkdir -p $(dir $@)
    @cp  $< $@

[Edit]:
Although the version somewhat worked, I still needed to do following adjustments:

Files in source repository are stored under data directory - fixed by using $addprefix call

When file in $(DESTDIR) already existed, it was never copied - used the .FORCE target. (Another option would be --always-make commandline option).

Eventually, the working Makefile looks like that:

# File are stored under data/
FILES= \
    foo/file1.ext \
    bar/file2.txe \
    bar/dir/file3.txt

ifneq ($(filter env_check,$(MAKECMDGOALS)),$())
  ifndef DESTDIR
    $(error DESTDIR not defined)
  endif
endif

.PHONY: deploy help

help:
    @echo "Deploy stuff"

# Check whether certain directories in the output are present
env_check:
    @test -d $(DESTDIR)/WEB-INF -a -d $(DESTDIR)/META-INF || \
        ( echo "DESTDIR: \"$(DESTDIR)\" is not proper deployment path" && exit 1 )

DST_FILES := $(addprefix $(DESTDIR)/, $(FILES))

# We need to add our path prefix to local files and FORCE to always do the copying
$(DST_FILES) : $(addprefix $(DESTDIR), %) : $(addprefix data,%) .FORCE
    @cp -pv $< $@

.FORCE:

deploy: env_check $(DST_FILES)
    @echo "Deployment done..."


问:
Gantt editable chart for ReactJs
I'm looking for an editable Gantt chart component that can be used in ReactJS. The need is to plot a resource Gantt chart where the user can change tasks on the time axis and also between the resources.

Preferably open source.

答:
You can take a look at this React Gantt chart component made with the help of dhtmlxGantt (js gantt chart library): https://github.com/DHTMLX/react-gantt-demo

Tutorial: https://dhtmlx.com/blog/create-react-gantt-chart-component-dhtmlxgantt/

Title: Gantt editable chart for ReactJs