问:
Python regex to remove all tags that aren't between two other tags
I am using python and want to remove all html tags from a string that aren't enclosed in certain tags. In this example, I want to remove all the html tags that aren't enclosed in the tags and also not remove that enclosing tag as well.

For example:

```<code><h1>Morning</h1>
<header>
    <h1>Afternoon</h1>
    <h2>Evening</h2>
</header>
<h2>Night</h2>
</code>```

Result:

```<code>Morning
<header>
    <h1>Afternoon</h1>
    <h2>Evening</h2>
</header>
Night
</code>```

I've spent hours on it but no luck.
I know that the following will find ALL tags:

```<code>re.sub('<.*?>', '', mystring)
</code>```

And this will find anything within the header tags:

```<code>re.sub('<header>.*?</header>', '', mystring)
</code>```

But how do I negate it, so that the first regex ignores what the second regex finds? Any help is greatly appreciated! Thank you! :)

答:
You can do this quickly and easily using BeautifulSoup, as mentioned by Josep Valls in the comments. Here's how:

```<code>from bs4 import BeautifulSoup

soup = BeautifulSoup('''<h1>Morning</h1>
<header>
    <h1>Afternoon</h1>
    <h2>Evening</h2>
</header>
<h2>Night</h2>''', 'html.parser')

for tag in soup.find_all(recursive=False):
    if not tag.findChildren():
        tag.unwrap()

print(soup)
</code>```

This prints out:

```<code>Morning
<header>
<h1>Afternoon</h1>
<h2>Evening</h2>
</header>
Night
</code>```

Body:
I am using python and want to remove all html tags from a string that aren't enclosed in certain tags. In this example, I want to remove all the html tags that aren't enclosed in the tags and also not remove that enclosing tag as well.

For example:

Morning

Afternoon

Evening

Night

Result:

Morning

Afternoon

Evening

Night

I've spent hours on it but no luck.
I know that the following will find ALL tags:

re.sub('<.*?>', '', mystring)

And this will find anything within the header tags:

re.sub('.*?', '', mystring)

But how do I negate it, so that the first regex ignores what the second regex finds? Any help is greatly appreciated! Thank you! :)

Body:
You can do this quickly and easily using BeautifulSoup, as mentioned by Josep Valls in the comments. Here's how:

from bs4 import BeautifulSoup

soup = BeautifulSoup('''<h1>Morning</h1>
<header>
    <h1>Afternoon</h1>
    <h2>Evening</h2>
</header>
<h2>Night</h2>''', 'html.parser')

for tag in soup.find_all(recursive=False):
    if not tag.findChildren():
        tag.unwrap()

print(soup)

This prints out:

Morning
<header>
<h1>Afternoon</h1>
<h2>Evening</h2>
</header>
Night


来源: stackexchange

问:
getElementById not working in Google Chrome extension for <embed>
In my Google Chrome extension content script I have the following:

```<code>jQuery(document).ready(function() {
    var player = document.getElementById('player');
    console.log(player);
    console.log(document);
});
</code>```

I'm running it on any Hulu video, which has the following embed with id='player'

```<code><embed id="player" type="application/x-shockwave-flash" src="/site-player/playerwrapper.swf?cb=e80c477cL" width="100%" height="428" style="z-index:10;" name="player" quality="high" allowscriptaccess="always" allowfullscreen="true" bgcolor="#000000" flashvars="bitrate=700000&user_id=-1&startLoadWrapperTime=1299572732904&overrideBrand=&referrer=http://www.hulu.com/watch/20338/saturday-night-live-steve-carell-monologue#continuous_play=on&continuous_play_on=true&sortBy=&initMode=4&modes=4&content_id=7751491&cb=2011-3-8-8&v=3">
</code>```

For example, the following link http://www.hulu.com/watch/20337/saturday-night-live-snl-digital-short-the-japanese-office

But when the script is run, console.log(player) returns null. However, console.log(document) returns the proper document object.
Even if I try var player = Document.prototype.getElementById.apply(document, ['player']);
I still get null.

The funny thing is, if I try it from the Chrome JavaScript Console, it works fine, I get the proper <embed> printed to console.

Any ideas why this isn't working in my content script?

UPDATE:
As requested, here are the complete contents of my chrome extension folder:

manifest.json:

```<code>{
    "name": "gebidtest",
    "version": "1",
    "permissions": [
      "http://*/*",
      "https://*/*"
    ],
    "content_scripts": [{
      "matches": ["http://*/*"],
      "js": ["jquery-1.5.1.min.js","app.js"]
    }]
}
</code>```

app.js:

```<code>jQuery(document).ready( function() {
    var player = document.getElementById('player');
    console.log(player);
    console.log(document);
});
</code>```

jquery-1.5.1.min.js: I just downloaded it

I'm using Chrome version 10.0.648.127 on a Mac, but I also tried it on a PC with the same results

答:
Use defer.</p>

```<code><script defer>...</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In my Google Chrome extension content script I have the following:

jQuery(document).ready(function() {
    var player = document.getElementById('player');
    console.log(player);
    console.log(document);
});

I'm running it on any Hulu video, which has the following embed with id='player'

<embed id="player" type="application/x-shockwave-flash" src="/site-player/playerwrapper.swf?cb=e80c477cL" width="100%" height="428" style="z-index:10;" name="player" quality="high" allowscriptaccess="always" allowfullscreen="true" bgcolor="#000000" flashvars="bitrate=700000&user_id=-1&startLoadWrapperTime=1299572732904&overrideBrand=&referrer=http://www.hulu.com/watch/20338/saturday-night-live-steve-carell-monologue#continuous_play=on&continuous_play_on=true&sortBy=&initMode=4&modes=4&content_id=7751491&cb=2011-3-8-8&v=3">

For example, the following link http://www.hulu.com/watch/20337/saturday-night-live-snl-digital-short-the-japanese-office

But when the script is run, console.log(player) returns null. However, console.log(document) returns the proper document object.
Even if I try var player = Document.prototype.getElementById.apply(document, ['player']);
I still get null.

The funny thing is, if I try it from the Chrome JavaScript Console, it works fine, I get the proper <embed> printed to console.

Any ideas why this isn't working in my content script?

UPDATE:
As requested, here are the complete contents of my chrome extension folder:

manifest.json:

{
    "name": "gebidtest",
    "version": "1",
    "permissions": [
      "http://*/*",
      "https://*/*"
    ],
    "content_scripts": [{
      "matches": ["http://*/*"],
      "js": ["jquery-1.5.1.min.js","app.js"]
    }]
}

app.js:

jQuery(document).ready( function() {
    var player = document.getElementById('player');
    console.log(player);
    console.log(document);
});

jquery-1.5.1.min.js: I just downloaded it

I'm using Chrome version 10.0.648.127 on a Mac, but I also tried it on a PC with the same results

Body:
Use defer.

<script defer>...</script>

ContentLicense: CC BY-SA 3.0


问:
Unmarshall XML to embedded struct in go
I have a flat XML structure, which I want to unmarshall in to a struct which has one part embedded.  Is this possible?   What is the syntax, or what custom method can I write?

In this example, I tag the nested struct with a guess: xml:"", which is skipped over by "encoding/xml".

```<code>type FloatHolder struct {
    Value float32    `xml:"value"`
}

type pv struct {
    XMLName    xml.Name  `xml:"series"`
    Test1 FloatHolder `xml:""`   // does not populate :-(
    Test2 FloatHolder `xml:"nested"` // populates
}
func main() {
    contents := `<series>
                   <nested>
                     <value>1234</value>
                   </nested>
                   <value>1234</value>
                 </series>`

    m := &pv{}

    err := xml.Unmarshal([]byte(contents), &m)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%f %f\n", m.Test1.Value, m.Test2.Value)
}
</code>```

Output: "0.000000 1234.000000"

Playground: https://play.golang.org/p/aEdDLFYqL5

Thanks!

答:
EDIT: After comment interaction.

Yes you can. Let's say

XML:

```<code><series>
    <value>123456</value>
</series>
</code>```

Struct definition:

```<code>type FloatHolder struct {
    Value float32 `xml:",chardata"`
}

