答:
At the very top of your CSS Styles, where you have:

```<code>.hide {
  z-index: 2;
  display: none;
}
</code>```

remove the display: none; so you are left with:

```<code>.hide {
  z-index: 2;
}
</code>```

Title: Div with Background Image Not Showing

Body:
I am sure I am missing something simple here: I am creating a map with different image overlays. I got the map to work but the map doesn't show up until you push a button. I need it to show up always. Currently the map is set as a background image. If I set it as an image none of the buttons work. Does anyone know what I'm missing?

var alertName = document.getElementsByClassName("alertName");

var myFunction = function() {

  var hide = document.getElementsByClassName("hide");

  for (var i = 0; i < hide.length; i++) {

    hide[i].style.display = "none";

  }

  var name = this.getAttribute("name");

  var show = document.querySelector('.' + name);

  if (show.style.display = "none") {

    show.style.display = "block";

  } else {

    show.style.display = "none";

  }

};

for (var i = 0; i < alertName.length; i++) {

  alertName[i].addEventListener('click', myFunction);

}

.hide {
  z-index: 2;
  display: none;
}

.hidingsection {
  background-image: url("https://res.cloudinary.com/dnu8yyawg/image/upload/v1559077777/elke/map_base_1_gv6ehh.png");
  background-repeat: no-repeat;
}

.container {
  display: flex;
  flex-flow: row
}

.hidingsection {
  z-index: 0;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />

          <button class="alertName" name="schoolContent">Schools</button>

          <button class="alertName" name="recreationContent">Recreation</button>

          <button class="alertName" name="restaurantsContent">Restaurants</button>

          <button class="alertName" name="banksContent">Banks</button>

          <button class="alertName" name="groceriesContent">Groceries</button>

          <button class="alertName" name="transportationContent"> Transportation</button>

          <button class="alertName" name="libraryContent">Library</button>

Body:
At the very top of your CSS Styles, where you have:

.hide {
  z-index: 2;
  display: none;
}

remove the display: none; so you are left with:

.hide {
  z-index: 2;
}


来源: stackexchange

问:
Regex with negative lookahead and dot matches newline modifier (/s)
I have a PHP script and I need to match the last occurence of a specific string.

Let's say I have the following scenarios:

1

```<code><p class="TPTexto" style="text-autospace: none; ">
<font face="Arial" size="2" color="#FF0000">Este texto não substitui o publicado no DOU de  28.9.2006.</font>
</p>
</code>```

2

```<code>Este texto abc def
<p class="TPTexto" style="text-autospace: none; ">
<font face="Arial" size="2" color="#FF0000">Este texto não substitui o publicado no DOU de  28.9.2006.</font>
</p>
</code>```

3

```<code>Este texto abc def
<p class="TPTexto" style="text-autospace: none; ">
<font face="Arial" size="2" color="#FF0000">Este
texto não substitui o publicado no DOU de  28.9.2006.</font>
</p>
</code>```

4

```<code>Este texto abc def
<p class="TPTexto" style="text-autospace: none; ">
<font face="Arial" size="2" color="#FF0000">Este <font></font>
texto não substitui o publicado no DOU de  28.9.2006.</font>
</p>
</code>```

5

```<code>Este texto abc def
<p class="TPTexto" style="text-autospace: none; ">
<font face="Arial" size="2" color="#FF0000">Este            texto não substitui     o     publicado no DOU de  28.9.2006.</font>
</p>
</code>```

I want to match Este texto não substitui o publicado in all cases, accepting some occasional garbage in between, like Este \ntexto não substitui o publicado.

So I went with the following regex:

/Este(?:.(?!Este))+?texto.+?n.+?o.+?substitui.+?o.+?publicado/uis

The flags:

u to accept unicode characters

i to accept insensitive content

s to make dot (.) match newlines (so my negative lookahead works)

This way I would match the last Este and the following text, as I want, right? Nope! The s modifier kills it.

(I'm using this PHP tool to test it btw)

I don't know why the s modifier kills it in this case. Any help would be very appreciated.

I'm using PHP's preg_match_all on this project.

Edit:

Noticed it wasn't clear: I need the SECOND Este texto... not the first.

答:
Your regular expression is OK. You could just prepend your regex with this:

```<code>\A.*\K
</code>```

\A asserts beginning of input string

.* matches entire input string immediately and then tries to backtrack to match the next pattern which is Este

\K resets output up to the point so that you'll see the desired string only

I removed the lookahead and made your regex a bit simpler. Putting it all together we have this:

```<code>\A.*\KEste.+?texto.+?n.+?o.+?substitui.+?o.+?publicado
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a PHP script and I need to match the last occurence of a specific string.

Let's say I have the following scenarios:

1

Este texto não substitui o publicado no DOU de  28.9.2006.

2

Este texto abc def

Este texto não substitui o publicado no DOU de  28.9.2006.

3

Este texto abc def

Este
texto não substitui o publicado no DOU de  28.9.2006.

4

Este texto abc def

Este
texto não substitui o publicado no DOU de  28.9.2006.

5

Este texto abc def

Este            texto não substitui     o     publicado no DOU de  28.9.2006.

I want to match Este texto não substitui o publicado in all cases, accepting some occasional garbage in between, like Este \ntexto não substitui o publicado.

So I went with the following regex:

/Este(?:.(?!Este))+?texto.+?n.+?o.+?substitui.+?o.+?publicado/uis

The flags:

u to accept unicode characters

i to accept insensitive content

s to make dot (.) match newlines (so my negative lookahead works)

This way I would match the last Este and the following text, as I want, right? Nope! The s modifier kills it.

(I'm using this PHP tool to test it btw)

I don't know why the s modifier kills it in this case. Any help would be very appreciated.

I'm using PHP's preg_match_all on this project.

Edit:

Noticed it wasn't clear: I need the SECOND Este texto... not the first.

Body:
Your regular expression is OK. You could just prepend your regex with this:

\A.*\K

\A asserts beginning of input string

.* matches entire input string immediately and then tries to backtrack to match the next pattern which is Este

\K resets output up to the point so that you'll see the desired string only

I removed the lookahead and made your regex a bit simpler. Putting it all together we have this:

\A.*\KEste.+?texto.+?n.+?o.+?substitui.+?o.+?publicado


问:
Rearranging RGB values to GRB, GBR, BRG, BGR, and RBG through an entire directory
I have a directory of images for a CNN. I would like to be able to rearrange each band in a different order to help better train my model to allow it to recognize my objects. I so far have some code working with cv2. It is separating the bands, but I am having trouble rearranging the bands.

```<code>import cv2
import numpy

img = cv2.imread("IMG_4540.jpg")
g,b,r = cv2.split(img)
cv2.imwrite('green_channel.jpg', g)
</code>```

I would like to have 6 separate images all with different band combinations from one singular image if possible.

答:
You can just form all reorderings with numpy's indexing capabilities. </p>

```<code>import numpy as np
from itertools import permutations
# first generate all sets of rearrangements you'd like to make..
orderings = [p for p in permutations(np.arange(3)) if p!=(0,1,2)]
# [(0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
# rbg, brg, and so on.

# then reorder along axis=-1 using these. (0,1,2) --> (0,2,1) and so on.
for order in orderings:
    reordered = im[...,order]
    # then save each an appropriate filename
    cv2.imsave('filename.jpg', reordered)
del reordered, order
</code>```

Body:
I have a directory of images for a CNN. I would like to be able to rearrange each band in a different order to help better train my model to allow it to recognize my objects. I so far have some code working with cv2. It is separating the bands, but I am having trouble rearranging the bands.

import cv2
import numpy

img = cv2.imread("IMG_4540.jpg")
g,b,r = cv2.split(img)
cv2.imwrite('green_channel.jpg', g)

I would like to have 6 separate images all with different band combinations from one singular image if possible.

Body:
You can just form all reorderings with numpy's indexing capabilities.

import numpy as np
from itertools import permutations
# first generate all sets of rearrangements you'd like to make..
orderings = [p for p in permutations(np.arange(3)) if p!=(0,1,2)]
# [(0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
# rbg, brg, and so on.

# then reorder along axis=-1 using these. (0,1,2) --> (0,2,1) and so on.
for order in orderings:
    reordered = im[...,order]
    # then save each an appropriate filename
    cv2.imsave('filename.jpg', reordered)
del reordered, order


问:
ToggleClass Based on checkbox status
So I've got some nav that consists of form checkboxes floated next to a traditional anchors. If the corresponding checkbox is not checked, I want to add a class (that basically will be styled to dim the anchor tag). What's the best way to do this systematically?</p>

```<code><div id="navPod">
    <form method="post" action="#" id="contentFilterForm" name="contentFilterForm">
        <input type="hidden" name="q" value="<?php echo $q;?>" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'projects'){ echo "checked=\"checked\"";} if($proj){ echo "checked=\"checked\"";} ?> name="pr" value="1" id="filterProjects" />
        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'playground'){ echo "checked=\"checked\"";} if($playground){ echo "checked=\"checked\"";} ?> type="checkbox" name="pl" value="1" id="filterPlayground" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'about'){ echo "checked=\"checked\"";} if($culture){ echo "checked=\"checked\"";} ?> name="cu" value="1" id="filterCulture" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'leadership'){ echo "checked=\"checked\"";} if($leadership){ echo "checked=\"checked\"";} ?> name="le" value="1" id="filterLeadership" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'careers'){ echo "checked=\"checked\"";} if($jobs){ echo "checked=\"checked\"";} ?> name="ca" value="1" id="filterCareers" />

        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'blog'){ echo "checked=\"checked\"";} if($blog){ echo "checked=\"checked\"";} ?> type="checkbox" name="bl" value="1" id="filterBlog" />
        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'delicious'){ echo "checked=\"checked\"";} if($links){ echo "checked=\"checked\"";} ?> type="checkbox" name="li" value="1" id="filterDelicious" />

        <input id="refreshSubmit" type="button" value="" onclick="createURLS()"/>
    </form>

    <div class="subnav">
        <a id="projectsLink" title="Projects" href="/projects/" <?php if($pagetype == 'projects'){ echo "class=\"currentPage\""; } ?> >Projects</a><br />
        <a id="playgroundLink" title="Playground" href="/playground/" <?php if($pagetype == 'playground'){ echo "class=\"currentPage\""; } ?> >Playground</a><br />
        <a id="aboutLink" title="About Centerline Digital" href="/about/" <?php if($pagetype == 'about'){ echo "class=\"currentPage\""; } ?> >About Us</a><br />
        <a id="leadershipLink" title="Leadership" href="/leadership/" <?php if($pagetype == 'leadership'){ echo "class=\"currentPage\""; } ?> >Leadership</a><br />
        <a id="careersLink" title="Careers" href="/careers/" <?php if($pagetype == 'careers'){ echo "class=\"currentPage\""; } ?> >Careers</a><br />
        <a id="blogLink" title="Blog" href="/blog/" <?php if($pagetype == 'blog'){ echo "class=\"currentPage\""; } ?> >Blog</a><br />
        <a id="thoughtsLink" title="Thoughts and Links" href="/thoughts/" <?php if($pagetype == 'delicious'){ echo "class=\"currentPage\""; } ?> >Thoughts and Links</a><br />

        <a target="_blank" title="Subscribe to Custom Feed" id="feedLink" href="/dyn/">Subscribe to Custom Feed</a>
    </div>
