问:
execute script on ajax success
here is my javascript code in my php document:-

```<code> ( function() {
if (window.CHITIKA === undefined) { window.CHITIKA = { 'units' : [] }; };
var unit = {"calltype":"async[2]","publisher":"soodsidhant","width":728,"height":90,"sid":"Chitika Default"};
var placement_id = window.CHITIKA.units.length;
window.CHITIKA.units.push(unit);
document.write('<div id="chitikaAdBlock-' + placement_id + '"></div>');
   }());
</code>```

this javascript makes a div on loading just below where the script is placed.

and i have a separate x.js file which sends data through ajax...
i want to execute the above code when get success.

one more thing if this script is executed from x.js where will it create the div in my site??? Also am i able to change that position???

i had already tried :- giving the script tag in my php document an id="ads" as [ answered here ] and calling it in ajax success by

```<code>eval(document.getElementById("ads").innerHTML);
</code>```

and it didn't helped also with this method there was no error in console

答: Put this function in your file with the ajax request and then call it in the .succuess(...) callback from POST or PUT or whatever.

Title: execute script on ajax success

Body:
here is my javascript code in my php document:-

 ( function() {
if (window.CHITIKA === undefined) { window.CHITIKA = { 'units' : [] }; };
var unit = {"calltype":"async[2]","publisher":"soodsidhant","width":728,"height":90,"sid":"Chitika Default"};
var placement_id = window.CHITIKA.units.length;
window.CHITIKA.units.push(unit);
document.write('

');
   }());

this javascript makes a div on loading just below where the script is placed.

and i have a separate x.js file which sends data through ajax...
i want to execute the above code when get success.

one more thing if this script is executed from x.js where will it create the div in my site??? Also am i able to change that position???

i had already tried :- giving the script tag in my php document an id="ads" as [ answered here ] and calling it in ajax success by

eval(document.getElementById("ads").innerHTML);

and it didn't helped also with this method there was no error in console


来源: stackexchange

问:
How to get current route in Symfony 2?
How do I get the current route in Symfony 2?

For example, routing.yml:

```<code>somePage:
   pattern: /page/
   defaults: { _controller: "AcmeBundle:Test:index" }
</code>```

How can I get this somePage value?

答:
With Symfony 3.3, I have used this method and working fine.

I have 4 routes like

admin_category_index,  admin_category_detail,  admin_category_create,
  admin_category_update

And just one line make an active class for all routes.

```<code><li  {% if app.request.get('_route') starts with 'admin_category' %} class="active"{% endif %}>
 <a href="{{ path('admin_category_index') }}">Product Categoires</a>
</li>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get current route in Symfony 2?

Body:
How do I get the current route in Symfony 2?

For example, routing.yml:

somePage:
   pattern: /page/
   defaults: { _controller: "AcmeBundle:Test:index" }

How can I get this somePage value?

Body:
With Symfony 3.3, I have used this method and working fine.

I have 4 routes like

admin_category_index,  admin_category_detail,  admin_category_create,
  admin_category_update

And just one line make an active class for all routes.

<li  {% if app.request.get('_route') starts with 'admin_category' %} class="active"{% endif %}>
 <a href="{{ path('admin_category_index') }}">Product Categoires</a>
</li>


问:
Change specific value in PHP variable
I have a variable $var and it contain comma separated value.

```<code>$var = 'the_ring,hangover,wonder_woman';
</code>```

I want to make it like below.

```<code>$var = 'The Ring,Hangover,Wonder Woman';
</code>```

I tried $parts = explode(',', $var); also I tried strpos() and  stripos() but not able to figure it out.

What can I do to achieve this?

答:
```<code>$var = 'the_ring,hangover,wonder_woman';

$list = explode(',', $var);

$list = array_map( function($name){
    return ucwords(str_replace('_',' ', $name));
}, $list);
</code>```

Returns:

```<code>Array
(
    [0] => The Ring
    [1] => Hangover
    [2] => Wonder Woman
)
</code>```

Imploding:

```<code>$imploded = implode(',', $list);
</code>```

Returns:

```<code>'The Ring,Hangover,Wonder Woman'
</code>```

Title: Change specific value in PHP variable

Body:
I have a variable $var and it contain comma separated value.

$var = 'the_ring,hangover,wonder_woman';

I want to make it like below.

$var = 'The Ring,Hangover,Wonder Woman';

I tried $parts = explode(',', $var); also I tried strpos() and  stripos() but not able to figure it out.

What can I do to achieve this?

Body:
$var = 'the_ring,hangover,wonder_woman';

$list = explode(',', $var);

$list = array_map( function($name){
    return ucwords(str_replace('_',' ', $name));
}, $list);

Returns:

Array
(
    [0] => The Ring
    [1] => Hangover
    [2] => Wonder Woman
)

Imploding:

$imploded = implode(',', $list);

Returns:

'The Ring,Hangover,Wonder Woman'


问:
bootstrap + mixitup filter on load issue
We are trying to show our portfolio in bootstrap via MixItUp v3.1.11 filtering and are trying to load a certain category (not all the projects) when the page is loaded.

Patrick Kunka has provided an example how it could be done here.

Same problem was asked here

Our issue is that the reccomended soultion is not working. My guess is that it is related to the change of selector due to bootstrap + mixitup issues:

control: '[data-mixitup-control]'

Here is the piece of code that is at the end of the page:

```<code>var containerEl = document.querySelector('#selector');

        var mixer = mixitup(containerEl, {
            selectors: {
                target: '.mix',
                control: '[data-mixitup-control]'
        },
            animation: {
                effects: 'fade scale stagger(50ms)' // Set a 'stagger' effect for the loading animation
            },
            load: {
                filter: 'none' // Ensure all targets start from hidden (i.e. display: none;)
            }
        });

        // Add a class to the container to remove 'visibility: hidden;' from targets. This
        // prevents any flickr of content before the page's JavaScript has loaded.

        containerEl.classList.add('mixitup-ready');

        // Show all targets in the container

        mixer.show()
            .then(function() {
                // Remove the stagger effect for any subsequent operations

                mixer.configure({
                    animation: {
                        effects: 'fade scale'
                    },
            load: {
                filter: '.residential' // Ensure all targets start from hidden (i.e. display: none;)
            }
                });
            });
</code>```

When I change the filter to desired .residential it does not work.

I also tried to add this:

```<code>    $(function(){
  $('#selector').mixItUp({
    load: {
      filter: '.residential'
    }
  });
});
</code>```

No luck. Any idea anyone where could the problem be?

答:
In combination with MixItUp Version 3.1.11 and Bootstrap 3 try this example.

Add data-mixitup-control to avoid conflicts with other data-attributes:

```<code><button type="button" class="control" data-mixitup-control data-filter=".residential">Residential</button>
</code>```

Initialize MixItUp:

```<code>var containerEl = document.querySelector('.container');

var mixer = mixitup(containerEl, {
    selectors: {
        control: '[data-mixitup-control]'
    },
    load: {
        filter: '.residential'
    }
});
</code>```

You don't need to set the 'fade scale' animation effect separately - it's the default setting. https://www.kunkalabs.com/mixitup/docs/configuration-object/

Body:
We are trying to show our portfolio in bootstrap via MixItUp v3.1.11 filtering and are trying to load a certain category (not all the projects) when the page is loaded.

Patrick Kunka has provided an example how it could be done here.

Same problem was asked here

Our issue is that the reccomended soultion is not working. My guess is that it is related to the change of selector due to bootstrap + mixitup issues:

control: '[data-mixitup-control]'

Here is the piece of code that is at the end of the page:

var containerEl = document.querySelector('#selector');

        var mixer = mixitup(containerEl, {
            selectors: {
                target: '.mix',
                control: '[data-mixitup-control]'
        },
            animation: {
                effects: 'fade scale stagger(50ms)' // Set a 'stagger' effect for the loading animation
            },
            load: {
                filter: 'none' // Ensure all targets start from hidden (i.e. display: none;)
            }
        });

        // Add a class to the container to remove 'visibility: hidden;' from targets. This
        // prevents any flickr of content before the page's JavaScript has loaded.

        containerEl.classList.add('mixitup-ready');

        // Show all targets in the container

        mixer.show()
            .then(function() {
                // Remove the stagger effect for any subsequent operations

                mixer.configure({
                    animation: {
                        effects: 'fade scale'
                    },
            load: {
                filter: '.residential' // Ensure all targets start from hidden (i.e. display: none;)
            }
                });
            });

When I change the filter to desired .residential it does not work.

I also tried to add this:

    $(function(){
  $('#selector').mixItUp({
    load: {
      filter: '.residential'
    }
  });
});

No luck. Any idea anyone where could the problem be?

Body:
In combination with MixItUp Version 3.1.11 and Bootstrap 3 try this example.

Add data-mixitup-control to avoid conflicts with other data-attributes:

<button type="button" class="control" data-mixitup-control data-filter=".residential">Residential</button>

Initialize MixItUp:

var containerEl = document.querySelector('.container');

var mixer = mixitup(containerEl, {
    selectors: {
        control: '[data-mixitup-control]'
    },
    load: {
        filter: '.residential'
    }
});

You don't need to set the 'fade scale' animation effect separately - it's the default setting. https://www.kunkalabs.com/mixitup/docs/configuration-object/


问:
Retrying URL: Connection reset by peer during fetch
I'm having trouble with one of the domains my Google Search Appliance (version 7.2) is crawling.

The retrieval error I'm getting is:

Retrying URL: Connection reset by peer during fetch

Can anyone tell me what can cause such an error or have suggestions how to solve this issue?

答:
If you use chrome dev, you can do the following things to have a try. The things I also meet today, but I had solved just now.

You can input chrome://net-internals/#hsts to the chrome search box. Then you will see a webpage.

Input a domain name to add it to the HSTS sit:

the line of Domain:[ ],you can input www.google.com.hk

this is the way to let chrome visit www.google.com.hk by https  forcibly

I hope it can help you


问:
Why does my carbon-cache process occupies ever increasing amount of memory?
I'm using graphite+diamond to monitor hundreds of my servers. I found that the carbon-cache is killed by oom-killer every 20 hours. At first, I thought maybe it's due to my disk is relative slow since it's a SATA disk, not SSD. However, when I use iostat to check the util of my disk, it's only about 70%:

```<code>Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            2.00     0.00  313.00    0.00  2484.00     0.00    15.87     0.84    2.67    2.67    0.00   2.43  76.05

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            1.50   144.50  261.50  306.50  2136.00  1804.00    13.87     1.13    2.00    3.03    1.11   1.27  72.30

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            0.50    97.00  137.00  332.50  1120.00  1718.00    12.09     1.98    4.23    6.69    3.21   1.70  79.90

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            2.50     0.00  163.50    0.00  1334.00     0.00    16.32     0.63    3.86    3.86    0.00   3.58  58.50

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            1.00   102.00  131.50  167.00  1048.00  1076.00    14.23     0.71    2.39    4.32    0.87   1.80  53.65

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            0.00     0.00   83.00    0.50   642.00     4.00    15.47     0.20    2.46    2.47    0.00   2.33  19.45
</code>```

And my CPU usage is also not very high:

```<code>%Cpu0  : 34.8 us,  5.2 sy,  0.0 ni, 58.2 id,  0.0 wa,  0.0 hi,  1.0 si,  0.7 st
%Cpu1  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu2  :  0.0 us,  0.0 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.3 st
%Cpu3  :  6.5 us,  1.7 sy,  0.0 ni,  5.4 id, 85.7 wa,  0.0 hi,  0.0 si,  0.7 st
</code>```

How should I deal with this problem?

PS: our console.log is as follows:

```<code>07/06/2017 19:41:57 :: Sorted 16 cache queues in 0.000308 seconds
07/06/2017 19:41:57 :: Sorted 2 cache queues in 0.000200 seconds
07/06/2017 19:41:58 :: Sorted 564 cache queues in 0.000762 seconds
07/06/2017 19:41:58 :: Sorted 116 cache queues in 0.000388 seconds
07/06/2017 19:41:59 :: Sorted 820 cache queues in 0.001008 seconds
07/06/2017 19:42:00 :: Sorted 52 cache queues in 0.000354 seconds
07/06/2017 19:42:00 :: Sorted 1 cache queues in 0.000175 seconds
07/06/2017 19:42:01 :: Sorted 491 cache queues in 0.000530 seconds
07/06/2017 19:42:01 :: Sorted 101 cache queues in 0.000431 seconds
07/06/2017 19:42:01 :: Sorted 21 cache queues in 0.000283 seconds
07/06/2017 19:42:02 :: Sorted 1342 cache queues in 0.001589 seconds
07/06/2017 19:42:02 :: Sorted 224 cache queues in 0.000525 seconds
07/06/2017 19:42:02 :: Sorted 67 cache queues in 0.000299 seconds
07/06/2017 19:42:03 :: Sorted 1812 cache queues in 0.002230 seconds
07/06/2017 19:42:03 :: Sorted 360 cache queues in 0.000583 seconds
07/06/2017 19:42:03 :: Sorted 109 cache queues in 0.000430 seconds
07/06/2017 19:42:03 :: Sorted 27 cache queues in 0.000269 seconds
07/06/2017 19:42:04 :: Sorted 1570 cache queues in 0.001632 seconds
07/06/2017 19:42:05 :: Sorted 348 cache queues in 0.000656 seconds
</code>```

答:
Carbon has a ratelimit on how much writes it does per second. If your disk isn't saturated yet you can increase this. Be careful that if you set this too high you can starve other applications on this system or other hosts if you are on shared storage (SAN/NAS).

You can find this rate limit in the carbon.conf file. The setting is:

MAX_UPDATES_PER_SECOND =

To prevent the system from killing carbon you could consider configuring the maximum cache size. This will prevent carbon being killed, but will drop metrics if it hits the limit. The limit is in number of points in the cache, see the metric carbon.agents.$instance.cache.size to determine a good value. Also in carbon.conf:

MAX_CACHE_SIZE =

Also keep in mind that due to Python's Global Interpreter Lock (GIL), carbon can only run on one core at the same time. Your current CPU usage seems fine, but if your load increases more you could consider running 4 carbon caches (as you have 4 cores) with a carbon-relay in front to fully utilize your systems resources.

Body:
I'm using graphite+diamond to monitor hundreds of my servers. I found that the carbon-cache is killed by oom-killer every 20 hours. At first, I thought maybe it's due to my disk is relative slow since it's a SATA disk, not SSD. However, when I use iostat to check the util of my disk, it's only about 70%:

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            2.00     0.00  313.00    0.00  2484.00     0.00    15.87     0.84    2.67    2.67    0.00   2.43  76.05

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            1.50   144.50  261.50  306.50  2136.00  1804.00    13.87     1.13    2.00    3.03    1.11   1.27  72.30

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            0.50    97.00  137.00  332.50  1120.00  1718.00    12.09     1.98    4.23    6.69    3.21   1.70  79.90

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            2.50     0.00  163.50    0.00  1334.00     0.00    16.32     0.63    3.86    3.86    0.00   3.58  58.50

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            1.00   102.00  131.50  167.00  1048.00  1076.00    14.23     0.71    2.39    4.32    0.87   1.80  53.65

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvdap1            0.00     0.00   83.00    0.50   642.00     4.00    15.47     0.20    2.46    2.47    0.00   2.33  19.45

And my CPU usage is also not very high:

%Cpu0  : 34.8 us,  5.2 sy,  0.0 ni, 58.2 id,  0.0 wa,  0.0 hi,  1.0 si,  0.7 st
%Cpu1  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu2  :  0.0 us,  0.0 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.3 st
%Cpu3  :  6.5 us,  1.7 sy,  0.0 ni,  5.4 id, 85.7 wa,  0.0 hi,  0.0 si,  0.7 st

How should I deal with this problem?

PS: our console.log is as follows:

07/06/2017 19:41:57 :: Sorted 16 cache queues in 0.000308 seconds
07/06/2017 19:41:57 :: Sorted 2 cache queues in 0.000200 seconds
07/06/2017 19:41:58 :: Sorted 564 cache queues in 0.000762 seconds
07/06/2017 19:41:58 :: Sorted 116 cache queues in 0.000388 seconds
07/06/2017 19:41:59 :: Sorted 820 cache queues in 0.001008 seconds
07/06/2017 19:42:00 :: Sorted 52 cache queues in 0.000354 seconds
07/06/2017 19:42:00 :: Sorted 1 cache queues in 0.000175 seconds
07/06/2017 19:42:01 :: Sorted 491 cache queues in 0.000530 seconds
07/06/2017 19:42:01 :: Sorted 101 cache queues in 0.000431 seconds
07/06/2017 19:42:01 :: Sorted 21 cache queues in 0.000283 seconds
07/06/2017 19:42:02 :: Sorted 1342 cache queues in 0.001589 seconds
07/06/2017 19:42:02 :: Sorted 224 cache queues in 0.000525 seconds
07/06/2017 19:42:02 :: Sorted 67 cache queues in 0.000299 seconds
07/06/2017 19:42:03 :: Sorted 1812 cache queues in 0.002230 seconds
07/06/2017 19:42:03 :: Sorted 360 cache queues in 0.000583 seconds
07/06/2017 19:42:03 :: Sorted 109 cache queues in 0.000430 seconds
07/06/2017 19:42:03 :: Sorted 27 cache queues in 0.000269 seconds
07/06/2017 19:42:04 :: Sorted 1570 cache queues in 0.001632 seconds
07/06/2017 19:42:05 :: Sorted 348 cache queues in 0.000656 seconds


问:
Equal height navigation bars
I have two pages in my app: One embedded in a UINavigationController and one thats not. The page that's not in the UINavigationController has a UINavigationBar that I dragged in and set its prompt to an empty string to increase its height a bit. However, this causes it to be slightly taller than the page that's embedded in a UINavigationController. Here's a side by side picture:

If I set a prompt on the navigation bar of left page it's height becomes too tall. When I go to the storyboard inspector I see the height it should be is 74:

Does anybody know how to artificially make the bar on the page embedded in a UINavigationController the same height as the one that's not?

答:
This situation is common for others who added the UINavigationBar manually (i.e. not via embedding inside UINavigationController).

Generic UINavigationBar would have height of 44 points

The issue is the 20 points gap above the manually added UINavigationBar.

In the case of embedded version, the gap (assuming it exists) has the same background color as the UINavigationBar. When you add the prompt, it added 30 points expanding upward. So instead of 20 + 44 = 64 points, now you have 74 points.  And the embedded UINavigationBar has 64 points. Thus the difference of 10 points. And for the same reason, add " " (space) on embedded UINavigationBar will cause the height to be higher than 74 points.

I think your best bet would be to also embed the other ViewController inside a new UINavigationController.  iOS is smart enough to treat it as if there is only one NavigationController, not two. The user would not experiencing any difference. As for the programmer, you need to take into account the extra UINavigationController if you need to find the second ViewController programmatically.

Title: Equal height navigation bars


问:
How do I insert data retrieved from database into pre-styled HTML tags?
I want to display the data I retrieve from a database table in styled HTML.
Please look at the code below, the commented out line works and I would like to fill in the data in the
 below the comment.
Thanks in advance

I know my code is vulnerable, but I want to get it to work before I worry about security.

```<code><body>
<div id="wrapper" class="menu">
    <?php require('inc-nav.php') ?>

    <section class="content">

        <?php
        require('connect.php');

        $conn = mysqli_connect($servername, $username, $password, $dbname);
        $sql = "SELECT name, breed, age FROM dogs";
        $result = mysqli_query($conn, $sql);

        if (mysqli_num_rows($result) > 0) {
            // output data of each row
            while($dogs = mysqli_fetch_assoc($result)) {
//          echo 'Name: ' . $dogs['name'] . '<br>' . 'Breed: ' . $dogs['breed'] . '<br>' . 'Age: ' . $dogs['age'] . '<br><hr>';
                echo '
                <section class="profile">
                    <figure class="profile-pic"><img src="images/1.jpg" alt=""></figure>
                    <h1 class="name">Name</h1>
                    <h2 class="description1">Breed | gender | age</h2>
                    <p class="description2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto corporis dolores dolorum eaque eum in nemo quos totam ullam. Autem?</p>
                    <button class="cta-profile"><a href="#">Read more</a></button>
                </section>
                ';
            }
        } else {
            echo "0 results";
        }

        mysqli_close($conn);
        ?>

    </section>

    <?php require('inc-footer.php');?>
</div>
</code>```

答:
```<code> echo '
               <section class="profile">
                    <figure class="profile-pic"><img src="images/1.jpg" alt=""></figure>
                    <h1 class="name">'.$dogs["name"].'</h1>
                    <h2 class="description1">'.$dogs["breed"].' | '.$dogs["age"].'</h2>
                    <p class="description2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto corporis dolores dolorum eaque eum in nemo quos totam ullam. Autem?</p>
                    <button class="cta-profile"><a href="#">Read more</a></button>
                </section>
                ';
</code>```

Body:
I want to display the data I retrieve from a database table in styled HTML.
Please look at the code below, the commented out line works and I would like to fill in the data in the
 below the comment.
Thanks in advance

I know my code is vulnerable, but I want to get it to work before I worry about security.

    <?php require('inc-nav.php') ?>

        <?php
        require('connect.php');

        $conn = mysqli_connect($servername, $username, $password, $dbname);
        $sql = "SELECT name, breed, age FROM dogs";
        $result = mysqli_query($conn, $sql);

        if (mysqli_num_rows($result) > 0) {
            // output data of each row
            while($dogs = mysqli_fetch_assoc($result)) {
//          echo 'Name: ' . $dogs['name'] . '
' . 'Breed: ' . $dogs['breed'] . '
' . 'Age: ' . $dogs['age'] . '

';
                echo '

Name

Breed | gender | age

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto corporis dolores dolorum eaque eum in nemo quos totam ullam. Autem?

                    <button class="cta-profile">Read more</button>

                ';
            }
        } else {
            echo "0 results";
        }

        mysqli_close($conn);
        ?>

    <?php require('inc-footer.php');?>


问:
Logstash Grok match to last index unti begin of UserAgent
I have this log message:

```<code>"sid-cmascioieiow89322&New*Sou,th%20Skvn%20and%20ir&o,n%20Age,Mozilla/5.0 (Linux; Android 6.0; CHM-U01 Build/HonorCHM-U01) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36"
</code>```

And the pattern:

```<code>"(?[^&])&(?[^,]),%{GREEDYDATA:User_Agent}"
</code>```

The problem is p2 sometimes contains zero or one or more then one comma. I want to match to the last comma before UserAgent because UserAgent some time contains commas.

This is the grok debugger link: https://grokdebug.herokuapp.com/

Now:

```<code>{
    "p1": [
        "sid-cmascioieiow89322"
    ],
    "p2": [
        "New*Sou"
    ],
    "User_Agent": [
        "th%20Skvn%20and%20iro,n%20Age,Mozilla/5.0 (Linux; Android 6.0; CHM-U01 Build/HonorCHM-U01) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36"
    ]
}
</code>```

I want like this:

```<code>{
    "p1": [
        "sid-cmascioieiow89322"
    ],
    "p2": [
        "New*Sou,th%20Skvn%20and%20ir&o,n%20Age"
    ],
    "User_Agent": [
        "Mozilla/5.0 (Linux; Android 6.0; CHM-U01 Build/HonorCHM-U01) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36"
    ]
}
</code>```

Thank you for your help.

答:
The part of string that you want to capture into p2 part has no whitespaces. Thus, instead of a [^,]* pattern that matches any zero or more chars other than , you may use \S* - any 0+ non-whitespace chars as many as possible, thus \S*, will match the comma that is the last in the streak of non-whitespace chars.

```<code>(?<p1>[^&]*)&(?<p2>\S*),%{GREEDYDATA:User_Agent}
             ^^^^^^^^^^
</code>```

This is how this regex matches your log data:

See the Grok demo screenshot:

Body:
I have this log message:

"sid-cmascioieiow89322&New*Sou,th%20Skvn%20and%20ir&o,n%20Age,Mozilla/5.0 (Linux; Android 6.0; CHM-U01 Build/HonorCHM-U01) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36"

And the pattern:

"(?[^&])&(?[^,]),%{GREEDYDATA:User_Agent}"

The problem is p2 sometimes contains zero or one or more then one comma. I want to match to the last comma before UserAgent because UserAgent some time contains commas.

This is the grok debugger link: https://grokdebug.herokuapp.com/

Now:

{
    "p1": [
        "sid-cmascioieiow89322"
    ],
    "p2": [
        "New*Sou"
    ],
    "User_Agent": [
        "th%20Skvn%20and%20iro,n%20Age,Mozilla/5.0 (Linux; Android 6.0; CHM-U01 Build/HonorCHM-U01) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36"
    ]
}

I want like this:

{
    "p1": [
        "sid-cmascioieiow89322"
    ],
    "p2": [
        "New*Sou,th%20Skvn%20and%20ir&o,n%20Age"
    ],
    "User_Agent": [
        "Mozilla/5.0 (Linux; Android 6.0; CHM-U01 Build/HonorCHM-U01) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36"
    ]
}

Thank you for your help.

Body:
The part of string that you want to capture into p2 part has no whitespaces. Thus, instead of a [^,]* pattern that matches any zero or more chars other than , you may use \S* - any 0+ non-whitespace chars as many as possible, thus \S*, will match the comma that is the last in the streak of non-whitespace chars.

(?<p1>[^&]*)&(?<p2>\S*),%{GREEDYDATA:User_Agent}
             ^^^^^^^^^^

This is how this regex matches your log data:

See the Grok demo screenshot:


问:
How to create directory automatically on SD card
I'm trying to save my file to the following location

FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);
but I'm getting the exception java.io.FileNotFoundException

However, when I put the path as "/sdcard/" it works.

Now I'm assuming that I'm not able to create directory automatically this way.

Can someone suggest how to create a directory and sub-directory using code?

答:
Had the same problem and just want to add that AndroidManifest.xml also needs this permission:</p>

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Body:
Had the same problem and just want to add that AndroidManifest.xml also needs this permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

ContentLicense: CC BY-SA 2.5


问:
Google Maps API v3 - Custom Marker not appearing
I am sure this is a simple fix, but I've been searching all over and everything I try just does not work. All I'm trying to do is replace the default marker with a custom icon, but it will not show up. Here's my code:

```<code><script type="text/javascript">

function initialize() {
var myLatlng = new google.maps.LatLng(43.041936,-88.044523);
var mapOptions = {
    center:myLatlng,
    zoom:15,
    disableDefaultUI:true,
    mapTypeId:google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("milwaukeeMap"), mapOptions);

var marker = new google.maps.Marker();
    marker.setPosition(myLatlng);
    marker.setMap(map);
    marker.setIcon('/images/map-marker.png');
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</code>```

I know the image is in the correct location; I can find it in my browser if I type the path. I've checked and double-checked, but is there a problem with my code? Sorry, I can't provide a live example.

答:
I found that in some cases, externally hosted icons need an extra parameter e.g.</p>

```<code>images/map-marker.png?raw=true
</code>```

Body:
I am sure this is a simple fix, but I've been searching all over and everything I try just does not work. All I'm trying to do is replace the default marker with a custom icon, but it will not show up. Here's my code:

I know the image is in the correct location; I can find it in my browser if I type the path. I've checked and double-checked, but is there a problem with my code? Sorry, I can't provide a live example.

Body:
I found that in some cases, externally hosted icons need an extra parameter e.g.

images/map-marker.png?raw=true


问:
This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint
New Layout editor in Android Studio 2.2 keeps showing this error on views like EditText and Buttons. kindly help.Also, any links that help in onboarding with the new constraint layout would be appreciated.

code:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.set.email.MainActivity"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:text="To:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="7dp"
        tools:layout_editor_absoluteY="4dp"
        android:id="@+id/textTo"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="24dp"
        android:id="@+id/editTo"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Medium"/>

    <EditText
        android:layout_width="384dp"
        android:layout_height="42dp"
        android:inputType="textPersonName"
        android:ems="10"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="94dp"
        android:id="@+id/editSubject"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Medium"/>

    <EditText
        android:layout_width="384dp"
        android:layout_height="273dp"
        android:inputType="textPersonName"
        android:ems="10"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="179dp"
        android:id="@+id/editMessage"
        app:layout_constraintLeft_toLeftOf="@+id/activity_main"
        tools:layout_constraintLeft_creator="50"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Medium"/>

    <Button
        android:text="Send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="140dp"
        tools:layout_editor_absoluteY="454dp"
        android:id="@+id/btnSend"
        app:layout_constraintLeft_toLeftOf="@+id/editMessage"
        tools:layout_constraintLeft_creator="0"
        app:layout_constraintRight_toRightOf="@+id/activity_main"
        android:layout_marginEnd="16dp"
        tools:layout_constraintRight_creator="0"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Medium"/>

</android.support.constraint.ConstraintLayout>
</code>```

答:
Just copy this code to all components that you will drag.

```<code>app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
</code>```

example:

```<code><TextView
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:text="To:"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteX="7dp"
    tools:layout_editor_absoluteY="4dp"
    android:id="@+id/textTo"/>
</code>```

Body:
New Layout editor in Android Studio 2.2 keeps showing this error on views like EditText and Buttons. kindly help.Also, any links that help in onboarding with the new constraint layout would be appreciated.

code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.set.email.MainActivity"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:text="To:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="7dp"
        tools:layout_editor_absoluteY="4dp"
        android:id="@+id/textTo"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="24dp"
        android:id="@+id/editTo"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Medium"/>

    <EditText
        android:layout_width="384dp"
        android:layout_height="42dp"
        android:inputType="textPersonName"
        android:ems="10"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="94dp"
        android:id="@+id/editSubject"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Medium"/>

    <EditText
        android:layout_width="384dp"
        android:layout_height="273dp"
        android:inputType="textPersonName"
        android:ems="10"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="179dp"
        android:id="@+id/editMessage"
        app:layout_constraintLeft_toLeftOf="@+id/activity_main"
        tools:layout_constraintLeft_creator="50"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Medium"/>

    <Button
        android:text="Send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="140dp"
        tools:layout_editor_absoluteY="454dp"
        android:id="@+id/btnSend"
        app:layout_constraintLeft_toLeftOf="@+id/editMessage"
        tools:layout_constraintLeft_creator="0"
        app:layout_constraintRight_toRightOf="@+id/activity_main"
        android:layout_marginEnd="16dp"
        tools:layout_constraintRight_creator="0"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Medium"/>

</android.support.constraint.ConstraintLayout>

Body:
Just copy this code to all components that you will drag.

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"

example:

<TextView
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:text="To:"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteX="7dp"
    tools:layout_editor_absoluteY="4dp"
    android:id="@+id/textTo"/>

ContentLicense: CC BY-SA 4.0


问:
How to handle try catch exception in ride robot framework?
I'm using RIDE robotframework, i want to handle an exception when the application is crashed i close it then open a new instance of it.

```<code>*** Settings ***
Library           SikuliLibrary

*** Variables ***
${openProject}    sikuli_captured\\Emna\\openProject.png
${DataBaseSTProject}    sikuli_captured\\Emna\\DataBaseSTProject.png
${testSession}    sikuli_captured\\Emna\\testSession.png
${menu}           sikuli_captured\\menu.png
${fileName}       sikuli_captured\\Emna\\fileName.png
${save}           sikuli_captured\\Emna\\save.png

*** Test Cases ***
createNewProject
    Click    ${menu}
    Click    ${testSession}
    Input Text    ${fileName}    FirstProjecT3
    Click    ${save}

openTestProject
    Click    ${openProject}
    Double Click    ${DataBaseSTProject}
</code>```

Any suggestion would be appreciated.

Thanks for your help :)

答:
In Robot Framework the concept of Try/Catch/Finally is not present. In essence your Test Case body is the Try part of this trifecta and the other two are combined into the [Teardown] keywords of the respective Test Suite, Test Case or Keyword sections.

Within this Teardown keyword it is possible to recognize if a Test Case has Passed or Failed through the automatic variables of Robot Framework itself or the Run Keyword If ... family of keywords. This would allow you to create a separate section for the Catch, and finally. In the below section of code an example is given of a pass and fail test case, each using the same Teardown.

This construct should allow you to check if a step in a test case failed, verify if the application has crashed (through the Sikuli image test of the popup) and then close and restart the application.

```<code>*** Test Cases ***

Open Application and fail
    Log to Console    About to Fail
    Fail
    Log to Console    Will never trigger.
    [Teardown]    Generic Test Case Teardown

Open Application and Pass
    Log to Console    About to Pass
    No Operation
    Log to Console    Will trigger.
    [Teardown]    Generic Test Case Teardown

*** Keywords ***
Generic Test Case Teardown
    # Catch of Try Catch Finally
    Run Keyword If Test Failed    Test Case Catch

    # Finally of Try Catch Finally
    #  RKITS is only executed when test passed.
    Run Keyword If Test Passed    Test Case Finally
    #  Always executed regardless of test execution status.
    Log To Console     I am always executed.

Test Case Catch
    Log To Console    Test Case Catch

Test Case Finally
    Log To Console    Test Case Finally
</code>```

Body:
I'm using RIDE robotframework, i want to handle an exception when the application is crashed i close it then open a new instance of it.

*** Settings ***
Library           SikuliLibrary

*** Variables ***
${openProject}    sikuli_captured\\Emna\\openProject.png
${DataBaseSTProject}    sikuli_captured\\Emna\\DataBaseSTProject.png
${testSession}    sikuli_captured\\Emna\\testSession.png
${menu}           sikuli_captured\\menu.png
${fileName}       sikuli_captured\\Emna\\fileName.png
${save}           sikuli_captured\\Emna\\save.png

*** Test Cases ***
createNewProject
    Click    ${menu}
    Click    ${testSession}
    Input Text    ${fileName}    FirstProjecT3
    Click    ${save}

openTestProject
    Click    ${openProject}
    Double Click    ${DataBaseSTProject}

Any suggestion would be appreciated.

Thanks for your help :)