type pv struct {
    XMLName xml.Name    `xml:"series"`
    Test2   FloatHolder `xml:"value"`
}
</code>```

Go Playground link: https://play.golang.org/p/9sWQaw0HlS

Actually it's not a nested field, as per your XML. It belongs to series element.

Update your struct to following:

```<code>type pv struct {
    XMLName xml.Name    `xml:"series"`
    Test1   float32     `xml:"value"`
    Test2   FloatHolder `xml:"nested"`
}
</code>```

Go Playground Link: https://play.golang.org/p/-mWrUMJXxX

Title: Unmarshall XML to embedded struct in go

Body:
I have a flat XML structure, which I want to unmarshall in to a struct which has one part embedded.  Is this possible?   What is the syntax, or what custom method can I write?

In this example, I tag the nested struct with a guess: xml:"", which is skipped over by "encoding/xml".

type FloatHolder struct {
    Value float32    `xml:"value"`
}

type pv struct {
    XMLName    xml.Name  `xml:"series"`
    Test1 FloatHolder `xml:""`   // does not populate :-(
    Test2 FloatHolder `xml:"nested"` // populates
}
func main() {
    contents := `<series>
                   <nested>
                     <value>1234</value>
                   </nested>
                   <value>1234</value>
                 </series>`

    m := &pv{}

    err := xml.Unmarshal([]byte(contents), &m)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%f %f\n", m.Test1.Value, m.Test2.Value)
}

Output: "0.000000 1234.000000"

Playground: https://play.golang.org/p/aEdDLFYqL5

Thanks!

Body:
EDIT: After comment interaction.

Yes you can. Let's say

XML:

<series>
    <value>123456</value>
</series>

Struct definition:

type FloatHolder struct {
    Value float32 `xml:",chardata"`
}

type pv struct {
    XMLName xml.Name    `xml:"series"`
    Test2   FloatHolder `xml:"value"`
}

Go Playground link: https://play.golang.org/p/9sWQaw0HlS

Actually it's not a nested field, as per your XML. It belongs to series element.

Update your struct to following:

type pv struct {
    XMLName xml.Name    `xml:"series"`
    Test1   float32     `xml:"value"`
    Test2   FloatHolder `xml:"nested"`
}

Go Playground Link: https://play.golang.org/p/-mWrUMJXxX


问:
How to implement a memory heap
Wasn't exactly sure how to phrase the title, but the question is:

I've heard of programmers allocating a large section of contiguous memory at the start of a program and then dealing it out as necessary. This is, in contrast to simply going to the OS every time memory is needed.
I've heard that this would be faster because it would avoid the cost of asking the OS for contiguous blocks of memory constantly.

I believe the JVM does just this, maintaining its own section of memory and then allocating objects from that.

My question is, how would one actually implement this?

答:
Most C and C++ compilers already provide a heap memory-manager as part of the standard library, so you don't need to do anything at all in order to avoid hitting the OS with every request.

If you want to improve performance, there are a number of improved allocators around that you can simply link with and go.  e.g. Hoard, which wheaties mentioned in a now-deleted answer (which actually was quite good -- wheaties, why'd you delete it?).

If you want to write your own heap manager as a learning exercise, here are the basic things it needs to do:

Request a big block of memory from the OS

Keep a linked list of the free blocks

When an allocation request comes in:

search the list for a block that's big enough for the requested size plus some book-keeping variables stored alongside.

split off a big enough chunk of the block for the current request, put the rest back in the free list

if no block is big enough, go back to the OS and ask for another big chunk

When a deallocation request comes in

read the header to find out the size

add the newly freed block onto the free list

optionally, see if the memory immediately following is also listed on the free list, and combine both adjacent blocks into one bigger one (called coalescing the heap)

ContentLicense: CC BY-SA 4.0

Title: How to implement a memory heap


问:
Pass required positional argument to super class without adding it in subclass' constructor
I have such a class:

```<code>class C1:

    def __init__(self, arg1, kwarg1=1, kwarg2=2):
        ...
</code>```

Now I want to create a C2 that just changes default values of kwarg1 and kwarg2 in C1. It's some sort of functools.partial but for classes.

I can do it it this way:

```<code>class C2(C1):

    def __init__(self, arg1, kwarg1=3, kwarg2=4):
        super().__init(arg1, kwarg1=kwarg1, kwarg2=kwarg2)
</code>```

But I don't like that I need to pass arg1 to C2 constructor and then pass it as it is to C1 with super().__init(arg1, ...).

I'd like to do something like this:

```<code>class C2(C1):

    def __init__(self, kwarg1=3, kwarg2=4, *args, **kwargs):
        super().__init(kwarg1=kwarg1, kwarg2=kwarg2, *args, **kwargs)
</code>```

but this doesn't work:

```<code>TypeError: __init__() missing 1 required positional argument: 'arg1'
</code>```

Is there any way I can pass arg1 to C1 from C2 without mentioning it in C2's constructor

答:
You can do it on an even more convoluted way, but at least you won't be passing the dreaded arg1:

```<code>class C2(C1):

    def __init__(self, *args, **kwargs):
        kwargs["kwarg1"] = kwargs.get("kwarg1", 3)
        kwargs["kwarg2"] = kwargs.get("kwarg2", 4)
        super().__init__(*args, **kwargs)
</code>```

But you'll still need to keep your positional arguments when initializing C2.

Body:
I have such a class:

class C1:

    def __init__(self, arg1, kwarg1=1, kwarg2=2):
        ...

Now I want to create a C2 that just changes default values of kwarg1 and kwarg2 in C1. It's some sort of functools.partial but for classes.

I can do it it this way:

class C2(C1):

    def __init__(self, arg1, kwarg1=3, kwarg2=4):
        super().__init(arg1, kwarg1=kwarg1, kwarg2=kwarg2)

But I don't like that I need to pass arg1 to C2 constructor and then pass it as it is to C1 with super().__init(arg1, ...).

I'd like to do something like this:

class C2(C1):

    def __init__(self, kwarg1=3, kwarg2=4, *args, **kwargs):
        super().__init(kwarg1=kwarg1, kwarg2=kwarg2, *args, **kwargs)

but this doesn't work:

TypeError: __init__() missing 1 required positional argument: 'arg1'

Is there any way I can pass arg1 to C1 from C2 without mentioning it in C2's constructor

Body:
You can do it on an even more convoluted way, but at least you won't be passing the dreaded arg1:

class C2(C1):

    def __init__(self, *args, **kwargs):
        kwargs["kwarg1"] = kwargs.get("kwarg1", 3)
        kwargs["kwarg2"] = kwargs.get("kwarg2", 4)
        super().__init__(*args, **kwargs)

But you'll still need to keep your positional arguments when initializing C2.


问:
Remove duplicate values of specific key in multidimensional array in PHP but remove the last?
I have an array like this

```<code> Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )

    [4] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )
)
</code>```

As you can see the first and last arrays are the same, so my code to remove the duplicates is like this

```<code>foreach ($my_array as $k => $v) {

    foreach ($my_arrays as $key => $value) {

        if ($k != $key && $v['clave'] == $value['clave']) {

            unset($my_array[$k]);
        }
    }
}
</code>```

And this works fine but I would like to remove the last array and let the first one to keep the order in which I added every array, so the result should be

```<code>Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )
)
</code>```

Because in the way I do it is removing always the first duplicates and the last always remains, some idea how to achieve this? I hope you can help me, thanks.

答:
Try this one.

```<code>$array = array(
  array('clave' => 10215484 , 'descripcion' => 'Azucena viva de agua'),
  array('clave' => 10215484 , 'descripcion' => 'Azucena viva de agua bentin'),
  array('clave' => 10215484 , 'descripcion' => 'Azucena viva de agua corva'),
  array('clave' => 10215484 , 'descripcion' => 'Azucena viva de agua')
);

$new_array = array_unique($array, SORT_REGULAR);
echo '```';
print_r($new_array);
```

<p>This will return:</p>

```Array
(
[0] => Array
    (
        [clave] => 10215484
        [descripcion] => Azucena viva de agua
    )

[1] => Array
    (
        [clave] => 10215484
        [descripcion] => Azucena viva de agua bentin
    )

[2] => Array
    (
        [clave] => 10215484
        [descripcion] => Azucena viva de agua corva
    )
)
```

Body:
I have an array like this

 Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )

    [4] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )
)

As you can see the first and last arrays are the same, so my code to remove the duplicates is like this

foreach ($my_array as $k => $v) {

    foreach ($my_arrays as $key => $value) {

        if ($k != $key && $v['clave'] == $value['clave']) {

            unset($my_array[$k]);
        }
    }
}

And this works fine but I would like to remove the last array and let the first one to keep the order in which I added every array, so the result should be

Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )
)

Because in the way I do it is removing always the first duplicates and the last always remains, some idea how to achieve this? I hope you can help me, thanks.

Body:
Try this one.

$array = array(
  array('clave' => 10215484 , 'descripcion' => 'Azucena viva de agua'),
  array('clave' => 10215484 , 'descripcion' => 'Azucena viva de agua bentin'),
  array('clave' => 10215484 , 'descripcion' => 'Azucena viva de agua corva'),
  array('clave' => 10215484 , 'descripcion' => 'Azucena viva de agua')
);

$new_array = array_unique($array, SORT_REGULAR);
echo '<pre>';
print_r($new_array);

This will return:

Array
(
[0] => Array
    (
        [clave] => 10215484
        [descripcion] => Azucena viva de agua
    )

[1] => Array
    (
        [clave] => 10215484
        [descripcion] => Azucena viva de agua bentin
    )

[2] => Array
    (
        [clave] => 10215484
        [descripcion] => Azucena viva de agua corva
    )
)


问:
python - how to compare a key of the dictionary with a string character
I am new to python and I need to compare a character in string with a key in a dictionary. But I am not able to figure out a way to compare that character with a key. I am only able to compare it with the value at dict[key]

I am trying to implement something like this:

```<code>score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
     "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
     "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
     "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
     "x": 8, "z": 10}