</div>
</code>```

答:
```<code>$(function(){
    $("a[id$='Link']").each(function(){
        var checkboxID = this.id.replace("Link", "");
        checkboxID = "filter" + checkboxID[0].toUpperCase() + checkboxID.substr(1);

        $(this).addClass($("#" + checkboxID).is(":checked") ? "dim" : "");
    })
})
</code>```

ContentLicense: CC BY-SA 3.0

Title: ToggleClass Based on checkbox status

Body:
So I've got some nav that consists of form checkboxes floated next to a traditional anchors. If the corresponding checkbox is not checked, I want to add a class (that basically will be styled to dim the anchor tag). What's the best way to do this systematically?

    <form method="post" action="#" id="contentFilterForm" name="contentFilterForm">
        <input type="hidden" name="q" value="<?php echo $q;?>" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'projects'){ echo "checked=\"checked\"";} if($proj){ echo "checked=\"checked\"";} ?> name="pr" value="1" id="filterProjects" />
        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'playground'){ echo "checked=\"checked\"";} if($playground){ echo "checked=\"checked\"";} ?> type="checkbox" name="pl" value="1" id="filterPlayground" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'about'){ echo "checked=\"checked\"";} if($culture){ echo "checked=\"checked\"";} ?> name="cu" value="1" id="filterCulture" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'leadership'){ echo "checked=\"checked\"";} if($leadership){ echo "checked=\"checked\"";} ?> name="le" value="1" id="filterLeadership" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'careers'){ echo "checked=\"checked\"";} if($jobs){ echo "checked=\"checked\"";} ?> name="ca" value="1" id="filterCareers" />

        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'blog'){ echo "checked=\"checked\"";} if($blog){ echo "checked=\"checked\"";} ?> type="checkbox" name="bl" value="1" id="filterBlog" />
        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'delicious'){ echo "checked=\"checked\"";} if($links){ echo "checked=\"checked\"";} ?> type="checkbox" name="li" value="1" id="filterDelicious" />

        <input id="refreshSubmit" type="button" value="" onclick="createURLS()"/>
    </form>

        <a id="projectsLink" title="Projects" href="/projects/" <?php if($pagetype == 'projects'){ echo "class=\"currentPage\""; } ?> >Projects

        <a id="playgroundLink" title="Playground" href="/playground/" <?php if($pagetype == 'playground'){ echo "class=\"currentPage\""; } ?> >Playground

        <a id="aboutLink" title="About Centerline Digital" href="/about/" <?php if($pagetype == 'about'){ echo "class=\"currentPage\""; } ?> >About Us

        <a id="leadershipLink" title="Leadership" href="/leadership/" <?php if($pagetype == 'leadership'){ echo "class=\"currentPage\""; } ?> >Leadership

        <a id="careersLink" title="Careers" href="/careers/" <?php if($pagetype == 'careers'){ echo "class=\"currentPage\""; } ?> >Careers

        <a id="blogLink" title="Blog" href="/blog/" <?php if($pagetype == 'blog'){ echo "class=\"currentPage\""; } ?> >Blog

        <a id="thoughtsLink" title="Thoughts and Links" href="/thoughts/" <?php if($pagetype == 'delicious'){ echo "class=\"currentPage\""; } ?> >Thoughts and Links

        Subscribe to Custom Feed


问:
CakePhp3.7 Plugin Autoload option is not available
Prior to CakePhp3.7 it was possible to load a plugin using the autoload option:

```<code>Plugin::load('ContactManager', ['autoload' => true]);
</code>```

This was very useful if you couldn't (or didn't want to) use composer to autoload plugins.

Since version 3.7.0: Plugin::load() and autoload option are deprecated.

```<code>$this->addPlugin('ContactManager');
</code>```

Should be used instead of Plugin::load. But autoload option is not available on addPlugin().

How can I replicate the autoload functionality in CakePhp3.7 without using composer?

答:
Well, there isn't much you can do other than re-implementing/replicating what Plugin::load() does, that is registering an autoloader, see:

https://github.com/cakephp/cakephp/blob/3.7.8/src/Core/Plugin.php#L130-L142

https://github.com/cakephp/cakephp/blob/3.7.8/src/Core/Plugin.php#L157-L170

You could for example put it in your Application class:

```<code>use Cake\Core\ClassLoader;
use Cake\Core\Plugin;

// ...

class Application extends BaseApplication
{
    // ...

    protected static $_loader;

    public function bootstrap()
    {
        // ...

        $this->addPlugin('ContactManager', ['autoload' => true]);
    }

    public function addPlugin($name, array $config = [])
    {
        parent::addplugin($name, $config);

        $config += [
            'autoload' => false,
            'classBase' => 'src',
        ];

        if ($config['autoload'] === true) {
            if (!isset($config['path'])) {
                $config['path'] = Plugin::getCollection()->findPath($name);
            }

            if (empty(static::$_loader)) {
                static::$_loader = new ClassLoader();
                static::$_loader->register();
            }
            static::$_loader->addNamespace(
                str_replace('/', '\\', $name),
                $config['path'] . $config['classBase'] . DIRECTORY_SEPARATOR
            );
            static::$_loader->addNamespace(
                str_replace('/', '\\', $name) . '\Test',
                $config['path'] . 'tests' . DIRECTORY_SEPARATOR
            );
        }

        return $this;
    }

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

For now \Cake\Core\ClassLoader isn't deprecated, but it might become at one point, so that you may have to re-implement that too.

Body:
Prior to CakePhp3.7 it was possible to load a plugin using the autoload option:

Plugin::load('ContactManager', ['autoload' => true]);

This was very useful if you couldn't (or didn't want to) use composer to autoload plugins.

Since version 3.7.0: Plugin::load() and autoload option are deprecated.

$this->addPlugin('ContactManager');

Should be used instead of Plugin::load. But autoload option is not available on addPlugin().

How can I replicate the autoload functionality in CakePhp3.7 without using composer?

Body:
Well, there isn't much you can do other than re-implementing/replicating what Plugin::load() does, that is registering an autoloader, see:

https://github.com/cakephp/cakephp/blob/3.7.8/src/Core/Plugin.php#L130-L142

https://github.com/cakephp/cakephp/blob/3.7.8/src/Core/Plugin.php#L157-L170

You could for example put it in your Application class:

use Cake\Core\ClassLoader;
use Cake\Core\Plugin;

// ...

class Application extends BaseApplication
{
    // ...

    protected static $_loader;

    public function bootstrap()
    {
        // ...

        $this->addPlugin('ContactManager', ['autoload' => true]);
    }

    public function addPlugin($name, array $config = [])
    {
        parent::addplugin($name, $config);

        $config += [
            'autoload' => false,
            'classBase' => 'src',
        ];

        if ($config['autoload'] === true) {
            if (!isset($config['path'])) {
                $config['path'] = Plugin::getCollection()->findPath($name);
            }

            if (empty(static::$_loader)) {
                static::$_loader = new ClassLoader();
                static::$_loader->register();
            }
            static::$_loader->addNamespace(
                str_replace('/', '\\', $name),
                $config['path'] . $config['classBase'] . DIRECTORY_SEPARATOR
            );
            static::$_loader->addNamespace(
                str_replace('/', '\\', $name) . '\Test',
                $config['path'] . 'tests' . DIRECTORY_SEPARATOR
            );
        }

        return $this;
    }

    // ...
}

For now \Cake\Core\ClassLoader isn't deprecated, but it might become at one point, so that you may have to re-implement that too.


问:
refactor code to throw RuntimeException instead of return a value
I need to refactor an existing code because of code duplication.

The following structure occures more then 10 times in a crazy class:

```<code>public MyType doSomething(...) {
    MyType myType = ........
    if (myType == null) {
        final String message = "...";
        LOGGER.error(message);
        throw new XxxRuntimeException(message));
    }
    return myType;
}
</code>```

I would like to refactor LOGGER.error and throw new RuntimeException lines to a new method like this:

```<code>private void logErrorAndThrowRuntimeException(String message) {
    LOGGER.error(message);
    throw new XxxRuntimeException(message));
}
</code>```

The problem with this is there is no return value inside the if contition after refactor.

I an not able to change the type of the exception from RuntimeException to Exception because this application has a crazy logic and RuntimeExceptin needs to be thrown.

Any idea how to refactor this two lines of code to a new method and keep the logic of the original method untouched?

答:
Declare a Throwable return type:

```<code>private XxxRuntimeException logErrorAndThrowRuntimeException(String message) {
    LOGGER.error(message);
    // You can throw here, or return if you'd prefer.
    throw new XxxRuntimeException(message));
}
</code>```

Then you can throw this at the call site to indicate that the if body cannot complete normally:

```<code>public MyType doSomething(...) {
    MyType myType = ........
    if (myType == null) {
        final String message = "...";
        throw logErrorAndThrowRuntimeException(message);
    }
    return myType;
}
</code>```

Body:
I need to refactor an existing code because of code duplication.

The following structure occures more then 10 times in a crazy class:

public MyType doSomething(...) {
    MyType myType = ........
    if (myType == null) {
        final String message = "...";
        LOGGER.error(message);
        throw new XxxRuntimeException(message));
    }
    return myType;
}

I would like to refactor LOGGER.error and throw new RuntimeException lines to a new method like this:

private void logErrorAndThrowRuntimeException(String message) {
    LOGGER.error(message);
    throw new XxxRuntimeException(message));
}

The problem with this is there is no return value inside the if contition after refactor.

I an not able to change the type of the exception from RuntimeException to Exception because this application has a crazy logic and RuntimeExceptin needs to be thrown.

Any idea how to refactor this two lines of code to a new method and keep the logic of the original method untouched?

Body:
Declare a Throwable return type:

private XxxRuntimeException logErrorAndThrowRuntimeException(String message) {
    LOGGER.error(message);
    // You can throw here, or return if you'd prefer.
    throw new XxxRuntimeException(message));
}

Then you can throw this at the call site to indicate that the if body cannot complete normally:

public MyType doSomething(...) {
    MyType myType = ........
    if (myType == null) {
        final String message = "...";
        throw logErrorAndThrowRuntimeException(message);
    }
    return myType;
}