Body:
In Robot Framework the concept of Try/Catch/Finally is not present. In essence your Test Case body is the Try part of this trifecta and the other two are combined into the [Teardown] keywords of the respective Test Suite, Test Case or Keyword sections.

Within this Teardown keyword it is possible to recognize if a Test Case has Passed or Failed through the automatic variables of Robot Framework itself or the Run Keyword If ... family of keywords. This would allow you to create a separate section for the Catch, and finally. In the below section of code an example is given of a pass and fail test case, each using the same Teardown.

This construct should allow you to check if a step in a test case failed, verify if the application has crashed (through the Sikuli image test of the popup) and then close and restart the application.

*** Test Cases ***

Open Application and fail
    Log to Console    About to Fail
    Fail
    Log to Console    Will never trigger.
    [Teardown]    Generic Test Case Teardown

Open Application and Pass
    Log to Console    About to Pass
    No Operation
    Log to Console    Will trigger.
    [Teardown]    Generic Test Case Teardown

*** Keywords ***
Generic Test Case Teardown
    # Catch of Try Catch Finally
    Run Keyword If Test Failed    Test Case Catch

    # Finally of Try Catch Finally
    #  RKITS is only executed when test passed.
    Run Keyword If Test Passed    Test Case Finally
    #  Always executed regardless of test execution status.
    Log To Console     I am always executed.