def compare(word):
   res = 0
   for letter in word:
       if score[**What should i put in here**] == letter:
          res += score[letter]
   return res
</code>```

where score[key] represents the value at that particular key as a whole. Is there a way to compare a key to the letter, instead of the value?

My aim is to compare the "letter" in "word" with the keys in dictionary and add the values against the characters and return the result.

答: I recognize this problem in the Codecademy: Python course. In the problem you are doing, you must add word = word.lower() at the start of the function. Otherwise, if you check for words containing capital letters, the program will get errors. In other words, "D" is not in the dictionary, but "d" is. Hope this helps.

Body:
I am new to python and I need to compare a character in string with a key in a dictionary. But I am not able to figure out a way to compare that character with a key. I am only able to compare it with the value at dict[key]

I am trying to implement something like this:

score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
     "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
     "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
     "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
     "x": 8, "z": 10}

def compare(word):
   res = 0
   for letter in word:
       if score[**What should i put in here**] == letter:
          res += score[letter]
   return res

where score[key] represents the value at that particular key as a whole. Is there a way to compare a key to the letter, instead of the value?

My aim is to compare the "letter" in "word" with the keys in dictionary and add the values against the characters and return the result.


问:
MySql count(*) super slow with concurrent queries
I have a script that tries to read all the rows from a table like this:

```<code>select count(*) from table where col1 = 'Y' or col1 is null;
</code>```

col1 and col2 are not indexed and this query usually takes ~20 seconds but if someone is already running this query, it takes ages and gets blocked.

We just have around 100k rows in the table and I tried it without the where clause and it causes the same issue.

The table uses InnoDB so, it doesn't store the exact count but I am curious if there is any concurrency parameter I should look into. I am not sure if absence of indexes on the table causes the issue but it doesn't make sense to me.

Thanks!

答:
It looks like your SELECT COUNT(*)... query is being serialized with other operations on your table. Unless you tell the MySQL server otherwise, your query will do its best to be very precise.

Try changing the transaction isolation level by issuing this command immediately before your query.

```<code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
</code>```

Setting this enables so-called dirty reads, which means you might not count everything in the table that changes during your operation. But that probably will not foul up your application too badly.

(Adding appropriate indexes is always a good idea, but not the cause of the problem you ask about.)

Body:
I have a script that tries to read all the rows from a table like this:

select count(*) from table where col1 = 'Y' or col1 is null;

col1 and col2 are not indexed and this query usually takes ~20 seconds but if someone is already running this query, it takes ages and gets blocked.

We just have around 100k rows in the table and I tried it without the where clause and it causes the same issue.

The table uses InnoDB so, it doesn't store the exact count but I am curious if there is any concurrency parameter I should look into. I am not sure if absence of indexes on the table causes the issue but it doesn't make sense to me.

Thanks!

Body:
It looks like your SELECT COUNT(*)... query is being serialized with other operations on your table. Unless you tell the MySQL server otherwise, your query will do its best to be very precise.

Try changing the transaction isolation level by issuing this command immediately before your query.

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

Setting this enables so-called dirty reads, which means you might not count everything in the table that changes during your operation. But that probably will not foul up your application too badly.

(Adding appropriate indexes is always a good idea, but not the cause of the problem you ask about.)


问:
Optimal way of fetching and appending large amount of images on slower connections
At the moment, I'm fetching 100-200 images via ajax-php-mongodb, ajax providing the initial call with parameters, server side php finding the appropriate mongo doc that has the array of all the grid fs file ids of the images, then php fetches the bytes of the images from gridfs, base64 encodes it, stores them all into a php array via loop and echos back the array string to ajax, which calls a function that appends the images.

The problem is on slower connections, especially older 3G conenctions, if the connection breaks halfway through, then the whole ajax request fails for all of the images.

Is there an established way where I could deal with this? I've thought of doing a continuous ajax request that confirms the data received every x/imageAmount times, but I was wondering if there is an established way of doing this, or maybe even a library.

Thanks.

答:
The penalty for doing 100-200 requests is stablishing the TCP connection, so use keep alive to reuse connections.
With keep alive, http headers will be sent per request anyway, so, to compensate that do not do base64.

You can also cache images in memory to reduce latency and mongodb load (gridfs is not too eficient)


问:
Template specialization ambiguity: either specialized or original method may be linked
Look at base::m_visible method in tps.hpp (it's «default»):

```<code>#include <sstream>
#include <iostream>

template <typename T> struct base
{
  void m_log() const;
  void m_visible() const;
};

struct inheritor: base<inheritor>
{
  void log() const;
};

template <typename T> void base<T>::m_log() const
{
  std::ostringstream os;
  m_visible();
  os.str(""); // We have «default/default» if comment here, :-0
  std::cout << os.str();
}

template <typename T> void base<T>::m_visible() const
{
  std::cout
    << "default" << std::endl
  ;
}
</code>```

which specialized for inheritor struct in tps_spec.cpp (named «spec»):

```<code>#include "tps.hpp"

template <> void base<inheritor>::m_visible() const
{
  std::cout
    << "spec" << std::endl
  ;
}

void inheritor::log() const
{
  m_log();
}
</code>```

and further called from tps_main.cpp:

```<code>#include "tps.hpp"

int main(int, char **argv)
{
  std::cout << argv[0] << ": ";
  inheritor().m_log(); // We have «spec/spec» if call inheritor::log
  return 0;
}
</code>```

Result depends on order of compilation units (GCC 4.8.4):

```<code>g++ -Wall -O3 -o tps1 tps_spec.cpp tps_main.cpp && g++ -Wall -O3 -o tps2 tps_main.cpp tps_spec.cpp && ./tps1 ; ./tps2
./tps1: spec
./tps2: default
</code>```

and this happens only with optimization -O3. Any experimental editions, marked by comments yields different results. Why?

答:
Because this is undefined behavior.

If a template is specialized, this specialization must be "visible" everywhere.

You declare and implement the specialization in one translation unit. That specialized template declaration is, basically, completely internal to that translation unit and the specialization is only visible to that translation unit. Your tps_main translation unit has no visibility, and no knowledge whatsoever, of the template specialization; as such linking it together with a different translation unit, that has this template specialization visible, results in undefined behavior.

You need to declare and define (with some exceptions that are not very relevant here) the specialization in the header file, so that every translation unit that includes the header file with the definition of the template will also have the definition of the specialization as well.

A template specialization is not an "implementation" of the template, of some kind, for the specialized template instance. A template specialization is, basically, a completely independent class declaration. Therefore, if you have a translation unit that uses that class, it must have that class declared.

You can't just declare a class in one translation unit, and expect to use it in a different translation unit without the other translation unit seeing that declaration.

Basically, all your translation units that you are linking together must have the same class, object, and template declarations. This includes template specializations.

This is just a round-about way of saying that C++ templates can only be portably defined in header files.

Body:
Look at base::m_visible method in tps.hpp (it's «default»):

#include <sstream>
#include <iostream>

template <typename T> struct base
{
  void m_log() const;
  void m_visible() const;
};

struct inheritor: base<inheritor>
{
  void log() const;
};

template <typename T> void base<T>::m_log() const
{
  std::ostringstream os;
  m_visible();
  os.str(""); // We have «default/default» if comment here, :-0
  std::cout << os.str();
}

template <typename T> void base<T>::m_visible() const
{
  std::cout
    << "default" << std::endl
  ;
}

which specialized for inheritor struct in tps_spec.cpp (named «spec»):

#include "tps.hpp"

template <> void base<inheritor>::m_visible() const
{
  std::cout
    << "spec" << std::endl
  ;
}

void inheritor::log() const
{
  m_log();
}

and further called from tps_main.cpp:

#include "tps.hpp"

int main(int, char **argv)
{
  std::cout << argv[0] << ": ";
  inheritor().m_log(); // We have «spec/spec» if call inheritor::log
  return 0;
}

Result depends on order of compilation units (GCC 4.8.4):

g++ -Wall -O3 -o tps1 tps_spec.cpp tps_main.cpp && g++ -Wall -O3 -o tps2 tps_main.cpp tps_spec.cpp && ./tps1 ; ./tps2
./tps1: spec
./tps2: default

and this happens only with optimization -O3. Any experimental editions, marked by comments yields different results. Why?


问:
Nested each do loops printing unexpectedly in Ruby
I have two arrays containing strings. I'm trying to iterate through both arrays with nested .each do loops to see if any elements in the first array have a substring of any of the elements in the second array. I'm using .include? within the nested loops to check this. I want the result to be the string printed the number of times it matches an element in partials.

This is the method that isn't working

```<code>def orphanCheck(partials, partials1, duplicatesArray)
  partials1.each do |i|
    partials.each do |j|
      if i.include?(j)
        duplicatesArray.push(i)
      end
    end
  end