问:
Kotlin float/int indirect comparison
For a project I am trying to implement a Bit class, that does all the usual stuff a bit should do.

The constructor should be able to take any Number and set the Bit's internal state to 0 if the given value is 0, else set it to 1.

All works for integer inputs but when I get to float... apparently 0.0 is not equal to 0.

```<code>class Bit(value: Number) {
    var value: Int = (value != 0).toInt() // I implemented Bool-to-Int myself
}
</code>```

Now the problem:

```<code>println(Bit(0).value)   // Prints 0
println(Bit(0f).value)  // Prints 1
</code>```

I thought this was some kind of approximation error, but when I tried print(0f != 0) I got Operator '!=' cannot be applied to 'Float' and 'Int'. However it had no issue comparing the numbers trough the constructor.

I feel there is some hidden type-casting magic I'm not aware of here so my question is basically "why is this not behaving as intended and what would be an elegant way to make it behave as intended?"

答:
It has to do with value representation being boxed as stated in docs.

As you've noticed you're not able to compare different types (when Float and Int are being represented natively). But you're not doing that, instead you use a Number type.

Consider following example:

```<code>println(0.0f == 0)  // error: Operator '==' cannot be applied to 'Float' and 'Int'
val n : Number = 0L  // this forces value to be boxed
println(n == 0)   // compiles and prints false
</code>```

At first compiler warns you that it's not possible to perform comparison. However if you box numerical value with an object then it is possible to use equalsTo operator as you have.

You will find that it returns true if and only if both sides are of the same type and same value.

Don't want to rain on your parade, but correct way of implementing your class is declaring separate constructors for each number type. That will prevent compiler from boxing your values and let you properly determine equality:

```<code>class Bit constructor(value : Boolean) {
    val value = if(value) 1 else 0

    constructor(value : Int) : this(value == 0)
    constructor(value : Float) : this(value == 0f)
    constructor(value : Long) : this(value == 0L)
    // etc
}
</code>```

Title: Kotlin float/int indirect comparison

Body:
For a project I am trying to implement a Bit class, that does all the usual stuff a bit should do.

The constructor should be able to take any Number and set the Bit's internal state to 0 if the given value is 0, else set it to 1.

All works for integer inputs but when I get to float... apparently 0.0 is not equal to 0.

class Bit(value: Number) {
    var value: Int = (value != 0).toInt() // I implemented Bool-to-Int myself
}

Now the problem:

println(Bit(0).value)   // Prints 0
println(Bit(0f).value)  // Prints 1

I thought this was some kind of approximation error, but when I tried print(0f != 0) I got Operator '!=' cannot be applied to 'Float' and 'Int'. However it had no issue comparing the numbers trough the constructor.

I feel there is some hidden type-casting magic I'm not aware of here so my question is basically "why is this not behaving as intended and what would be an elegant way to make it behave as intended?"

Body:
It has to do with value representation being boxed as stated in docs.

As you've noticed you're not able to compare different types (when Float and Int are being represented natively). But you're not doing that, instead you use a Number type.

Consider following example:

println(0.0f == 0)  // error: Operator '==' cannot be applied to 'Float' and 'Int'
val n : Number = 0L  // this forces value to be boxed
println(n == 0)   // compiles and prints false

At first compiler warns you that it's not possible to perform comparison. However if you box numerical value with an object then it is possible to use equalsTo operator as you have.

You will find that it returns true if and only if both sides are of the same type and same value.

Don't want to rain on your parade, but correct way of implementing your class is declaring separate constructors for each number type. That will prevent compiler from boxing your values and let you properly determine equality:

class Bit constructor(value : Boolean) {
    val value = if(value) 1 else 0

    constructor(value : Int) : this(value == 0)
    constructor(value : Float) : this(value == 0f)
    constructor(value : Long) : this(value == 0L)
    // etc
}


问:
Modify grid-template-columns using javascript
I am trying to change the size of grid-template-columns upon the click of a button (https://jsfiddle.net/3ft6svgk/2/).

html:

```<code><div class="grid-squares">
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
    <button id="firstButton">Learn More</button>
  </div>
   <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
   <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
   <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
</div>
</code>```

css:

```<code>.grid-squares{
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 300px;
}
</code>```

javscript:

```<code>firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
  squaresGrid = document.getElementsByClassName("grid-squares");
  squaresGrid.style.gridTemplateColumns = "1000px";
}
</code>```

With this code I am getting

```<code>"Uncaught TypeError: Cannot set property 'gridTemplateColumns' of undefined
    at HTMLButtonElement.repairsAndUpgradesButton.onclick"
</code>```

in the console. How can I properly change the value of grid-template-columns?

答:
try this:</p>

```<code>firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
  squaresGrid = document.getElementsByClassName("grid-squares");
  squaresGrid[0].style.gridTemplateColumns = "1000px";
}
</code>```

Body:
I am trying to change the size of grid-template-columns upon the click of a button (https://jsfiddle.net/3ft6svgk/2/).

html:

Lorem Ipsum

    <button id="firstButton">Learn More</button>

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

css:

.grid-squares{
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 300px;
}

javscript:

firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
  squaresGrid = document.getElementsByClassName("grid-squares");
  squaresGrid.style.gridTemplateColumns = "1000px";
}

With this code I am getting

"Uncaught TypeError: Cannot set property 'gridTemplateColumns' of undefined
    at HTMLButtonElement.repairsAndUpgradesButton.onclick"

in the console. How can I properly change the value of grid-template-columns?

Body:
try this:

firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
  squaresGrid = document.getElementsByClassName("grid-squares");
  squaresGrid[0].style.gridTemplateColumns = "1000px";
}


问:
Any way to create a legend title in Bokeh?
Is there any way to add a title to legends, e.g. current legend on the left, legend with title on the right.  This particular legend is placed outside the plot are so I don't know if I can fake it with  a text glyph.

答:
As of the latest version of Bokeh (1.2) you can add a title to your legend as follows:

p.legend.title = 'Example Title'
```
<p>The complete example:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np

from bokeh.layouts import gridplot
from bokeh.plotting import figure, show, output_file

x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)

TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"

p1 = figure(title="Legend Example", tools=TOOLS)

p1.circle(x,   y, legend="sin(x)")
p1.circle(x, 2*y, legend="2*sin(x)", color="orange")
p1.circle(x, 3*y, legend="3*sin(x)", color="green")

p1.legend.title = 'Example Title'

p2 = figure(title="Another Legend Example", tools=TOOLS)

p2.circle(x, y, legend="sin(x)")
p2.line(x, y, legend="sin(x)")

p2.line(x, 2*y, legend="2*sin(x)", line_dash=(4, 4), line_color="orange", line_width=2)

p2.square(x, 3*y, legend="3*sin(x)", fill_color=None, line_color="green")
p2.line(x, 3*y, legend="3*sin(x)", line_color="green")

output_file("legend.html", title="legend.py example")

show(gridplot([p1, p2], ncols=2, plot_width=400, plot_height=400))
</code>```

This code was taken from the official docs

Body:
As of the latest version of Bokeh (1.2) you can add a title to your legend as follows:

p.legend.title = 'Example Title'

The complete example:

import numpy as np

from bokeh.layouts import gridplot
from bokeh.plotting import figure, show, output_file

x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)

TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"

p1 = figure(title="Legend Example", tools=TOOLS)

p1.circle(x,   y, legend="sin(x)")
p1.circle(x, 2*y, legend="2*sin(x)", color="orange")
p1.circle(x, 3*y, legend="3*sin(x)", color="green")

p1.legend.title = 'Example Title'

p2 = figure(title="Another Legend Example", tools=TOOLS)

p2.circle(x, y, legend="sin(x)")
p2.line(x, y, legend="sin(x)")

p2.line(x, 2*y, legend="2*sin(x)", line_dash=(4, 4), line_color="orange", line_width=2)

p2.square(x, 3*y, legend="3*sin(x)", fill_color=None, line_color="green")
p2.line(x, 3*y, legend="3*sin(x)", line_color="green")

output_file("legend.html", title="legend.py example")

show(gridplot([p1, p2], ncols=2, plot_width=400, plot_height=400))

This code was taken from the official docs


问:
Transform array into a binary array
I currently have a numpy array with the following data:

```<code>array([0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0,
   1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0,
   0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0,
   1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1,
   0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1,
   0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0])
</code>```

I need to transform it into an array that looks as follows:

```<code>array([0., 1.],
      [0., 1.],
      [1., 0.],
      [1., 0.],
      [1., 0.],
      [0., 1.],
      [1., 0.],
      [1., 0.],
      [1., 0.],
      [1., 0.],
      ...
      [0., 1.])
</code>```

I recognize the first step as obviously being a transform into a float, but I don't know where to start as far as the next step. Is there a map function that will work well? A lambda? A for loop? I feel like it would be simple if I already had it in a different array format, but I don't know how to conditionally add a dimension and then populate it with precisely the binary opposite of what is already there. Is all that based on an if-then conditional? Sorry, I'm just relatively new to Python so I don't know all the tools yet.

答:
You can use advanced indexing into an appropriate template:

```<code>small_example = np.array([1,0,0,1,1,1,0,1])
(1-np.eye(2))[small_example]
# array([[1., 0.],
#        [0., 1.],
#        [0., 1.],
#        [1., 0.],
#        [1., 0.],
#        [1., 0.],
#        [0., 1.],
#        [1., 0.]])
</code>```

The same idea can also be implemented using np.where:

```<code>np.where(small_example[:,None], *np.eye(2))
# array([[1., 0.],
#        [0., 1.],
#        [0., 1.],
#        [1., 0.],
#        [1., 0.],
#        [1., 0.],
#        [0., 1.],
#        [1., 0.]])
</code>```

A more direct approach showing how to create column an row vectors, how to broadcast them together and how to cast the dtype:

```<code>(np.c_[small_example]^np.r_[:2]).astype(float)
# array([[1., 0.],
#        [0., 1.],
#        [0., 1.],
#        [1., 0.],
#        [1., 0.],
#        [1., 0.],
#        [0., 1.],
#        [1., 0.]])
</code>```

We can also column stack the input and its "negative"; we use 1.0 to trigger type promotion:

```<code>np.c_[small_example,1.0-small_example]
# array([[1., 0.],
#        [0., 1.],
#        [0., 1.],
#        [1., 0.],
#        [1., 0.],
#        [1., 0.],
#        [0., 1.],
#        [1., 0.]])
</code>```

Title: Transform array into a binary array

Body:
I currently have a numpy array with the following data:

array([0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0,
   1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0,
   0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0,
   1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1,
   0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1,
   0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0])

I need to transform it into an array that looks as follows:

