问:
Tab-content not showing up
I'm working with tabs that show content for two data-target(no problem in that). I've added a script which automatically changes tab after 5 sec. Tab changes but the tab-content doesn't show up. I don't know why. Any help would be appreciated. Thanks.

Codepen Here

$(document).ready(function () {
            var timeInterval, currnetIndex = 1;
            tabCount = 5;
            var tabContentObj = $('.tab-content');
            changeTabIndex();
            timeInterval = setInterval(function () { changeTabIndex(); }, 4 * 1000);

            function changeTabIndex() {
                if (currnetIndex > tabCount) {
                    currnetIndex = 1;
                }
                tabContentObj.hide();
                $('ul#myTab').find('li.active').removeClass('active');
                var currentAncorObj = $('ul#myTab').find('li a').eq(currnetIndex - 1);
                currentAncorObj.parent().addClass('active');
                $(currentAncorObj.attr('href')).show();
                currnetIndex++;

            };

            $('#myTab li').mouseenter(function () {
                clearInterval(timeInterval);
            }).mouseleave(function () {
                timeInterval = setInterval(function () { changeTabIndex(); }, 4 * 1000);
            });

            $('#myTab li a').click(function () {
                tabContentObj.hide();
                $('ul#myTab').find('li.active').removeClass('active');
                var currentAncorObj = $(this);
                currnetIndex = $('ul#myTab').find('li a').index($(this)) + 1;
                currentAncorObj.parent().addClass('active');
                $(currentAncorObj.attr('href')).show();
                currnetIndex++;

                //return false;
            });
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.how-it-works {
 padding-bottom: 30px;
}
.board .nav-tabs {
 position: relative;
 margin: 40px auto;
 margin-bottom: 0;
 box-sizing: border-box;
}
.board > div.board-inner > .nav-tabs {
 border: none;
}
p.narrow{
 width: 60%;
 margin: 10px auto;
}
.liner{
 height: 2px;
 background: #ddd;
 position: absolute;
 width: 80%;
 margin: 0 auto;
 left: 0;
 right: 0;
 top: 50%;
 z-index: 1;
}
.nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus {
 color: #555555;
 cursor: default;
 border: 0;
 border-bottom-color: transparent;
 outline: 0;
}
span.round-tabs{
 width: 70px;
 height: 70px;
 line-height: 70px;
 display: inline-block;
 border-radius: 100px;
 background: white;
 z-index: 2;
 position: absolute;
 left: 0;
 text-align: center;
 font-size: 25px;
}
span.round-tabs.one{
 border: 2px solid #ddd;
 color: #ddd;
}
li.active span.round-tabs.one, li.active span.round-tabs.two, li.active span.round-tabs.three, li.active span.round-tabs.four, li.active span.round-tabs.five{
 background: #36ABE7 !important;
 border: 2px solid #2AC7CC;
 color: #fff;
}

span.round-tabs,.two{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.three{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.four{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.five{
 border: 2px solid #ddd;
 color: #ddd;
}
.nav-tabs > li.active > a.span.round-tabs{
 background: #fafafa;
}
.nav-tabs > li{
 width: 20%;
}
.nav-tabs > li a{
 width: 70px;
 height: 70px;
 margin: 0px auto;
 border-radius: 100%;
 padding: 0;
}

.nav-tabs > li a:hover{
 background: transparent;
}
.tab-pane{
 position: relative;
 padding-top: 50px;
}
.btn-outline-rounded{
 padding: 10px 40px;
 margin: 20px 0;
 border: 2px solid transparent;
 border-radius: 25px;
}
.btn.green{
 background-color: #69cb95;
 color: #fff;
}
@media(max-width: 585px){
 .board{
  width: 90%;
  height: auto !important;
 }
 span.round-tabs{
  font-size: 16px;
  width: 50px;
  height: 50px;
  line-height: 50px;
 }
 .tab-content.head{
  font-size:20px;
 }
 .nav-tabs > li a{
  width: 50px;
  height: 50px;
  line-height: 50px;
 }
 li.active:after{
  content:"";
  position: absolute;
  left: 35%;
 }
 .btn-outline-rounded{
  padding: 12px 20px;
 }
}</code>```

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>

Our Services

Service Title 1

Service Title 2

Service Title 3

Service Title 4

Service Title 5

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

```

Please look at the codepen. Snippet have some problem.
1

答:
Change this line in jQuery

it should be like this

```<code>var tabContentObj = $('.tab-content .tab-pane');
</code>```

it was

```<code>var tabContentObj = $('.tab-content');
</code>```

You were hiding whole tab-content div You have to only hide tab-pane div

EDIT

Replace this line

```<code>$(currentAncorObj.attr('href')).show();
</code>```

With this

```<code>$(currentAncorObj.attr('data-target')).show().addClass("in");
</code>```

before this you only show href elements you have to show both element which are in data-target attribute and also for have add class in.

DEMO

Try with it hope it will helps you.

Title: Tab-content not showing up

Body:
I'm working with tabs that show content for two data-target(no problem in that). I've added a script which automatically changes tab after 5 sec. Tab changes but the tab-content doesn't show up. I don't know why. Any help would be appreciated. Thanks.

Codepen Here

$(document).ready(function () {
            var timeInterval, currnetIndex = 1;
            tabCount = 5;
            var tabContentObj = $('.tab-content');
            changeTabIndex();
            timeInterval = setInterval(function () { changeTabIndex(); }, 4 * 1000);

            function changeTabIndex() {
                if (currnetIndex > tabCount) {
                    currnetIndex = 1;
                }
                tabContentObj.hide();
                $('ul#myTab').find('li.active').removeClass('active');
                var currentAncorObj = $('ul#myTab').find('li a').eq(currnetIndex - 1);
                currentAncorObj.parent().addClass('active');
                $(currentAncorObj.attr('href')).show();
                currnetIndex++;

            };

            $('#myTab li').mouseenter(function () {
                clearInterval(timeInterval);
            }).mouseleave(function () {
                timeInterval = setInterval(function () { changeTabIndex(); }, 4 * 1000);
            });

            $('#myTab li a').click(function () {
                tabContentObj.hide();
                $('ul#myTab').find('li.active').removeClass('active');
                var currentAncorObj = $(this);
                currnetIndex = $('ul#myTab').find('li a').index($(this)) + 1;
                currentAncorObj.parent().addClass('active');
                $(currentAncorObj.attr('href')).show();
                currnetIndex++;

                //return false;
            });
        });

.how-it-works {
 padding-bottom: 30px;
}
.board .nav-tabs {
 position: relative;
 margin: 40px auto;
 margin-bottom: 0;
 box-sizing: border-box;
}
.board > div.board-inner > .nav-tabs {
 border: none;
}
p.narrow{
 width: 60%;
 margin: 10px auto;
}
.liner{
 height: 2px;
 background: #ddd;
 position: absolute;
 width: 80%;
 margin: 0 auto;
 left: 0;
 right: 0;
 top: 50%;
 z-index: 1;
}
.nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus {
 color: #555555;
 cursor: default;
 border: 0;
 border-bottom-color: transparent;
 outline: 0;
}
span.round-tabs{
 width: 70px;
 height: 70px;
 line-height: 70px;
 display: inline-block;
 border-radius: 100px;
 background: white;
 z-index: 2;
 position: absolute;
 left: 0;
 text-align: center;
 font-size: 25px;
}
span.round-tabs.one{
 border: 2px solid #ddd;
 color: #ddd;
}
li.active span.round-tabs.one, li.active span.round-tabs.two, li.active span.round-tabs.three, li.active span.round-tabs.four, li.active span.round-tabs.five{
 background: #36ABE7 !important;
 border: 2px solid #2AC7CC;
 color: #fff;
}

span.round-tabs,.two{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.three{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.four{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.five{
 border: 2px solid #ddd;
 color: #ddd;
}
.nav-tabs > li.active > a.span.round-tabs{
 background: #fafafa;
}
.nav-tabs > li{
 width: 20%;
}
.nav-tabs > li a{
 width: 70px;
 height: 70px;
 margin: 0px auto;
 border-radius: 100%;
 padding: 0;
}

.nav-tabs > li a:hover{
 background: transparent;
}
.tab-pane{
 position: relative;
 padding-top: 50px;
}
.btn-outline-rounded{
 padding: 10px 40px;
 margin: 20px 0;
 border: 2px solid transparent;
 border-radius: 25px;
}
.btn.green{
 background-color: #69cb95;
 color: #fff;
}
@media(max-width: 585px){
 .board{
  width: 90%;
  height: auto !important;
 }
 span.round-tabs{
  font-size: 16px;
  width: 50px;
  height: 50px;
  line-height: 50px;
 }
 .tab-content.head{
  font-size:20px;
 }
 .nav-tabs > li a{
  width: 50px;
  height: 50px;
  line-height: 50px;
 }
 li.active:after{
  content:"";
  position: absolute;
  left: 35%;
 }
 .btn-outline-rounded{
  padding: 12px 20px;
 }
}

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>

Our Services

Service Title 1

Service Title 2

Service Title 3

Service Title 4

Service Title 5

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

Please look at the codepen. Snippet have some problem.
1

Body:
Change this line in jQuery

it should be like this

var tabContentObj = $('.tab-content .tab-pane');

it was

var tabContentObj = $('.tab-content');

You were hiding whole tab-content div You have to only hide tab-pane div

EDIT

Replace this line

$(currentAncorObj.attr('href')).show();

With this

$(currentAncorObj.attr('data-target')).show().addClass("in");

before this you only show href elements you have to show both element which are in data-target attribute and also for have add class in.

DEMO

Try with it hope it will helps you.


来源: stackexchange

问:
Validating/Allowing YouTube Embed Code
hopefully this is a simple question. I have a simple custom forum on my site written in PHP. For security reasons I don't allow any HTML in the forum posts. I only allow certain BBCode tags. I would however like to allow embedded YouTube videos.

So my question is this: What's the best (most secure) way to validate the YouTube embed code? YouTube is currently using iframes to embed videos, but obviously I can't just allow the iframe tag. I also need to ensure the src of the iframe is a YouTube URL, and ensure there's no other malicious bits of code in the iframe code.

答:
You should allow users to use something like this:

```<code>[youtube]http://www.youtube.com/watch?v=te-TiL9YVaE[/youtube]
</code>```

And then turn it to embed code using PHP when displaying a message:

```<code>function bb_youtube($post) {
    return preg_replace(
                            "#\[youtube].*?v=([^&]+).*?\[/youtube\]#im",
                            '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/$1?fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/$1?fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>',
                            $post
                           );
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Validating/Allowing YouTube Embed Code

Body:
You should allow users to use something like this:

[youtube]http://www.youtube.com/watch?v=te-TiL9YVaE[/youtube]

And then turn it to embed code using PHP when displaying a message:

function bb_youtube($post) {
    return preg_replace(
                            "#\[youtube].*?v=([^&]+).*?\[/youtube\]#im",
                            '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/$1?fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/$1?fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>',
                            $post
                           );
}


问:
Can boost's interprocess segment manager allocators be themselves shared with other processes?
I am creating a shared interprocess map using boost::interprocess.
For this I create an allocator from the segment_manager of the shared memory segment where the map is located.

The element value type of the map is a basic_string which is itself templated to use a char allocator created from the same segment manager.
In one process I create the map and in the other I search for an item using the maps iterator in that process and in some cases I call map::erase with the iterator.

This causes an access violation exception and I know that I am making the call with a valid iterator.
The access violation occurs in the call to the destructor of the basic_string that is the 'second' of the 'pair' pointed to by the iterator.
When I perform the same erase operation using an iterator in the writing process immediately after insertion there is no access violation.

It looks as though the reading process is trying to release the memory of the element using the element's allocator, which was created in the writing process whereas that allocator is only valid in the process that created it.

Does this mean that the allocators themselves cannot be shared?

I would have expected that allocator to be usable in both processes as its state should contain only relative pointers that are valid in both processes.
If not, how can I share elements that use shared memory (heap) allocations between processes?
Should I have created those allocators in a special way in the writing process before passing them to the basic_string elements to allow me to use them in anerase operation in another process?

What else might be causing the access violation?

答:
The allocators are fine (the magic is in offset_ptr and it's transparent across process boundaries).

If the "client" destructs strings, then you're doing something else than reading. Most likely, you're receiving a copy, like:

```<code>auto by_copy = smap.find(key)->second; // makes a copy
</code>```

Try, e.g. to do

```<code>auto const& by_ref = smap.find(key)->second; // doesn't copy
</code>```

Alternatively you might be doing smap[key] which automatically allocates if the key wasn't there. This could cause an old-fashioned race condition  (sharing data between processes is much like sharing data between threads: you need proper synchronization).

Lastly, you didn't mention /anything/ about the key, but if it, too, is a string then just the lookup-by-key is prone to allocate from shared memory (and, it being a temporary, it would destruct). The race condition looms again. See also want to efficiently overcome mismatch between key types in a map in Boost.Interprocess shared memory

Demo

In the absence of a proper SSCCE or MCVE, let me throw one at you. You might spot something you do differently.

```<code>#include <iostream>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/containers/map.hpp>

namespace bip = boost::interprocess;

namespace shared {
    namespace bc  = boost::container;

    using Segment = bip::managed_shared_memory;
    using Manager = Segment::segment_manager;
    template <typename T>
    using Alloc   = bc::scoped_allocator_adaptor<bip::allocator<T, Manager> >;

    using String  = bip::basic_string<char, std::char_traits<char>, Alloc<char> >;
    template <typename K, typename V, typename Cmp = std::less<K> >
        using Map = bip::map<K, V, Cmp, Alloc<std::pair<K const, V> > >;
};

int main() {
    using namespace shared;

    Segment smt(bip::open_or_create, "de06c60a-0b80-4b20-a805-b3f405f35427", 20ul<<20); // 20 mb
    auto& mat = *smt.find_or_construct<Map<String, String> >("dict")(smt.get_segment_manager());

    if (mat.empty()) {
        mat.emplace("1", "one");
        mat.emplace("2", "two");
        mat.emplace("3", "three");
    } else {
        // shared string factory
        auto ss = [&](auto... stuff) { return String(stuff..., smt.get_segment_manager()); };

        auto  copy = mat.at(ss("3")); // constructs and destructs temp String("3"); constructs copy
        auto& ref  = mat.at(ss("2")); // constructs and destructs temp String("2"); no copy
        std::cout << "copy: " << copy << "\n";
        std::cout << "ref: "  << ref  << "\n";

        // iterate with no shared temps or copies:
        for (auto& p : mat)
            std::cout << "entry '" << p.first << "' -> '" << p.second << "'\n";
    } // destructs copy
}
</code>```

The same on Coliru, but with memory-mapped files (because shared memory is not allowed on there):

Live On Coliru

```<code>using Segment = bip::managed_mapped_file;
</code>```

Prints nothing first run, subsequent runs:

```<code>copy: three
ref: two
entry '1' -> 'one'
entry '2' -> 'two'
entry '3' -> 'three'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The allocators are fine (the magic is in offset_ptr and it's transparent across process boundaries).

If the "client" destructs strings, then you're doing something else than reading. Most likely, you're receiving a copy, like:

auto by_copy = smap.find(key)->second; // makes a copy

Try, e.g. to do

auto const& by_ref = smap.find(key)->second; // doesn't copy

Alternatively you might be doing smap[key] which automatically allocates if the key wasn't there. This could cause an old-fashioned race condition  (sharing data between processes is much like sharing data between threads: you need proper synchronization).

Lastly, you didn't mention /anything/ about the key, but if it, too, is a string then just the lookup-by-key is prone to allocate from shared memory (and, it being a temporary, it would destruct). The race condition looms again. See also want to efficiently overcome mismatch between key types in a map in Boost.Interprocess shared memory

Demo

In the absence of a proper SSCCE or MCVE, let me throw one at you. You might spot something you do differently.

#include <iostream>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/containers/map.hpp>

namespace bip = boost::interprocess;

namespace shared {
    namespace bc  = boost::container;

    using Segment = bip::managed_shared_memory;
    using Manager = Segment::segment_manager;
    template <typename T>
    using Alloc   = bc::scoped_allocator_adaptor<bip::allocator<T, Manager> >;

    using String  = bip::basic_string<char, std::char_traits<char>, Alloc<char> >;
    template <typename K, typename V, typename Cmp = std::less<K> >
        using Map = bip::map<K, V, Cmp, Alloc<std::pair<K const, V> > >;
};

int main() {
    using namespace shared;

    Segment smt(bip::open_or_create, "de06c60a-0b80-4b20-a805-b3f405f35427", 20ul<<20); // 20 mb
    auto& mat = *smt.find_or_construct<Map<String, String> >("dict")(smt.get_segment_manager());

    if (mat.empty()) {
        mat.emplace("1", "one");
        mat.emplace("2", "two");
        mat.emplace("3", "three");
    } else {
        // shared string factory
        auto ss = [&](auto... stuff) { return String(stuff..., smt.get_segment_manager()); };

        auto  copy = mat.at(ss("3")); // constructs and destructs temp String("3"); constructs copy
        auto& ref  = mat.at(ss("2")); // constructs and destructs temp String("2"); no copy
        std::cout << "copy: " << copy << "\n";
        std::cout << "ref: "  << ref  << "\n";

        // iterate with no shared temps or copies:
        for (auto& p : mat)
            std::cout << "entry '" << p.first << "' -> '" << p.second << "'\n";
    } // destructs copy
}

The same on Coliru, but with memory-mapped files (because shared memory is not allowed on there):

Live On Coliru

using Segment = bip::managed_mapped_file;

Prints nothing first run, subsequent runs:

copy: three
ref: two
entry '1' -> 'one'
entry '2' -> 'two'
entry '3' -> 'three'


问:
Why are my icons not showing up?
This is a zip to the full project QuickLinks.v4

I have been collaborating on a project and we are stuck on an issue, we want all of the icon to have a right click menu that has several options that are unique to each icon. We are almost done but now the icons are not being drawn to the screen. We are only working on the first 5 at the time. This is my first time working with jQuery and I would appreciate any help.

I will now post pieces of the project that I think are relevant.

icon.html

```<code><a target="_blank">
    <img class="icons" />
    <div class="data">
           <div>
                 <input type="hidden" class="login" />
                 <input type="hidden" class="username" />
                 <input type="hidden" class="password" />
           </div>
    </div>
</a>
</code>```

icon.js

```<code>function buildIcons() {
    var icons = [
        ["https://discordapp.com/", "discord-icon", "icons/discord.png", "social", "Discord",
            [
                 ["Main Account", "lela_null", "somepass"],
                 ["Bot Account", "Uta Yuki", "somepass"]
            ]
        ],
        ["https://www.youtube.com/", "youtube-icon", "icons/youtube.png", "social", "YouTube",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://www.facebook.com/?sk=h_chr", "facebook-icon", "icons/facebook.png", "social", "Facebook",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://www.twitter.com/", "twitter-icon", "icons/twitter.png", "social", "Twitter",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://mg.mail.yahoo.com/neo/launch?.rand=8647i3s40jpvp", "ymail-icon", "icons/ymail.png", "social", "Yahoo Mail",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ]
    ];

    $.get('data/icon.html', function(data) {
        var icon;
        icons.forEach(function(iconData, index, array) {
            console.log(index);
            icon = $(data).insertAfter("#" + iconData[3]);
            $(icon).find("img").attr("src", iconData[2]);
        });
    });
};
</code>```

script.js

```<code>/* get icon id */
function buildMenu(iconId) {
    $("#remove").click(function() {
       $("#" + iconId).hide();
       cancel();
    });
    $("#menu-title").text($("#"+iconId).data("name"));
    $("#site-link").attr("href", $("#" + iconId).parent().attr("href")).click(cancel);
    switch(iconId) {
    };
}

/* set right click for icons */
$(document).ready(function() {
    buildIcons();
    $(".icons").on("contextmenu", function(e) {
        buildMenu(this.id);
        $("#contextmenu").show().css({
            top: e.clientY,
            left: e.clientX
        });
        e.preventDefault();
    });
});

function cancel() {
    $("#contextmenu").hide();
}
</code>```

There is more files and code, if you may need, you may download it above.

Also the console says TypeError: a is null in my jQuery.js file.

答:
Check this</p>

```<code>$.get('data/icon.html', function(data) {
    icons.forEach(function(iconData, index, array) {
        console.log(index);

        // Get 'data' as jQuery object
        var $data = $(data);

        // Find image tag and set source
        $data.find('img').attr('src', iconData[2]);

        //Finally put it on page
        $data.insertAfter("#" + iconData[3]);
    });
});
</code>```

Title: Why are my icons not showing up?

Body:
This is a zip to the full project QuickLinks.v4

I have been collaborating on a project and we are stuck on an issue, we want all of the icon to have a right click menu that has several options that are unique to each icon. We are almost done but now the icons are not being drawn to the screen. We are only working on the first 5 at the time. This is my first time working with jQuery and I would appreciate any help.

I will now post pieces of the project that I think are relevant.

icon.html

                 <input type="hidden" class="login" />
                 <input type="hidden" class="username" />
                 <input type="hidden" class="password" />

icon.js

function buildIcons() {
    var icons = [
        ["https://discordapp.com/", "discord-icon", "icons/discord.png", "social", "Discord",
            [
                 ["Main Account", "lela_null", "somepass"],
                 ["Bot Account", "Uta Yuki", "somepass"]
            ]
        ],
        ["https://www.youtube.com/", "youtube-icon", "icons/youtube.png", "social", "YouTube",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://www.facebook.com/?sk=h_chr", "facebook-icon", "icons/facebook.png", "social", "Facebook",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://www.twitter.com/", "twitter-icon", "icons/twitter.png", "social", "Twitter",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ],
        ["https://mg.mail.yahoo.com/neo/launch?.rand=8647i3s40jpvp", "ymail-icon", "icons/ymail.png", "social", "Yahoo Mail",
            [
                 ["Main Account", "lela@email", "somepass"],
            ]
        ]
    ];

    $.get('data/icon.html', function(data) {
        var icon;
        icons.forEach(function(iconData, index, array) {
            console.log(index);
            icon = $(data).insertAfter("#" + iconData[3]);
            $(icon).find("img").attr("src", iconData[2]);
        });
    });
};

script.js

/* get icon id */
function buildMenu(iconId) {
    $("#remove").click(function() {
       $("#" + iconId).hide();
       cancel();
    });
    $("#menu-title").text($("#"+iconId).data("name"));
    $("#site-link").attr("href", $("#" + iconId).parent().attr("href")).click(cancel);
    switch(iconId) {
    };
}

/* set right click for icons */
$(document).ready(function() {
    buildIcons();
    $(".icons").on("contextmenu", function(e) {
        buildMenu(this.id);
        $("#contextmenu").show().css({
            top: e.clientY,
            left: e.clientX
        });
        e.preventDefault();
    });
});

function cancel() {
    $("#contextmenu").hide();
}

There is more files and code, if you may need, you may download it above.

Also the console says TypeError: a is null in my jQuery.js file.

Body:
Check this

$.get('data/icon.html', function(data) {
    icons.forEach(function(iconData, index, array) {
        console.log(index);

        // Get 'data' as jQuery object
        var $data = $(data);

        // Find image tag and set source
        $data.find('img').attr('src', iconData[2]);

        //Finally put it on page
        $data.insertAfter("#" + iconData[3]);
    });
});


问:
Discord.py create_custom_emojis usage
I'm making a bot with Discord.py and I've some question how to use the function create_custom_emojis() because whatever I do, I keep getting the HTTP Error 400.

Here's my code to create the emoji:

```<code>with open("data/emojis/image.png", "rb") as image:
    image_byte = image.read()
    emoji = await self.bot.create_custom_emoji(server, name="emo", image=image_byte)
</code>```

And the error I get:

```<code>Traceback (most recent call last):
  File "C:\Program Files (x86)\Python35\lib\asyncio\tasks.py", line 239, in _step
    result = coro.send(None)
  File "C:\Users\armel\Downloads\Discord bot\Red-DiscordBot\cogs\moga.py", line 385, in read_feeds
    message = await self._feed_check(server, chan_id, name, infos)
  File "C:\Users\armel\Downloads\Discord bot\Red-DiscordBot\cogs\moga.py", line 198, in _feed_check
    await self.create_custom_emojis(server)
  File "C:\Users\armel\Downloads\Discord bot\Red-DiscordBot\cogs\moga.py", line 189, in create_custom_emojis
    emoji = await self.bot.create_custom_emoji(server, name=name, image=image_byte)
  File "lib\discord\client.py", line 2519, in create_custom_emoji
    data = yield from self.http.create_custom_emoji(server.id, name, img)
  File "lib\discord\http.py", line 202, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: BAD REQUEST (status code: 400)
</code>```

答:
```<code>image_byte = image.read()
</code>```

Do not attempt to read from image. It is already a byte like object. Simply send this as the image.

```<code>emoji = await self.bot.create_custom_emoji(server, name="emo", image=image)
</code>```

Title: Discord.py create_custom_emojis usage

Body:
I'm making a bot with Discord.py and I've some question how to use the function create_custom_emojis() because whatever I do, I keep getting the HTTP Error 400.

Here's my code to create the emoji:

with open("data/emojis/image.png", "rb") as image:
    image_byte = image.read()
    emoji = await self.bot.create_custom_emoji(server, name="emo", image=image_byte)

And the error I get:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python35\lib\asyncio\tasks.py", line 239, in _step
    result = coro.send(None)
  File "C:\Users\armel\Downloads\Discord bot\Red-DiscordBot\cogs\moga.py", line 385, in read_feeds
    message = await self._feed_check(server, chan_id, name, infos)
  File "C:\Users\armel\Downloads\Discord bot\Red-DiscordBot\cogs\moga.py", line 198, in _feed_check
    await self.create_custom_emojis(server)
  File "C:\Users\armel\Downloads\Discord bot\Red-DiscordBot\cogs\moga.py", line 189, in create_custom_emojis
    emoji = await self.bot.create_custom_emoji(server, name=name, image=image_byte)
  File "lib\discord\client.py", line 2519, in create_custom_emoji
    data = yield from self.http.create_custom_emoji(server.id, name, img)
  File "lib\discord\http.py", line 202, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: BAD REQUEST (status code: 400)

Body:
image_byte = image.read()

Do not attempt to read from image. It is already a byte like object. Simply send this as the image.

emoji = await self.bot.create_custom_emoji(server, name="emo", image=image)


问:
Could not get json value while fetching all data from table using Python
I need to display the db table data in a tabular format but I could not find the data in JSON format using Python. I am providing my code below.

```<code>def view_book(request):
    """ This function is used for disply all the data """

    conn = sqlite3.connect("db.sqlite3")
    cursor = conn.cursor()
    cursor.execute("SELECT  * FROM booking_meeting ORDER BY id desc")
    all_value = cursor.fetchall()
    root = []
    json_output=json.dumps(all_value)
    print(json_output)
    for book in json_output:
        root.append(
            {'lname': book.location_name,
             'roomname': book.room_name,
             'seat': book.no_seat,
             'project': book.projector,
             'video': book.video,
             'from_date': book.from_date,
             'to_date': book.to_date})
    return render(request, 'booking/view_book.html', {'people': root})
</code>```

Here I am getting the following error.

```<code>Request Method: GET
Request URL:    http://127.0.0.1:8000/view_book/
Django Version: 1.11.2
Exception Type: AttributeError
Exception Value:
'str' object has no attribute 'location_name'
</code>```

Here I need to append all data into JSON format so that I will be able to display it in table.

答:
Why are you trying to access the attributes after dumping them to JSON? JSON is a string, you cannot iterate through its properties without parsing.

Don't use JSON at all if you're not going to print it, render your data into JSON after you process it:

```<code>def view_book(request):
    """ This function is used for disply all the data """

    conn = sqlite3.connect("db.sqlite3")
    conn.row_factory = sqlite3.Row  # needs this to create dictionaries
    cursor = conn.cursor()
    cursor.execute("SELECT  * FROM booking_meeting ORDER BY id desc")
    all_value = cursor.fetchall()
    root = []
    for book in all_value:
        book = dict(book)  # map it into a dict
        root.append(
            {'lname': book["location_name"],
             'roomname': book["room_name"],
             'seat': book["no_seat"],
             'project': book["projector"],
             'video': book["video"],
             'from_date': book["from_date"],
             'to_date': book["to_date"]})
    return render(request, 'booking/view_book.html', {'people': root})
</code>```

Of course, if you want your people to hold a literal JSON turn it into JSON before returning:

```<code>    return render(request, 'booking/view_book.html', {'people': json.dumps(root)})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to display the db table data in a tabular format but I could not find the data in JSON format using Python. I am providing my code below.

def view_book(request):
    """ This function is used for disply all the data """

    conn = sqlite3.connect("db.sqlite3")
    cursor = conn.cursor()
    cursor.execute("SELECT  * FROM booking_meeting ORDER BY id desc")
    all_value = cursor.fetchall()
    root = []
    json_output=json.dumps(all_value)
    print(json_output)
    for book in json_output:
        root.append(
            {'lname': book.location_name,
             'roomname': book.room_name,
             'seat': book.no_seat,
             'project': book.projector,
             'video': book.video,
             'from_date': book.from_date,
             'to_date': book.to_date})
    return render(request, 'booking/view_book.html', {'people': root})

Here I am getting the following error.

Request Method: GET
Request URL:    http://127.0.0.1:8000/view_book/
Django Version: 1.11.2
Exception Type: AttributeError
Exception Value:
'str' object has no attribute 'location_name'

Here I need to append all data into JSON format so that I will be able to display it in table.

Body:
Why are you trying to access the attributes after dumping them to JSON? JSON is a string, you cannot iterate through its properties without parsing.

Don't use JSON at all if you're not going to print it, render your data into JSON after you process it:

def view_book(request):
    """ This function is used for disply all the data """

    conn = sqlite3.connect("db.sqlite3")
    conn.row_factory = sqlite3.Row  # needs this to create dictionaries
    cursor = conn.cursor()
    cursor.execute("SELECT  * FROM booking_meeting ORDER BY id desc")
    all_value = cursor.fetchall()
    root = []
    for book in all_value:
        book = dict(book)  # map it into a dict
        root.append(
            {'lname': book["location_name"],
             'roomname': book["room_name"],
             'seat': book["no_seat"],
             'project': book["projector"],
             'video': book["video"],
             'from_date': book["from_date"],
             'to_date': book["to_date"]})
    return render(request, 'booking/view_book.html', {'people': root})

Of course, if you want your people to hold a literal JSON turn it into JSON before returning:

    return render(request, 'booking/view_book.html', {'people': json.dumps(root)})


答:
When you do all_value = cursor.fetchall() then all_value is already a iterable of your records.

When you then execute json_output=json.dumps(all_value) you're converting it all to a string.

As a result, for book in json_output: will be iterating over a string.

You can simply skip the JSON conversion:

```<code>def view_book(request):
    """ This function is used for disply all the data """

    conn = sqlite3.connect("db.sqlite3")
    cursor = conn.cursor()
    cursor.execute("SELECT  * FROM booking_meeting ORDER BY id desc")
    all_value = cursor.fetchall()
    root = []
    for book in all_value:
        root.append(
            {'lname': book.location_name,
             'roomname': book.room_name,
             'seat': book.no_seat,
             'project': book.projector,
             'video': book.video,
             'from_date': book.from_date,
             'to_date': book.to_date})
    return render(request, 'booking/view_book.html', {'people': root})
</code>```

Title: Could not get json value while fetching all data from table using Python

Body:
When you do all_value = cursor.fetchall() then all_value is already a iterable of your records.

When you then execute json_output=json.dumps(all_value) you're converting it all to a string.

As a result, for book in json_output: will be iterating over a string.

You can simply skip the JSON conversion:

def view_book(request):
    """ This function is used for disply all the data """

    conn = sqlite3.connect("db.sqlite3")
    cursor = conn.cursor()
    cursor.execute("SELECT  * FROM booking_meeting ORDER BY id desc")
    all_value = cursor.fetchall()
    root = []
    for book in all_value:
        root.append(
            {'lname': book.location_name,
             'roomname': book.room_name,
             'seat': book.no_seat,
             'project': book.projector,
             'video': book.video,
             'from_date': book.from_date,
             'to_date': book.to_date})
    return render(request, 'booking/view_book.html', {'people': root})


问:
How to Get A Element First Child Text Using Jquery And Class Selector?
I Have Two Element Inside a Element. like below =>

```<code><div class="NDateCount" style="display:inline-block">
     <!--Issue to solve-->
     <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
     <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
     <!--End of Issue to solve-->
</div>
</code>```

i have this kind of div more than 10 time with is generating dynamically. and i want first child of div element which is small text; and i have done so far ==>

```<code>    var ReloadTime = function () {
        $('.NDateCount').each(function () {
            var OldValue = $(this).first().text();
            alert(OldValue);
         });
        setTimeout(ReloadTime, 50);
    }
</code>```

but the above function giving something like both small tag innner text.
like ==>

is there ant way to solve this problem......

答:
first() is returning the div element and therefore you get the text within it.

Get the children of $(this) and then use first():

```<code>var OldValue = $(this).children().first().text();
</code>```

var ReloadTime = function() {
  $('.NDateCount').each(function() {
    var OldValue = $(this).children().first().text();
    alert(OldValue);
  });
  //setTimeout(ReloadTime, 50);
}

ReloadTime();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="NDateCount" style="display:inline-block">
  <!--Issue to solve-->
  <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
  <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
  <!--End of Issue to solve-->
</div>
<div class="NDateCount" style="display:inline-block">
  <!--Issue to solve-->
  <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
  <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
  <!--End of Issue to solve-->
</div></code>```

Body:
I Have Two Element Inside a Element. like below =>

     2017-07-08T12:44:10.367+06:00
     <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"> 3 hours ago

i have this kind of div more than 10 time with is generating dynamically. and i want first child of div element which is small text; and i have done so far ==>

    var ReloadTime = function () {
        $('.NDateCount').each(function () {
            var OldValue = $(this).first().text();
            alert(OldValue);
         });
        setTimeout(ReloadTime, 50);
    }

but the above function giving something like both small tag innner text.
like ==>

is there ant way to solve this problem......

Body:
first() is returning the div element and therefore you get the text within it.

Get the children of $(this) and then use first():

var OldValue = $(this).children().first().text();

var ReloadTime = function() {
  $('.NDateCount').each(function() {
    var OldValue = $(this).children().first().text();
    alert(OldValue);
  });
  //setTimeout(ReloadTime, 50);
}

ReloadTime();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="NDateCount" style="display:inline-block">
  <!--Issue to solve-->
  <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
  <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
  <!--End of Issue to solve-->
</div>
<div class="NDateCount" style="display:inline-block">
  <!--Issue to solve-->
  <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
  <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
  <!--End of Issue to solve-->
</div>


问:
How to show graph on JFrame
I have a JPanel to create a graph which cannot be editable.

When the graph shows, the edge name is covered by boundary of JFrame.

How can I show that edge name without being covered by JFrame?

My Example

This is my code:

```<code>package myapp;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.layout.hierarchical.mxHierarchicalLayout;
import com.mxgraph.model.mxICell;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;

public class CreateGraph extends JFrame {

private static final long serialVersionUID = 8083868183987456695L;
mxICell a, b, c, d, e, f, g, h;

public CreateGraph() {
final mxGraph graph = new mxGraph();
Object parent = graph.getDefaultParent();

graph.getModel().beginUpdate();
try {

    a = (mxICell) graph.insertVertex(parent, null, "a", 0, 0, 80, 30);
    b = (mxICell) graph.insertVertex(parent, null, "b", 0, 0, 80, 30);
    c = (mxICell) graph.insertVertex(parent, null, "c", 0, 0, 80, 30);
    d = (mxICell) graph.insertVertex(parent, null, "d", 0, 0, 80, 30);

    graph.insertEdge(parent, null, "ab", a, b);
    graph.insertEdge(parent, null, "bc", b, c);
    graph.insertEdge(parent, null, "cd", c, b);
    graph.insertEdge(parent, null, "cd", c, d);
    graph.insertEdge(parent, null, "da", d, a);

    graph.setCellsEditable(false);
    graph.setCellsMovable(false);
    graph.setCellsSelectable(false);

} finally {
    graph.getModel().endUpdate();
}

// define layout
mxIGraphLayout layout = new mxHierarchicalLayout(graph);
layout.execute(graph.getDefaultParent());

mxGraphComponent graphComponent = new mxGraphComponent(graph);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(graphComponent, BorderLayout.CENTER);

}

public static void main(String[] args) {
    CreateGraph frame = new CreateGraph();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    frame.setVisible(true);
}

}
</code>```

答:
Maybe don't want to use a BorderLayout, since you don't really have a use case like How to Use BorderLayout or Border Layout not working.

Your edge is at X-position 0, which just inside your layout.

One option is solving your problem withing JGraph itself, by adding a constant like private final double X_OFFSET = 10 and then add it to the X-coordinate of every graph operation.

Title: How to show graph on JFrame

Body:
I have a JPanel to create a graph which cannot be editable.

When the graph shows, the edge name is covered by boundary of JFrame.

How can I show that edge name without being covered by JFrame?

My Example

This is my code:

package myapp;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.layout.hierarchical.mxHierarchicalLayout;
import com.mxgraph.model.mxICell;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;

public class CreateGraph extends JFrame {

private static final long serialVersionUID = 8083868183987456695L;
mxICell a, b, c, d, e, f, g, h;

public CreateGraph() {
final mxGraph graph = new mxGraph();
Object parent = graph.getDefaultParent();

graph.getModel().beginUpdate();
try {

    a = (mxICell) graph.insertVertex(parent, null, "a", 0, 0, 80, 30);
    b = (mxICell) graph.insertVertex(parent, null, "b", 0, 0, 80, 30);
    c = (mxICell) graph.insertVertex(parent, null, "c", 0, 0, 80, 30);
    d = (mxICell) graph.insertVertex(parent, null, "d", 0, 0, 80, 30);

    graph.insertEdge(parent, null, "ab", a, b);
    graph.insertEdge(parent, null, "bc", b, c);
    graph.insertEdge(parent, null, "cd", c, b);
    graph.insertEdge(parent, null, "cd", c, d);
    graph.insertEdge(parent, null, "da", d, a);

    graph.setCellsEditable(false);
    graph.setCellsMovable(false);
    graph.setCellsSelectable(false);

} finally {
    graph.getModel().endUpdate();
}

// define layout
mxIGraphLayout layout = new mxHierarchicalLayout(graph);
layout.execute(graph.getDefaultParent());

mxGraphComponent graphComponent = new mxGraphComponent(graph);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(graphComponent, BorderLayout.CENTER);

}

public static void main(String[] args) {
    CreateGraph frame = new CreateGraph();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    frame.setVisible(true);
}

}


答:
The problem is that once you convert it into JSON object, it is treated as string by python. So while iterating, you are not getting 'book' as an object, rather as a string, and that is why you are getting this error. You can try the following approaches:

1) iterate over all_value rather than json_output.

2) iterate over json.loads(json_output). I am not sure if this would work.

3) It is not a good practice to write raw SQL queries, rather use django ORM. You might like to do this:

```<code>def view_book(request):
    """ This function is used for disply all the data """

    all_value = BookingMeeting.objects.order_by('-id')
    root = []
    for book in all_value:
        root.append(
            {'lname': book.location_name,
             'roomname': book.room_name,
             'seat': book.no_seat,
             'project': book.projector,
             'video': book.video,
             'from_date': book.from_date,
             'to_date': book.to_date})
    json_output=json.dumps(root)
    return render(request, 'booking/view_book.html', {'people': root})
</code>```

Body:
The problem is that once you convert it into JSON object, it is treated as string by python. So while iterating, you are not getting 'book' as an object, rather as a string, and that is why you are getting this error. You can try the following approaches:

1) iterate over all_value rather than json_output.

2) iterate over json.loads(json_output). I am not sure if this would work.

3) It is not a good practice to write raw SQL queries, rather use django ORM. You might like to do this:

def view_book(request):
    """ This function is used for disply all the data """

    all_value = BookingMeeting.objects.order_by('-id')
    root = []
    for book in all_value:
        root.append(
            {'lname': book.location_name,
             'roomname': book.room_name,
             'seat': book.no_seat,
             'project': book.projector,
             'video': book.video,
             'from_date': book.from_date,
             'to_date': book.to_date})
    json_output=json.dumps(root)
    return render(request, 'booking/view_book.html', {'people': root})


问:
How to define where libs are loaded from
I am trying to compile omniORB on AIX 6.1 with gcc 4.2.0.

The initialization does not work as it is picking up the non pthreaded library.

If I set LIBPATH to /opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/ omniNames will not work, as the streams interface gives an exception.

Setting the LIBPATH to /opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/pthread seems to work, but other non pthreaded programs will pick up the pthreaded lib which may cause problems...

The link looks like this:

```<code>g++ -o omniNames -O2 -Wall -Wno-unused -fexceptions -Wl,-brtl -Wl,-blibpath:/lib:/usr/lib:/opt/dbx/omniORB-4/lib -L../../../lib -L../../../../lib omniNames.o NamingContext_i.o log.o omniNamesWin.o -lomniORB4-ar -lomnithread34 -lpthreads
</code>```

How do I resolve this ??

Note that I have tried to change libpath using configure arguments but without success.

答:
Each OS uses its own unique set of environment variables to decide where to search for shared libraries.

Most UNIX like systems use LD_LIBRARY_PATH (but it varies).

I found that the most effective way to find which environment variable to use is to look at the man page for dlopen() on the platform you are building for.

Edited: also note that these variables act like the PATH environment variables, in that they are a list of paths that are ':' separated. So could you not set the environment like this:

```<code># Using  tcsh syntax for setting environment. Your shell may very.
setenv LIBPATH "/opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/:/opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/pthread"
</code>```

Body:
I am trying to compile omniORB on AIX 6.1 with gcc 4.2.0.

The initialization does not work as it is picking up the non pthreaded library.

If I set LIBPATH to /opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/ omniNames will not work, as the streams interface gives an exception.

Setting the LIBPATH to /opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/pthread seems to work, but other non pthreaded programs will pick up the pthreaded lib which may cause problems...

The link looks like this:

g++ -o omniNames -O2 -Wall -Wno-unused -fexceptions -Wl,-brtl -Wl,-blibpath:/lib:/usr/lib:/opt/dbx/omniORB-4/lib -L../../../lib -L../../../../lib omniNames.o NamingContext_i.o log.o omniNamesWin.o -lomniORB4-ar -lomnithread34 -lpthreads

How do I resolve this ??

Note that I have tried to change libpath using configure arguments but without success.

Body:
Each OS uses its own unique set of environment variables to decide where to search for shared libraries.

Most UNIX like systems use LD_LIBRARY_PATH (but it varies).

I found that the most effective way to find which environment variable to use is to look at the man page for dlopen() on the platform you are building for.

Edited: also note that these variables act like the PATH environment variables, in that they are a list of paths that are ':' separated. So could you not set the environment like this:

# Using  tcsh syntax for setting environment. Your shell may very.
setenv LIBPATH "/opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/:/opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/pthread"


答:
var ReloadTime = function () {
        $('.NDateCount').each(function () {
            var OldValue = $(this).find('small').first().text();
            alert(OldValue);
         });
    }

setTimeout(ReloadTime, 50);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="NDateCount" style="display:inline-block">
     <!--Issue to solve-->
     <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
     <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
     <!--End of Issue to solve-->
</div></code>```

First, the main mistake you are doing is that setTimeout() function is inside the ReloadTime() function. So the function is not called by setTimeout() unless you trigger that function once. So i disagree with the above answer. Secondly, the use of $(this) inside the each function reference to the individual $('.NDateCount') element so to achieve what you need, you first need to find the element  under $(this) and then get the first() element, and finally the text()

Title: How to Get A Element First Child Text Using Jquery And Class Selector?

Body:
var ReloadTime = function () {
        $('.NDateCount').each(function () {
            var OldValue = $(this).find('small').first().text();
            alert(OldValue);
         });
    }

setTimeout(ReloadTime, 50);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="NDateCount" style="display:inline-block">
     <!--Issue to solve-->
     <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
     <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
     <!--End of Issue to solve-->
</div>

First, the main mistake you are doing is that setTimeout() function is inside the ReloadTime() function. So the function is not called by setTimeout() unless you trigger that function once. So i disagree with the above answer. Secondly, the use of $(this) inside the each function reference to the individual $('.NDateCount') element so to achieve what you need, you first need to find the element <small> under $(this) and then get the first() element, and finally the text()


问:
Observables: Validate dummy data from a mock class without http
I'm learning Observables and trying to implement a service for login validation.
Dummy data is like this

export class Users {
  public users: IUser[] = [];

  constructor() {
    this.users = [
      new IUser({ username: "protagonist", password: "hello123" }),
      new IUser({ username: "rono67", password: "!@vioped" }),
      new IUser({ username: "donaldtrump", password: "melenia@34" })
    ];
  }
```

<p>and structure of IUser is like this.</p>

<pre class="lang-js prettyprint-override"><code>export class IUser {
    usename:string;
    password:string;
}
</code>```

I'm passing the entered username and password to the service class and I want to have an observable call which traverse through the dummy data and if it finds the matching credentials, it shall return it. I do not want to make any HTTP call. Method is something like this-

```<code> validLogin(accountInfo: IUser): Observable<IUser> {
        return ---------
          .map((user:IUser) => user.filter((user:IUser) => user.usernanme == accountInfo.username && user.password == accountInfo.password);
      }
</code>```

I'm not sure what piece of code needs to be written in the place of return ------. All of the results which I got in the web are implementing "return this.http.post"

Is it possible to apply RxJs on mock data? Kindly suggest.

答:
You can use Observable.of or Observable.from to create an Observable object from anything. Since, you want to do some operation on IUser array, I suggest you use Observable.of

Here what it would look like

```<code>export class Users {
   public users: IUser[] = [];
   _users: Observable<IUser[]>;

   constructor() {
      let users = [
      // your dummy data
      ];

      for (let user of users) {
          this.users.push(new IUser(user));
      }
      this._users = Observable.of(this.users);
  }

   validLogin(accountInfo: IUser): Observable<IUser> {
    return this._users.map((user:IUser) =>
           user.filter((user:IUser) => user.usernanme == accountInfo.username && user.password == accountInfo.password);
   }

}
</code>```

Body:
I'm learning Observables and trying to implement a service for login validation.
Dummy data is like this

export class Users {
  public users: IUser[] = [];

  constructor() {
    this.users = [
      new IUser({ username: "protagonist", password: "hello123" }),
      new IUser({ username: "rono67", password: "!@vioped" }),
      new IUser({ username: "donaldtrump", password: "melenia@34" })
    ];
  }

and structure of IUser is like this.

export class IUser {
    usename:string;
    password:string;
}

I'm passing the entered username and password to the service class and I want to have an observable call which traverse through the dummy data and if it finds the matching credentials, it shall return it. I do not want to make any HTTP call. Method is something like this-

 validLogin(accountInfo: IUser): Observable<IUser> {
        return ---------
          .map((user:IUser) => user.filter((user:IUser) => user.usernanme == accountInfo.username && user.password == accountInfo.password);
      }

I'm not sure what piece of code needs to be written in the place of return ------. All of the results which I got in the web are implementing "return this.http.post"

Is it possible to apply RxJs on mock data? Kindly suggest.

Body:
You can use Observable.of or Observable.from to create an Observable object from anything. Since, you want to do some operation on IUser array, I suggest you use Observable.of

Here what it would look like

export class Users {
   public users: IUser[] = [];
   _users: Observable<IUser[]>;

   constructor() {
      let users = [
      // your dummy data
      ];

      for (let user of users) {
          this.users.push(new IUser(user));
      }
      this._users = Observable.of(this.users);
  }

   validLogin(accountInfo: IUser): Observable<IUser> {
    return this._users.map((user:IUser) =>
           user.filter((user:IUser) => user.usernanme == accountInfo.username && user.password == accountInfo.password);
   }

}


问:
Random behavior in C#: repeats the same number
I type the following code in the VS 2017:

```<code>namespace Test {
    class MyClass {
        public static Random randomkey;
        static MyClass() {
            randomkey = new Random();
        }
        public MyClass() {
            randomkey = new Random();
        }
        public int returnkey() => randomkey.Next();
    }
    class Program {
        private static void Main(string[] args) {
            try {
                Console.WriteLine(MyClass.randomkey.Next());
                var x = new MyClass();
                Console.WriteLine(x.returnkey());
                var y = new MyClass();
                Console.WriteLine(y.returnkey());
                Console.ReadLine();
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
    }
}
</code>```

Then click the "Debug" button, I found the results very strange:

Output - The same random number

Then, I tried to click the "Run to Cursor" button and the results became different:

Output - Different random numbers

Why?

答:
The random function is using the system time to initialize the random number genertator.  So running your code really fast gets the same random number.  Add a sleep and then you get expected results.</p>

```<code>       private static void Main(string[] args) {
            try {
                Console.WriteLine(MyClass.randomkey.Next());
                System.Threading.Thread.Sleep(5);
                var x = new MyClass();
                Console.WriteLine(x.returnkey());
                System.Threading.Thread.Sleep(5);
                var y = new MyClass();
                Console.WriteLine(y.returnkey());
                Console.ReadLine();
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
</code>```

Body:
I type the following code in the VS 2017:

namespace Test {
    class MyClass {
        public static Random randomkey;
        static MyClass() {
            randomkey = new Random();
        }
        public MyClass() {
            randomkey = new Random();
        }
        public int returnkey() => randomkey.Next();
    }
    class Program {
        private static void Main(string[] args) {
            try {
                Console.WriteLine(MyClass.randomkey.Next());
                var x = new MyClass();
                Console.WriteLine(x.returnkey());
                var y = new MyClass();
                Console.WriteLine(y.returnkey());
                Console.ReadLine();
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
    }
}

Then click the "Debug" button, I found the results very strange:

Output - The same random number

Then, I tried to click the "Run to Cursor" button and the results became different:

Output - Different random numbers

Why?

Body:
The random function is using the system time to initialize the random number genertator.  So running your code really fast gets the same random number.  Add a sleep and then you get expected results.

       private static void Main(string[] args) {
            try {
                Console.WriteLine(MyClass.randomkey.Next());
                System.Threading.Thread.Sleep(5);
                var x = new MyClass();
                Console.WriteLine(x.returnkey());
                System.Threading.Thread.Sleep(5);
                var y = new MyClass();
                Console.WriteLine(y.returnkey());
                Console.ReadLine();
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }


问:
django-registration seems to be shortening hashed password when using subclassed RegistrationView
I'm trying to setup django-registration form with an extra field or two. I've read the documentation and scoured StackOverflow. I'm getting a problem where the user is registered with the new fields but when I try and login it doesn't recognise the password.

I've created a new view (I've just cut and pasted register from django-registration because I just want it running initially):

```<code>class MyRegistrationView (RegistrationView):
    form_class = UserRegForm

    def register(self, form):
        new_user = RegistrationProfile.objects.create_inactive_user(
            form,
            site=get_current_site(self.request)
        )
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=self.request)
        return new_user
</code>```

It uses this form:

```<code>class UserRegForm(RegistrationForm):
    CHOICES = Institution.objects.all().order_by('name')

    institution=forms.ChoiceField(choices=( (x.id, x.name) for x in CHOICES ),
                                  required = True)
</code>```

These are the additional models:

```<code>class Institution(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return u'%s' % (self.name)

class UserProfile(models.Model):
    user=models.OneToOneField(User, on_delete=models.CASCADE)
    institution=models.ForeignKey(
        Institution,
        null=True,
        blank=True)

    def __unicode__(self):
        return u'%s' % (self.user)
</code>```

My URL

```<code>url(r'^register', views.MyRegistrationView.as_view(form_class=UserRegForm), name='registration_register'),
</code>```

And I've added this to save the data: from models import UserProfile from forms import UserRegForm

```<code>def user_created(sender, user, request, **kwargs):
    form = UserRegForm(request.POST)

    try: data = UserProfile.objects.get(user=user)
    except: data = UserProfile(user=user)
    data.institution = form.data["institution"]
    data.save()

from registration.signals import user_registered
user_registered.connect(user_created)
</code>```

Everything works in that the user is registered, an email is sent out, the institution is saved to the UserProfile, but when I try and login using the new user (having activated the account) it tells me the username and password don't match.

When I look at the database the hashed paasword string seems to be 10 characters shorter than the admins (setup using manage.py createsuperuser) so I am doing something I shouldn't or not doing something I should.

Help would be much appreciated.

答:
I solved this by basically copying all of RegistrationView into MyRegistrationView.  The login now works are well.  I'm not sure why this was necessary.

```<code>from registration.backends.model_activation.views import RegistrationView
from registration.models import RegistrationProfile
from registration import signals
from django.contrib.sites.shortcuts import get_current_site
from django.core import signing
from django.template.loader import render_to_string
from django.conf import settings
REGISTRATION_SALT = getattr(settings, 'REGISTRATION_SALT', 'registration')

class MyRegistrationView (RegistrationView):
    form_class = UserRegForm
    email_body_template = 'registration/activation_email.txt'
    email_subject_template = 'registration/activation_email_subject.txt'

    def register(self, form):
        new_user = self.create_inactive_user(form)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=self.request)
        return new_user

    def get_success_url(self, user):
        return ('registration_complete', (), {})

    def create_inactive_user(self, form):
        """
        Create the inactive user account and send an email containing
        activation instructions.

        """
        new_user = form.save(commit=False)
        new_user.is_active = False
        new_user.save()

        self.send_activation_email(new_user)

        return new_user

    def get_activation_key(self, user):
        """
        Generate the activation key which will be emailed to the user.

        """
        return signing.dumps(
            obj=getattr(user, user.USERNAME_FIELD),
            salt=REGISTRATION_SALT
        )

    def get_email_context(self, activation_key):
        """
        Build the template context used for the activation email.

        """
        return {
            'activation_key': activation_key,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
            'site': get_current_site(self.request)
        }

    def send_activation_email(self, user):
        """
        Send the activation email. The activation key is simply the
        username, signed using TimestampSigner.

        """
        activation_key = self.get_activation_key(user)
        context = self.get_email_context(activation_key)
        context.update({
            'user': user
        })
        subject = render_to_string(self.email_subject_template,
                                   context)
        # Force subject to a single line to avoid header-injection
        # issues.
        subject = ''.join(subject.splitlines())
        message = render_to_string(self.email_body_template,
                                   context)
        user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
</code>```

Remaining issue is it just reloads the Registration page rather than going to registration complete?

Body:
I'm trying to setup django-registration form with an extra field or two. I've read the documentation and scoured StackOverflow. I'm getting a problem where the user is registered with the new fields but when I try and login it doesn't recognise the password.

I've created a new view (I've just cut and pasted register from django-registration because I just want it running initially):

class MyRegistrationView (RegistrationView):
    form_class = UserRegForm

    def register(self, form):
        new_user = RegistrationProfile.objects.create_inactive_user(
            form,
            site=get_current_site(self.request)
        )
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=self.request)
        return new_user

It uses this form:

class UserRegForm(RegistrationForm):
    CHOICES = Institution.objects.all().order_by('name')

    institution=forms.ChoiceField(choices=( (x.id, x.name) for x in CHOICES ),
                                  required = True)

These are the additional models:

class Institution(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return u'%s' % (self.name)

class UserProfile(models.Model):
    user=models.OneToOneField(User, on_delete=models.CASCADE)
    institution=models.ForeignKey(
        Institution,
        null=True,
        blank=True)

    def __unicode__(self):
        return u'%s' % (self.user)

My URL

url(r'^register', views.MyRegistrationView.as_view(form_class=UserRegForm), name='registration_register'),

And I've added this to save the data: from models import UserProfile from forms import UserRegForm

def user_created(sender, user, request, **kwargs):
    form = UserRegForm(request.POST)

    try: data = UserProfile.objects.get(user=user)
    except: data = UserProfile(user=user)
    data.institution = form.data["institution"]
    data.save()

from registration.signals import user_registered
user_registered.connect(user_created)

Everything works in that the user is registered, an email is sent out, the institution is saved to the UserProfile, but when I try and login using the new user (having activated the account) it tells me the username and password don't match.

When I look at the database the hashed paasword string seems to be 10 characters shorter than the admins (setup using manage.py createsuperuser) so I am doing something I shouldn't or not doing something I should.

Help would be much appreciated.

Body:
I solved this by basically copying all of RegistrationView into MyRegistrationView.  The login now works are well.  I'm not sure why this was necessary.

from registration.backends.model_activation.views import RegistrationView
from registration.models import RegistrationProfile
from registration import signals
from django.contrib.sites.shortcuts import get_current_site
from django.core import signing
from django.template.loader import render_to_string
from django.conf import settings
REGISTRATION_SALT = getattr(settings, 'REGISTRATION_SALT', 'registration')

class MyRegistrationView (RegistrationView):
    form_class = UserRegForm
    email_body_template = 'registration/activation_email.txt'
    email_subject_template = 'registration/activation_email_subject.txt'

    def register(self, form):
        new_user = self.create_inactive_user(form)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=self.request)
        return new_user

    def get_success_url(self, user):
        return ('registration_complete', (), {})

    def create_inactive_user(self, form):
        """
        Create the inactive user account and send an email containing
        activation instructions.

        """
        new_user = form.save(commit=False)
        new_user.is_active = False
        new_user.save()

        self.send_activation_email(new_user)

        return new_user

    def get_activation_key(self, user):
        """
        Generate the activation key which will be emailed to the user.

        """
        return signing.dumps(
            obj=getattr(user, user.USERNAME_FIELD),
            salt=REGISTRATION_SALT
        )

    def get_email_context(self, activation_key):
        """
        Build the template context used for the activation email.

        """
        return {
            'activation_key': activation_key,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
            'site': get_current_site(self.request)
        }

    def send_activation_email(self, user):
        """
        Send the activation email. The activation key is simply the
        username, signed using TimestampSigner.

        """
        activation_key = self.get_activation_key(user)
        context = self.get_email_context(activation_key)
        context.update({
            'user': user
        })
        subject = render_to_string(self.email_subject_template,
                                   context)
        # Force subject to a single line to avoid header-injection
        # issues.
        subject = ''.join(subject.splitlines())
        message = render_to_string(self.email_body_template,
                                   context)
        user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)

Remaining issue is it just reloads the Registration page rather than going to registration complete?


问:
Automatically Execute a command when opening a new Integrated Terminal in VSCode IDE
Can VSCode IDE do this?
Execute a command such as running a batch file or powershell script automatically when a new Integrated Terminal is opened?</p>

答:
Yes, you can use the "terminal.integrated.shellArgs" setting to pass arguments to the shell. For instance, the following will print Hello World when opening a new Terminal instance:

"terminal.integrated.shellArgs.windows": [
    "-NoExit", "-Command", "Write-Host Hello World"
]
```


问:
Using QMDIArea with Qt 4.4.
I'm using the QMdiArea in Qt 4.4.

If a new project is created, I add a number of sub windows to a QMdiArea. I'd like to disallow the user to close a sub window during runtime. The sub windows should only be closed if the whole application is closed or if a new project is created.

How can I do this?

答:
You need to define your own subWindow. create a subclass of QMdiSubWindow and override the closeEvent(QCloseEvent *closeEvent). you can control it by argument. for example:

```<code>void ChildWindow::closeEvent(QCloseEvent *closeEvent)
{
  if(/*condition C*/)
    closeEvent->accept();
  else
   closeEvent->ignore(); // you can do something else, like
                         // writing a string in status bar ...
}
</code>```

then subclass the QMdiArea and override QMdiArea::closeAllSubWindows () like this:

```<code>class MainWindowArea : public QMdiArea
{
    Q_OBJECT
public:
    explicit MainWindowArea(QWidget *parent = 0);

signals:
    void closeAllSubWindows();
public slots:

};
// Implementation:
MainWindowArea::closeAllSubWindows()
{
    // set close condition (new project is creating, C = true)
    foreach(QMdiSubWindow* sub,this->subWindowList())
    {
        (qobject_cast<ChildWindow*>(sub))->close();
    }
}
</code>```

you may also need to override close slot of your mdi area.

OwnerDisplayName: nutario

Title: Using QMDIArea with Qt 4.4.

Body:
You need to define your own subWindow. create a subclass of QMdiSubWindow and override the closeEvent(QCloseEvent *closeEvent). you can control it by argument. for example:

void ChildWindow::closeEvent(QCloseEvent *closeEvent)
{
  if(/*condition C*/)
    closeEvent->accept();
  else
   closeEvent->ignore(); // you can do something else, like
                         // writing a string in status bar ...
}

then subclass the QMdiArea and override QMdiArea::closeAllSubWindows () like this:

class MainWindowArea : public QMdiArea
{
    Q_OBJECT
public:
    explicit MainWindowArea(QWidget *parent = 0);

signals:
    void closeAllSubWindows();
public slots:

};
// Implementation:
MainWindowArea::closeAllSubWindows()
{
    // set close condition (new project is creating, C = true)
    foreach(QMdiSubWindow* sub,this->subWindowList())
    {
        (qobject_cast<ChildWindow*>(sub))->close();
    }
}

you may also need to override close slot of your mdi area.


问:
Teradata / SQL join data conversion
This has been racking my brain for the entire afternoon, and I feel like I am missing something obvious. Thanks in advance.

I have two table, A and B. Table A has a column called A_id, and it has type DECIMAL(16,0). Table B has a column called B_id, and it has type varchar(100). I am trying to an inner join, ideally from A to B. After that, I also need to filter the result with a where clause, such as A = 12345. So far, I have tried below things.

```<code>select A.A_id, B.B_id
from A
join B on B.B_id = cast(cast(A.A_id as bigint) as archer(100))
where A_id = '12345';
</code>```

(I also tried cast A,A_id directly to varchar)

This doesn't produce any error, but it returns no result. I know they are same A_id and B_ids.

Furthermore, below code works and return good result

```<code>select A.A_id, B.B_id
from B
join a on B.B_id = A.A_id
where B_id = '12345';
</code>```

If I take out the where clause, then sql will return error message (2620) suggesting that I have bad character. Similarly, if I don't do any casting, sql will return error message. I assume there are some sort of implicit casting going on that made the second chunk of code work.

I really need help on how to make the first chunk of code work. So, how to cast A.A_id correctly so the join will actually work.

答:
When you compare a numeric and a character value the string will always be casted to a Float (which is the most flexible numeric format), see Implicit Type Convesions.

Your double cast simply removes the period which is part of the default format of a Decimal, and results in a string '12345' instead of '12345.'.

Obviously there's some bad data in table B which can't be casted to a numeric and the where B_id = '12345' removes that before the cast.

Of course it's a wrong data model when you have to join two columns with different data types, less efficient and statistics are lost.

As a workaround you can apply

```<code>on TO_NUMBER(B.B_id) = A.A_id -- TD14+
</code>```

or

```<code>on TRYCAST(B.B_id AS DECIMAL(16.0)) = A.A_id -- TD15.10+
</code>```

Both return NULL for bad data, but don't fail.

Title: Teradata / SQL join data conversion

Body:
This has been racking my brain for the entire afternoon, and I feel like I am missing something obvious. Thanks in advance.

I have two table, A and B. Table A has a column called A_id, and it has type DECIMAL(16,0). Table B has a column called B_id, and it has type varchar(100). I am trying to an inner join, ideally from A to B. After that, I also need to filter the result with a where clause, such as A = 12345. So far, I have tried below things.

select A.A_id, B.B_id
from A
join B on B.B_id = cast(cast(A.A_id as bigint) as archer(100))
where A_id = '12345';

(I also tried cast A,A_id directly to varchar)

This doesn't produce any error, but it returns no result. I know they are same A_id and B_ids.

Furthermore, below code works and return good result

select A.A_id, B.B_id
from B
join a on B.B_id = A.A_id
where B_id = '12345';

If I take out the where clause, then sql will return error message (2620) suggesting that I have bad character. Similarly, if I don't do any casting, sql will return error message. I assume there are some sort of implicit casting going on that made the second chunk of code work.

I really need help on how to make the first chunk of code work. So, how to cast A.A_id correctly so the join will actually work.

Body:
When you compare a numeric and a character value the string will always be casted to a Float (which is the most flexible numeric format), see Implicit Type Convesions.

Your double cast simply removes the period which is part of the default format of a Decimal, and results in a string '12345' instead of '12345.'.

Obviously there's some bad data in table B which can't be casted to a numeric and the where B_id = '12345' removes that before the cast.

Of course it's a wrong data model when you have to join two columns with different data types, less efficient and statistics are lost.

As a workaround you can apply

on TO_NUMBER(B.B_id) = A.A_id -- TD14+

or

on TRYCAST(B.B_id AS DECIMAL(16.0)) = A.A_id -- TD15.10+

Both return NULL for bad data, but don't fail.


问:
Angular - Correctly using RXJS expand operator to make recursive http calls
I am attempting to make recursive http calls to Reddit's API using a value from the previous call. The problem is that the previous call is not finished before the next one starts, so duplicate calls are being made. The "after" value should be updated for every call until the "after" value is undefined. I found this related post and have attempted to use the solution described, but I can't figure out how to make sure the previous call is finished before making the next call. Below is my actual code:</p>

```<code>private getSavedPostsForAuthenticatedUser(username: string, after: string, userPosts: any) {
    const headers = new Headers();
    if (!userPosts) {
        userPosts = [];
    }
    headers.append('Authorization', `Bearer ${this._token}`);
    const redditUrl = `${RetainerConfig.redditOauthUrl}user/${username}/saved`;
    const url = after ? `${redditUrl}/?after=${after}` : redditUrl;
    return this._http.get(url, { headers: headers })
        .map(response => response.json())
        .expand(response => {
            if (response.data) {
                for (const post of response.data.children) {
                    userPosts.push(post);
                }
                if (response.data.after) {
                    return this.getSavedPostsForAuthenticatedUser(username, response.data.after, userPosts);
                }
            }
            return Observable.of(userPosts);
        });
</code>```

答:
Returning the same function getSavedPostsForAuthenticatedUser will cause recursive expands. To solve this you need to separate the http observable.

  private getSavedPostsForAuthenticatedUser(username: string, after: string, userPosts: any) {
    const request$ = this._getRequest(username, after, userPosts);
    if (!userPosts) {
      userPosts = [];
    }
    return request$
      .expand(response => {
        if (response.data) {
          for (const post of response.data.children) {
            userPosts.push(post);
          }
          if (response.data.after) {
            return this._getRequest(username, response.data.after, userPosts);
          }
        }
        return Observable.of(userPosts);
      });
  }

  private _getRequest(username: string, after: string) {
    const headers = new Headers();
    headers.append('Authorization', `Bearer ${this._token}`);
    const redditUrl = `${RetainerConfig.redditOauthUrl}user/${username}/saved`;
    const url = after ? `${redditUrl}/?after=${after}` : redditUrl;

    return this._http.get(url, {headers: headers})
      .map(response => response.json());
  }
```

To stop the expanding you may use Observable.empty(). Please refer to this post.

Body:
I am attempting to make recursive http calls to Reddit's API using a value from the previous call. The problem is that the previous call is not finished before the next one starts, so duplicate calls are being made. The "after" value should be updated for every call until the "after" value is undefined. I found this related post and have attempted to use the solution described, but I can't figure out how to make sure the previous call is finished before making the next call. Below is my actual code:

private getSavedPostsForAuthenticatedUser(username: string, after: string, userPosts: any) {
    const headers = new Headers();
    if (!userPosts) {
        userPosts = [];
    }
    headers.append('Authorization', `Bearer ${this._token}`);
    const redditUrl = `${RetainerConfig.redditOauthUrl}user/${username}/saved`;
    const url = after ? `${redditUrl}/?after=${after}` : redditUrl;
    return this._http.get(url, { headers: headers })
        .map(response => response.json())
        .expand(response => {
            if (response.data) {
                for (const post of response.data.children) {
                    userPosts.push(post);
                }
                if (response.data.after) {
                    return this.getSavedPostsForAuthenticatedUser(username, response.data.after, userPosts);
                }
            }
            return Observable.of(userPosts);
        });

Body:
Returning the same function getSavedPostsForAuthenticatedUser will cause recursive expands. To solve this you need to separate the http observable.

  private getSavedPostsForAuthenticatedUser(username: string, after: string, userPosts: any) {
    const request$ = this._getRequest(username, after, userPosts);
    if (!userPosts) {
      userPosts = [];
    }
    return request$
      .expand(response => {
        if (response.data) {
          for (const post of response.data.children) {
            userPosts.push(post);
          }
          if (response.data.after) {
            return this._getRequest(username, response.data.after, userPosts);
          }
        }
        return Observable.of(userPosts);
      });
  }

  private _getRequest(username: string, after: string) {
    const headers = new Headers();
    headers.append('Authorization', `Bearer ${this._token}`);
    const redditUrl = `${RetainerConfig.redditOauthUrl}user/${username}/saved`;
    const url = after ? `${redditUrl}/?after=${after}` : redditUrl;

    return this._http.get(url, {headers: headers})
      .map(response => response.json());
  }

To stop the expanding you may use Observable.empty(). Please refer to this post.


问:
How to do a simple search in string in Firebase database?
I want to create a simple search in my app, but cannot find anything on interwebs about it, that's more recent than 2014. There must be a better way. There are startAt and endAt functions but they don't work as expected and are case sensitive. How do you guys solve this problem? How can this functionality still not exist in 2016?</p>

答:
I don't know about the certainty of this approach but using the firebase version 10.2.6 on android, i get to do something like this:

```<code>firebaseDatabase.getReference("parent")
                            .orderByChild("childNode")
                            .startAt("[a-zA-Z0-9]*")
                            .endAt(searchString)
</code>```

It seems to work well sometimes

Body:
I don't know about the certainty of this approach but using the firebase version 10.2.6 on android, i get to do something like this:

firebaseDatabase.getReference("parent")
                            .orderByChild("childNode")
                            .startAt("[a-zA-Z0-9]*")
                            .endAt(searchString)

It seems to work well sometimes


问:
WPF ActualWidth is zero
I have a user control which has a Canvas of height 100 and width 1920.

At the loading of the control, I go to an external source, download a text file and add TextBlocks to the Canvas. Then I want to create a marquee scrolling effect which should work just fine, except after I add the TextBlocks to the Canvas, I need to get their width for calculation purposes but the ActualWidth property is always zero.

Here is some code:

```<code>private readonly LinkedList<TextBlock> textBlocks = new LinkedList<TextBlock>();

public LocalNewsControl()
{
    Loaded += LocalNewsControlLoaded;
}

private void LocalNewsControlLoaded(object sender, RoutedEventArgs e)
{
    LoadDataContext();
}

private void LoadDataContext()
{
    DataContext = new NewsItemsViewModel((exception) => LoadNewsItems());
}

private void LoadNewsItems()
{
    var viewModel = (NewsItemsViewModel)DataContext;

    NewsCanvas.Children.Clear();
    textBlocks.Clear();

    foreach (var newsViewModel in viewModel.NewsItems)
    {
        var tb = new TextBlock
        {
            Text = newsViewModel.Headline,
            FontSize = 28,
            FontWeight = FontWeights.Normal,
            Foreground = Brushes.Black
        };

        NewsCanvas.Children.Add(tb);

        Canvas.SetTop(tb, 20);
        Canvas.SetLeft(tb, -999);

        textBlocks.AddLast(tb);
    }

    Dispatcher.BeginInvoke(new Action(() =>
    {
        var node = textBlocks.First;

        while (node != null)
        {
            if (node.Previous != null)
            {
                //THIS IS WHERE ActualWidth is always ZERO
                var left = Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + Gap;
                Canvas.SetLeft(node.Value, left);
            }
            else
                Canvas.SetLeft(node.Value, NewsCanvas.Width + Gap);

            node = node.Next;
        }
    }));
}
</code>```

答:
Any Control's ActualHeight or ActualWidth will always be zero before they are Loaded > Measured > Arranged > Rendered.

In your case, I recommend using Loaded or SizeChanged event of that TextBlock to your advantage.

Title: WPF ActualWidth is zero

Body:
I have a user control which has a Canvas of height 100 and width 1920.

At the loading of the control, I go to an external source, download a text file and add TextBlocks to the Canvas. Then I want to create a marquee scrolling effect which should work just fine, except after I add the TextBlocks to the Canvas, I need to get their width for calculation purposes but the ActualWidth property is always zero.

Here is some code:

private readonly LinkedList<TextBlock> textBlocks = new LinkedList<TextBlock>();

public LocalNewsControl()
{
    Loaded += LocalNewsControlLoaded;
}

private void LocalNewsControlLoaded(object sender, RoutedEventArgs e)
{
    LoadDataContext();
}

private void LoadDataContext()
{
    DataContext = new NewsItemsViewModel((exception) => LoadNewsItems());
}

private void LoadNewsItems()
{
    var viewModel = (NewsItemsViewModel)DataContext;

    NewsCanvas.Children.Clear();
    textBlocks.Clear();

    foreach (var newsViewModel in viewModel.NewsItems)
    {
        var tb = new TextBlock
        {
            Text = newsViewModel.Headline,
            FontSize = 28,
            FontWeight = FontWeights.Normal,
            Foreground = Brushes.Black
        };

        NewsCanvas.Children.Add(tb);

        Canvas.SetTop(tb, 20);
        Canvas.SetLeft(tb, -999);

        textBlocks.AddLast(tb);
    }

    Dispatcher.BeginInvoke(new Action(() =>
    {
        var node = textBlocks.First;

        while (node != null)
        {
            if (node.Previous != null)
            {
                //THIS IS WHERE ActualWidth is always ZERO
                var left = Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + Gap;
                Canvas.SetLeft(node.Value, left);
            }
            else
                Canvas.SetLeft(node.Value, NewsCanvas.Width + Gap);

            node = node.Next;
        }
    }));
}