end
</code>```

I'm using this as a helper method to define partials and partials1

```<code>def manipulate(monthEmails, todayEmails, partials, partials1)
  monthEmails.each do |i|
    email = EmailAddress.new(i.to_s)
    partials.push(email.host_name.to_s)
  end
  todayEmails.each do |j|
    todaySignup = j.to_s.slice(11, 100)
    partials1.push(todaySignup)
  end
end
</code>```

And then I'm calling the two with the following

```<code>manipulate(allUnique, todayEmails, partials, partials1)

orphanCheck(partials, partials1, duplicatesArray)
#puts duplicatesArray
</code>```

duplicatesArray is printing some strings that shouldn't be matches and it's printing some strings more times than I want. For example, gmail.com isn't in partials at all but me@gmail.com, which is in partials1 once, is being pushed to duplicatesArray three times. If yahoo.com is in partials three times, then I would want me@yahoo.com (from partials1) to be pushed to duplicatesArray three times, for example.

答:
To be sure you could be doing:

```<code>  partials1.each do |i|
    i_ups=i.split('@')[-1]
    partials.each do |j|
      if i_ups===j
        duplicatesArray.push(i)
        break
      end
    end
  end
</code>```

If I understood correctly (partials is only the host part of the email provider and partials1 is the full email address)

Body:
I have two arrays containing strings. I'm trying to iterate through both arrays with nested .each do loops to see if any elements in the first array have a substring of any of the elements in the second array. I'm using .include? within the nested loops to check this. I want the result to be the string printed the number of times it matches an element in partials.

This is the method that isn't working

def orphanCheck(partials, partials1, duplicatesArray)
  partials1.each do |i|
    partials.each do |j|
      if i.include?(j)
        duplicatesArray.push(i)
      end
    end
  end
end

I'm using this as a helper method to define partials and partials1

def manipulate(monthEmails, todayEmails, partials, partials1)
  monthEmails.each do |i|
    email = EmailAddress.new(i.to_s)
    partials.push(email.host_name.to_s)
  end
  todayEmails.each do |j|
    todaySignup = j.to_s.slice(11, 100)
    partials1.push(todaySignup)
  end
end

And then I'm calling the two with the following

manipulate(allUnique, todayEmails, partials, partials1)

orphanCheck(partials, partials1, duplicatesArray)
#puts duplicatesArray

duplicatesArray is printing some strings that shouldn't be matches and it's printing some strings more times than I want. For example, gmail.com isn't in partials at all but me@gmail.com, which is in partials1 once, is being pushed to duplicatesArray three times. If yahoo.com is in partials three times, then I would want me@yahoo.com (from partials1) to be pushed to duplicatesArray three times, for example.

Body:
To be sure you could be doing:

  partials1.each do |i|
    i_ups=i.split('@')[-1]
    partials.each do |j|
      if i_ups===j
        duplicatesArray.push(i)
        break
      end
    end
  end

If I understood correctly (partials is only the host part of the email provider and partials1 is the full email address)


问:
Error connecting to MySQL Server with Hibernate 5 and JPA
I am upgrading to Hibernate 5 and JPA and having trouble connecting to MySQL Server 5.7.18 (Java 8, ojdbc8). Using mysql from the command line I can connect and access the database just fine so I know the server is up, and the user/passwords are correct. The PeopleEntity.class uses annotations rather than a mapping file.

The exception is "Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]". I have tried both "jdbc:oracle:thin:@localhost:3306:TestHibernate" and "jdbc:mysql://localhost:3306/TestHibernate"

Any suggestions for how to correct the problem would be appreciated.

```<code>final Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.jdbc.user", LoginInfo.getLoginInfo().getUsername());
properties.put("javax.persistence.jdbc.password", LoginInfo.getLoginInfo().getPassword());
properties.put("javax.persistence.jdbc.url", "jdbc:oracle:thin:@localhost:3306:TestHibernate");
// or
properties.put("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/TestHibernate");
try {
    Persistence.createEntityManagerFactory("PeopleEntity", properties);
} catch (final PersistenceException error) {
    Logger.error(getClass(), error.getMessage());
}
</code>```

From persistence.xml

```<code><persistence
    xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
    version="2.1">

    <persistence-unit
        name="PeopleEntity"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.billsdesk.util.hibernate.tests.PeopleEntity</class>
        <properties>
            <property
                name="hibernate.connection.driver_class"
                value="com.mysql.jdbc.Driver"></property>
            <property
                name="javax.persistence.jdbc.driver"
                value="oracle.jdbc.OracleDriver"></property>
            <property
                name="hibernate.dialect"
                value="org.hibernate.dialect.MySQL5Dialect" />

            <!-- URL, user, and password are passed as properties -->

        </properties>
    </persistence-unit>
</persistence>
</code>```

From the pom.xml

```<code><dependencies>

    <!-- Hibernate -->

    <dependency>
        <groupId>com.oracle.jdbc</groupId>
        <artifactId>ojdbc8</artifactId>
        <version>12.2.0.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.10.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>persistence-api</artifactId>
        <version>1.0.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.8.2</version>
    </dependency>
</dependencies>
</code>```

The Hibernate trace

```<code>14:00:45.861 [main] INFO  org.hibernate.Version - HHH000412: Hibernate Core {5.2.10.Final}
14:00:45.862 [main] INFO  org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
14:00:45.910 [main] INFO  org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
14:00:46.088 [main] WARN  org.hibernate.orm.connections.pooling - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
14:00:46.127 [main] INFO  org.hibernate.orm.connections.pooling - HHH10001005: using driver [oracle.jdbc.OracleDriver] at URL [jdbc:oracle:thin:@localhost:3306:TestHibernate]
14:00:46.127 [main] INFO  org.hibernate.orm.connections.pooling - HHH10001001: Connection properties: {user=sa, password=****}
14:00:46.128 [main] INFO  org.hibernate.orm.connections.pooling - HHH10001003: Autocommit mode: false
14:00:46.130 [main] INFO  org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 20 (min=1)
2017-07-06 14:00:46 SEVERE Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
</code>```

答:
Despite the fact that MySQL is a product of Oracle Corporation, the "Oracle" database product and the "MySQL" database product are two very different creatures. Using an "Oracle" JDBC driver is never going to work with a MySQL database server.

As a minimal implementation, I got the following to work with just four (4) files. It may not be the "best" or the most "modern" way of doing it, but it did work for me.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.demo</groupId>
  <artifactId>so44959525</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>
  </dependencies>
</project>
```

<p><strong>src/main/resources/hibernate.cfg.xml</strong></p>

<pre class="lang-xml prettyprint-override"><code><?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection properties -->
        <property name="connection.url">jdbc:mysql://localhost:3307/mydb</property>
        <property name="connection.username">root</property>
        <property name="connection.password">whatever</property>
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!--
        Automatic schema generation. Possible values:

        none (default value), create-only, drop, create, create-drop, validate, and update

        https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl
        -->
        <property name="hbm2ddl.auto">create</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="format_sql">false</property>

        <mapping class="com.example.demo.Person"/>

    </session-factory>

</hibernate-configuration>
</code>```

src/main/java/com/example/demo/Person.java

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    public int getId() { return id; }

    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public Person() {
        // no-argument constructor required by Hibernate
    }

    public Person (String name) {
        this.name = name;
    }
}
```

<p><strong>src/main/java/com/example/demo/DemoMain.java</strong></p>