Test Case Catch
    Log To Console    Test Case Catch

Test Case Finally
    Log To Console    Test Case Finally


问:
How can I change the color of one letter in JavaScript?
I have a string and I want to change just one color letter in JavaScript.

HTML:

```<code><div id="lettersList">Hello</div>
</code>```

In my JavaScript file, I retrieve like this (normal)

```<code>var lettres = document.getElementById("lettersList");
</code>```

But I don't know how to change the color of just one word (the 'o' of "hello" for example).
If I change thanks to

for (var i=0; i<lettres.length; i++ { lettres[i].style.color = "yellow"; }

it changes all the text (of course). But I don't want that.

答:
it works with

```<code>for(var i = 0; i<letters.length; i++){ if(i == 4 { element.innerHTML =element.innerHTML.replace(letters[i], '<span style="color:yellow;">'+letters[i]+'</span>');}}
</code>```

But if a word contains two similar letters, I can't color the both... Why that ?

Body:
I have a string and I want to change just one color letter in JavaScript.

HTML:

Hello

In my JavaScript file, I retrieve like this (normal)

var lettres = document.getElementById("lettersList");

But I don't know how to change the color of just one word (the 'o' of "hello" for example).
If I change thanks to

for (var i=0; i<lettres.length; i++ { lettres[i].style.color = "yellow"; }

it changes all the text (of course). But I don't want that.

Body:
it works with

for(var i = 0; i<letters.length; i++){ if(i == 4 { element.innerHTML =element.innerHTML.replace(letters[i], '<span style="color:yellow;">'+letters[i]+'</span>');}}

But if a word contains two similar letters, I can't color the both... Why that ?


问:
Can we increase the Parallelism for Non-Keyed Windows by setParallelism?
From the article below we know the parallelism is 1 for non-keyed streams, so can we increase the parallelism by setParallelism ?
"In case of non-keyed streams, your original stream will not be split into multiple logical streams and all the windowing logic will be performed by a single task, i.e. with parallelism of 1."

https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/windows.html#keyed-vs-non-keyed-windows

答: As soon as you would try to use setParallelism to set a different value than 1 on an operator of a stream within an All Window operator, an exception will be thrown. This functionality is also exposed, as you can use forceNonParallel to ensure that the parallelism of the corresponding operator cannot be overridden.</p>


问:
Hooking up UIButton to closure? (Swift, target-action)
I want to hook up a UIButton to a piece of code – from what I have found, the preferred method to do this in Swift is still to use the addTarget(target: AnyObject?, action: Selector, forControlEvents: UIControlEvents) function. This uses the Selector construct presumably for backwards compatibility with Obj-C libraries. I think I understand the reason for @selector in Obj-C – being able to refer to a method since in Obj-C methods are not first-class values.

In Swift though, functions are first-class values. Is there a way to connect a UIButton to a closure, something similar to this:

```<code>// -- Some code here that sets up an object X

let buttonForObjectX = UIButton()

// -- configure properties here of the button in regards to object
// -- for example title

buttonForObjectX.addAction(action: {() in

  // this button is bound to object X, so do stuff relevant to X

}, forControlEvents: UIControlEvents.TouchUpOutside)
</code>```

To my knowledge, the above is currently not possible. Considering that Swift looks like it's aiming to be a quite functional, why is this? The two options could clearly co-exist for backwards compatibility. Why doesn't this work more like onClick() in JS? It seems that the only way to hook up a UIButton to a target-action pair is to use something that exists solely for backwards compatibility reasons (Selector).

My use case is to create UIButtons in a loop for different objects, and then hook each up to a closure. (Setting a tag / looking up in a dictionary / subclassing UIButton are dirty semi-solutions, but I'm interested in how to do this functionally, ie this closure approach)

答:
The associatedObject and wrapping and pointers and import of ObjectiveC are unnecessary, at least in Swift 3. This works great and is much more Swift-y. Feel free to throw a typealias in there for () -> () if you find it more readable, bit I find it easier to read the block signature directly.

```<code>import UIKit

class BlockButton: UIButton {
    fileprivate var onAction: (() -> ())?

    func addClosure(_ closure: @escaping () -> (), for control: UIControlEvents) {
        self.addTarget(self, action: #selector(actionHandler), for: control)
        self.onAction = closure
    }

    dynamic fileprivate func actionHandler() {
        onAction?()
    }
}
</code>```

Body:
I want to hook up a UIButton to a piece of code – from what I have found, the preferred method to do this in Swift is still to use the addTarget(target: AnyObject?, action: Selector, forControlEvents: UIControlEvents) function. This uses the Selector construct presumably for backwards compatibility with Obj-C libraries. I think I understand the reason for @selector in Obj-C – being able to refer to a method since in Obj-C methods are not first-class values.

In Swift though, functions are first-class values. Is there a way to connect a UIButton to a closure, something similar to this:

// -- Some code here that sets up an object X

let buttonForObjectX = UIButton()

// -- configure properties here of the button in regards to object
// -- for example title

buttonForObjectX.addAction(action: {() in

  // this button is bound to object X, so do stuff relevant to X

}, forControlEvents: UIControlEvents.TouchUpOutside)

To my knowledge, the above is currently not possible. Considering that Swift looks like it's aiming to be a quite functional, why is this? The two options could clearly co-exist for backwards compatibility. Why doesn't this work more like onClick() in JS? It seems that the only way to hook up a UIButton to a target-action pair is to use something that exists solely for backwards compatibility reasons (Selector).

My use case is to create UIButtons in a loop for different objects, and then hook each up to a closure. (Setting a tag / looking up in a dictionary / subclassing UIButton are dirty semi-solutions, but I'm interested in how to do this functionally, ie this closure approach)

Body:
The associatedObject and wrapping and pointers and import of ObjectiveC are unnecessary, at least in Swift 3. This works great and is much more Swift-y. Feel free to throw a typealias in there for () -> () if you find it more readable, bit I find it easier to read the block signature directly.

import UIKit

class BlockButton: UIButton {
    fileprivate var onAction: (() -> ())?

    func addClosure(_ closure: @escaping () -> (), for control: UIControlEvents) {
        self.addTarget(self, action: #selector(actionHandler), for: control)
        self.onAction = closure
    }

    dynamic fileprivate func actionHandler() {
        onAction?()
    }
}


问:
base64 bytesstring to string to bytestring again in Python?
I'm trying to pass images down the wire in json objects.
{ image: "b'stuff'"} or whatever format it needs to be.

I've tried a variety of things and I keep getting the issues:

File "/usr/lib/python3.5/base64.py", line 521, in _input_type_check
    raise TypeError(msg) from err
TypeError: expected bytes-like object, not str

This is easily replicated because the behavior follows this:

```<code>np.zeros((32,32,3), dtype=np.uint8)
encoded = base64.encodebytes(image)

encoded = str(encoded) #this happens when you send via json

decoded = base64.decodebytes(encoded)
d_image = np.fromstring(decoded, dtype=np.uint8)
d_image = np.reshape(d_image, (32, 32, 3))
</code>```

Is there any details on how to decode the string properly or get it into a numpy array?  I can't seem to get it to work for the life of me.

答:
Base64 is a binary-to-binary encoding in Python. It takes raw bytes and gives raw bytes to be sent anywhere. This can easily be converted to and from text, as base64 will always be ascii.

To convert the bytes into a numpy array, you want to use numpy.frombuffer().

```<code>encoded = base64.encodebytes(image_bytes).decode('US-ASCII')
# Send this in the JSON
</code>```

```<code>encoded = json['image'].encode('US-ASCII')  # Convert back to bytes
image_bytes = base64.decodebytes(encoded)

d_image = numpy.frombuffer(image_bytes)
</code>```

Body:
I'm trying to pass images down the wire in json objects.
{ image: "b'stuff'"} or whatever format it needs to be.

I've tried a variety of things and I keep getting the issues:

File "/usr/lib/python3.5/base64.py", line 521, in _input_type_check
    raise TypeError(msg) from err
TypeError: expected bytes-like object, not str

This is easily replicated because the behavior follows this:

np.zeros((32,32,3), dtype=np.uint8)
encoded = base64.encodebytes(image)

encoded = str(encoded) #this happens when you send via json

decoded = base64.decodebytes(encoded)
d_image = np.fromstring(decoded, dtype=np.uint8)
d_image = np.reshape(d_image, (32, 32, 3))

Is there any details on how to decode the string properly or get it into a numpy array?  I can't seem to get it to work for the life of me.

Body:
Base64 is a binary-to-binary encoding in Python. It takes raw bytes and gives raw bytes to be sent anywhere. This can easily be converted to and from text, as base64 will always be ascii.

To convert the bytes into a numpy array, you want to use numpy.frombuffer().

encoded = base64.encodebytes(image_bytes).decode('US-ASCII')
# Send this in the JSON

encoded = json['image'].encode('US-ASCII')  # Convert back to bytes
image_bytes = base64.decodebytes(encoded)

d_image = numpy.frombuffer(image_bytes)


问:
How to track element impressions via Google Tag Mager?
How do I track via GTM if certain element have impressions? Let say I would like to know how many times this element have been seen?

 class"text">Text</span</div

答:
You could create a custom JavaScript variable to check if an element with the .box class exists.

Something like:

```<code>if(document.getElementsByClassName("box")){
    return true;
} else {
    return false;
}
</code>```

You can then use this in your trigger (eg. your custom variable > equals > true).

Body:
You could create a custom JavaScript variable to check if an element with the .box class exists.

Something like:

if(document.getElementsByClassName("box")){
    return true;
} else {
    return false;
}

You can then use this in your trigger (eg. your custom variable > equals > true).


问:
Double Value error in C
I am having a bit problem with this simple code.

I have tried different type castings, but I have not got any issue in here. If anybody tell me the reason that why its always printing 0.0000000 or something like that, I will be regretful and thanks in advance.

```<code>#include<stdio.h>
main()
{
    double num1,num5;
    printf ("Hello user\n");
    printf ("Let the thickness of black and white brick are same and the value
             is 2m\nAnd the gap between them is 1m\n");
    printf ("\nEnter the length of the road:\n");
    scanf ("%lf",&num1);
    num5 = ((2/5)*num1);
    printf ("%lf",num5);
    return 0;
}
</code>```

答:
2 and 5 are integers they are not double. Adding decimal point will yield the correct result.

Something like this.

```<code>num5 = ((2.0/5.0)* num1);
</code>```

or

```<code>  num5 = ((2.0/5)* num1);
</code>```

or

```<code>  num5 = ((2/5.0)* num1);
</code>```

Title: Double Value error in C

Body:
I am having a bit problem with this simple code.

I have tried different type castings, but I have not got any issue in here. If anybody tell me the reason that why its always printing 0.0000000 or something like that, I will be regretful and thanks in advance.

#include<stdio.h>
main()
{
    double num1,num5;
    printf ("Hello user\n");
    printf ("Let the thickness of black and white brick are same and the value
             is 2m\nAnd the gap between them is 1m\n");
    printf ("\nEnter the length of the road:\n");
    scanf ("%lf",&num1);
    num5 = ((2/5)*num1);
    printf ("%lf",num5);
    return 0;
}

Body:
2 and 5 are integers they are not double. Adding decimal point will yield the correct result.

Something like this.

num5 = ((2.0/5.0)* num1);

or

  num5 = ((2.0/5)* num1);

or

  num5 = ((2/5.0)* num1);


问:
Primitive makefile failure for compiling
I am trying to learn makefile, but I fail badly.
One example (which is very primitive) but I should understand it to go ahead is this one

```<code>f90_simple: f1.o
    gfortran f1.o
     mv a.out f90_simple
f90_simple.o:   f1.f90
    gfortran -c f1.f90
</code>```

it does not work, and I get this error
I get this error

```<code>make: *** No rule to make target `f1.o', needed by `f90_simple'.  Stop.
</code>```

could you please advise me?

thanks

答:
Your first rule says that before f90_simple can be built, the target f1.o must be built.

But there's no rule in your makefile that tells make how to build the target f1.o, and make can't find any built-in rule that can build it (based on the source files make has available), so it prints that error.

You do have a rule that tells make how to build a target f90_simple.o... but that's not the target make is looking for.  Most likely you want your makefile to either be:

```<code>f90_simple: f1.o
        gfortran $^
        mv a.out $@

f1.o: f1.f90
        gfortran -o $@ -c $<
</code>```

or else:

```<code>f90_simple: f90_simple.o
        gfortran $^
        mv a.out $@

f90_simple.o: f1.f90
        gfortran -o $@ -c $<
</code>```

but you can't mix and match them, or make doesn't know what to do.

I think you would really benefit from reading at least the introductory chapters in The GNU Make Manual.

Body:
I am trying to learn makefile, but I fail badly.
One example (which is very primitive) but I should understand it to go ahead is this one

f90_simple: f1.o
    gfortran f1.o
     mv a.out f90_simple
f90_simple.o:   f1.f90
    gfortran -c f1.f90

it does not work, and I get this error
I get this error

make: *** No rule to make target `f1.o', needed by `f90_simple'.  Stop.

could you please advise me?

thanks

Body:
Your first rule says that before f90_simple can be built, the target f1.o must be built.

But there's no rule in your makefile that tells make how to build the target f1.o, and make can't find any built-in rule that can build it (based on the source files make has available), so it prints that error.

You do have a rule that tells make how to build a target f90_simple.o... but that's not the target make is looking for.  Most likely you want your makefile to either be:

f90_simple: f1.o
        gfortran $^
        mv a.out $@

f1.o: f1.f90
        gfortran -o $@ -c $<

or else:

f90_simple: f90_simple.o
        gfortran $^
        mv a.out $@

f90_simple.o: f1.f90
        gfortran -o $@ -c $<

but you can't mix and match them, or make doesn't know what to do.

I think you would really benefit from reading at least the introductory chapters in The GNU Make Manual.


问:
Merging WPF ResourceDictionary at Runtime
I have a WPF user control which defines some default styles and images which I would like to be able to override at runtime with custom styles and images contained in resource assembly.

The styles and images are contained in a ResourceDictionary called DefaultResources.xaml in an assembly named Olbert.JumpForJoy.DefaultResources:

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    x:Name="J4JResources">

    <BitmapImage x:Key="J4JMessageBoxImage" UriSource="assets/j4jmsgbox.png" />
    <BitmapImage x:Key="J4JWizardImage" UriSource="assets/j4jtransparent.png" />
    <Color x:Key="J4JButton0Color">#bb911e</Color>
    <Color x:Key="J4JButton1Color">#252315</Color>
    <Color x:Key="J4JButton2Color">#bc513e</Color>
    <Color x:Key="J4JButtonHighlightColor">Orange</Color>

</ResourceDictionary>
</code>```

To provide this to an app, I add a nuget package created when the resource project is compiled to the application where the custom resources are to be used. I've confirmed the dll gets added to the targeted bin directory.

I try to load the custom resource assembly in the App.xaml.cs file, within the OnStartup() method:

```<code>public partial class App : Application
{
    public const string ResourceDll = "Olbert.JumpForJoy.DefaultResources";

    protected override void OnStartup( StartupEventArgs e )
    {
        try
        {
            var resDllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{ResourceDll}.dll");

            if (File.Exists(resDllPath))
            {
                var resAssembly = Assembly.LoadFile(resDllPath);
                var uriText = $"pack://application:,,,/{resAssembly.GetName().Name};component/DefaultResources.xaml";

                ResourceDictionary j4jRD = new ResourceDictionary {
                        Source = new Uri(uriText)
                    };

                Resources.MergedDictionaries.Add(j4jRD);
            }
        }
        catch (Exception ex)
        {
        }
    }
}
</code>```

But an exception gets thrown when the ResourceDictionary is created. The message is "Cannot locate resource 'defaultresources.xaml'".

I've tried quite a few tweaks to the uri definition to solve this, none of which have worked. The resource assembly is versioned, but whether or not I include a specific version in the uri definition I get the same error.

If there's a different way of merging an optional resource assembly into a WPF project I'd love to hear about it. An answer to my specific problem would be appreciated, too :)

Update

If I try to do this through app.xaml:

```<code><ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/Olbert.JumpForJoy.DefaultResources;component/DefaultResources.xaml" />
    <ResourceDictionary Source="NotifyIconResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</code>```

I get a design-time error "An error occurred while finding the resource dictionary..."

Calling resAssembly.GetManifestResourceNames() in my original approach showed that the resources do exist in the custom assembly. But they appear "under" the assembly's default namespace:

Olbert.JumpForJoy.WPF.DefaultResources.xaml

Which makes me wonder if I need to specify that namespace, somehow, in defining the Uri.

答:
For the sake of others struggling with this problem, here's the solution I dicovered: the problem was that the default namespace for the external resource assembly must be the same as the name of that assembly's DLL. If the names are different the pack Uri syntax fails.

I've documented this more fully on my blog at http://jumpforjoysoftware.com/2017/06/the-pain-of-shared-wpf-resources/

Body:
I have a WPF user control which defines some default styles and images which I would like to be able to override at runtime with custom styles and images contained in resource assembly.

The styles and images are contained in a ResourceDictionary called DefaultResources.xaml in an assembly named Olbert.JumpForJoy.DefaultResources:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    x:Name="J4JResources">

    <BitmapImage x:Key="J4JMessageBoxImage" UriSource="assets/j4jmsgbox.png" />
    <BitmapImage x:Key="J4JWizardImage" UriSource="assets/j4jtransparent.png" />
    <Color x:Key="J4JButton0Color">#bb911e</Color>
    <Color x:Key="J4JButton1Color">#252315</Color>
    <Color x:Key="J4JButton2Color">#bc513e</Color>
    <Color x:Key="J4JButtonHighlightColor">Orange</Color>

</ResourceDictionary>

To provide this to an app, I add a nuget package created when the resource project is compiled to the application where the custom resources are to be used. I've confirmed the dll gets added to the targeted bin directory.

I try to load the custom resource assembly in the App.xaml.cs file, within the OnStartup() method:

public partial class App : Application
{
    public const string ResourceDll = "Olbert.JumpForJoy.DefaultResources";

    protected override void OnStartup( StartupEventArgs e )
    {
        try
        {
            var resDllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{ResourceDll}.dll");

            if (File.Exists(resDllPath))
            {
                var resAssembly = Assembly.LoadFile(resDllPath);
                var uriText = $"pack://application:,,,/{resAssembly.GetName().Name};component/DefaultResources.xaml";

                ResourceDictionary j4jRD = new ResourceDictionary {
                        Source = new Uri(uriText)
                    };

                Resources.MergedDictionaries.Add(j4jRD);
            }
        }
        catch (Exception ex)
        {
        }
    }
}

But an exception gets thrown when the ResourceDictionary is created. The message is "Cannot locate resource 'defaultresources.xaml'".

I've tried quite a few tweaks to the uri definition to solve this, none of which have worked. The resource assembly is versioned, but whether or not I include a specific version in the uri definition I get the same error.

If there's a different way of merging an optional resource assembly into a WPF project I'd love to hear about it. An answer to my specific problem would be appreciated, too :)

Update

If I try to do this through app.xaml:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/Olbert.JumpForJoy.DefaultResources;component/DefaultResources.xaml" />
    <ResourceDictionary Source="NotifyIconResources.xaml"/>
</ResourceDictionary.MergedDictionaries>

I get a design-time error "An error occurred while finding the resource dictionary..."

Calling resAssembly.GetManifestResourceNames() in my original approach showed that the resources do exist in the custom assembly. But they appear "under" the assembly's default namespace:

Olbert.JumpForJoy.WPF.DefaultResources.xaml

Which makes me wonder if I need to specify that namespace, somehow, in defining the Uri.


问:
Nginx subdomain proxy pass order
I have two apps running on ports 3000 and 3030.

mydomain.com should point to 127.0.0.1:3000 while app.mydomain.com should point to 127.0.0.1:3030.

Using the configuration below, app.mydomain.com displays the app running on port 3000 instead of 3030. If I change the order, it's vice versa.

The sites-available/default file:

```<code># Redirect to HTTPS
server {
    listen 80;
    server_name _;
    return 301 https://$host$request_uri;
}

# Landing page
server {
    listen 443;

    server_name www.mydomain.com mydomain.com;

    ssl on;
    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

# App
server {
    listen 443;

    server_name app.mydomain.com;

    ssl on;
    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3030;
    }
}
</code>```

答:
The problem in my case was that I am using an IDN domain (with the character ä). I failed to mention this in the question.

Changing the server_names to the punycode version solved the issue.

Title: Nginx subdomain proxy pass order

Body:
I have two apps running on ports 3000 and 3030.

mydomain.com should point to 127.0.0.1:3000 while app.mydomain.com should point to 127.0.0.1:3030.

Using the configuration below, app.mydomain.com displays the app running on port 3000 instead of 3030. If I change the order, it's vice versa.

The sites-available/default file:

# Redirect to HTTPS
server {
    listen 80;
    server_name _;
    return 301 https://$host$request_uri;
}

# Landing page
server {
    listen 443;

    server_name www.mydomain.com mydomain.com;

    ssl on;
    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

# App
server {
    listen 443;

    server_name app.mydomain.com;

    ssl on;
    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3030;
    }
}


问:
Struts 2.0.14 GET parametrs are not URLDecoded, is that a bug?
I've got a problem with the parameters passed in the url.

Let say the request is: /struts/MyAction.action?param=foo%40bar.com

The action field gets the "param" field set to "foo%40bar.com",
is that a bug or I am expecting too much from Struts?

My intuition tells me that I should get the value: "foo@bar.com", as for instance would happen if I passed that parameter as a POST form field.

I am using the default interceptor stack and my action class extends ActionSupport. I get the some behaviour on WebSphere6.1 & GlassFish2.1.

Thanks

Hi Again,

The problem was caused by a bug in the proxy implementation. We've written a custom proxy server that was standing in front of the web application. It was encoding the URL parameters for the second time and that's why in Struts I had %40 instead of @.
Bug has been fixed now and parameters are being passed correctly.

Thanks for all your help

答:
As rado indicated, the Servlet Container is responsible for decoding the parameter values in the HttpServletRequest. If your values are not being URL decoded, then something is off.

Servlet Tutorial: Handling Form Data

First, what version of the Servlet API are you using? 2.5? 2.4? Do you have the correct XSD schema defined in your web.xml for the version you are using? Also, check that the version you are using matches the one that is provided by your application server.


问:
AngularJS execute a function after the completion of another function
I execute a function that calls two functions sequentially, to run the second function should first finish the first one. But this does not happen, perhaps because the first function is asynchronous. I read that I need to use "promise" I tried it, in different way, but it doesn't works. So I rewrote the function as I initially wrote:

```<code>function fail() {
    // Get the snackbar DIV
    var x = document.getElementById("snackbar")

    // Add the "show" class to DIV
    x.className = "show";

    // After 3 seconds, remove the show class from DIV
    setTimeout(function(){ x.className = x.className.replace("show", "");}, 3000);

}

function _goback(){
    $location.url('/app/dispensers');
}

//Check if the item is still available (if nobody bought it)
function _checkavailability(response){
    if (response.data == ""){
              console.log("Accesso non autorizzato")
    }
    $scope.infoproductbyid = response.data;
    if($scope.infoproductbyid.purchaseTime == null){
        console.log("Item disponibile");
        //if the item is available, it's possible to proceeds to checkout
        $location.url('/app/notregcheckout');
    }
    else{
        console.log("Spiacente, item non più disponibile");
      //  localStorage.clear("tokenidproduct");
        //_showSB();
        fail();
        _goback();
    }
}
</code>```

In the last rows, you can see that I call fail() function for first, and _goback() function for second. I want that _goback()starts when fail()finish, but fail() contains a timeout, and I think that for this reason the function is asynchronous. I don't understand how I can do

答:
Use the $timeout service to create a promise:

```<code>function fail() {
    // Get the snackbar DIV
    var x = document.getElementById("snackbar")

    // Add the "show" class to DIV
    x.className = "show";

    // After 3 seconds, remove the show class from DIV
    var promise = $timeout(function() {
      x.className = x.className.replace("show", "");
    }, 3000);

    //RETURN promise
    return promise;
}
</code>```

Then use the .then method to wait:

```<code>fail().then(function() {
    _goback();
});
</code>```

Body:
I execute a function that calls two functions sequentially, to run the second function should first finish the first one. But this does not happen, perhaps because the first function is asynchronous. I read that I need to use "promise" I tried it, in different way, but it doesn't works. So I rewrote the function as I initially wrote:

function fail() {
    // Get the snackbar DIV
    var x = document.getElementById("snackbar")

    // Add the "show" class to DIV
    x.className = "show";

    // After 3 seconds, remove the show class from DIV
    setTimeout(function(){ x.className = x.className.replace("show", "");}, 3000);

}

function _goback(){
    $location.url('/app/dispensers');
}

//Check if the item is still available (if nobody bought it)
function _checkavailability(response){
    if (response.data == ""){
              console.log("Accesso non autorizzato")
    }
    $scope.infoproductbyid = response.data;
    if($scope.infoproductbyid.purchaseTime == null){
        console.log("Item disponibile");
        //if the item is available, it's possible to proceeds to checkout
        $location.url('/app/notregcheckout');
    }
    else{
        console.log("Spiacente, item non più disponibile");
      //  localStorage.clear("tokenidproduct");
        //_showSB();
        fail();
        _goback();
    }
}

In the last rows, you can see that I call fail() function for first, and _goback() function for second. I want that _goback()starts when fail()finish, but fail() contains a timeout, and I think that for this reason the function is asynchronous. I don't understand how I can do

Body:
Use the $timeout service to create a promise:

function fail() {
    // Get the snackbar DIV
    var x = document.getElementById("snackbar")

    // Add the "show" class to DIV
    x.className = "show";

    // After 3 seconds, remove the show class from DIV
    var promise = $timeout(function() {
      x.className = x.className.replace("show", "");
    }, 3000);

    //RETURN promise
    return promise;
}

Then use the .then method to wait:

fail().then(function() {
    _goback();
});


问:
StackoverflowExcepton in Spring message i18n ReloadableResourceBundleMessageSource
I am enabling message i18n in my Spring web app. For this, I have below code in my servlet.xml

```<code><bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages/message"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
</code>```

After adding above code, as soon as I hit my application in browser, I get below exception log:

```<code>SEVERE: Servlet.service() for servlet [default] in context with path [/ERP-Web] threw exception [Filter execution threw an exception] with root cause
java.lang.StackOverflowError
    at org.springframework.context.support.ReloadableResourceBundleMessageSource.getMergedProperties(ReloadableResourceBundleMessageSource.java:235)
    at org.springframework.context.support.ReloadableResourceBundleMessageSource.resolveCodeWithoutArguments(ReloadableResourceBundleMessageSource.java:176)
    at org.springframework.context.support.AbstractMessageSource.getMessageInternal(AbstractMessageSource.java:209)
    at org.springframework.context.support.AbstractMessageSource.getMessageFromParent(AbstractMessageSource.java:257)
</code>```

where last 2 lines were repeated 100s of times and gives me StackoverflowException.

Exactly same exception is coming when I am using ResourceBundleMessageSource class.

My spring version is 4.3.6.RELEASE.

Below is content of my properties file

```<code>action.add.success = New {0} added successfully.
action.add.failure = Some error occurred in adding new {0}. Please try again later or contact administrator.
</code>```

Sample project is on GitHub

答:
Very strange situation ;-)

The fundamental problem is that the messageSource gets auto-wired to itself (in the parentMessageSource property) because you use default-autowire="byType" this causes the stackoverflow exceptions for unknown message codes that messes up everything. Must say that logback adds mess to the mess as sometimes seems that the exception happens in its code, Log4J handles it better.

Autowiring is not good for big projects, and this your situation is a classical case of why, however if you must use it change the messageSource bean adding the following:

```<code>       <property name="parentMessageSource"><null/></property>
</code>```

In this way you wire yourself the parent and no autowiring happens.

This restores the normal situation in which not found messages are reported with a NoSuchMessageException

Then:

In controller you must request hello.world message, not message

You are missing a default resource, that is a no-locale-suffix file that represents the default locale or your application. In your case would be messages/message.properties To be simple the default locale of your application is that one for which you have all messages. Start with that and then add new languages (that might be incomplete).

Body:
I am enabling message i18n in my Spring web app. For this, I have below code in my servlet.xml

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages/message"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

After adding above code, as soon as I hit my application in browser, I get below exception log:

SEVERE: Servlet.service() for servlet [default] in context with path [/ERP-Web] threw exception [Filter execution threw an exception] with root cause
java.lang.StackOverflowError
    at org.springframework.context.support.ReloadableResourceBundleMessageSource.getMergedProperties(ReloadableResourceBundleMessageSource.java:235)
    at org.springframework.context.support.ReloadableResourceBundleMessageSource.resolveCodeWithoutArguments(ReloadableResourceBundleMessageSource.java:176)
    at org.springframework.context.support.AbstractMessageSource.getMessageInternal(AbstractMessageSource.java:209)
    at org.springframework.context.support.AbstractMessageSource.getMessageFromParent(AbstractMessageSource.java:257)

where last 2 lines were repeated 100s of times and gives me StackoverflowException.

Exactly same exception is coming when I am using ResourceBundleMessageSource class.

My spring version is 4.3.6.RELEASE.

Below is content of my properties file

action.add.success = New {0} added successfully.
action.add.failure = Some error occurred in adding new {0}. Please try again later or contact administrator.

Sample project is on GitHub

Body:
Very strange situation ;-)

The fundamental problem is that the messageSource gets auto-wired to itself (in the parentMessageSource property) because you use default-autowire="byType" this causes the stackoverflow exceptions for unknown message codes that messes up everything. Must say that logback adds mess to the mess as sometimes seems that the exception happens in its code, Log4J handles it better.

Autowiring is not good for big projects, and this your situation is a classical case of why, however if you must use it change the messageSource bean adding the following:

       <property name="parentMessageSource"><null/></property>

In this way you wire yourself the parent and no autowiring happens.

This restores the normal situation in which not found messages are reported with a NoSuchMessageException

Then:

In controller you must request hello.world message, not message

You are missing a default resource, that is a no-locale-suffix file that represents the default locale or your application. In your case would be messages/message.properties To be simple the default locale of your application is that one for which you have all messages. Start with that and then add new languages (that might be incomplete).


问:
html5 audio player and .aif files on the web
I have been asked to use aif audio files on a website. I am using jplayer.

Would there be a noticeable difference using .aif?

Which browsers support .aif?

Would you advise using .aif for the web?

Would it mean I would need 3 versions of each track to cover all Browsers/OS?

Like so:

```<code><audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
<source src="horse.aif" type="audio/aif">
    Your browser does not support the audio element.
 </audio>
</code>```

Thanks :)

答:
Check your own browser. </p>

<p>I could not find a comprehensive list like you have asked for. So this is the second best. </p>

Body:
I have been asked to use aif audio files on a website. I am using jplayer.

Would there be a noticeable difference using .aif?

Which browsers support .aif?

Would you advise using .aif for the web?

Would it mean I would need 3 versions of each track to cover all Browsers/OS?

Like so:

<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
<source src="horse.aif" type="audio/aif">
    Your browser does not support the audio element.
 </audio>

Thanks :)

Body:
Check your own browser.

I could not find a comprehensive list like you have asked for. So this is the second best.


问:
Send specific data per node and gather results in MPI-Python
I have trouble executing this program in mpi4py. My objective is to send specific data to a particular node (that is why I am not using scatter). After that, process the data in each node, and finally gather all the results.

Apparently, my program does not understand how to gather the data from different nodes (maybe because gather is designed to work with scatter). I tried to send the date with comm.send() and gather with comm.gather(). When I execute the program, it runs forever, and I don't see any result.

Can you help me to find out how to gather the data from the different nodes? Is there other function to do this? May I need a loop over the nodes?

```<code>from mpi4py import MPI
import numpy as np

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

if rank == 0:
    data = list(np.arange(size) + 1)
    for i in range(size):
        comm.send(data[i], dest=i)
else:
    data = comm.recv(source=0)
    data += 1

print("rank", rank, "has data", data)

newData = comm.gather(data, root = 0)

if rank == 0:

    print("master collected", newData)
</code>```

答:
The reason why this is blocking is that you are trying to send data from rank 0 to itself before the matching receive is posted. This is a deadlock. Now you could simply skip sending from rank 0 to itself - just copy the appropriate data. Or you could use non-blocking point to point communication (isend / irecv).

However, you shouldn't. The idiomatic approach is indeed to use scatter, and it works just fine, e.g.:

```<code>if rank == 0:
    full_data = list(np.arange(size) + 1)
else:
    full_data = None
data = comm.scatter(full_data)
</code>```

Body:
I have trouble executing this program in mpi4py. My objective is to send specific data to a particular node (that is why I am not using scatter). After that, process the data in each node, and finally gather all the results.

Apparently, my program does not understand how to gather the data from different nodes (maybe because gather is designed to work with scatter). I tried to send the date with comm.send() and gather with comm.gather(). When I execute the program, it runs forever, and I don't see any result.

Can you help me to find out how to gather the data from the different nodes? Is there other function to do this? May I need a loop over the nodes?

from mpi4py import MPI
import numpy as np

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

if rank == 0:
    data = list(np.arange(size) + 1)
    for i in range(size):
        comm.send(data[i], dest=i)
else:
    data = comm.recv(source=0)
    data += 1

print("rank", rank, "has data", data)

newData = comm.gather(data, root = 0)

if rank == 0:

    print("master collected", newData)

Body:
The reason why this is blocking is that you are trying to send data from rank 0 to itself before the matching receive is posted. This is a deadlock. Now you could simply skip sending from rank 0 to itself - just copy the appropriate data. Or you could use non-blocking point to point communication (isend / irecv).

However, you shouldn't. The idiomatic approach is indeed to use scatter, and it works just fine, e.g.:

if rank == 0:
    full_data = list(np.arange(size) + 1)
else:
    full_data = None
data = comm.scatter(full_data)


问:
Query with compare predicate in CloudKit
I have some CKRecords in Cloudkit, the records has two property of int type, which may be called 'cost' and 'price',  I want to query records whose 'cost' > 'price', but the application crashed when I write a query like this:

```<code>CKQuery *query = [[CKQuery alloc] initWithRecordType:@"MyRecordType" predicate:
[NSPredicate predicateWithFormat:@"cost > price"]];
</code>```

this is the crash info given by Xcode:

Terminating app due to uncaught exception 'CKException', reason: 'Invalid predicate, Invalid right expression,  is not a function expression

Please Help, thanks in advance.

答:
OK,

Thought some more about this.

You query all records, but select only two fields; the cost and the price.

```<code>let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Whatever", predicate: predicate)
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["cost","price"]
</code>```

Then you do your query [which should be quicker], sort out the records you want and then go get them with publicDB.fetchRecordWithID.

Yes, I know more than one query, in fact it looks like a lot more, but wait I think there is an answers in WWDC 2015 Tips & Tricks in Cloudkit; Watch the session and you might find something in there too. Here the code to fetch a record, if you have the record ID.

```<code>publicDB.fetchRecordWithID(), completionHandler: {record, error in
if error != nil {
    println("there was an error \(error)")
} else {
    NSOperationQueue.mainQueue().addOperationWithBlock {
        self.plasticOne.text = (record.objectForKey("subCategory") as String)
    }
</code>```

}
   })