array([0., 1.],
      [0., 1.],
      [1., 0.],
      [1., 0.],
      [1., 0.],
      [0., 1.],
      [1., 0.],
      [1., 0.],
      [1., 0.],
      [1., 0.],
      ...
      [0., 1.])

I recognize the first step as obviously being a transform into a float, but I don't know where to start as far as the next step. Is there a map function that will work well? A lambda? A for loop? I feel like it would be simple if I already had it in a different array format, but I don't know how to conditionally add a dimension and then populate it with precisely the binary opposite of what is already there. Is all that based on an if-then conditional? Sorry, I'm just relatively new to Python so I don't know all the tools yet.

Body:
You can use advanced indexing into an appropriate template:

small_example = np.array([1,0,0,1,1,1,0,1])
(1-np.eye(2))[small_example]
# array([[1., 0.],
#        [0., 1.],
#        [0., 1.],
#        [1., 0.],
#        [1., 0.],
#        [1., 0.],
#        [0., 1.],
#        [1., 0.]])

The same idea can also be implemented using np.where:

np.where(small_example[:,None], *np.eye(2))
# array([[1., 0.],
#        [0., 1.],
#        [0., 1.],
#        [1., 0.],
#        [1., 0.],
#        [1., 0.],
#        [0., 1.],
#        [1., 0.]])

A more direct approach showing how to create column an row vectors, how to broadcast them together and how to cast the dtype:

(np.c_[small_example]^np.r_[:2]).astype(float)
# array([[1., 0.],
#        [0., 1.],
#        [0., 1.],
#        [1., 0.],
#        [1., 0.],
#        [1., 0.],
#        [0., 1.],
#        [1., 0.]])

We can also column stack the input and its "negative"; we use 1.0 to trigger type promotion:

np.c_[small_example,1.0-small_example]
# array([[1., 0.],
#        [0., 1.],
#        [0., 1.],
#        [1., 0.],
#        [1., 0.],
#        [1., 0.],
#        [0., 1.],
#        [1., 0.]])