<pre class="lang-java prettyprint-override"><code>package com.example.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class DemoMain {

    public static void main(String[] args) {
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try (SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory()) {
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            for (String newGuy : new String[] { "Rodd", "Todd" }) {
                int newId = (int) session.save(new Person(newGuy));
                System.out.printf("\"%s\" inserted as id %d%n", newGuy, newId);
            }
            session.getTransaction().commit();
            session.close();
        } catch (Exception e) {
            e.printStackTrace(System.err);
        } finally {
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }

}
</code>```

Body:
I am upgrading to Hibernate 5 and JPA and having trouble connecting to MySQL Server 5.7.18 (Java 8, ojdbc8). Using mysql from the command line I can connect and access the database just fine so I know the server is up, and the user/passwords are correct. The PeopleEntity.class uses annotations rather than a mapping file.

The exception is "Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]". I have tried both "jdbc:oracle:thin:@localhost:3306:TestHibernate" and "jdbc:mysql://localhost:3306/TestHibernate"

Any suggestions for how to correct the problem would be appreciated.

final Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.jdbc.user", LoginInfo.getLoginInfo().getUsername());
properties.put("javax.persistence.jdbc.password", LoginInfo.getLoginInfo().getPassword());
properties.put("javax.persistence.jdbc.url", "jdbc:oracle:thin:@localhost:3306:TestHibernate");
// or
properties.put("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/TestHibernate");
try {
    Persistence.createEntityManagerFactory("PeopleEntity", properties);
} catch (final PersistenceException error) {
    Logger.error(getClass(), error.getMessage());
}

From persistence.xml

<persistence
    xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
    version="2.1">

    <persistence-unit
        name="PeopleEntity"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.billsdesk.util.hibernate.tests.PeopleEntity</class>
        <properties>
            <property
                name="hibernate.connection.driver_class"
                value="com.mysql.jdbc.Driver"></property>
            <property
                name="javax.persistence.jdbc.driver"
                value="oracle.jdbc.OracleDriver"></property>
            <property
                name="hibernate.dialect"
                value="org.hibernate.dialect.MySQL5Dialect" />

        </properties>
    </persistence-unit>
</persistence>

From the pom.xml

<dependencies>

    <dependency>
        <groupId>com.oracle.jdbc</groupId>
        <artifactId>ojdbc8</artifactId>
        <version>12.2.0.1</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.10.Final</version>
    </dependency>

    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>persistence-api</artifactId>
        <version>1.0.2</version>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.8.2</version>
    </dependency>
</dependencies>

The Hibernate trace

14:00:45.861 [main] INFO  org.hibernate.Version - HHH000412: Hibernate Core {5.2.10.Final}
14:00:45.862 [main] INFO  org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
14:00:45.910 [main] INFO  org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
14:00:46.088 [main] WARN  org.hibernate.orm.connections.pooling - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
14:00:46.127 [main] INFO  org.hibernate.orm.connections.pooling - HHH10001005: using driver [oracle.jdbc.OracleDriver] at URL [jdbc:oracle:thin:@localhost:3306:TestHibernate]
14:00:46.127 [main] INFO  org.hibernate.orm.connections.pooling - HHH10001001: Connection properties: {user=sa, password=****}
14:00:46.128 [main] INFO  org.hibernate.orm.connections.pooling - HHH10001003: Autocommit mode: false
14:00:46.130 [main] INFO  org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 20 (min=1)
2017-07-06 14:00:46 SEVERE Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Body:
Despite the fact that MySQL is a product of Oracle Corporation, the "Oracle" database product and the "MySQL" database product are two very different creatures. Using an "Oracle" JDBC driver is never going to work with a MySQL database server.

As a minimal implementation, I got the following to work with just four (4) files. It may not be the "best" or the most "modern" way of doing it, but it did work for me.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.demo</groupId>
  <artifactId>so44959525</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>
  </dependencies>
</project>

src/main/resources/hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection properties -->
        <property name="connection.url">jdbc:mysql://localhost:3307/mydb</property>
        <property name="connection.username">root</property>
        <property name="connection.password">whatever</property>
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!--
        Automatic schema generation. Possible values:

        none (default value), create-only, drop, create, create-drop, validate, and update

        https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl
        -->
        <property name="hbm2ddl.auto">create</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="format_sql">false</property>

        <mapping class="com.example.demo.Person"/>

    </session-factory>

</hibernate-configuration>

src/main/java/com/example/demo/Person.java

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    public int getId() { return id; }

    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public Person() {
        // no-argument constructor required by Hibernate
    }

    public Person (String name) {
        this.name = name;
    }
}

src/main/java/com/example/demo/DemoMain.java

package com.example.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class DemoMain {

    public static void main(String[] args) {
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try (SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory()) {
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            for (String newGuy : new String[] { "Rodd", "Todd" }) {
                int newId = (int) session.save(new Person(newGuy));
                System.out.printf("\"%s\" inserted as id %d%n", newGuy, newId);
            }
            session.getTransaction().commit();
            session.close();
        } catch (Exception e) {
            e.printStackTrace(System.err);
        } finally {
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }

}


问:
Forward slash (/) character in SAP Vora table columns
I've got data from a SAP BW InfoProvider written to HDFS. Now I'm trying to make that data available for reporting in Vora 1.3.

I'm trying to run a statement in Vora Tools SQL console, starting with:

```<code>CREATE TABLE F002_5_F (calyear string,
    calmonth string,
    /bic/zfiscweek string,
    doc_currcy string,
    co_area string,
    /bic/zbillamt decimal(17,2),
    ......)
USING com.sap.spark.vora
OPTIONS (.....
</code>```

And upon execution Vora reports a syntax error in lines for fields with names containing "/bic/" part.
As a workaround, I tried quoting field names, e.g. "/bic/zfiscweek". But then Vora reported a syntax error in the line "USING com.sap.spark.vora".

Any comment on how field names with "/" character should be treated in Vora modelling?

答:
Try surrounding the column names with backticks.

```<code>CREATE TABLE SLASHTABLE (`/A1` double, `/A2` int, `/A3` string)
USING com.sap.spark.vora
OPTIONS (files "/user/vora/test.csv");
</code>```

This also works in SELECT queries:

```<code>SELECT `/A1` from SLASHTABLE;
</code>```

Body:
I've got data from a SAP BW InfoProvider written to HDFS. Now I'm trying to make that data available for reporting in Vora 1.3.

I'm trying to run a statement in Vora Tools SQL console, starting with:

CREATE TABLE F002_5_F (calyear string,
    calmonth string,
    /bic/zfiscweek string,
    doc_currcy string,
    co_area string,
    /bic/zbillamt decimal(17,2),
    ......)
USING com.sap.spark.vora
OPTIONS (.....

And upon execution Vora reports a syntax error in lines for fields with names containing "/bic/" part.
As a workaround, I tried quoting field names, e.g. "/bic/zfiscweek". But then Vora reported a syntax error in the line "USING com.sap.spark.vora".

Any comment on how field names with "/" character should be treated in Vora modelling?

Body:
Try surrounding the column names with backticks.

CREATE TABLE SLASHTABLE (`/A1` double, `/A2` int, `/A3` string)
USING com.sap.spark.vora
OPTIONS (files "/user/vora/test.csv");

This also works in SELECT queries:

SELECT `/A1` from SLASHTABLE;


问:
Add Tooltip to Tabs in Shiny
I am trying to add tooltips/popovers using the shinyBS package for a Shiny application but am having an issue due to tabs don't have input/ids. This is preventing the tooltip from firing. Any thoughts?

```<code>library(shiny)
library(shinyBS)

    shinyApp(
      ui = tagList(
         navbarPage(
           theme = "cerulean",  # <--- To use a theme, uncomment this
          "shinythemes",
          tabPanel(id="test","Navbar 1",
                   bsTooltip("test", title="Test Title", trigger = "hover"),
                   sidebarPanel(
                     fileInput("file", "File input:"),
                     textInput("txt", "Text input:", "general"),
                     sliderInput("slider", "Slider input:", 1, 100, 30),
                     tags$h5("Deafult actionButton:"),
                     actionButton("action", "Search"),

                     tags$h5("actionButton with CSS class:"),
                     actionButton("action2", "Action button", class = "btn-primary")
                   ),
                   mainPanel(
                     tabsetPanel(
                       tabPanel("Tab 1",
                                bsTooltip("Tab 1", title="Test Title"),
                                h4("Table"),
                                tableOutput("table"),
                                h4("Verbatim text output"),
                                verbatimTextOutput("txtout"),
                                h1("Header 1"),
                                h2("Header 2"),
                                h3("Header 3"),
                                h4("Header 4"),
                                h5("Header 5")
                       ),
                       tabPanel("Tab 2"),
                       tabPanel("Tab 3")
                     )
                   )
          ),
          tabPanel("Navbar 2"),
          tabPanel("Navbar 3")
        )
      ),
      server = function(input, output) {
        output$txtout <- renderText({
          paste(input$txt, input$slider, format(input$date), sep = ", ")
        })
        output$table <- renderTable({
          head(cars, 4)
        })
      }
    )
</code>```

Attached is a test application using TabPanels and Tabset Panels for testing.

答:
Here is a minimal example that adds a tooltip to forst tab

```<code>library(shiny)
library(shinyBS)

shinyApp(
  ui = tagList(
    navbarPage(
      theme = "cerulean",  # <--- To use a theme, uncomment this
      "shinythemes",
      tabPanel(id="test","Navbar 1",
               bsTooltip("test", title="Test Title", trigger = "hover"),
               sidebarPanel(
                 fileInput("file", "File input:"),
                 textInput("txt", "Text input:", "general"),
                 sliderInput("slider", "Slider input:", 1, 100, 30),
                 tags$h5("Deafult actionButton:"),
                 actionButton("action", "Search"),

                 tags$h5("actionButton with CSS class:"),
                 actionButton("action2", "Action button", class = "btn-primary")
               ),
               mainPanel(
                 tabsetPanel(
                   tabPanel("Tab 1",
                            bsTooltip("Tab 1", title="Test Title"),
                            div(id = "my_id",                       #changed
                                h4("Table"),
                                tableOutput("table"),
                                h4("Verbatim text output"),
                                verbatimTextOutput("txtout"),
                                h1("Header 1"),
                                h2("Header 2"),
                                h3("Header 3"),
                                h4("Header 4"),
                                h5("Header 5")
                            ),                                      # changed
                            bsTooltip('my_id','some text...')       # changed
                   ),
                   tabPanel("Tab 2"),
                   tabPanel("Tab 3")
                 )
               )
      ),
      tabPanel("Navbar 2"),
      tabPanel("Navbar 3")
    )
  ),
  server = function(input, output) {
    output$txtout <- renderText({
      paste(input$txt, input$slider, format(input$date), sep = ", ")
    })
    output$table <- renderTable({
      head(cars, 4)
    })
  }
)
</code>```

As you can see, I have only changed 3 lines

The first and the second line wraps the contents of the first tab inside a div. The div has an id my_id which will be used later

The third line adds the tooltip by using the div id

Basycally, you should be able to wrap whatever content you want into a div, give it an id and then add a popover. If you run into any problems with this approach, please let me know.

Title: Add Tooltip to Tabs in Shiny

Body:
I am trying to add tooltips/popovers using the shinyBS package for a Shiny application but am having an issue due to tabs don't have input/ids. This is preventing the tooltip from firing. Any thoughts?

library(shiny)
library(shinyBS)

    shinyApp(
      ui = tagList(
         navbarPage(
           theme = "cerulean",  # <--- To use a theme, uncomment this
          "shinythemes",
          tabPanel(id="test","Navbar 1",
                   bsTooltip("test", title="Test Title", trigger = "hover"),
                   sidebarPanel(
                     fileInput("file", "File input:"),
                     textInput("txt", "Text input:", "general"),
                     sliderInput("slider", "Slider input:", 1, 100, 30),
                     tags$h5("Deafult actionButton:"),
                     actionButton("action", "Search"),

                     tags$h5("actionButton with CSS class:"),
                     actionButton("action2", "Action button", class = "btn-primary")
                   ),
                   mainPanel(
                     tabsetPanel(
                       tabPanel("Tab 1",
                                bsTooltip("Tab 1", title="Test Title"),
                                h4("Table"),
                                tableOutput("table"),
                                h4("Verbatim text output"),
                                verbatimTextOutput("txtout"),
                                h1("Header 1"),
                                h2("Header 2"),
                                h3("Header 3"),
                                h4("Header 4"),
                                h5("Header 5")
                       ),
                       tabPanel("Tab 2"),
                       tabPanel("Tab 3")
                     )
                   )
          ),
          tabPanel("Navbar 2"),
          tabPanel("Navbar 3")
        )
      ),
      server = function(input, output) {
        output$txtout <- renderText({
          paste(input$txt, input$slider, format(input$date), sep = ", ")
        })
        output$table <- renderTable({
          head(cars, 4)
        })
      }
    )

Attached is a test application using TabPanels and Tabset Panels for testing.

Body:
Here is a minimal example that adds a tooltip to forst tab

library(shiny)
library(shinyBS)

shinyApp(
  ui = tagList(
    navbarPage(
      theme = "cerulean",  # <--- To use a theme, uncomment this
      "shinythemes",
      tabPanel(id="test","Navbar 1",
               bsTooltip("test", title="Test Title", trigger = "hover"),
               sidebarPanel(
                 fileInput("file", "File input:"),
                 textInput("txt", "Text input:", "general"),
                 sliderInput("slider", "Slider input:", 1, 100, 30),
                 tags$h5("Deafult actionButton:"),
                 actionButton("action", "Search"),

                 tags$h5("actionButton with CSS class:"),
                 actionButton("action2", "Action button", class = "btn-primary")
               ),
               mainPanel(
                 tabsetPanel(
                   tabPanel("Tab 1",
                            bsTooltip("Tab 1", title="Test Title"),
                            div(id = "my_id",                       #changed
                                h4("Table"),
                                tableOutput("table"),
                                h4("Verbatim text output"),
                                verbatimTextOutput("txtout"),
                                h1("Header 1"),
                                h2("Header 2"),
                                h3("Header 3"),
                                h4("Header 4"),
                                h5("Header 5")
                            ),                                      # changed
                            bsTooltip('my_id','some text...')       # changed
                   ),
                   tabPanel("Tab 2"),
                   tabPanel("Tab 3")
                 )
               )
      ),
      tabPanel("Navbar 2"),
      tabPanel("Navbar 3")
    )
  ),
  server = function(input, output) {
    output$txtout <- renderText({
      paste(input$txt, input$slider, format(input$date), sep = ", ")
    })
    output$table <- renderTable({
      head(cars, 4)
    })
  }
)

As you can see, I have only changed 3 lines

The first and the second line wraps the contents of the first tab inside a div. The div has an id my_id which will be used later

The third line adds the tooltip by using the div id

Basycally, you should be able to wrap whatever content you want into a div, give it an id and then add a popover. If you run into any problems with this approach, please let me know.


问:
How to scale down an astroid
I'm working on a assignment to generate 2 astroids (Not Asteroids) on a 400x400 Display Panel. Via a method called "drawAstroids", I was able to make the first one, but I'm having some trouble making the 2nd one. Instead of making the following:
2 astroids
This is what's happening:
1 astroid and one yuck!

I thought I could just change the scale an size settings with the second method, but I can't seem to make the 2nd one look like a smaller version of the 1st one. This is my code so far. Any tips as to how to resolve this issue would be greatly appreciated.

```<code>import java.awt.*;

public class GraphicsProject
{

    //main method
   public static void main (String[]args){
    //Initialize the variable
    //The Window is 400 x 400 pixels in size
    DrawingPanel panel = new DrawingPanel (400,400);
    panel.setBackground(Color.BLACK);
    Graphics g = panel.getGraphics();
    g.setColor(Color.GREEN);
    drawAstroid1(g,0,0,400);
    g.setColor(Color.BLUE);
    drawAstroid2(g,0,0,200);
    }

   public static void drawAstroid1(Graphics g, int x, int y, int size){
       int scale = size/40;

       for (int i = 0; i <= 20; i++ ){
           g.drawLine(x + size/2, y + scale * i, size/2 + scale * i, size/2);
           g.drawLine(x + size/2, y + scale * i, 200 - scale * i, size/2);
           g.drawLine(x + size/2, size - scale * i, 200 - scale * i, size/2);
           g.drawLine(x + size/2, size - scale * i, size/2 + scale * i, size/2);

        }
    }
   public static void drawAstroid2(Graphics g, int x, int y, int size){
       int scale = size/40;

       for (int i = 0; i <= 20; i++ ){
           g.drawLine(x + size/2, y + scale * i, size/2 + scale * i, size/2);
           g.drawLine(x + size/2, y + scale * i, 200 - scale * i, size/2);
           g.drawLine(x + size/2, size - scale * i, 200 - scale * i, size/2);
           g.drawLine(x + size/2, size - scale * i, size/2 + scale * i, size/2);

        }
    }
}
</code>```

答: I think your problem stems from the hardcoded value of 200. Your images are different sizes, and the x coordinate that represents the horizontal center of the image changes with size. If you replace the 200 with an expression that gives you the center x coordinate considering the size of the image, you should get a better result. You should also ask yourself why you are passing in x and y values to your two methods, and what you are doing with them -- in particular why the x and y are only added to the first coordinate in each line.</p>

Title: How to scale down an astroid

Body:
I'm working on a assignment to generate 2 astroids (Not Asteroids) on a 400x400 Display Panel. Via a method called "drawAstroids", I was able to make the first one, but I'm having some trouble making the 2nd one. Instead of making the following:
2 astroids
This is what's happening:
1 astroid and one yuck!

I thought I could just change the scale an size settings with the second method, but I can't seem to make the 2nd one look like a smaller version of the 1st one. This is my code so far. Any tips as to how to resolve this issue would be greatly appreciated.

import java.awt.*;

public class GraphicsProject
{

    //main method
   public static void main (String[]args){
    //Initialize the variable
    //The Window is 400 x 400 pixels in size
    DrawingPanel panel = new DrawingPanel (400,400);
    panel.setBackground(Color.BLACK);
    Graphics g = panel.getGraphics();
    g.setColor(Color.GREEN);
    drawAstroid1(g,0,0,400);
    g.setColor(Color.BLUE);
    drawAstroid2(g,0,0,200);
    }

   public static void drawAstroid1(Graphics g, int x, int y, int size){
       int scale = size/40;

       for (int i = 0; i <= 20; i++ ){
           g.drawLine(x + size/2, y + scale * i, size/2 + scale * i, size/2);
           g.drawLine(x + size/2, y + scale * i, 200 - scale * i, size/2);
           g.drawLine(x + size/2, size - scale * i, 200 - scale * i, size/2);
           g.drawLine(x + size/2, size - scale * i, size/2 + scale * i, size/2);

        }
    }
   public static void drawAstroid2(Graphics g, int x, int y, int size){
       int scale = size/40;

       for (int i = 0; i <= 20; i++ ){
           g.drawLine(x + size/2, y + scale * i, size/2 + scale * i, size/2);
           g.drawLine(x + size/2, y + scale * i, 200 - scale * i, size/2);
           g.drawLine(x + size/2, size - scale * i, 200 - scale * i, size/2);
           g.drawLine(x + size/2, size - scale * i, size/2 + scale * i, size/2);

        }
    }
}


问:
Is there a difference between these TimeSpan methods?
Are these statements syntactically the same and perform the same ?
Which is preferable?

```<code>TimeSpan ts = TimeSpan.FromTicks(100000);
</code>```

or

```<code>TimeSpan ts = new TimeSpan(100000);
</code>```

答:
There is no difference between them. The static method initialize new instance using the following constructor.

TimeSpan(Int64) which initializes a new instance of the TimeSpan structure to the specified number of ticks.

```<code>[__DynamicallyInvokable]
public static TimeSpan FromTicks(long value)
{
    return new TimeSpan(value);
}
</code>```

Body:
Are these statements syntactically the same and perform the same ?
Which is preferable?

TimeSpan ts = TimeSpan.FromTicks(100000);

or

TimeSpan ts = new TimeSpan(100000);

Body:
There is no difference between them. The static method initialize new instance using the following constructor.

TimeSpan(Int64) which initializes a new instance of the TimeSpan structure to the specified number of ticks.

[__DynamicallyInvokable]
public static TimeSpan FromTicks(long value)
{
    return new TimeSpan(value);
}


问:
How to add Jsoup to my Android Studio project?
I am trying to use jsoup in my android studio project but i keep getting this error: Error:(10, 16) Gradle: error: package org.jsoup does not exist.

Could you guys tell me the steps on how to add jsoup library to my project? Thanks in advance.

Edit: For learning purpuse i am running the java code alone without main activity!

code:

```<code>package com.jsoupTest.jsoupTest;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.UnsupportedMimeTypeException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class JsoupGetRequest {

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

        String dc=Jsoup.connect("http://somelink.com").timeout(6000).get();
        System.out.println(dc);
    }

}
</code>```

答:
You should add your dependencies in your build.gradle file.
Please check the screenshot attached.

Body:
I am trying to use jsoup in my android studio project but i keep getting this error: Error:(10, 16) Gradle: error: package org.jsoup does not exist.

Could you guys tell me the steps on how to add jsoup library to my project? Thanks in advance.

Edit: For learning purpuse i am running the java code alone without main activity!

code:

package com.jsoupTest.jsoupTest;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.UnsupportedMimeTypeException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class JsoupGetRequest {

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

        String dc=Jsoup.connect("http://somelink.com").timeout(6000).get();
        System.out.println(dc);
    }

}


问:
Does LinkedHashMap#put keep order when key is override? (JAVA)
Here would be a LinkedHashMap, imagine it had many values inside of it.

LinkedHashMap map = new LinkedHashMap<>();

My question is, if one of the existing values was, for example, at index 4 and the same key was .put into the map, will it simply replace the value and remain at 4? Or, will it add onto the end?

答:
The documentation of LinkedHashMap explicitly points this out:

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

So the value is replaced, but the iteration order will remain the same. For your example, the entry with key 4 will remain at the same position for the iteration.


问:
EC2 Instance Types with Fastest Download Speed
I'm looking for the most appropriate EC2 Instance Type to download large files at a fast rate. There are several options of Network performances, and I'm leaning towards "Up to 10 Gigabit" or "10 Gigabit". Is there a recommended Model with this networking performance options that best fit the requirement? Would it be possible to download 4~6GB files in under an hour?</p>

答:
Network bandwidth available to an Amazon EC2 instance is based upon the Instance Type. Basically, larger instances have more bandwidth.

Instances that show 10+ Gigabit networking only provide this bandwidth within the same Placement Group, which is within one Availability Zone. It does not apply to Internet bandwidth.

You should create a test that you can run on various instance types to determine the throughput. Preferably multi-thread such tests so that you are fully-utilizing available bandwidth.

You should also experiment with running multiple, smaller instances because they might have more aggregate bandwidth than fewer, larger instances.


问:
Android Bluetooth LE - Read float characteristic
I am trying to read the float characteristic of a connected Bluetooth LE device(Genuino 101). For testing purposes, the device provides a FloatCharacteristic with the hardcoded Value '55.3'. While I am able to receive a string that somehow resembles the float, I cannot read an actual float value.

Here's the code fragment that handles a string:

```<code>// For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for(byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
        }