Sorry I cannot give you more than that without writing the code myself, and if I do that than you end up using my answer, and I sure you're answer is going to be better :)

Body:
I have some CKRecords in Cloudkit, the records has two property of int type, which may be called 'cost' and 'price',  I want to query records whose 'cost' > 'price', but the application crashed when I write a query like this:

CKQuery *query = [[CKQuery alloc] initWithRecordType:@"MyRecordType" predicate:
[NSPredicate predicateWithFormat:@"cost > price"]];

this is the crash info given by Xcode:

Terminating app due to uncaught exception 'CKException', reason: 'Invalid predicate, Invalid right expression,  is not a function expression

Please Help, thanks in advance.

Body:
OK,

Thought some more about this.

You query all records, but select only two fields; the cost and the price.

let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Whatever", predicate: predicate)
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["cost","price"]

Then you do your query [which should be quicker], sort out the records you want and then go get them with publicDB.fetchRecordWithID.

Yes, I know more than one query, in fact it looks like a lot more, but wait I think there is an answers in WWDC 2015 Tips & Tricks in Cloudkit; Watch the session and you might find something in there too. Here the code to fetch a record, if you have the record ID.

publicDB.fetchRecordWithID(), completionHandler: {record, error in
if error != nil {
    println("there was an error \(error)")
} else {
    NSOperationQueue.mainQueue().addOperationWithBlock {
        self.plasticOne.text = (record.objectForKey("subCategory") as String)
    }

}
   })