问:
Save Workspace - save all variables to a file. Python doesn't have it)
I cannot understand it. Very simple, and obvious functionality:
You have a code in any programming language, You run it. In this code You generate variables, than You save them (the values, names, namely everything) to a file, with one command. When it's saved You may open such a file in Your code also with simple command.
It works perfect in matlab (save Workspace , load Workspace ) - in python there's some weird "pickle" protocol, which produces errors all the time, while all I want to do is save variable, and load it again in another session (?????)
f.e. You cannot save class with variables (in Matlab there's no problem)
You cannot load arrays in cPickle (but YOu can save them (?????) )
Why don't make it easier?
Is there a way to save the current variables with values, and then load them?</p>

答: It's an old thread, but thought I should throw it out there anyway - Spyder the Scientific Python development environment allows you to do just this through the Variable explorer. There's a button there Save data that packs your whole workspace up in a .spydata file that you can later reload. Works like a charm when you're switching between projects!

ContentLicense: CC BY-SA 2.5


问:
PhpUnit Mock an inbuilt function
Is there a way to mock/override an inbuilt function shell_exec in PHPUnit. I am aware of Mockery and I cannot use other libraries apart from PHPUnit.

I have tried for more than 3 hours and somewhere stuck. Any pointers / links would be highly appreciated.

I am using Zend-Framework 2.

答:
An answer for non-homogeneous namespaces;

As @notnotundefined pointed out, the solution here depends on the tests living in the same namespace as the code being tested.  The following is how to accomplish the same test with competing namespaces.

```<code><?php

namespace My\Namespace {
    /**
     * Override shell_exec() in the My\Namespace namespace when testing
     *
     * @return int
     */
    function shell_exec()
    {
        return // return your mock or whatever value you want to use for testing
    }
}

namespace My\Namespace\Tests {
    class SomeClassTest extends \PHPUnit_Framework_TestCase
    {
        public function testSomething()
        {
            // The above override will be used when calling shell_exec
            // from My\Namespace\SomeClass::something() because the
            // current namespace is searched before the global.
            // https://www.php.net/manual/en/language.namespaces.fallback.php
            (new SomeClass())->something();
        }
    }
}
</code>```

Title: PhpUnit Mock an inbuilt function

Body:
An answer for non-homogeneous namespaces;

As @notnotundefined pointed out, the solution here depends on the tests living in the same namespace as the code being tested.  The following is how to accomplish the same test with competing namespaces.

<?php

namespace My\Namespace {
    /**
     * Override shell_exec() in the My\Namespace namespace when testing
     *
     * @return int
     */
    function shell_exec()
    {
        return // return your mock or whatever value you want to use for testing
    }
}

namespace My\Namespace\Tests {
    class SomeClassTest extends \PHPUnit_Framework_TestCase
    {
        public function testSomething()
        {
            // The above override will be used when calling shell_exec
            // from My\Namespace\SomeClass::something() because the
            // current namespace is searched before the global.
            // https://www.php.net/manual/en/language.namespaces.fallback.php
            (new SomeClass())->something();
        }
    }
}


问:
AWS IoT Analytics Delta Window
I am having real problems getting the AWS IoT Analytics Delta Window (docs) to work.

I am trying to set it up so that every day a query is run to get the last 1 hour of data only. According to the docs the schedule feature can be used to run the query using a cron expression (in my case every hour) and the delta window should restrict my query to only include records that are in the specified time window (in my case the last hour).

The SQL query I am running is simply SELECT * FROM dev_iot_analytics_datastore and if I don't include any delta window I get the records as expected. Unfortunately when I include a delta expression I get nothing (ever). I left the data accumulating for about 10 days now so there are a couple of million records in the database. Given that I was unsure what the optimal format would be I have included the following temporal fields in the entries:

```<code>datetime  :  2019-05-15T01:29:26.509
(A string formatted using ISO Local Date Time)

timestamp_sec  :  1557883766
(A unix epoch expressed in seconds)

timestamp_milli  :  1557883766509
(A unix epoch expressed in milliseconds)

</code>```

There is also a value automatically added by AWS called __dt which is a uses the same format as my datetime except it seems to be accurate to within 1 day. i.e. All values entered within a given day have the same value (e.g. 2019-05-15 00:00:00.00)

I have tried a range of expressions (including the suggested AWS expression) from both standard SQL and Presto as I'm not sure which one is being used for this query. I know they use a subset of Presto for the analytics so it makes sense that they would use it for the delta but the docs simply say '... any valid SQL expression'.

Expressions I have tried so far with no luck:

```<code>
from_unixtime(timestamp_sec)
from_unixtime(timestamp_milli)
cast(from_unixtime(unixtime_sec) as date)
cast(from_unixtime(unixtime_milli) as date)
date_format(from_unixtime(timestamp_sec), '%Y-%m-%dT%h:%i:%s')
date_format(from_unixtime(timestamp_milli), '%Y-%m-%dT%h:%i:%s')
from_iso8601_timestamp(datetime)

</code>```

答:
What are the offset and time expression parameters that you are using?

Since delta windows are effectively filters inserted into your SQL, you can troubleshoot them by manually inserting the filter expression into your data set's query.

Namely, applying a delta window filter with -3 minute (negative) offset and 'from_unixtime(my_timestamp)' time expression to a 'SELECT my_field FROM my_datastore' query translates to an equivalent query:

```<code>SELECT my_field FROM
    (SELECT * FROM "my_datastore" WHERE
        (__dt between date_trunc('day', iota_latest_succeeded_schedule_time() - interval '1' day)
                  and date_trunc('day', iota_current_schedule_time() + interval '1' day)) AND
        iota_latest_succeeded_schedule_time() - interval '3' minute < from_unixtime(my_timestamp) AND
        from_unixtime(my_timestamp) <= iota_current_schedule_time() - interval '3' minute)
</code>```

Try using a similar query (with no delta time filter) with correct values for offset and time expression and see what you get, The (_dt between ...) is just an optimization for limiting the scanned partitions. You can remove it for the purposes of troubleshooting.

Title: AWS IoT Analytics Delta Window

Body:
I am having real problems getting the AWS IoT Analytics Delta Window (docs) to work.

I am trying to set it up so that every day a query is run to get the last 1 hour of data only. According to the docs the schedule feature can be used to run the query using a cron expression (in my case every hour) and the delta window should restrict my query to only include records that are in the specified time window (in my case the last hour).

The SQL query I am running is simply SELECT * FROM dev_iot_analytics_datastore and if I don't include any delta window I get the records as expected. Unfortunately when I include a delta expression I get nothing (ever). I left the data accumulating for about 10 days now so there are a couple of million records in the database. Given that I was unsure what the optimal format would be I have included the following temporal fields in the entries:

datetime  :  2019-05-15T01:29:26.509
(A string formatted using ISO Local Date Time)

timestamp_sec  :  1557883766
(A unix epoch expressed in seconds)

timestamp_milli  :  1557883766509
(A unix epoch expressed in milliseconds)

There is also a value automatically added by AWS called __dt which is a uses the same format as my datetime except it seems to be accurate to within 1 day. i.e. All values entered within a given day have the same value (e.g. 2019-05-15 00:00:00.00)

I have tried a range of expressions (including the suggested AWS expression) from both standard SQL and Presto as I'm not sure which one is being used for this query. I know they use a subset of Presto for the analytics so it makes sense that they would use it for the delta but the docs simply say '... any valid SQL expression'.

Expressions I have tried so far with no luck:

from_unixtime(timestamp_sec)
from_unixtime(timestamp_milli)
cast(from_unixtime(unixtime_sec) as date)
cast(from_unixtime(unixtime_milli) as date)
date_format(from_unixtime(timestamp_sec), '%Y-%m-%dT%h:%i:%s')
date_format(from_unixtime(timestamp_milli), '%Y-%m-%dT%h:%i:%s')
from_iso8601_timestamp(datetime)

Body:
What are the offset and time expression parameters that you are using?

Since delta windows are effectively filters inserted into your SQL, you can troubleshoot them by manually inserting the filter expression into your data set's query.

Namely, applying a delta window filter with -3 minute (negative) offset and 'from_unixtime(my_timestamp)' time expression to a 'SELECT my_field FROM my_datastore' query translates to an equivalent query:

SELECT my_field FROM
    (SELECT * FROM "my_datastore" WHERE
        (__dt between date_trunc('day', iota_latest_succeeded_schedule_time() - interval '1' day)
                  and date_trunc('day', iota_current_schedule_time() + interval '1' day)) AND
        iota_latest_succeeded_schedule_time() - interval '3' minute < from_unixtime(my_timestamp) AND
        from_unixtime(my_timestamp) <= iota_current_schedule_time() - interval '3' minute)

Try using a similar query (with no delta time filter) with correct values for offset and time expression and see what you get, The (_dt between ...) is just an optimization for limiting the scanned partitions. You can remove it for the purposes of troubleshooting.


问:
Unable to Create Extract - Tableau and Spark SQL
I am trying to make extract information from Spark SQL. Following error message showing while creating extract.

[Simba][Hardy] (35) Error from server: error code: '0' error message: 'org.apache.spark.SparkException: Job aborted due to stage failure: Total size of serialized results of 906 tasks (4.0 GB) is bigger than spark.driver.maxResultSize (4.0 GB)'.

答:
A quick fix is just changing the setting in your execution context.

spark.sql("set spark.driver.maxResultSize = 8G")


问:
How I can shuffle multiple JSON data in foreach? (PHP)
It is not the same logic as other questions.

There are two JSON data. I want to ensure that the answers to the question are written in complex form. But I couldn't do it. I can get a single JSON when I can, but I get the error when there is more than one JSON

Questions: The total number of people in the world?

Options: {'opt1':'4 Billion','opt2':'5 Billion','opt3':'6
Billion','opt4':'7 Billion'}

Answer: {"0":"2","1":"3"} // correct answers: 2. & 3. options
(multiple)

Code

```<code>   $options = json_decode($quiz->options);
   $answers = json_decode($quiz->answerOfQuestion, true);

   foreach ($options as $key => $firstvalue) {
        if (in_array(substr($key, -1), $answers)) {
        // correct options
            echo "<input type='checkbox' value='".substr($key, -1)."'>";
        } else {
        // wrong options
            echo "<input type='checkbox' value='".substr($key, -1)."'>";
        }
    }
</code>```

What have I done?

```<code>   $options = shuffle(json_decode($quiz->options));
   $answers = shuffle(json_decode($quiz->answerOfQuestion, true));
</code>```

Error:

```<code>Unknown error type: [8] Only variables should be passed by reference
Unknown error type: [2] shuffle() expects parameter 1 to be array, object given
Unknown error type: [8] Only variables should be passed by reference
Unknown error type: [2] Invalid argument supplied for foreach()
</code>```

How can I make the complex writing shuffle?

答:
The error messages are fairly self-explanatory. You can't pass a value to shuffle, only a variable. Secondly, shuffle takes an array, not an object, so when you json_decode($options) you need to pass true as the second parameter to make it return an array. Note that because your $options is an associative array, shuffle won't work for you as it reindexes the array with numeric keys. Instead you can use uasort to shuffle it instead:

```<code>$answers = '{"0":"2","1":"3"}';
$answers = json_decode($answers, true);
$options = '{"opt1":"4 Billion","opt2":"5 Billion","opt3":"6 Billion","opt4":"7 Billion"}';
$options = json_decode($options, true);
uasort($options, function ($a, $b) {
    return rand(-1, 1);
});
foreach ($options as $key => $value) {
    echo $value;
    if (in_array(substr($key, -1), $answers)) {
    // correct options
        echo "<input type='checkbox' value='".substr($key, -1)."'>" . PHP_EOL;
    } else {
    // wrong options
        echo "<input type='checkbox' value='".substr($key, -1)."'>" . PHP_EOL;
    }
}
</code>```

Output (random):

```<code>4 Billion<input type='checkbox' value='1'>
5 Billion<input type='checkbox' value='2'>
7 Billion<input type='checkbox' value='4'>
6 Billion<input type='checkbox' value='3'>
</code>```

Demo on dbfiddle

Body:
It is not the same logic as other questions.

There are two JSON data. I want to ensure that the answers to the question are written in complex form. But I couldn't do it. I can get a single JSON when I can, but I get the error when there is more than one JSON

Questions: The total number of people in the world?

Options: {'opt1':'4 Billion','opt2':'5 Billion','opt3':'6
Billion','opt4':'7 Billion'}

Answer: {"0":"2","1":"3"} // correct answers: 2. & 3. options
(multiple)

Code

   $options = json_decode($quiz->options);
   $answers = json_decode($quiz->answerOfQuestion, true);

   foreach ($options as $key => $firstvalue) {
        if (in_array(substr($key, -1), $answers)) {
        // correct options
            echo "<input type='checkbox' value='".substr($key, -1)."'>";
        } else {
        // wrong options
            echo "<input type='checkbox' value='".substr($key, -1)."'>";
        }
    }

What have I done?

   $options = shuffle(json_decode($quiz->options));
   $answers = shuffle(json_decode($quiz->answerOfQuestion, true));

Error:

Unknown error type: [8] Only variables should be passed by reference
Unknown error type: [2] shuffle() expects parameter 1 to be array, object given
Unknown error type: [8] Only variables should be passed by reference
Unknown error type: [2] Invalid argument supplied for foreach()

How can I make the complex writing shuffle?

Body:
The error messages are fairly self-explanatory. You can't pass a value to shuffle, only a variable. Secondly, shuffle takes an array, not an object, so when you json_decode($options) you need to pass true as the second parameter to make it return an array. Note that because your $options is an associative array, shuffle won't work for you as it reindexes the array with numeric keys. Instead you can use uasort to shuffle it instead:

$answers = '{"0":"2","1":"3"}';
$answers = json_decode($answers, true);
$options = '{"opt1":"4 Billion","opt2":"5 Billion","opt3":"6 Billion","opt4":"7 Billion"}';
$options = json_decode($options, true);
uasort($options, function ($a, $b) {
    return rand(-1, 1);
});
foreach ($options as $key => $value) {
    echo $value;
    if (in_array(substr($key, -1), $answers)) {
    // correct options
        echo "<input type='checkbox' value='".substr($key, -1)."'>" . PHP_EOL;
    } else {
    // wrong options
        echo "<input type='checkbox' value='".substr($key, -1)."'>" . PHP_EOL;
    }
}

Output (random):

4 Billion<input type='checkbox' value='1'>
5 Billion<input type='checkbox' value='2'>
7 Billion<input type='checkbox' value='4'>
6 Billion<input type='checkbox' value='3'>

Demo on dbfiddle


问:
RegEx for replacing a JavaScript pattern
I have tons of html files with expression like this:

```<code>eval('enterData.style.pixelTop=' + y);
</code>```

and I want to eliminate the eval expression and just execute the code, in other words change it to:

```<code>enterData.style.pixelTop =  y;
</code>```

Can anybody help me with this. Im breaking my head trying to get a solution but i only know how to eliminate the eval with:

```<code>Regex: eval\('(.*)'\)
Replace: $1
</code>```

Im using java for regex.

答:
I'm guessing that we could capture both desired vars separately with an expression such as:

```<code>.+'(.+?)'\s+?[+\-*]+\s+([a-z]+).+
</code>```

We can surely simplify this expression, but I was not sure about other inputs that we might have.

Java

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = ".+'(.+?)'\\s+?[+\\-*]+\\s+([a-z]+).+";
final String string = "eval('enterData.style.pixelTop=' + y);\n"
     + "eval('enterData.style.pixelTop=' + x);";
final String subst = "$1$2;";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println(result);
</code>```

Test

const regex = /.+'(.+?)'\s+?[+\-*]+\s+([a-z]+).+/gm;
const str = `eval('enterData.style.pixelTop=' + y);
eval('enterData.style.pixelTop=' + x);`;
const subst = `$1$2;`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);```

Demo

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I have tons of html files with expression like this:

eval('enterData.style.pixelTop=' + y);

and I want to eliminate the eval expression and just execute the code, in other words change it to:

enterData.style.pixelTop =  y;

Can anybody help me with this. Im breaking my head trying to get a solution but i only know how to eliminate the eval with:

Regex: eval\('(.*)'\)
Replace: $1

Im using java for regex.

Body:
I'm guessing that we could capture both desired vars separately with an expression such as:

.+'(.+?)'\s+?[+\-*]+\s+([a-z]+).+

We can surely simplify this expression, but I was not sure about other inputs that we might have.

Java

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = ".+'(.+?)'\\s+?[+\\-*]+\\s+([a-z]+).+";
final String string = "eval('enterData.style.pixelTop=' + y);\n"
     + "eval('enterData.style.pixelTop=' + x);";
final String subst = "$1$2;";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println(result);

Test

const regex = /.+'(.+?)'\s+?[+\-*]+\s+([a-z]+).+/gm;
const str = `eval('enterData.style.pixelTop=' + y);
eval('enterData.style.pixelTop=' + x);`;
const subst = `$1$2;`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

Demo

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
Firestore security rule read permission if data meets condition
How to set up the security rule where the user can only read the data where it matches with the condition. for example, I have users collection and some of the users' field enabled is true and for some other it's false. I want the user to read only documents where enabled is true. </p>

<p>this is the security rule I have applied but I am receiving permission denied error. </p>

```<code>service cloud.firestore {
  match /databases/{database}/documents {

    match /users/{user} {
        allow read: if resource.data.enabled != false;

    }

  }
}
</code>```

答:
Firestore Security Rules are not filters; the query restrictions should match the rules restrictions, so, for example, the query for that rule should be something like this:</p>

```<code>db.collection('users').where('enabled', '==', true).get().then(/*callback*/)
</code>```

Body:
How to set up the security rule where the user can only read the data where it matches with the condition. for example, I have users collection and some of the users' field enabled is true and for some other it's false. I want the user to read only documents where enabled is true.

this is the security rule I have applied but I am receiving permission denied error.

service cloud.firestore {
  match /databases/{database}/documents {

    match /users/{user} {
        allow read: if resource.data.enabled != false;

    }

  }
}

Body:
Firestore Security Rules are not filters; the query restrictions should match the rules restrictions, so, for example, the query for that rule should be something like this:

db.collection('users').where('enabled', '==', true).get().then(/*callback*/)


问:
databinding must include a layout file
I have following very simple layout and wanted to switch to using data binding. Now I'm getting following error in my controller_main.xml:

```<code>Error:Execution failed for task ':app:dataBindingProcessLayoutsDebug_pro'.
</code>```

****/ data binding error ****msg:[44 68 44 68 25] must include a layout
  file:...\app\src\main\res\layout\controller_main.xml
  ****\ data binding error ****

Any ideas? The error says, the resource android:layout id in the include tag is missing (that's my interpretation of the error), but that's not true. Commenting out the include tag removes the error.

Does anyone see the problem?

controller_main.xml

```<code><layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" >

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:fitsSystemWindows="true"
        android:background="?attr/main_background_color"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <RelativeLayout
            android:id="@+id/rlContent"
            android:fitsSystemWindows="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </RelativeLayout>

        <include
            android:layout_width="fill_parent"
            android:layout_height="@dimen/tool_bar_top_padding"
            android:id="@+id/stub_view_main_header_fixed"
            android:layout="@layout/view_main_header_fixed"
            app:elevation="0dp"/>

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

        </android.support.design.widget.AppBarLayout>

    </android.support.design.widget.CoordinatorLayout>

</layout>
</code>```

view_main_header_fixed.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<View
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/vStatusbarBackground"
    android:layout_width="match_parent"
    android:layout_height="@dimen/tool_bar_top_padding" />
</code>```

答:
I had the exact same error, but for a different reason.
I was using <include> opening tag and </include> closing tag instead of <include for opening and /> for closing. It's little strange, but anyway your question helped me find my mistake. Thanks.

Title: databinding must include a layout file

Body:
I have following very simple layout and wanted to switch to using data binding. Now I'm getting following error in my controller_main.xml:

Error:Execution failed for task ':app:dataBindingProcessLayoutsDebug_pro'.

****/ data binding error ****msg:[44 68 44 68 25] must include a layout
  file:...\app\src\main\res\layout\controller_main.xml
  ****\ data binding error ****

Any ideas? The error says, the resource android:layout id in the include tag is missing (that's my interpretation of the error), but that's not true. Commenting out the include tag removes the error.

Does anyone see the problem?

controller_main.xml

<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" >

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:fitsSystemWindows="true"
        android:background="?attr/main_background_color"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <RelativeLayout
            android:id="@+id/rlContent"
            android:fitsSystemWindows="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </RelativeLayout>

        <include
            android:layout_width="fill_parent"
            android:layout_height="@dimen/tool_bar_top_padding"
            android:id="@+id/stub_view_main_header_fixed"
            android:layout="@layout/view_main_header_fixed"
            app:elevation="0dp"/>

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

        </android.support.design.widget.AppBarLayout>

    </android.support.design.widget.CoordinatorLayout>

</layout>

view_main_header_fixed.xml

<?xml version="1.0" encoding="utf-8"?>
<View
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/vStatusbarBackground"
    android:layout_width="match_parent"
    android:layout_height="@dimen/tool_bar_top_padding" />


问:
Loading an entire cache line at once to avoid contention for multiple elements of it
Assuming that there are three pieces of data that I need from a heavily contended cache line, is there a way to load all three things "atomically" so as to avoid more than one roundtrip to any other core?

I don't actually need a correctness guarantee of atomicity for a snapshot of all 3 members, just in the normal case that all three items are read in the same clock cycle.  I want to avoid the case where the cache line arrives, but then an invalidate request comes in before all 3 objects are read.  That would result in the 3rd access needing to send another request to share the line, making contention even worse.

For example,

```<code>class alignas(std::hardware_destructive_interference_size) Something {
    std::atomic<uint64_t> one;
    std::uint64_t two;
    std::uint64_t three;
};

void bar(std::uint64_t, std::uint64_t, std::uint64_t);

void f1(Something& something) {
    auto one = something.one.load(std::memory_order_relaxed);
    auto two = something.two;
    if (one == 0) {
        bar(one, two, something.three);
    } else {
        bar(one, two, 0);
    }

}

void f2(Something& something) {
    while (true) {
        baz(something.a.exchange(...));
    }
}
</code>```

Can I somehow ensure that one, two and three all get loaded together without multiple RFOs under heavy contention (assume f1 and f2 are running concurrently)?

The target architecture / platform for the purposes of this question is Intel x86 Broadwell, but if there is a technique or compiler intrinsic that allows doing something best-effort like this somewhat portably, that would be great as well.

答:
As long as the size of std::atomic<uint64_t> is at most 16 bytes (which is the case in all major compilers), the total size of one, two, and three does not exceed 32 bytes. Therefore, you can define a union of __m256i and Something where the Something field is aligned to 32-bytes to ensure that it is fully contained within a single 64-byte cache line.  To load all of the three values at the same time, you can use a single 32-byte AVX load uop. The corresponding compiler intrinsic is _mm256_load_si256, which causes the compiler to emit the VMOVDQA ymm1, m256 instruction. This instruction is supported with a single load uop decoding on Intel Haswell and later.

The 32-byte alignment is really only needed to ensure that all of the fields are contained within a 64-byte cache line. However, _mm256_load_si256 requires the specified memory address to be 32-byte aligned. Alternatively, _mm256_loadu_si256 could be used instead in case the address is not 32-byte aligned.

Body:
Assuming that there are three pieces of data that I need from a heavily contended cache line, is there a way to load all three things "atomically" so as to avoid more than one roundtrip to any other core?

I don't actually need a correctness guarantee of atomicity for a snapshot of all 3 members, just in the normal case that all three items are read in the same clock cycle.  I want to avoid the case where the cache line arrives, but then an invalidate request comes in before all 3 objects are read.  That would result in the 3rd access needing to send another request to share the line, making contention even worse.

For example,

class alignas(std::hardware_destructive_interference_size) Something {
    std::atomic<uint64_t> one;
    std::uint64_t two;
    std::uint64_t three;
};

void bar(std::uint64_t, std::uint64_t, std::uint64_t);

void f1(Something& something) {
    auto one = something.one.load(std::memory_order_relaxed);
    auto two = something.two;
    if (one == 0) {
        bar(one, two, something.three);
    } else {
        bar(one, two, 0);
    }

}

void f2(Something& something) {
    while (true) {
        baz(something.a.exchange(...));
    }
}

Can I somehow ensure that one, two and three all get loaded together without multiple RFOs under heavy contention (assume f1 and f2 are running concurrently)?

The target architecture / platform for the purposes of this question is Intel x86 Broadwell, but if there is a technique or compiler intrinsic that allows doing something best-effort like this somewhat portably, that would be great as well.


问:
How to bind an enumeration to combobox
I would bind the values of an enumeration with a combobox control.

I've written this code:

```<code>cboPriorLogicalOperator.DataSource = Enum.GetValues(typeof(MyEnum))
    .Cast<MyEnum>()
    .Select(p => new { Key = (int)p, Value = p.ToString() })
    .ToList();

myComboBox.DisplayMember = "Value";
myComboBox.ValueMember = "Key";
</code>```

It works well but I wonder if there is a simpler way.

答:
I think your code is beautiful!

The only improvement would be to place the code in an Extension Method.

EDIT:

When I think about it, what you want to do is to use the Enum as in the definition and not an instance of the enum, which is required by extensions methods.

I found this question, which solves it really nicely:

```<code>public class SelectList
{
    // Normal SelectList properties/methods go here

    public static SelectList Of<T>()
    {
       Type t = typeof(T);
       if (t.IsEnum)
       {
           var values = from Enum e in Enum.GetValues(t)
                        select new { ID = e, Name = e.ToString() };
           return new SelectList(values, "Id", "Name");
       }
       return null;
    }
}

// called with
var list = SelectList.Of<Things>();
</code>```

Only you might want to return a Dictionary<int, string> and not a SelectList, but you get the idea.

EDIT2:

Here we go with a code example that covers the case you are looking at.

```<code>public class EnumList
{
    public static IEnumerable<KeyValuePair<T, string>> Of<T>()
    {
        return Enum.GetValues(typeof (T))
            .Cast<T>()
            .Select(p => new KeyValuePair<T, string>(p, p.ToString()))
            .ToList();
    }
}
</code>```

Or this version perhaps, where the key is an int

```<code>public class EnumList
{
    public static IEnumerable<KeyValuePair<int, string>> Of<T>()
    {
        return Enum.GetValues(typeof (T))
            .Cast<T>()
            .Select(p => new KeyValuePair<int, string>(Convert.ToInt32(p), p.ToString()))
            .ToList();
    }
}
</code>```

Title: How to bind an enumeration to combobox

Body:
I would bind the values of an enumeration with a combobox control.

I've written this code:

cboPriorLogicalOperator.DataSource = Enum.GetValues(typeof(MyEnum))
    .Cast<MyEnum>()
    .Select(p => new { Key = (int)p, Value = p.ToString() })
    .ToList();

myComboBox.DisplayMember = "Value";
myComboBox.ValueMember = "Key";

It works well but I wonder if there is a simpler way.

Body:
I think your code is beautiful!

The only improvement would be to place the code in an Extension Method.

EDIT:

When I think about it, what you want to do is to use the Enum as in the definition and not an instance of the enum, which is required by extensions methods.

I found this question, which solves it really nicely:

public class SelectList
{
    // Normal SelectList properties/methods go here

    public static SelectList Of<T>()
    {
       Type t = typeof(T);
       if (t.IsEnum)
       {
           var values = from Enum e in Enum.GetValues(t)
                        select new { ID = e, Name = e.ToString() };
           return new SelectList(values, "Id", "Name");
       }
       return null;
    }
}

// called with
var list = SelectList.Of<Things>();

Only you might want to return a Dictionary<int, string> and not a SelectList, but you get the idea.

EDIT2:

Here we go with a code example that covers the case you are looking at.

public class EnumList
{
    public static IEnumerable<KeyValuePair<T, string>> Of<T>()
    {
        return Enum.GetValues(typeof (T))
            .Cast<T>()
            .Select(p => new KeyValuePair<T, string>(p, p.ToString()))
            .ToList();
    }
}

Or this version perhaps, where the key is an int

public class EnumList
{
    public static IEnumerable<KeyValuePair<int, string>> Of<T>()
    {
        return Enum.GetValues(typeof (T))
            .Cast<T>()
            .Select(p => new KeyValuePair<int, string>(Convert.ToInt32(p), p.ToString()))
            .ToList();
    }
}


问:
bitbake grpc cross compile/configure failing with error c-ares::cares references the file /usr/lib/libcares.so.2.2.0
I am having issues with finding c-ares dependencies when building grpc in open-embedded.Error in the log when looking for the dependency c-ares during configure is shown in the log as -

--

```<code>Found ZLIB: ....../poky/build/tmp-glibc/sysroots/arm7/usr/lib/libz.so (found version "1.2.8")
CMake Error at ....../poky/build/tmp-glibc/sysroots/arm7/usr/lib/cmake/c-ares/c-ares-targets.cmake:70 (message):
   The imported target "c-ares::cares" references the file
      "/usr/lib/libcares.so.2.2.0"

but this file does not exist.  Possible reasons include:

   * The file was deleted, renamed, or moved to another location.

   * An install or uninstall procedure did not complete successfully.

   * The installation package was faulty and contained

    "/home/...../poky/build/tmp-glibc/sysroots/arm7/usr/lib/cmake/c-ares/c-ares-targets.cmake"
   but not all the files it references.
</code>```

--

Issue seem to be how cmake has configured the import prefix for c-ares,which is configured as below in  file - poky/build/tmp-glibc/sysroots/arm7/usr/lib/cmake/c-ares/c-ares-targets.cmake. I believe it should be the path into the target staging directory

set(_IMPORT_PREFIX "/usr")

Can someone please help me identify the issue here? what needs to be configured in the c-ares recipe in order to get the  _IMPORT_PREFIX right??
Any help is much appreciated.
Thanks

答:
I came across this issue today when building a newer gRPC in an older (daisy) BitBake environment.  The solutions I came to were either backporting this upstream change to the cmake.bbclass or hacking in the updated variable definitions in a .bbappend to the cmake invocation by way of the EXTRA_OECMAKE variable.

I chose the latter, as I only seemed to need this for c-ares, and wanted to limit my impact.  I did not end up digging into the difference between how c-ares and other gRPC dependencies (e.g. gflags) generate CMake export targets files.  I assume there's some way the ultimate target paths are generated within the respective projects' CMakeLists.txt files.

diff --git a/meta/classes/cmake.bbclass b/meta/classes/cmake.bbclass
index b18152a8ed..5203d8aca1 100644
--- a/meta/classes/cmake.bbclass
+++ b/meta/classes/cmake.bbclass
@@ -108,15 +108,15 @@ cmake_do_configure() {
      ${OECMAKE_SITEFILE} \
      ${OECMAKE_SOURCEPATH} \
      -DCMAKE_INSTALL_PREFIX:PATH=${prefix} \
-     -DCMAKE_INSTALL_BINDIR:PATH=${bindir} \
-     -DCMAKE_INSTALL_SBINDIR:PATH=${sbindir} \
-     -DCMAKE_INSTALL_LIBEXECDIR:PATH=${libexecdir} \
+     -DCMAKE_INSTALL_BINDIR:PATH=${@os.path.relpath(d.getVar('bindir', True), d.getVar('prefix', True))} \
+     -DCMAKE_INSTALL_SBINDIR:PATH=${@os.path.relpath(d.getVar('sbindir', True), d.getVar('prefix', True))} \
+     -DCMAKE_INSTALL_LIBEXECDIR:PATH=${@os.path.relpath(d.getVar('libexecdir', True), d.getVar('prefix', True))} \
      -DCMAKE_INSTALL_SYSCONFDIR:PATH=${sysconfdir} \
-     -DCMAKE_INSTALL_SHAREDSTATEDIR:PATH=${sharedstatedir} \
+     -DCMAKE_INSTALL_SHAREDSTATEDIR:PATH=${@os.path.relpath(d.getVar('sharedstatedir', True), d.  getVar('prefix', True))} \
      -DCMAKE_INSTALL_LOCALSTATEDIR:PATH=${localstatedir} \
-     -DCMAKE_INSTALL_LIBDIR:PATH=${libdir} \
-     -DCMAKE_INSTALL_INCLUDEDIR:PATH=${includedir} \
-     -DCMAKE_INSTALL_DATAROOTDIR:PATH=${datadir} \
+     -DCMAKE_INSTALL_LIBDIR:PATH=${@os.path.relpath(d.getVar('libdir', True), d.getVar('prefix', True))} \
+     -DCMAKE_INSTALL_INCLUDEDIR:PATH=${@os.path.relpath(d.getVar('includedir', True), d.getVar('prefix', True))} \
+     -DCMAKE_INSTALL_DATAROOTDIR:PATH=${@os.path.relpath(d.getVar('datadir', True), d.getVar('prefix', True))} \
      -DCMAKE_INSTALL_SO_NO_EXE=0 \
      -DCMAKE_TOOLCHAIN_FILE=${WORKDIR}/toolchain.cmake \
      -DCMAKE_VERBOSE_MAKEFILE=1 \
```

Body:
I am having issues with finding c-ares dependencies when building grpc in open-embedded.Error in the log when looking for the dependency c-ares during configure is shown in the log as -

--

Found ZLIB: ....../poky/build/tmp-glibc/sysroots/arm7/usr/lib/libz.so (found version "1.2.8")
CMake Error at ....../poky/build/tmp-glibc/sysroots/arm7/usr/lib/cmake/c-ares/c-ares-targets.cmake:70 (message):
   The imported target "c-ares::cares" references the file
      "/usr/lib/libcares.so.2.2.0"

but this file does not exist.  Possible reasons include:

   * The file was deleted, renamed, or moved to another location.

   * An install or uninstall procedure did not complete successfully.

   * The installation package was faulty and contained

    "/home/...../poky/build/tmp-glibc/sysroots/arm7/usr/lib/cmake/c-ares/c-ares-targets.cmake"
   but not all the files it references.

--

Issue seem to be how cmake has configured the import prefix for c-ares,which is configured as below in  file - poky/build/tmp-glibc/sysroots/arm7/usr/lib/cmake/c-ares/c-ares-targets.cmake. I believe it should be the path into the target staging directory

set(_IMPORT_PREFIX "/usr")

Can someone please help me identify the issue here? what needs to be configured in the c-ares recipe in order to get the  _IMPORT_PREFIX right??
Any help is much appreciated.
Thanks


问:
Stop Ansible playbook if docker install with amazon-linux-extras does not succeed

What specific changes need to be made to the code below so that the ansible playbook will fail if the "Install docker" task below does not succeed?

Currently, the playbook reports "changed" as the result of the "Install docker" task below, and thus the playbook continues into subsequent tasks whether or not the installation of docker has been successful.

```<code>---
- name: Install some stuff.
  hosts: firstgroup, secondgroup
  remote_user: someuser
  become: true
  become_method: sudo
  become_user: root

  tasks:

     - name: Install docker
       command: amazon-linux-extras install -y docker
</code>```

As you can see, this is running in Amazon Linux 2, and the installation is being done using amazon-linux-extras.

答:
The command module will always get executed. That's because it's an extremely hard (if not impossible) problem to determine whether an arbitrary command needs to be executed or not if it has been run before.

What you can do is process the output of the command to determine whether the app was installed or not. This can be done using registers.

Body:
What specific changes need to be made to the code below so that the ansible playbook will fail if the "Install docker" task below does not succeed?

Currently, the playbook reports "changed" as the result of the "Install docker" task below, and thus the playbook continues into subsequent tasks whether or not the installation of docker has been successful.

---
- name: Install some stuff.
  hosts: firstgroup, secondgroup
  remote_user: someuser
  become: true
  become_method: sudo
  become_user: root

  tasks:

     - name: Install docker
       command: amazon-linux-extras install -y docker

As you can see, this is running in Amazon Linux 2, and the installation is being done using amazon-linux-extras.


问:
Is there a VS code extension to show a list of options for css?
Is there a VS code extension that lets users view options for CSS?

For example:

```<code>body {
 cursor: (at this point I want to see the extension telling me what my options are. Such as 'pointer', 'default', 'move', 'wait' and etc)
}
</code>```

Just thought it would save my time to go on w3school to see what my options are.

答:
Check out IntelliSense for CSS:
https://marketplace.visualstudio.com/items?itemName=Zignd.html-css-class-completion

Not sure if it does it automatically, but with Ctrl + Space it shows a list of suggestions:

Also, if you press the same combination while having the list, you'll get a description:

Body:
Is there a VS code extension that lets users view options for CSS?

For example:

body {
 cursor: (at this point I want to see the extension telling me what my options are. Such as 'pointer', 'default', 'move', 'wait' and etc)
}

Just thought it would save my time to go on w3school to see what my options are.


问:
Why Does Reassigning Function Pointer Slow Down Function Call
I have been using a function pointer, p, to call different functions. My problem is, the performance of calling p decreases dramatically if I point it to a different function after it has already been assigned a function. The performance is fine if I switch p between undefined and the same function over and over again, and fine when I only point it to one function, but switching between functions kills performance.

Below is the code I am using to test this scenario and here is the fiddle. I loop 500 times recursively and call p 1,000,000 times on each loop. p can be undefined or pointing to func1 or func2.

```<code>function func1() {} // two identical empty functions
function func2() {} // different in name only

var p = func1; // default to func1

var count  = 0; // current loop
var elapse = 0; // elapsed time for 1,000,000 calls on each loop
var start  = 0; // start time for 1,000,000 calls on each loop
var total  = 0; // total elapsed time for all loops

function loop() {

  start = performance.now(); // get start time

  for (let i = 0; i < 1000000; i ++) if (p !== undefined) p(); // do 1,000,000 calls or early out 1,000,000 times if undefined

    elapse = performance.now() - start;

  total += elapse; // used for getting average

  count ++;

  console.log(p + "\nelapsed " + elapse + "\naverage " + total / count);

  // Switch between the lines below to see the performance difference.
  p = (p === func1) ? p = undefined : p = func1; // best performance
  //p = (p === func1) ? p = func1 : p = func1; // good performance
  //p = (p === func1) ? p = func2 : p = func1; // bad performance

  // pattern: func1 -> undefined -> func2 -> undefined -> repeat
  /*if (p === undefined) p = (count % 4 === 0) ? p = func1 : p = func2;
  else p = undefined;*/ // also bad performance

  if (count < 500) loop(); // start the next loop

}

console.clear();

loop(); // start the loop
</code>```

Why does the performance of calling p drop significantly when it is assigned a different function? Also, why does setting p to undefined and back to the original function not change performance when setting p to undefined and then to a different function does?

答:
Even if I call p once while it points to func1 and then assign it to func2 and call it again before starting the loop, there is still a performance loss of about 2.5 ms on Chrome. If the cache has been reset, I don't understand the loss.

Your mental model of V8 isn't accurate.  It can JIT-compile JS to native machine code in some conditions, but anything it can't handle will "de-optimize" the whole function (or block or loop?) and make it interpreted.

I'm not much of an expert on JS or V8, but I've picked up some details.  Google found this:
https://ponyfoo.com/articles/an-introduction-to-speculative-optimization-in-v8

So it's not that you're invalidating "the cache" once, you're removing an invariant condition that it was optimizing based on.

Branch prediction as a cache for branch targets only matters once you get your JS runtime to JIT to native machine code instead of interpreting.  When interpreting, control dependencies in the JS are merely data dependencies in the interpreter running on the native CPU.

If removing this invariant de-optimizes the function, or the hot loop, then that's your problem, not branch prediction.

Body:
I have been using a function pointer, p, to call different functions. My problem is, the performance of calling p decreases dramatically if I point it to a different function after it has already been assigned a function. The performance is fine if I switch p between undefined and the same function over and over again, and fine when I only point it to one function, but switching between functions kills performance.

Below is the code I am using to test this scenario and here is the fiddle. I loop 500 times recursively and call p 1,000,000 times on each loop. p can be undefined or pointing to func1 or func2.

function func1() {} // two identical empty functions
function func2() {} // different in name only

var p = func1; // default to func1

var count  = 0; // current loop
var elapse = 0; // elapsed time for 1,000,000 calls on each loop
var start  = 0; // start time for 1,000,000 calls on each loop
var total  = 0; // total elapsed time for all loops

function loop() {

  start = performance.now(); // get start time

  for (let i = 0; i < 1000000; i ++) if (p !== undefined) p(); // do 1,000,000 calls or early out 1,000,000 times if undefined

    elapse = performance.now() - start;

  total += elapse; // used for getting average

  count ++;

  console.log(p + "\nelapsed " + elapse + "\naverage " + total / count);

  // Switch between the lines below to see the performance difference.
  p = (p === func1) ? p = undefined : p = func1; // best performance
  //p = (p === func1) ? p = func1 : p = func1; // good performance
  //p = (p === func1) ? p = func2 : p = func1; // bad performance

  // pattern: func1 -> undefined -> func2 -> undefined -> repeat
  /*if (p === undefined) p = (count % 4 === 0) ? p = func1 : p = func2;
  else p = undefined;*/ // also bad performance

  if (count < 500) loop(); // start the next loop

}

console.clear();

loop(); // start the loop

Why does the performance of calling p drop significantly when it is assigned a different function? Also, why does setting p to undefined and back to the original function not change performance when setting p to undefined and then to a different function does?


问:
Display HTML text in the Spark TextArea
The Below code is running well...

```<code><?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
      xmlns:s="library://ns.adobe.com/flex/spark"
      xmlns:mx="library://ns.adobe.com/flex/mx" >
 <fx:Declarations>
  <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" />
 </fx:Declarations>
  <s:Panel id="reader" title="Blog Reader" width="500">
  <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}">
   <mx:columns>
    <mx:DataGridColumn dataField="title" headerText="TITLE"/>
    <mx:DataGridColumn dataField="pubDate" headerText="Date"/>
   </mx:columns>
  </mx:DataGrid>
  <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/>
 </s:Panel>
 <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/>
 </s:Application>
</code>```

But when Textarea is changed to spark Textrea like below

```<code><s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/>
</code>```

Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.

答:
If you're using the RichEditableText component instead, you can do it this way using the TextConverter class

```<code>var myStr:String = "I contain <b>html</b> tags!";
myRichEditableText.textFlow = TextConverter.importToFlow(myStr, TextConverter.TEXT_FIELD_HTML_FORMAT);
</code>```

Title: Display HTML text in the Spark TextArea

Body:
The Below code is running well...

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
      xmlns:s="library://ns.adobe.com/flex/spark"
      xmlns:mx="library://ns.adobe.com/flex/mx" >
 <fx:Declarations>
  <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" />
 </fx:Declarations>
  <s:Panel id="reader" title="Blog Reader" width="500">
  <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}">
   <mx:columns>
    <mx:DataGridColumn dataField="title" headerText="TITLE"/>
    <mx:DataGridColumn dataField="pubDate" headerText="Date"/>
   </mx:columns>
  </mx:DataGrid>
  <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/>
 </s:Panel>
 <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/>
 </s:Application>

But when Textarea is changed to spark Textrea like below

<s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/>

Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.

Body:
If you're using the RichEditableText component instead, you can do it this way using the TextConverter class

var myStr:String = "I contain <b>html</b> tags!";
myRichEditableText.textFlow = TextConverter.importToFlow(myStr, TextConverter.TEXT_FIELD_HTML_FORMAT);


问:
How to ssh to my ec2 if i am not using default vpc
Well, I am almost giving up on aws it is really hard to do simple things here. My problem is I am following this link to setup cpanel for commercial use,
https://blog.cpanel.com/part-2-how-i-built-a-cpanel-hosting-environment-on-amazon-aws/

I set up my VPC, Subnet, Internet Gateways, Elastic IPs and Route Tables and still can not connect to my ec2. it is frustrating that I am wasting time over an ssh problem which can be solved in a matter of seconds in OVH and here AWS ruining my day any ideas?

I set up my VPC, Subnet, Internet Gateways, Elastic IPs and Route Tables

I really expect to connect to my ec2 with ease and be able to add more ec2/s to the service

答:
To be able to SSH into an Amazon EC2 instance, you'll need the following:

An Amazon VPC (the default one is fine, or create your own)

An Internet Gateway attached to the VPC (to connect it to the Internet)

A public subnet, which is defined as a subnet that has a route table where the route table sends traffic destined for 0.0.0.0/0 to the Internet Gateway

An Amazon EC2 instance in the public subnet, presumably a Linux instance since you want to SSH to it

When launching the instance, nominate a Keypair. If you launch from an Amazon-provided AMI (eg Amazon Linux 2), the keypair will be copied to /users/ec2-user/.ssh/authorized_keys at startup.

The instance should either be launched with Auto-assign Public IP to receive a random public IP address, or associate the instance with an Elastic IP address to associate a static IP address

A security group attached to the EC2 instance permitting inbound SSH access (port 22) either from 0.0.0.0/0 or your own IP address

Don't play with the Network Access Control List (NACL) settings - they default to allowing all traffic in/out

To connect to the instance:

```<code>ssh -i YOUR-KEYPAIR.pem ec2-user@IP-ADDRESS
</code>```

If the connection is immediately rejected, it suggests a problem with the keypair.

If the connection takes some time before failing, it suggests a network-related problem because it is unable to contact the instance. Some corporate networks block outbound SSH access, so try again from a different network (home vs office, or even tethered via your phone) to try and identify the issue.

Body:
To be able to SSH into an Amazon EC2 instance, you'll need the following:

An Amazon VPC (the default one is fine, or create your own)

An Internet Gateway attached to the VPC (to connect it to the Internet)

A public subnet, which is defined as a subnet that has a route table where the route table sends traffic destined for 0.0.0.0/0 to the Internet Gateway

An Amazon EC2 instance in the public subnet, presumably a Linux instance since you want to SSH to it

When launching the instance, nominate a Keypair. If you launch from an Amazon-provided AMI (eg Amazon Linux 2), the keypair will be copied to /users/ec2-user/.ssh/authorized_keys at startup.

The instance should either be launched with Auto-assign Public IP to receive a random public IP address, or associate the instance with an Elastic IP address to associate a static IP address

A security group attached to the EC2 instance permitting inbound SSH access (port 22) either from 0.0.0.0/0 or your own IP address

Don't play with the Network Access Control List (NACL) settings - they default to allowing all traffic in/out

To connect to the instance:

ssh -i YOUR-KEYPAIR.pem ec2-user@IP-ADDRESS

If the connection is immediately rejected, it suggests a problem with the keypair.

If the connection takes some time before failing, it suggests a network-related problem because it is unable to contact the instance. Some corporate networks block outbound SSH access, so try again from a different network (home vs office, or even tethered via your phone) to try and identify the issue.


问:
Get session values with the same index tag and select the bigger int value
I have a session variable called $_SESSION["shopping_cart"] which saves an array formed by user defined selections on a web page (meaning: products, codes, prices, descriptions and number of active months).

The array will look something like "Array => Array1["xxx"]=> ['product'] = "xxx", ['detail'] = "xxxxx", ['price'] = "xxx", ['envios'] = "x", Array2 => ...... and goes on. Now, SOME of the arrays in there will have an index ['envios'] = "x" and some of them won't. This specific index is always an INT value between 1-12. I need to select all of the values with a index ['envios'] and then save the bigger one of them in a separated variable $corval.

Is there any way to do that?

I found several session functions as session_search() or session_value() BUT all of them will return the value of the index when the input is equal to some array value. And I need to do it the other way around.

Long story short, I need to get all the values for the index ['envios'] inside the session array and save only the bigger of them into a different variable in php. If there is no ['envios'] index the the variable will be equal to 1.

This is the actual array data:

```<code>Array ( [BTWL001] => Array ( [name] => P�lulas Winky Lux [code] => BTWL001 [price] => 95.00 [quantity] => 1 [stock] => 8 [image] => /bubale/img/productimg/set5winki.jpg ) [PB001] =>
                     Array ( [name] => BOLSINHA UNICA [code] => PB001 [price] => 130.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/1month.png [envios] => 1 ) [PB003] =>
                     Array ( [name] => PLANO TRIMESTRAL [code] => PB003 [price] => 300.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/3month.png [envios] => 3 ) [PB012] =>
                     Array ( [name] => PLANO ANUAL [code] => PB012 [price] => 1080.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/12month.png [envios] => 12 ) )
</code>```

Note that there are 3 arrays with the index tag ['envios']. This array is stored in a session so I need to get only those "['envios']" values.

答:
well, after a lot of research I found a solution to this problem, so for those in search of something like this, here we go:

```<code>$col = $_SESSION['your session variable'];
$env = array_column($col, 'name of the index you need to extract');
</code>```

// here the $env will have a new array with only the values identified with the index you looked up for) //

```<code>$final = max($env);
</code>```

//you saved the maximum value of the array//

Body:
I have a session variable called $_SESSION["shopping_cart"] which saves an array formed by user defined selections on a web page (meaning: products, codes, prices, descriptions and number of active months).

The array will look something like "Array => Array1["xxx"]=> ['product'] = "xxx", ['detail'] = "xxxxx", ['price'] = "xxx", ['envios'] = "x", Array2 => ...... and goes on. Now, SOME of the arrays in there will have an index ['envios'] = "x" and some of them won't. This specific index is always an INT value between 1-12. I need to select all of the values with a index ['envios'] and then save the bigger one of them in a separated variable $corval.

Is there any way to do that?

I found several session functions as session_search() or session_value() BUT all of them will return the value of the index when the input is equal to some array value. And I need to do it the other way around.

Long story short, I need to get all the values for the index ['envios'] inside the session array and save only the bigger of them into a different variable in php. If there is no ['envios'] index the the variable will be equal to 1.

This is the actual array data:

Array ( [BTWL001] => Array ( [name] => P�lulas Winky Lux [code] => BTWL001 [price] => 95.00 [quantity] => 1 [stock] => 8 [image] => /bubale/img/productimg/set5winki.jpg ) [PB001] =>
                     Array ( [name] => BOLSINHA UNICA [code] => PB001 [price] => 130.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/1month.png [envios] => 1 ) [PB003] =>
                     Array ( [name] => PLANO TRIMESTRAL [code] => PB003 [price] => 300.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/3month.png [envios] => 3 ) [PB012] =>
                     Array ( [name] => PLANO ANUAL [code] => PB012 [price] => 1080.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/12month.png [envios] => 12 ) )

Note that there are 3 arrays with the index tag ['envios']. This array is stored in a session so I need to get only those "['envios']" values.

Body:
well, after a lot of research I found a solution to this problem, so for those in search of something like this, here we go:

$col = $_SESSION['your session variable'];
$env = array_column($col, 'name of the index you need to extract');

// here the $env will have a new array with only the values identified with the index you looked up for) //

$final = max($env);

//you saved the maximum value of the array//