</code>```

this is copied straight from the https://developer.android.com/samples/BluetoothLeGatt/index.html BLE demo project from the android developer homepage.
The intent is then handled by this snippet:

```<code>private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("Broadcast received");
        final String action = intent.getAction();
        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {

        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {

        } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {

        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
           displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

private void displayData(String data) {
    if (data != null) {
        System.out.println("Data Received: " + data);
    }
}
</code>```

Which leads to the output

```<code>I/System.out: Data Received: 33]B
I/System.out: 33 33 5D 42
</code>```

So, set aside the swapped endianness, this is the correct hex value for 55.3f.

However, if I try to use characteristic.getFloatValue(), I only get garbage. Here's how I tried figuring out how to receive an actual float:

```<code>final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            for (int i = 0; i< 333; i++) {
                try {
                    final float fData = characteristic.getFloatValue(BluetoothGattCharacteristic.FORMAT_FLOAT, i);
                    System.out.println("Offset = "+ i + ". Data that gets sent: " + fData + "/Data that we would expect: " + 55.3f);
                } catch (Exception e) {
                    System.out.println("Exception at offset " + i);
                }
            }
        }
</code>```

the output is always

```<code>I/System.out: Offset = 0. Data that gets sent: Infinity/Data that we would expect: 55.3
I/System.out: Exception at offset 1
I/System.out: Exception at offset 2
...
</code>```

What is my mistake here? Also, I'm not sure how the Offset parameter should be understood. Is it the offset in bit, in byte? Counting from MSB, from LSB?
Also the documentation of getFloatValue() claims "returns float - Cached value of the characteristic at a given offset or null if the requested offset exceeds the value size. ". But the above snippet grossly exceeds the maximum size of any gatt characteristic, yet instead of returning 'null', the method call throws exceptions.
So what's the correct way to get a float here?

答:
For the time being, I helped myself by formatting the data with </p>

```<code> float f1 = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getFloat();
</code>```

<p>.</p>

Body:
I am trying to read the float characteristic of a connected Bluetooth LE device(Genuino 101). For testing purposes, the device provides a FloatCharacteristic with the hardcoded Value '55.3'. While I am able to receive a string that somehow resembles the float, I cannot read an actual float value.

Here's the code fragment that handles a string:

// For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for(byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
        }

this is copied straight from the https://developer.android.com/samples/BluetoothLeGatt/index.html BLE demo project from the android developer homepage.
The intent is then handled by this snippet:

private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("Broadcast received");
        final String action = intent.getAction();
        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {

        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {

        } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {

        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
           displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

private void displayData(String data) {
    if (data != null) {
        System.out.println("Data Received: " + data);
    }
}

Which leads to the output

I/System.out: Data Received: 33]B
I/System.out: 33 33 5D 42

So, set aside the swapped endianness, this is the correct hex value for 55.3f.

However, if I try to use characteristic.getFloatValue(), I only get garbage. Here's how I tried figuring out how to receive an actual float:

final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            for (int i = 0; i< 333; i++) {
                try {
                    final float fData = characteristic.getFloatValue(BluetoothGattCharacteristic.FORMAT_FLOAT, i);
                    System.out.println("Offset = "+ i + ". Data that gets sent: " + fData + "/Data that we would expect: " + 55.3f);
                } catch (Exception e) {
                    System.out.println("Exception at offset " + i);
                }
            }
        }

the output is always

I/System.out: Offset = 0. Data that gets sent: Infinity/Data that we would expect: 55.3
I/System.out: Exception at offset 1
I/System.out: Exception at offset 2
...

What is my mistake here? Also, I'm not sure how the Offset parameter should be understood. Is it the offset in bit, in byte? Counting from MSB, from LSB?
Also the documentation of getFloatValue() claims "returns float - Cached value of the characteristic at a given offset or null if the requested offset exceeds the value size. ". But the above snippet grossly exceeds the maximum size of any gatt characteristic, yet instead of returning 'null', the method call throws exceptions.
So what's the correct way to get a float here?

Body:
For the time being, I helped myself by formatting the data with

 float f1 = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getFloat();

.


答:
From the reference:

TimeSpan.FromTicks Method (Int64)

This is a convenience method with the same behavior as the TimeSpan.TimeSpan(Int64) constructor. A single tick represents
  one hundred nanoseconds or one ten-millionth of a second. There are
  10,000 ticks in a millisecond.

Title: Is there a difference between these TimeSpan methods?


问:
Get current object on has_many side when saving
I am creating an Event that has many Equipments. I want to validate the Equipment model. How can I access the equipment's event that I am currently saving? I need that to get the date when the equipment will be used(date is known from Event model). Here is the code:</p>

```<code>class Event < ApplicationRecord
    has_many :equipment_events, class_name: EquipmentEvent
    has_many :equipment, through: :equipment_events