Sorry I cannot give you more than that without writing the code myself, and if I do that than you end up using my answer, and I sure you're answer is going to be better :)


问:
c++ 2D array row sort based on average row value
Helo,

I'm wondering if there's any working method for this?
I'm trying make this work, but no luck.

```<code>int mat[3][3];

    mat[0][0] = 4;mat[0][1] = 5;mat[0][2] = 3;

    mat[1][0] = 3;mat[1][1] = 2;mat[1][2] = 1;

    mat[2][0] = 1;mat[2][1] = 8;mat[2][2] = 9;
</code>```

Any idea? :)

答:
You should create a temporary data structure that is an array of tuples. The tuples would be the row index and the average of that row index. Then sort this tuple array based on the average using the standard sort() function. Then, run through the sorted tuple array to recompute the sorted matrix.

This would give you performance benefit of not copying the matrix rows during the swap done by the sort routine. If you only have 3 elements in your row, you may be okay with swap the whole row. But as you increase the number of columns the swapping would be become a bottleneck.

In 'pseudo code' you may do something like this:

```<code>function sort(input, numrows, numcols)
{
    pair<int, int> index[numrows];

    for (int i=0 to numrows) {
      index[i].second = i;
      // compute average of row[i] in the input matrix
      index[i].first = average_of_row(&input[i]);
    }

    // STL sort will sort the pair based on the average (.first member)
    sort(index.begin(), index.end());

    for (int i=0 to index.size())
    {
       // copy rows from input matrix to output matrix
       copy_row(&input[index[i].second], &output_matrix[i]);
    }

    return output;
}
</code>```

Body:
Helo,

I'm wondering if there's any working method for this?
I'm trying make this work, but no luck.

int mat[3][3];

    mat[0][0] = 4;mat[0][1] = 5;mat[0][2] = 3;

    mat[1][0] = 3;mat[1][1] = 2;mat[1][2] = 1;

    mat[2][0] = 1;mat[2][1] = 8;mat[2][2] = 9;

Any idea? :)

Body:
You should create a temporary data structure that is an array of tuples. The tuples would be the row index and the average of that row index. Then sort this tuple array based on the average using the standard sort() function. Then, run through the sorted tuple array to recompute the sorted matrix.

This would give you performance benefit of not copying the matrix rows during the swap done by the sort routine. If you only have 3 elements in your row, you may be okay with swap the whole row. But as you increase the number of columns the swapping would be become a bottleneck.

In 'pseudo code' you may do something like this:

function sort(input, numrows, numcols)
{
    pair<int, int> index[numrows];

    for (int i=0 to numrows) {
      index[i].second = i;
      // compute average of row[i] in the input matrix
      index[i].first = average_of_row(&input[i]);
    }

    // STL sort will sort the pair based on the average (.first member)
    sort(index.begin(), index.end());

    for (int i=0 to index.size())
    {
       // copy rows from input matrix to output matrix
       copy_row(&input[index[i].second], &output_matrix[i]);
    }

    return output;
}