end

class Equipment < ApplicationRecord
    has_many :equipment_events
    has_many :events, through: :equipment_events

    validate :equipment_already_used

  def equipment_already_used
     date = # <== HERE I need the date from this equipment's event that I am saving
  end

end
</code>```

答:
You need to move the validation from Equipment to EquipmentEvent, since Equipment and Event are independent entities.</p>

```<code>class EquipmentEvent < ApplicationRecord

  belongs_to :equipment
  belongs_to :event

  validate :equipment_already_used

  def equipment_already_used
    event.date # <== HERE
  end

end
</code>```

Body:
I am creating an Event that has many Equipments. I want to validate the Equipment model. How can I access the equipment's event that I am currently saving? I need that to get the date when the equipment will be used(date is known from Event model). Here is the code:

class Event < ApplicationRecord
    has_many :equipment_events, class_name: EquipmentEvent
    has_many :equipment, through: :equipment_events
end

class Equipment < ApplicationRecord
    has_many :equipment_events
    has_many :events, through: :equipment_events

    validate :equipment_already_used

  def equipment_already_used
     date = # <== HERE I need the date from this equipment's event that I am saving
  end

end

Body:
You need to move the validation from Equipment to EquipmentEvent, since Equipment and Event are independent entities.

class EquipmentEvent < ApplicationRecord

  belongs_to :equipment
  belongs_to :event

  validate :equipment_already_used

  def equipment_already_used
    event.date # <== HERE
  end

end


问:
Check if there are out of stock items in cart - WooCommerce
I need to display a section in my checkout order review ONLY IF there is an out of stock item in the cart (b/c our products are available on backorder). Here is the code that displays the section...

Functions.php:

```<code>function notes_in_cart() {
    global $woocommerce;
       if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }
    if ( WC()->cart->needs_shipping() ){
        //if cart has items out of stock
        //if (cart has out of stock product) {
        ?>
            <tr class="ceckoutStockMeta">
                <th>Item Shipments</th>

                <td>
                    <p style="color: red;">*You have one or more items in your cart that are currently out of stock. Please select a custom shipping option for your order.</p><br>
                    <form>

                        <input type="radio" name="stockOp" id="stockOption1" value="ship" />
                        <label for="stockOption1">Ship what is available now</label><br>

                        <input type="radio" name="stockOp" id="stockOption2" value="hold" />
                        <label for="stockOption2">Wait and ship together</label>
                    </form>
                </td>
            </tr>

        <?php

        //}
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'notes_in_cart' );
add_action( 'woocommerce_review_order_after_order_total', 'notes_in_cart' );
</code>```

Right now the section shows all the time. I know I will probably need to call the cart items and loop through with a foreach to determine if one is out of stock, but not sure how.

答:
Updated: As all your products are available on backorders, the only efficient way is to check in a foreach loop if the stock quantity "is sufficient" for each cart item quantity...

If the stock quantity of the product is smaller than the cart item quantity (WC displays "available on backorder"), then your "shipment note" is displayed.

Here is that code:

```<code>function notes_in_cart() {

    if ( ! $_POST || ( is_admin() && is_ajax() ) ){
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }

    // Loop that check if cart items have enough stock quantity
    $is_available_on_backorder = false;
    foreach ( WC()->cart->get_cart() as $item_values ) {

        $stock_qty = $item_values['data']->get_stock_quantity(); // Product stock
        $item_qty = $item_values['quantity']; // Cart Item quantity

        // Testing if the product has enough stock
        if( $stock_qty < $item_qty ){
             $is_available_on_backorder = true; // The condition is met
             break; // we stop the loop
        }
    }

    if ( WC()->cart->needs_shipping() && $is_available_on_backorder ){
        ?>
            <tr class="ceckoutStockMeta">
                <th>Item Shipments</th>
                <td>
                    <p style="color: red;">*You have one or more items in your cart that are currently out of stock. Please select a custom shipping option for your order.</p><br>
                    <form>
                        <input type="radio" name="stockOp" id="stockOption1" value="ship" />
                        <label for="stockOption1">Ship what is available now</label><br>

                        <input type="radio" name="stockOp" id="stockOption2" value="hold" />
                        <label for="stockOption2">Wait and ship together</label>
                    </form>
                </td>
            </tr>
        <?php
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'notes_in_cart' );
add_action( 'woocommerce_review_order_after_order_total', 'notes_in_cart' );
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Body:
I need to display a section in my checkout order review ONLY IF there is an out of stock item in the cart (b/c our products are available on backorder). Here is the code that displays the section...

Functions.php:

function notes_in_cart() {
    global $woocommerce;
       if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }
    if ( WC()->cart->needs_shipping() ){
        //if cart has items out of stock
        //if (cart has out of stock product) {
        ?>

                Item Shipments

*You have one or more items in your cart that are currently out of stock. Please select a custom shipping option for your order.

                    <form>

                        <input type="radio" name="stockOp" id="stockOption1" value="ship" />
                        Ship what is available now

                        <input type="radio" name="stockOp" id="stockOption2" value="hold" />
                        Wait and ship together
                    </form>

        <?php

        //}
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'notes_in_cart' );
add_action( 'woocommerce_review_order_after_order_total', 'notes_in_cart' );

Right now the section shows all the time. I know I will probably need to call the cart items and loop through with a foreach to determine if one is out of stock, but not sure how.

Body:
Updated: As all your products are available on backorders, the only efficient way is to check in a foreach loop if the stock quantity "is sufficient" for each cart item quantity...

If the stock quantity of the product is smaller than the cart item quantity (WC displays "available on backorder"), then your "shipment note" is displayed.

Here is that code:

function notes_in_cart() {

    if ( ! $_POST || ( is_admin() && is_ajax() ) ){
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }

    // Loop that check if cart items have enough stock quantity
    $is_available_on_backorder = false;
    foreach ( WC()->cart->get_cart() as $item_values ) {

        $stock_qty = $item_values['data']->get_stock_quantity(); // Product stock
        $item_qty = $item_values['quantity']; // Cart Item quantity

        // Testing if the product has enough stock
        if( $stock_qty < $item_qty ){
             $is_available_on_backorder = true; // The condition is met
             break; // we stop the loop
        }
    }

    if ( WC()->cart->needs_shipping() && $is_available_on_backorder ){
        ?>
            <tr class="ceckoutStockMeta">
                <th>Item Shipments</th>
                <td>
                    <p style="color: red;">*You have one or more items in your cart that are currently out of stock. Please select a custom shipping option for your order.</p><br>
                    <form>
                        <input type="radio" name="stockOp" id="stockOption1" value="ship" />
                        <label for="stockOption1">Ship what is available now</label><br>

                        <input type="radio" name="stockOp" id="stockOption2" value="hold" />
                        <label for="stockOption2">Wait and ship together</label>
                    </form>
                </td>
            </tr>
        <?php
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'notes_in_cart' );
add_action( 'woocommerce_review_order_after_order_total', 'notes_in_cart' );

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.