问:
SQL Server: Group By based on one column and get columns based on other column
My data:

```<code>ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
C                          ABCD                Yes
</code>```

My SQL should be able to do following:

Group by Column A

Select only those groups of A that contain Yes and Null both in the result of a

Expected Result is:

```<code>ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
</code>```

How do I select all values that satisfy above rule?

答:
```<code>    select * from t
    where
columnA in
    (select columnA from T where columnC is NULL) and
columnA in
    (select columnA from T where columnC = 'Yes')
</code>```

Body:
My data:

ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
C                          ABCD                Yes

My SQL should be able to do following:

Group by Column A

Select only those groups of A that contain Yes and Null both in the result of a

Expected Result is:

ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL

How do I select all values that satisfy above rule?


问:
Regex for everything *after* the first complete sentence (period and space) *after* N characters
I'd like to get smarter excerpts of sections of text. As I'll be using Movable Type's regex_replace function, I'm gonna be trying to grab everything after the first few sentences.

While \..* gets everything after the first period, that often leaves a too-short excerpt. How might I do the same thing (everything after the first period) but skipping the first 100 characters?

Alternatively, how would I just grab everything after, say, the second or third period?

答:
Complete sentence is vague, since different languages have different ways of encoding end-of-sentence. Let's assume that a space after a period is EOS:
/^.*?\.\s+(?:.{N})(.*)/ Replace N by desired number.


问:
How do I insert data retrieved from database into pre-styled HTML tags?
I want to display the data I retrieve from a database table in styled HTML.
Please look at the code below, the commented out line works and I would like to fill in the data in the
 below the comment.
Thanks in advance

I know my code is vulnerable, but I want to get it to work before I worry about security.

```<code><body>
<div id="wrapper" class="menu">
    <?php require('inc-nav.php') ?>

    <section class="content">

        <?php
        require('connect.php');

        $conn = mysqli_connect($servername, $username, $password, $dbname);
        $sql = "SELECT name, breed, age FROM dogs";
        $result = mysqli_query($conn, $sql);

        if (mysqli_num_rows($result) > 0) {
            // output data of each row
            while($dogs = mysqli_fetch_assoc($result)) {
//          echo 'Name: ' . $dogs['name'] . '<br>' . 'Breed: ' . $dogs['breed'] . '<br>' . 'Age: ' . $dogs['age'] . '<br><hr>';
                echo '
                <section class="profile">
                    <figure class="profile-pic"><img src="images/1.jpg" alt=""></figure>
                    <h1 class="name">Name</h1>
                    <h2 class="description1">Breed | gender | age</h2>
                    <p class="description2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto corporis dolores dolorum eaque eum in nemo quos totam ullam. Autem?</p>
                    <button class="cta-profile"><a href="#">Read more</a></button>
                </section>
                ';
            }
        } else {
            echo "0 results";
        }

        mysqli_close($conn);
        ?>

    </section>

    <?php require('inc-footer.php');?>
</div>
</code>```

答:
You want like this </p>

```<code><body>
<div id="wrapper" class="menu">
    <?php require('inc-nav.php') ?>

    <section class="content">

        <?php
        require('connect.php');

        $conn = mysqli_connect($servername, $username, $password, $dbname);
        $sql = "SELECT name, breed, age FROM dogs";
        $result = mysqli_query($conn, $sql);

        if (mysqli_num_rows($result) > 0) {
            // output data of each row
            while($dogs = mysqli_fetch_assoc($result)) {

             ?>
                <section class="profile">
                    <figure class="profile-pic"><img src="images/1.jpg" alt=""></figure>
                    <h1 class="name"><?php echo 'Name: ' .$dogs['name']; ?></h1>
                    <h2 class="description1"> <?php echo 'Breed: ' . $dogs['breed']; ?>  | gender | <?phpecho  'Age: ' . $dogs['age']; ?></h2>
                    <p class="description2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto corporis dolores dolorum eaque eum in nemo quos totam ullam. Autem?</p>
                    <button class="cta-profile"><a href="#">Read more</a></button>
                </section>
                <?php
            }
        } else {
            echo "0 results";
        }

        mysqli_close($conn);
        ?>

    </section>

    <?php require('inc-footer.php');?>
</div>
</code>```

Body:
I want to display the data I retrieve from a database table in styled HTML.
Please look at the code below, the commented out line works and I would like to fill in the data in the
 below the comment.
Thanks in advance

I know my code is vulnerable, but I want to get it to work before I worry about security.

    <?php require('inc-nav.php') ?>

        <?php
        require('connect.php');

        $conn = mysqli_connect($servername, $username, $password, $dbname);
        $sql = "SELECT name, breed, age FROM dogs";
        $result = mysqli_query($conn, $sql);

        if (mysqli_num_rows($result) > 0) {
            // output data of each row
            while($dogs = mysqli_fetch_assoc($result)) {
//          echo 'Name: ' . $dogs['name'] . '
' . 'Breed: ' . $dogs['breed'] . '
' . 'Age: ' . $dogs['age'] . '

';
                echo '

Name

Breed | gender | age

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto corporis dolores dolorum eaque eum in nemo quos totam ullam. Autem?

                    <button class="cta-profile">Read more</button>

                ';
            }
        } else {
            echo "0 results";
        }

        mysqli_close($conn);
        ?>

    <?php require('inc-footer.php');?>

Body:
You want like this

<body>
<div id="wrapper" class="menu">
    <?php require('inc-nav.php') ?>

    <section class="content">

        <?php
        require('connect.php');

        $conn = mysqli_connect($servername, $username, $password, $dbname);
        $sql = "SELECT name, breed, age FROM dogs";
        $result = mysqli_query($conn, $sql);

        if (mysqli_num_rows($result) > 0) {
            // output data of each row
            while($dogs = mysqli_fetch_assoc($result)) {

             ?>
                <section class="profile">
                    <figure class="profile-pic"><img src="images/1.jpg" alt=""></figure>
                    <h1 class="name"><?php echo 'Name: ' .$dogs['name']; ?></h1>
                    <h2 class="description1"> <?php echo 'Breed: ' . $dogs['breed']; ?>  | gender | <?phpecho  'Age: ' . $dogs['age']; ?></h2>
                    <p class="description2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto corporis dolores dolorum eaque eum in nemo quos totam ullam. Autem?</p>
                    <button class="cta-profile"><a href="#">Read more</a></button>
                </section>
                <?php
            }
        } else {
            echo "0 results";
        }

        mysqli_close($conn);
        ?>

    </section>

    <?php require('inc-footer.php');?>
</div>