问:
Passing Data Array from Controller to View Codeigniter
I'm trying to simplify my menu, that i will pass into my view, the problem is menu and submenu is not active. This is my controller:

```<code>parent::__construct();
    $this->menu = array(
      'menu'    => 'definition',
      'submenu' => 'workplace'
    );
</code>```

And i have this in my controller method:

```<code>$data = array(
    $this->menu, // menu is right here
    'list_workplace_type' => get_wp_type()->result_array()
  );
var_dump($data);die;
$this->load->view('wp', $data);
</code>```

And the result is like below:

```<code>array (size=2)
  0 =>
    array (size=2)
      'menu' => 'definition'
      'submenu' => 'workplace'
  'list_workplace_type' =>
    array (size=2)
      0 =>
        array (size=1)
          'szWorkplaceTypeName' => 'Kantor Pusat'
      1 =>
        array (size=1)
          'szWorkplaceTypeName' => 'Kantor Cabang'
</code>```

What I expected is more like this:

```<code>array (size=2)
  'menu' => 'definition'
  'submenu' => 'workplace'
  'list_workplace_type' =>
    array (size=2)
      0 =>
        array (size=1)
          'workplaceTypeName' => 'Kantor Pusat'
      1 =>
        array (size=1)
          'workplaceTypeName' => 'Kantor Cabang'
</code>```

I used array_push() but still doesn't work properly.

答:
I'll have to assume that get_wp_type() is a helper function.

You have used $result->result_array() which will give you the observed result.

What you need to use is $result->row_array() which will give you the result you are expecting.

So

```<code>$data = array(
    $this->menu, // menu is right here
    'list_workplace_type' => get_wp_type()->result_array()
  );
</code>```

becomes

```<code>$data = array(
    $this->menu, // menu is right here
    'list_workplace_type' => get_wp_type()->row_array()
  );
</code>```

Go and look them up in the codeigniter user guide. It's a good habit to get into.

Body:
I'm trying to simplify my menu, that i will pass into my view, the problem is menu and submenu is not active. This is my controller:

parent::__construct();
    $this->menu = array(
      'menu'    => 'definition',
      'submenu' => 'workplace'
    );

And i have this in my controller method:

$data = array(
    $this->menu, // menu is right here
    'list_workplace_type' => get_wp_type()->result_array()
  );
var_dump($data);die;
$this->load->view('wp', $data);

And the result is like below:

array (size=2)
  0 =>
    array (size=2)
      'menu' => 'definition'
      'submenu' => 'workplace'
  'list_workplace_type' =>
    array (size=2)
      0 =>
        array (size=1)
          'szWorkplaceTypeName' => 'Kantor Pusat'
      1 =>
        array (size=1)
          'szWorkplaceTypeName' => 'Kantor Cabang'

What I expected is more like this:

array (size=2)
  'menu' => 'definition'
  'submenu' => 'workplace'
  'list_workplace_type' =>
    array (size=2)
      0 =>
        array (size=1)
          'workplaceTypeName' => 'Kantor Pusat'
      1 =>
        array (size=1)
          'workplaceTypeName' => 'Kantor Cabang'

I used array_push() but still doesn't work properly.

Body:
I'll have to assume that get_wp_type() is a helper function.

You have used $result->result_array() which will give you the observed result.

What you need to use is $result->row_array() which will give you the result you are expecting.

So

$data = array(
    $this->menu, // menu is right here
    'list_workplace_type' => get_wp_type()->result_array()
  );

becomes

$data = array(
    $this->menu, // menu is right here
    'list_workplace_type' => get_wp_type()->row_array()
  );

Go and look them up in the codeigniter user guide. It's a good habit to get into.


来源: stackexchange

问:
Neo4j create new admin user from console
Is there any way to add neo4j admin user from console?
I found how to change default password for native user neo4j https://neo4j.com/docs/operations-manual/current/configuration/set-initial-password/ but didn't found how to add new admin user.

答: Since it was needed to set credentials before neo4j start I manually generated login and password using script from this comment and inserted them to neo4j auth file.</p>

ContentLicense: CC BY-SA 3.0


问:
MySQL json_remove returns null
I have a table called product_option_param that has a column povs of JSON type, which basically keeps JSON arrays with ids (for example, [1,2,3])

When I need to delete, for example, an id 1, I execute this:

```<code>UPDATE product_option_param
SET povs = JSON_REMOVE(
   povs, replace(JSON_SEARCH(povs, 'one', 1), '"', '')
)
WHERE json_search(povs, 'one', 1) IS NOT NULL
</code>```

But it just turns all cells that have 1 in the array into null. What am I doing wrong?

答:
Try:

SET @`id` := '1';

UPDATE `product_option_param`
SET `povs` =
  JSON_REMOVE(
    `povs`,
    JSON_UNQUOTE(
      JSON_SEARCH(
        REPLACE(
          REPLACE(
            REPLACE(
              `povs`,
              '[',
              '["'
            ),
            ']',
            '"]'
          ),
          ',',
          '","'
        ),
      'one',
      @`id`
    )
  )
)
WHERE
  JSON_CONTAINS(`povs`,  @`id`);
```

See db-fiddle.

Title: MySQL json_remove returns null

Body:
I have a table called product_option_param that has a column povs of JSON type, which basically keeps JSON arrays with ids (for example, [1,2,3])

When I need to delete, for example, an id 1, I execute this:

UPDATE product_option_param
SET povs = JSON_REMOVE(
   povs, replace(JSON_SEARCH(povs, 'one', 1), '"', '')
)
WHERE json_search(povs, 'one', 1) IS NOT NULL

But it just turns all cells that have 1 in the array into null. What am I doing wrong?

Body:
Try:

SET @`id` := '1';

UPDATE `product_option_param`
SET `povs` =
  JSON_REMOVE(
    `povs`,
    JSON_UNQUOTE(
      JSON_SEARCH(
        REPLACE(
          REPLACE(
            REPLACE(
              `povs`,
              '[',
              '["'
            ),
            ']',
            '"]'
          ),
          ',',
          '","'
        ),
      'one',
      @`id`
    )
  )
)
WHERE
  JSON_CONTAINS(`povs`,  @`id`);

See db-fiddle.


问:
Python import coding style
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?

Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of

```<code>import foo
from bar.baz import quux

def myFunction():
    foo.this.that(quux)
</code>```

I move all my imports into the function where they're actually used., like this:

```<code>def myFunction():
    import foo
    from bar.baz import quux

    foo.this.that(quux)
</code>```

This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.

Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.

答:
This does have a few disadvantages.

Testing

On the off chance you want to test your module through runtime modification, it may make it more difficult. Instead of doing

```<code>import mymodule
mymodule.othermodule = module_stub
</code>```

You'll have to do

```<code>import othermodule
othermodule.foo = foo_stub
</code>```

This means that you'll have to patch the othermodule globally, as opposed to just change what the reference in mymodule points to.

Dependency Tracking

This makes it non-obvious what modules your module depends on. This is especially irritating if you use many third party libraries or are re-organizing code.

I had to maintain some legacy code that used imports inline all over the place, it made the code extremely difficult to refactor or repackage.

Notes On Performance

Because of the way python caches modules, there isn't a performance hit. In fact, since the module is in the local namespace, there is a slight performance benefit to importing modules in a function.

Top Import

```<code>import random

def f():
    L = []
    for i in xrange(1000):
        L.append(random.random())

for i in xrange(10000):
    f()

$ time python test.py

real   0m1.569s
user   0m1.560s
sys    0m0.010s
</code>```

Import in Function Body

```<code>def f():
    import random
    L = []
    for i in xrange(1000):
        L.append(random.random())

for i in xrange(10000):
    f()

$ time python test2.py

real    0m1.385s
user    0m1.380s
sys     0m0.000s
</code>```

OwnerDisplayName: TokenMacGuy

ContentLicense: CC BY-SA 2.5

Title: Python import coding style

Body:
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?

Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of

import foo
from bar.baz import quux

def myFunction():
    foo.this.that(quux)

I move all my imports into the function where they're actually used., like this:

def myFunction():
    import foo
    from bar.baz import quux

    foo.this.that(quux)

This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.

Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.

Body:
This does have a few disadvantages.

Testing

On the off chance you want to test your module through runtime modification, it may make it more difficult. Instead of doing

import mymodule
mymodule.othermodule = module_stub

You'll have to do

import othermodule
othermodule.foo = foo_stub

This means that you'll have to patch the othermodule globally, as opposed to just change what the reference in mymodule points to.

Dependency Tracking

This makes it non-obvious what modules your module depends on. This is especially irritating if you use many third party libraries or are re-organizing code.

I had to maintain some legacy code that used imports inline all over the place, it made the code extremely difficult to refactor or repackage.

Notes On Performance

Because of the way python caches modules, there isn't a performance hit. In fact, since the module is in the local namespace, there is a slight performance benefit to importing modules in a function.

Top Import

import random

def f():
    L = []
    for i in xrange(1000):
        L.append(random.random())

for i in xrange(10000):
    f()

$ time python test.py

real   0m1.569s
user   0m1.560s
sys    0m0.010s

Import in Function Body

def f():
    import random
    L = []
    for i in xrange(1000):
        L.append(random.random())

for i in xrange(10000):
    f()

$ time python test2.py

real    0m1.385s
user    0m1.380s
sys     0m0.000s

OwnerDisplayName: Ryan

LastEditorDisplayName: Ryan


问:
How best to do a JavaScript array with non-consecutive indexes?
I'm writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive ID numbers.

(This is because I need to be able to efficiently look up the values later, using an ID number that comes from another source outside my control.)

For example:

```<code>var myObjects = [] ;

myObjects[471] = {foo: "bar"} ;

myObjects[3119] = {hello: "goodbye"}
</code>```

When I do console.log(myObjects), in the console I see the entire array printed out, with all the thousands of 'missing' indexes showing undefined.

My question is: does this matter? Is this wasting any memory?

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

答:
As I understand it from my reading of Crockford's "The Good Parts," this does not particularly waste memory, since javascript arrays are more like a special kind of key value collection than an actual array. The array's length is defined not as the number of addresses in the actual array, but as the highest-numbered index in the array.

But you are right that iterating through all possible values until you get to the array's length.  Better to do as you mention, and use an object with numeric keys.  This is possible by using the syntax myObj['x']=y where x is the symbol for some integer. e.g. myObj['5']=poodles Basically, convert your index to a string and you're fine to use it as an object key.

Body:
I'm writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive ID numbers.

(This is because I need to be able to efficiently look up the values later, using an ID number that comes from another source outside my control.)

For example:

var myObjects = [] ;

myObjects[471] = {foo: "bar"} ;

myObjects[3119] = {hello: "goodbye"}

When I do console.log(myObjects), in the console I see the entire array printed out, with all the thousands of 'missing' indexes showing undefined.

My question is: does this matter? Is this wasting any memory?

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?


问:
Selenium IE WebDriver only works while debugging
I am using Java Gradle, Selenium 3.8.0 and IEWebDriver 3.8.0.

Chrome and Firefox are working fine, but IE throws a org.openqa.selenium.TimeoutException: Expected condition failed Exception, although IE also works fine, if I debug my source code step by step.

Therefore I debuged a long time to find that problem and I noticed that IE looses the connection between WebDriver and Source Code, whenever a webDriver.get(..) is called, whichs looks like that:

```<code>driver.get(url);
waitForPageLoaded(driver);
</code>```

Because of that I assume that there are some timing issues, but I already tried to handle this:

```<code>public void waitForPageLoaded(WebDriver driver) {
        logger.debug("Wait until the page was loaded.");
        // IE seems to fail here.
        new WebDriverWait(driver, SeleniumConfigurator.TIME_OUT)
                .until(d -> ((JavascriptExecutor)d).executeScript("return document.readyState")
                        .equals("complete"));
    }
</code>```

Then I noticed that IE needs some more configuration settings, but I am not allowed to setup some of them: IT restrictions -> I cannot change regedit entries.

BUT, why does it work fine, while debugging?

This is my IE setup:

```<code>case IE:
                path = "../../../../../../resources/driver/win/IEDriverServer_32_v3-8-0.exe";
                url = getClass().getResource(path);
                if (url == null) {
                    logger.error("Could not find the Internet Explorer web driver binary at " + path + " ." +
                            "All test for this browser will be ignored.");
                    currentBrowserType = BrowserType.UNDEFINED;
                    break;
                }
                try {
                    System.setProperty("webdriver.ie.driver", Paths.get(url.toURI()).toFile().getAbsolutePath());
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                // https://sqa.stackexchange.com/questions/13077/unable-to-run-selenium-webdriver-script-in-ie11
                InternetExplorerOptions optionsIE = new InternetExplorerOptions();
                optionsIE.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
                optionsIE.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
                optionsIE.withAttachTimeout(SeleniumConfigurator.TIME_OUT, TimeUnit.SECONDS);

                //optionsIE.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, true);

                webDriver = new InternetExplorerDriver(optionsIE);
                currentBrowserType = BrowserType.IE;
                break;
</code>```

I have no idea what's going wrong here..

The first test works fine, after that the timeout exception appears (take a look at the comment):

```<code>@Test
    public void test_Contact() {
        Init();

        util.logTestStart("Test contact on index page..");
        String xPath = "//*[@id='contact-link']/a";
        WebElement element = webDriver.findElement(By.xpath(xPath));
        Assert.assertEquals(element.getAttribute("href"), "mailto:what@ever.com");
    }

    @Test
    public void test_LegalInformation() {
        Init();

        util.logTestStart("Test legal information on index page..");
        String xPath = "//*[@id='link-highlighted']/a";
        util.aTagClickByXPath(webDriver, xPath);

        Assert.assertEquals(webDriver.getCurrentUrl(), "http://whatever.com/");
    }

private void Init() {
        if (configurator == null) {
            configurator = SeleniumConfigurator.getInstance();
        }

        if (webDriver != configurator.getWebDriver()) {
            webDriver = configurator.getWebDriver();
        }

        if (util == null) {
            util = new SeleniumTestUtil();
        }

        // Open localhost as default
        util.goTo(webDriver, "http://localhost:8080/de/index");
    }

public void aTagClickByXPath(WebDriver driver, String xPath) {
        logger.debug("Performing a click on an a-Tag, xPath: " + xPath);
        WebElement element = driver.findElement(By.xpath(xPath));
        element.click(); // First click works, second one fails, cause of Timeout Exception
        waitForPageLoaded(driver);
    }
</code>```

Does anyone have a hint?

EDIT:

org.openqa.selenium.NoSuchWindowException: Unable to get browser get thrown for now. Timeout Exception didnt appears anymore. I changed nothing.

EDIT2:

Further information:

Node:

```<code><div class="col-xs-12" id="link-container">
                <div id="bike-link" class="pull-right">
                    <a href="http://whatever.com/?lang=D">
                        whatever
                        <i class="fa fa-chevron-right" aria-hidden="true"></i>
                    </a>
                </div>
                <div id="link-highlighted" class="pull-right">
                    <a href="http://whatever2.com/"> <!-- this one -->
                         Rechtliche Hinweise
                        <i class="fa fa-chevron-right" aria-hidden="true"></i>
                    </a>
                </div>
                <div id="contact-link" class="pull-right">
                    <a href="mailto:what@ever.com">
                        Kontakt
                        <i class="fa fa-chevron-right" aria-hidden="true"></i>
                    </a>
                </div>
            </div>
</code>```

Timeout definition:

```<code>public static final int TIME_OUT = 15;
</code>```

答:
There are a couple of facts which you may have to consider as follows :

First of all:

```<code>public void waitForPageLoaded(WebDriver driver)
</code>```

looks to me as a pure overhead. There is basically no need to write a separate wrapper function on top of WebDriverWait.

As per the current implementation of WebDriverWait in Selenium v3.8.1 the Constructors are as follows :

```<code>WebDriverWait(WebDriver driver, Clock clock, Sleeper sleeper, long timeOutInSeconds, long sleepTimeOut)
WebDriverWait(WebDriver driver, long timeOutInSeconds)
WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis)
</code>```

It is pretty much unclear how you have implemented:

```<code>WebDriverWait(driver, SeleniumConfigurator.TIME_OUT)
</code>```

The arguments looks error prone.

Again, the until condition

```<code>d -> ((JavascriptExecutor)d).executeScript("return document.readyState").equals("complete")
</code>```

is a overhead because the Client (i.e. the Web Browser) will never return the control back to the WebDriver instance until and unless 'document.readyState' is equal to "complete". Once this condition is fulfilled Selenium performs the next line of code. Hence the function

```<code>Boolean org.openqa.selenium.support.ui.FluentWait.until(Function<? super WebDriver, Boolean> arg0)
</code>```

will have no impact.

It's worth to mention that though the Client (i.e. the Web Browser) can return back the control to the WebDriver instance once 'document.readyState' equal to "complete" is achieved, it doesn't guarantees that all the WebElements on the new HTML DOM are VISIBLE, INTERACTABLE and CLICKABLE.

Finally, to address your main issue, I needed a clarification about  the node xPath = "//*[@id='link-highlighted']/a" to ensure whether invoking click() opens a new tab or url gets redirected. I don't see you handling either of the cases.

Solution

While dealing with InternetExplorer, keep in mind  InternetExplorerDriver runs in a real browser and supports Javascript.

Set the Browser Focus through :

```<code>capabilities.setCapability("requireWindowFocus", true);
</code>```

If click() opens a new window, switch() through the window_handles

References

You can find a couple of relevant detailed discussions in:

Do we have any generic function to check if page has completely loaded in Selenium

Selenium how to manage wait for page load?

Body:
I am using Java Gradle, Selenium 3.8.0 and IEWebDriver 3.8.0.

Chrome and Firefox are working fine, but IE throws a org.openqa.selenium.TimeoutException: Expected condition failed Exception, although IE also works fine, if I debug my source code step by step.

Therefore I debuged a long time to find that problem and I noticed that IE looses the connection between WebDriver and Source Code, whenever a webDriver.get(..) is called, whichs looks like that:

driver.get(url);
waitForPageLoaded(driver);

Because of that I assume that there are some timing issues, but I already tried to handle this:

public void waitForPageLoaded(WebDriver driver) {
        logger.debug("Wait until the page was loaded.");
        // IE seems to fail here.
        new WebDriverWait(driver, SeleniumConfigurator.TIME_OUT)
                .until(d -> ((JavascriptExecutor)d).executeScript("return document.readyState")
                        .equals("complete"));
    }

Then I noticed that IE needs some more configuration settings, but I am not allowed to setup some of them: IT restrictions -> I cannot change regedit entries.

BUT, why does it work fine, while debugging?

This is my IE setup:

case IE:
                path = "../../../../../../resources/driver/win/IEDriverServer_32_v3-8-0.exe";
                url = getClass().getResource(path);
                if (url == null) {
                    logger.error("Could not find the Internet Explorer web driver binary at " + path + " ." +
                            "All test for this browser will be ignored.");
                    currentBrowserType = BrowserType.UNDEFINED;
                    break;
                }
                try {
                    System.setProperty("webdriver.ie.driver", Paths.get(url.toURI()).toFile().getAbsolutePath());
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                // https://sqa.stackexchange.com/questions/13077/unable-to-run-selenium-webdriver-script-in-ie11
                InternetExplorerOptions optionsIE = new InternetExplorerOptions();
                optionsIE.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
                optionsIE.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
                optionsIE.withAttachTimeout(SeleniumConfigurator.TIME_OUT, TimeUnit.SECONDS);

                //optionsIE.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, true);

                webDriver = new InternetExplorerDriver(optionsIE);
                currentBrowserType = BrowserType.IE;
                break;

I have no idea what's going wrong here..

The first test works fine, after that the timeout exception appears (take a look at the comment):

@Test
    public void test_Contact() {
        Init();

        util.logTestStart("Test contact on index page..");
        String xPath = "//*[@id='contact-link']/a";
        WebElement element = webDriver.findElement(By.xpath(xPath));
        Assert.assertEquals(element.getAttribute("href"), "mailto:what@ever.com");
    }

    @Test
    public void test_LegalInformation() {
        Init();

        util.logTestStart("Test legal information on index page..");
        String xPath = "//*[@id='link-highlighted']/a";
        util.aTagClickByXPath(webDriver, xPath);

        Assert.assertEquals(webDriver.getCurrentUrl(), "http://whatever.com/");
    }

private void Init() {
        if (configurator == null) {
            configurator = SeleniumConfigurator.getInstance();
        }

        if (webDriver != configurator.getWebDriver()) {
            webDriver = configurator.getWebDriver();
        }

        if (util == null) {
            util = new SeleniumTestUtil();
        }

        // Open localhost as default
        util.goTo(webDriver, "http://localhost:8080/de/index");
    }

public void aTagClickByXPath(WebDriver driver, String xPath) {
        logger.debug("Performing a click on an a-Tag, xPath: " + xPath);
        WebElement element = driver.findElement(By.xpath(xPath));
        element.click(); // First click works, second one fails, cause of Timeout Exception
        waitForPageLoaded(driver);
    }

Does anyone have a hint?

EDIT:

org.openqa.selenium.NoSuchWindowException: Unable to get browser get thrown for now. Timeout Exception didnt appears anymore. I changed nothing.

EDIT2:

Further information:

Node:

                        whatever

                         Rechtliche Hinweise

                        Kontakt

Timeout definition:

public static final int TIME_OUT = 15;

Body:
There are a couple of facts which you may have to consider as follows :

First of all:

public void waitForPageLoaded(WebDriver driver)

looks to me as a pure overhead. There is basically no need to write a separate wrapper function on top of WebDriverWait.

As per the current implementation of WebDriverWait in Selenium v3.8.1 the Constructors are as follows :

WebDriverWait(WebDriver driver, Clock clock, Sleeper sleeper, long timeOutInSeconds, long sleepTimeOut)
WebDriverWait(WebDriver driver, long timeOutInSeconds)
WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis)

It is pretty much unclear how you have implemented:

WebDriverWait(driver, SeleniumConfigurator.TIME_OUT)

The arguments looks error prone.

Again, the until condition

d -> ((JavascriptExecutor)d).executeScript("return document.readyState").equals("complete")

is a overhead because the Client (i.e. the Web Browser) will never return the control back to the WebDriver instance until and unless 'document.readyState' is equal to "complete". Once this condition is fulfilled Selenium performs the next line of code. Hence the function

Boolean org.openqa.selenium.support.ui.FluentWait.until(Function<? super WebDriver, Boolean> arg0)

will have no impact.

It's worth to mention that though the Client (i.e. the Web Browser) can return back the control to the WebDriver instance once 'document.readyState' equal to "complete" is achieved, it doesn't guarantees that all the WebElements on the new HTML DOM are VISIBLE, INTERACTABLE and CLICKABLE.

Finally, to address your main issue, I needed a clarification about  the node xPath = "//*[@id='link-highlighted']/a" to ensure whether invoking click() opens a new tab or url gets redirected. I don't see you handling either of the cases.

Solution

While dealing with InternetExplorer, keep in mind  InternetExplorerDriver runs in a real browser and supports Javascript.

Set the Browser Focus through :

capabilities.setCapability("requireWindowFocus", true);

If click() opens a new window, switch() through the window_handles

References

You can find a couple of relevant detailed discussions in:

Do we have any generic function to check if page has completely loaded in Selenium

Selenium how to manage wait for page load?

ContentLicense: CC BY-SA 4.0


问:
Setting Big Query variables like mysql
what is the bigquery equivalent to mysql variables like?</p>

```<code>SET @fromdate = '2014-01-01 00:00:00',  -- dates for after 2013
@todate='2015-01-01 00:00:00',

@bfromdate = '2005-01-01 00:00:00', -- dates for before 2013
@btodate = '2005-01-01 00:00:00',

@achfromdate  = '2013-01-01 00:00:00', -- dates for ACH without submit time in 2013
@achtodate  = '2013-01-01 00:00:00',

@currency="USD";
</code>```

答:
You may want to consider looking into BigQuery's Parameterized Queries. BigQuery supports query parameters to help prevent SQL injection when queries are constructed using user input. This feature is only available with standard SQL syntax.

https://cloud.google.com/bigquery/docs/parameterized-queries

Title: Setting Big Query variables like mysql

Body:
what is the bigquery equivalent to mysql variables like?

SET @fromdate = '2014-01-01 00:00:00',  -- dates for after 2013
@todate='2015-01-01 00:00:00',

@bfromdate = '2005-01-01 00:00:00', -- dates for before 2013
@btodate = '2005-01-01 00:00:00',

@achfromdate  = '2013-01-01 00:00:00', -- dates for ACH without submit time in 2013
@achtodate  = '2013-01-01 00:00:00',

@currency="USD";


问:
Convert Documents (docs,pdf) to byte array in ASP.NET MVC
I'm having a trouble in converting a Documents to byte array. As of now I don't have a code in it. As I'm having a trouble in finding a right solution. I only have a helper in Converting Image to byte array.

Current code in converting Image to Byte and vice versa

```<code>public static Image ConvertBase64ToImage(string base64String)
{
    try
    {
        // Convert Base64 String to byte[]
        string res = base64String.Substring(base64String.IndexOf(',') + 1);
        byte[] imageBytes = Convert.FromBase64String(res);
        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

        // Convert byte[] to Image
        ms.Write(imageBytes, 0, imageBytes.Length);
        Image image = Image.FromStream(ms, true);
        return image;
    }
    catch
    {
        return null;
    }
}

public static string ConvertImageTo64BaseString(Image image)
{
    try
    {
        using (MemoryStream m = new MemoryStream())
        {
            image.Save(m, image.RawFormat);
            byte[] imageBytes = m.ToArray();

            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            return base64String;
        }
    }
    catch
    {
        return "";
    }
}
</code>```

And the Conversion

```<code>Image img = Image.FromStream(file.InputStream, true, true);
Session["userimage"] = "data:image/png;base64," + cHelper.ConvertImageTo64BaseString(img);
</code>```

答:
C# and .NET already support to read any file content(pdf/excel/image...) into a byte array. Look this example

A: var byteArrayData = File.ReadAllBytes("C:\\file\\myfile.pdf");

Or You can also use FileStream to read all byte contents of your files.

B:

```<code>            var buffer = new byte[16 * 1024];
            using (var stream = new FileStream("C:\\file\\myfile.pdf", FileMode.Open))
            {
                using (var memoryStream = new MemoryStream())
                {
                    int read;
                    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        memoryStream.Write(buffer, 0, read);
                    }
                    return memoryStream.ToArray();
                }
            }
</code>```

Body:
I'm having a trouble in converting a Documents to byte array. As of now I don't have a code in it. As I'm having a trouble in finding a right solution. I only have a helper in Converting Image to byte array.

Current code in converting Image to Byte and vice versa

public static Image ConvertBase64ToImage(string base64String)
{
    try
    {
        // Convert Base64 String to byte[]
        string res = base64String.Substring(base64String.IndexOf(',') + 1);
        byte[] imageBytes = Convert.FromBase64String(res);
        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

        // Convert byte[] to Image
        ms.Write(imageBytes, 0, imageBytes.Length);
        Image image = Image.FromStream(ms, true);
        return image;
    }
    catch
    {
        return null;
    }
}

public static string ConvertImageTo64BaseString(Image image)
{
    try
    {
        using (MemoryStream m = new MemoryStream())
        {
            image.Save(m, image.RawFormat);
            byte[] imageBytes = m.ToArray();

            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            return base64String;
        }
    }
    catch
    {
        return "";
    }
}

And the Conversion

Image img = Image.FromStream(file.InputStream, true, true);
Session["userimage"] = "data:image/png;base64," + cHelper.ConvertImageTo64BaseString(img);

Body:
C# and .NET already support to read any file content(pdf/excel/image...) into a byte array. Look this example

A: var byteArrayData = File.ReadAllBytes("C:\\file\\myfile.pdf");

Or You can also use FileStream to read all byte contents of your files.

B:

            var buffer = new byte[16 * 1024];
            using (var stream = new FileStream("C:\\file\\myfile.pdf", FileMode.Open))
            {
                using (var memoryStream = new MemoryStream())
                {
                    int read;
                    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        memoryStream.Write(buffer, 0, read);
                    }
                    return memoryStream.ToArray();
                }
            }


答:
As the comments have suggested it would be advisable to convert the graphic from shapes to to strokes and then use an animation library such as Anime JS or Greensock to perform the animation.

Conversion to strokes

For the conversion to strokes I used Illustrator, and then exported to SVG before optimizing the graphic with Jake Archibald's SVGOMG.

Animation example

I chose the Anime JS library for the animation - see the snippet below.

anime({
  targets: 'path',
  strokeDashoffset: [anime.setDashoffset, 0],
  easing: [0.550, 0.055, 0.100, 1.000],
  duration: 1500,
  delay: 1200,
  direction:'forwards'
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg {
  display: block;
  width: 300px;
  height: 300px;
  margin: 0 auto;
}</code>```

<svg id="mylogo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800"><path class="st0" d="M382 183.1h324l21 64H589.5v245.5s-2.5 22.5 10 48l-47 51.5s33 62.5 132 73v-61.5l-21.6-2.5-19.4-6.5-43.8 41.3"/><path class="st0" d="M552.5 592.1s-25.5-36-25.5-106v-237h-71.5l-105 315s-10.6 49-74.2 81.8C184 693.6 88 634.6 67.7 592.6c-23.3-32-26.7-88-26.7-88h130.3c-.2-7.4 2.1-14.9 7.1-21.2 11.1-13.7 31.3-15.9 45-4.8s15.9 31.3 4.8 45c-11.1 13.7-31.3 15.9-45 4.8-7.5-6.1-11.5-14.8-11.9-23.7"/><path d="M125.7 561.9s42.7 58.3 117.7 29l44.7 43" fill="none" stroke="#231f20" stroke-width="34" stroke-linecap="square" stroke-miterlimit="10"/><path class="st0" d="M335.7 589.2l-47.3-46 5.3-9.3L386 248.6l-50.5-1.3-3.2-.1c-62-2-90 64.7-90 64.7h-68c42-134 157.3-128 157.3-128l.7 61.9"/><path fill="#fff" d="M92.7 536.2h54v22.7h-54z"/></svg>```

Any further questions related to the graphic itself would be better on graphic design StackExchange.

Title: Complex filled SVG animation

Body:
I need to animate the logo like so:

Here is its SVG code:

<?xml version="1.0" encoding="utf-8"?>

  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 800 800" style="enable-background:new 0 0 800 800;" xml:space="preserve" id="mylogo">

  <g id="cap_arch_connector_vert">
   <path class="st0" d="M333.7,195.4c-5.4,0-10.7,0.4-16,1v39.3c5.2-0.8,10.6-1.2,16-1.2h16v-39.1H333.7z"/>
  </g>
  <g id="cap_bottom_arch">
   <path class="st0" d="M333.7,231c-56.4,0-103.2,41.8-111,96.1v0h32.5c7.4-36.5,39.8-64.1,78.5-64.1h65.2l10.4-32H333.7z"/>
  </g>
  <g id="arched_line_right">
   <path class="st0" d="M641.9,570l-23,23c18.7,14,42,22.3,67.1,22.3c5.4,0,10.8-0.4,16-1.1v-32.5c-5.2,1.1-10.5,1.6-16,1.6
    C669.7,583.3,654.5,578.4,641.9,570z"/>
  </g>
  <g id="right_leg_line_1">
   <path class="st0" d="M702,646.4c-5.3,0.6-10.6,0.9-16,0.9c-79.5,0-144.1-64.7-144.1-144.1l0.3-272.2h-32l-0.3,272.2
    c0,97.1,79,176.1,176.1,176.1c5.4,0,10.7-0.3,16-0.8V646.4z"/>
  </g>
  <g id="arch_under_circle">
   <path class="st0" d="M203.3,615.3c24.8,0,48.2-8.2,67.1-22.3l-23-23c-12.8,8.4-28,13.3-44.1,13.3c-26.1,0-49.4-12.6-64-32H102
    C120,589.1,158.7,615.3,203.3,615.3z"/>
  </g>
  <g id="circle">
   <path class="st0" d="M203.3,551.3c-26.5,0-48-21.6-48-48s21.5-48,48-48s48,21.6,48,48S229.8,551.3,203.3,551.3z M203.3,487.2
    c-8.8,0-16,7.2-16,16c0,8.8,7.2,16,16,16s16-7.2,16-16C219.3,494.4,212.1,487.2,203.3,487.2z"/>
  </g>
  <g id="line_to_circle">
   <path class="st0" d="M27.9,487.2c-0.5,5.3-0.7,10.6-0.7,16c0,5.4,0.3,10.7,0.8,16h145.7v-32H27.9z"/>
  </g>
  <g id="leg_connector">
   <path class="st0" d="M297,529l-13.5-13.5l-4.3,13.2c-2.3,6.7-5.4,12.9-9.1,18.6l12.4,12.4v0l34,34l0,0l7.6,7.6l22.4-22.9L297,529z"
    />
  </g>
  <g id="arch_connector">
   <path class="st0" d="M277.8,600.3l-7.4-7.4l0,0l-6-6l-3.8-3.8l0,0L247.4,570c-9.8,6.4-20.9,10.8-32.8,12.5l26.3,26.3l38.4,38.4
    l22.4-22.9L277.8,600.3z"/>
  </g>
  <g id="cap_mid-bottom_parallel_line">
   <polygon class="st0" points="542.2,231 443,231 432.6,263 542.1,263  "/>
  </g>
  <g id="arch_connector_very_right">
   <path class="st0" d="M686,583.3c-5.5,0-10.8-0.6-16-1.6v19.4v13.1v32.3v18.7v13.5c5.3,0.5,10.6,0.8,16,0.8s10.7-0.3,16-0.8v-13.5
    v-18.7v-32.3v-13.1v-19.4C696.8,582.7,691.5,583.3,686,583.3z"/>
  </g>
  <g id="arch_connector_right">
   <path class="st0" d="M674.7,582.5c-12-1.7-23.1-6.1-32.8-12.5l-13.1,13.1l-9,9l-24.4,24.4L584,626.6l25.9,20.7l49.4-49.4
    L674.7,582.5z"/>
  </g>
  <g id="right_leg_connector">
   <path class="st0" d="M619.2,547.3c-6.4-9.7-10.8-20.8-12.5-32.8l-26.3,26.3v0l-30.7,30.7l20.9,24.1l2.2-1.8l27.8-27.8L619.2,547.3z
    "/>
  </g>
  <g id="cap_arch_connector_hor">
   <path class="st0" d="M246.2,295.1h-48.4h-30.1h-3.5c-2.9,10.3-5,21-5.9,32h0.3l9.2,0v0h55h32.5c2.4-11.8,7.5-22.7,14.5-32H246.2z"
    />
  </g>
  <g id="cap_top_arch">
   <path class="st0" d="M333.7,166.9c-91.7,0-167.3,70.5-175.4,160.2l32.2,0c7.4-66.7,60.5-119.8,127.2-127.2v0.1c5.3-0.6,10.6-1,16-1
    h16v-25.2v-6.8H333.7z"/>
  </g>
  <g id="left_leg_line_1">
   <path class="st0" d="M309.6,538.8L409.3,231h-33.7l-96.4,297.7c-2.3,6.7-5.4,12.9-9.1,18.6l23,23
    C300.1,561,305.7,550.3,309.6,538.8z"/>
  </g>
  <g id="left_leg_line_2">
   <path class="st0" d="M443,231L340,548.8c-19.8,58.9-74.7,98.5-136.8,98.5c-79.5,0-144.1-64.7-144.1-144.1c0-5.4,0.3-10.7,0.9-16
    H27.9c-0.5,5.3-0.7,10.6-0.7,16c0,97.1,79,176.1,176.1,176.1c75.8,0,142.9-48.4,167.2-120.5L476.6,231H443z"/>
  </g>
  <g id="right_leg_line_2">
   <path class="st0" d="M619.2,547.3c-8.4-12.6-13.3-27.8-13.3-44.1l0.3-272.3h-32l-0.3,272.3c0,25.1,8.3,48.4,22.3,67.1L619.2,547.3z
    "/>
  </g>
  <g id="cap_top_parallel_line">
   <polygon class="st0" points="728.8,199 718.4,166.9 684.8,166.9 381.7,166.9 381.7,199 695.2,199  "/>
  </g>
  <g id="cap_bottom_parallel_line">
   <polygon class="st0" points="739.2,231 732.3,231 705.5,231 574.2,231 574.2,263 715.9,263 749.6,263  "/>
  </g>
  <g id="right_cap_corner">
   <polygon class="st0" points="749.6,263 739.2,231 739.2,231 728.8,199 728.8,199 718.4,166.9 684.8,166.9 714.2,257.7 714.2,257.7
    715.9,263  "/>
  </g>
  </svg>

I spend a lot of time looking for a solution but mostly I stumbled upon stroke SVG animations. Vivus.js looked like a good solution but it doesn't animate filled path, it works only with stroke. So does pretty much all examples I have found, like DrawSVG etc.
I broke down my SVG into simple elements so it would be easier to animate them. I suppose I have to use some SVG masks as I can't change the existing shape of the logo by applying stroke etc. The only animation that looks similar to mine is on Codepen. SVG code is pretty complicated there and I'm not sure whether the way it was animated there will solve my problem.

How can I animate the logo?

Body:
As the comments have suggested it would be advisable to convert the graphic from shapes to to strokes and then use an animation library such as Anime JS or Greensock to perform the animation.

Conversion to strokes

For the conversion to strokes I used Illustrator, and then exported to SVG before optimizing the graphic with Jake Archibald's SVGOMG.

Animation example

I chose the Anime JS library for the animation - see the snippet below.

anime({
  targets: 'path',
  strokeDashoffset: [anime.setDashoffset, 0],
  easing: [0.550, 0.055, 0.100, 1.000],
  duration: 1500,
  delay: 1200,
  direction:'forwards'
});

svg {
  display: block;
  width: 300px;
  height: 300px;
  margin: 0 auto;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.0/anime.min.js"></script>
<svg id="mylogo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800"><style>.st0{fill:none;stroke:#231f20;stroke-width:34;stroke-miterlimit:10}</style><path class="st0" d="M382 183.1h324l21 64H589.5v245.5s-2.5 22.5 10 48l-47 51.5s33 62.5 132 73v-61.5l-21.6-2.5-19.4-6.5-43.8 41.3"/><path class="st0" d="M552.5 592.1s-25.5-36-25.5-106v-237h-71.5l-105 315s-10.6 49-74.2 81.8C184 693.6 88 634.6 67.7 592.6c-23.3-32-26.7-88-26.7-88h130.3c-.2-7.4 2.1-14.9 7.1-21.2 11.1-13.7 31.3-15.9 45-4.8s15.9 31.3 4.8 45c-11.1 13.7-31.3 15.9-45 4.8-7.5-6.1-11.5-14.8-11.9-23.7"/><path d="M125.7 561.9s42.7 58.3 117.7 29l44.7 43" fill="none" stroke="#231f20" stroke-width="34" stroke-linecap="square" stroke-miterlimit="10"/><path class="st0" d="M335.7 589.2l-47.3-46 5.3-9.3L386 248.6l-50.5-1.3-3.2-.1c-62-2-90 64.7-90 64.7h-68c42-134 157.3-128 157.3-128l.7 61.9"/><path fill="#fff" d="M92.7 536.2h54v22.7h-54z"/></svg>

Any further questions related to the graphic itself would be better on graphic design StackExchange.


问:
PHP Calling a model method multiple times with having different value for parameter in codeiginter
I created a method in the model to get data from the database and then call it in the controller for multiple time with different method parameters($param) values. This is working for only one parameter value which one comes first. I Know i am doing it in wrong way but i am unable to find the solution for this. please help.

Actually, I am trying to have category based on their type('wordpress', 'magento', 'shopify') form database

My_model.php

```<code>class My_model extends CI_Model{

  public function fun_name($param){
       return $this->db->get_where('categories', array('type' => '$param'));
  }

}
</code>```

My_controller.php

```<code>class My_controller extends CI_Controller{
   public function get_data(){
       $this->load->model('my_model');
       $data = array(
           'first'   =>   $this->my_model->fun_name('wordpress'),
           'second'  =>   $this->my_model->fun_name('magento'),
           'third'   =>   $this->my_model->fun_name('shopify')
        );
       $this->load->view('index', $data);
   }
}
</code>```

答:
If that's your actual code,

```<code>class My_model extends CI_Model{
  public function fun_name($param){
    if($param = one){
       return $this->db->get_where('table', array('id' => '$param'));
    }
  }
}
</code>```

then the issue is in this line below -

```<code>    if($param = one){
</code>```

change it to

```<code>    if($param == 'one'){
</code>```

.

and in this

```<code>return $this->db->get_where('table', array('id' => '$param'));
</code>```

change it to this line below because you don't need quotes around variable

```<code>return $this->db->get_where('table', array('id' => $param));
</code>```

Obviously your code can be optimised better i.e. you may not need if - else the way you are doing but again without knowing the full scenario it's not easy to recommend a solution.

Body:
I created a method in the model to get data from the database and then call it in the controller for multiple time with different method parameters($param) values. This is working for only one parameter value which one comes first. I Know i am doing it in wrong way but i am unable to find the solution for this. please help.

Actually, I am trying to have category based on their type('wordpress', 'magento', 'shopify') form database

My_model.php

class My_model extends CI_Model{

  public function fun_name($param){
       return $this->db->get_where('categories', array('type' => '$param'));
  }

}

My_controller.php

class My_controller extends CI_Controller{
   public function get_data(){
       $this->load->model('my_model');
       $data = array(
           'first'   =>   $this->my_model->fun_name('wordpress'),
           'second'  =>   $this->my_model->fun_name('magento'),
           'third'   =>   $this->my_model->fun_name('shopify')
        );
       $this->load->view('index', $data);
   }
}

Body:
If that's your actual code,

class My_model extends CI_Model{
  public function fun_name($param){
    if($param = one){
       return $this->db->get_where('table', array('id' => '$param'));
    }
  }
}

then the issue is in this line below -

    if($param = one){

change it to

    if($param == 'one'){

.

and in this

return $this->db->get_where('table', array('id' => '$param'));

change it to this line below because you don't need quotes around variable

return $this->db->get_where('table', array('id' => $param));

Obviously your code can be optimised better i.e. you may not need if - else the way you are doing but again without knowing the full scenario it's not easy to recommend a solution.


问:
read csv/tsv with no header line in D3
I have CSV data which looks something like:

Data

```<code>1,1,10
1,2,50
1,3,5
etc...
</code>```

And I am trying to read in the data. However, my initial data does not contain a header row (as seen above) so it is taking the first data row to be the header (1,1,10). Is there anyway around this. I want to set the header names after I read the data

Javascript

```<code>d3.csv("data/testnh.csv", function(data) {
    console.log(data);
}
</code>```

Thanks!

答:
Try d3.csvParse(text)

d3.csv.parseRows seems doesn't work in modern d3 version.

Title: read csv/tsv with no header line in D3

Body:
I have CSV data which looks something like:

Data

1,1,10
1,2,50
1,3,5
etc...

And I am trying to read in the data. However, my initial data does not contain a header row (as seen above) so it is taking the first data row to be the header (1,1,10). Is there anyway around this. I want to set the header names after I read the data

Javascript

d3.csv("data/testnh.csv", function(data) {
    console.log(data);
}

Thanks!


问:
How to add the chrome binary to run e.g. Karma tests on headless chrome on a CI server
I like to run my karma unit tests on a headless chrome. Using karma-chrome-launcher and setting the browser to "ChromeHeadless" works on my machine. But on the CI server it fails with the message "No binary for ChromeHeadless browser on your platform."
Installing chrome on the CI machine is not possible. Is there another way to load the chrome binaries?
for example the google puppeteer module seems to load that when run. from the docs: "Puppeteer downloads and uses a specific version of Chromium". How can i achieve the same?</p>

答:
If what you fear is that download from the internet might be slow, you can tell puppeteer where to download chrome from and use a local address.

Use PUPPETEER_DOWNLOAD_HOST to specify where to download Chrome from and PUPPETEER_SKIP_CHROMIUM_DOWNLOAD to skip downloading Chrome altogether.

You can read more about this in the documentation.


问:
Malformed string while using ast.literal_eval
I used json dump and then json load on the same data. The data is unicode so I converted it to string. Using the ast.literla_eval I tried to get the type of the string to dict but I am getting error Malformed String.

output of json load is below

```<code>('data', u'{\n  "a": "spawning", \n  "addresses": "", \n  "image": "b", \n  "OS-EXT-STS:vm_state": "building", \n  "c:launched_at": null, \n  "d": "e (fgh)", \n  "user_id": "hhh", \n
    "accessIPv4": "", \n  "accessIPv6": "", \n  "name": "kk", \n  "created": "2017-12-08T07:52:44Z", \n  "z:xyz": []\n}', <type 'unicode'>)
</code>```

What I tried?

```<code>        with open('openstack_list.json', 'w') as e:
            json.dump(check_output(['openstack', 'server', 'show', i, '-f', 'json']), e)
        with open('openstack_list.json', 'r') as a:
            data = json.load(a)
            new_data = data.encode('utf-8')  # output type is unicode
            dict_data = ast.literal_eval(new_data) # output type is string
</code>```

I want output to be dictionary but I didnt get it. Also, json load gives a unicode data so I believe new_data = data.encode('utf-8')is redundant. But if I use ast.literal_eval without encoding I get Malformed string error. In any case, I am not able to get the data type to be dictionary.

Edits:

Error:

```<code>Traceback (most recent call last):
  File "openstack_resource_list.py", line 84, in <module>
    output = get_resources()
  File "openstack_resource_list.py", line 47, in get_resources
    dict_data = ast.literal_eval(new_data)
  File "/usr/lib64/python2.7/ast.py", line 80, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib64/python2.7/ast.py", line 63, in _convert
    in zip(node.keys, node.values))
  File "/usr/lib64/python2.7/ast.py", line 62, in <genexpr>
    return dict((_convert(k), _convert(v)) for k, v
  File "/usr/lib64/python2.7/ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string
</code>```

The data before json dump :

```<code>"{\n  \"aaa\": null, \n  \"addresses\": \"inner-net=192.168.0.173, x.x.x.x\", \n  \"image\": \"aaa (aaa)\",
    \n  \"aaa:vm_state\": \"active\", \n  \"aaa:launched_at\": \"2017-12-08T08:21:45.000000\", \n  \"flavor\": \"aaa4 (aaa)\",
    \n  \"id\": \"aaa\", \n  \"security_groups\": [\n    {\n      \"name\": \"default\"\n    }\n  ], \n  \"user_id\": \"aaa\",
    \n  \"OS-DCF:diskConfig\": \"MANUAL\", \n  \"accessIPv4\": \"\", \n  \"accessIPv6\": \"\", \n  \"progress\": 0, \n  \"Oaa:power_state\": 1, \n  \"project_id\": \"aaa\",
    \n  \"config_drive\": \"\", \n  \"status\": \"ACTIVE\", \n  \"updated\": \"2017-12-08T08:21:45Z\", \n  \"hostId\": \"aaa\", \n  \"OS-SRV-USG:terminated_at\": null,
    \n  \"key_name\": \"pg_ci\", \n  \"properties\": \"\", \n  \"OS-EXT-AZ:availability_zone\": \"nova\", \n  \"name\": \"taaa\", \n  \"created\": \"2017-12-08T08:21:31Z\", \n
    \"os-extended-volumes:volumes_attached\": [\n    {\n      \"id\": \"aaa\"\n    }\n  ]\n}"
</code>```

答:
That data returned by check_output is already JSON, so you should not JSON-ify it again with json.dump. You can just write it to the file as is, and the file will be a valid JSON file. And you can load it into a Python object with json.loads:

```<code>import json
from pprint import pprint

s = """{\n  \"aaa\": null, \n  \"addresses\": \"inner-net=192.168.0.173, x.x.x.x\", \n  \"image\": \"aaa (aaa)\",
    \n  \"aaa:vm_state\": \"active\", \n  \"aaa:launched_at\": \"2017-12-08T08:21:45.000000\", \n  \"flavor\": \"aaa4 (aaa)\",
    \n  \"id\": \"aaa\", \n  \"security_groups\": [\n    {\n      \"name\": \"default\"\n    }\n  ], \n  \"user_id\": \"aaa\",
    \n  \"OS-DCF:diskConfig\": \"MANUAL\", \n  \"accessIPv4\": \"\", \n  \"accessIPv6\": \"\", \n  \"progress\": 0, \n  \"Oaa:power_state\": 1, \n  \"project_id\": \"aaa\",
    \n  \"config_drive\": \"\", \n  \"status\": \"ACTIVE\", \n  \"updated\": \"2017-12-08T08:21:45Z\", \n  \"hostId\": \"aaa\", \n  \"OS-SRV-USG:terminated_at\": null,
    \n  \"key_name\": \"pg_ci\", \n  \"properties\": \"\", \n  \"OS-EXT-AZ:availability_zone\": \"nova\", \n  \"name\": \"taaa\", \n  \"created\": \"2017-12-08T08:21:31Z\", \n
    \"os-extended-volumes:volumes_attached\": [\n    {\n      \"id\": \"aaa\"\n    }\n  ]\n}"""

d = json.loads(s)
pprint(d)
</code>```

output

```<code>{'OS-DCF:diskConfig': 'MANUAL',
 'OS-EXT-AZ:availability_zone': 'nova',
 'OS-SRV-USG:terminated_at': None,
 'Oaa:power_state': 1,
 'aaa': None,
 'aaa:launched_at': '2017-12-08T08:21:45.000000',
 'aaa:vm_state': 'active',
 'accessIPv4': '',
 'accessIPv6': '',
 'addresses': 'inner-net=192.168.0.173, x.x.x.x',
 'config_drive': '',
 'created': '2017-12-08T08:21:31Z',
 'flavor': 'aaa4 (aaa)',
 'hostId': 'aaa',
 'id': 'aaa',
 'image': 'aaa (aaa)',
 'key_name': 'pg_ci',
 'name': 'taaa',
 'os-extended-volumes:volumes_attached': [{'id': 'aaa'}],
 'progress': 0,
 'project_id': 'aaa',
 'properties': '',
 'security_groups': [{'name': 'default'}],
 'status': 'ACTIVE',
 'updated': '2017-12-08T08:21:45Z',
 'user_id': 'aaa'}
</code>```

And if you want to make it into clean JSON, pass that Python object to json.dump or json.dumps

```<code>print(json.dumps(d, indent=4))
</code>```

output

```<code>{
    "aaa": null,
    "addresses": "inner-net=192.168.0.173, x.x.x.x",
    "image": "aaa (aaa)",
    "aaa:vm_state": "active",
    "aaa:launched_at": "2017-12-08T08:21:45.000000",
    "flavor": "aaa4 (aaa)",
    "id": "aaa",
    "security_groups": [
        {
            "name": "default"
        }
    ],
    "user_id": "aaa",
    "OS-DCF:diskConfig": "MANUAL",
    "accessIPv4": "",
    "accessIPv6": "",
    "progress": 0,
    "Oaa:power_state": 1,
    "project_id": "aaa",
    "config_drive": "",
    "status": "ACTIVE",
    "updated": "2017-12-08T08:21:45Z",
    "hostId": "aaa",
    "OS-SRV-USG:terminated_at": null,
    "key_name": "pg_ci",
    "properties": "",
    "OS-EXT-AZ:availability_zone": "nova",
    "name": "taaa",
    "created": "2017-12-08T08:21:31Z",
    "os-extended-volumes:volumes_attached": [
        {
            "id": "aaa"
        }
    ]
}
</code>```

In the original JSON the keys are sorted alphabetically. To do that in the cleaned-up JSON, just pass sort_keys=True to json.dumps.

Body:
I used json dump and then json load on the same data. The data is unicode so I converted it to string. Using the ast.literla_eval I tried to get the type of the string to dict but I am getting error Malformed String.

output of json load is below

('data', u'{\n  "a": "spawning", \n  "addresses": "", \n  "image": "b", \n  "OS-EXT-STS:vm_state": "building", \n  "c:launched_at": null, \n  "d": "e (fgh)", \n  "user_id": "hhh", \n
    "accessIPv4": "", \n  "accessIPv6": "", \n  "name": "kk", \n  "created": "2017-12-08T07:52:44Z", \n  "z:xyz": []\n}', <type 'unicode'>)

What I tried?

        with open('openstack_list.json', 'w') as e:
            json.dump(check_output(['openstack', 'server', 'show', i, '-f', 'json']), e)
        with open('openstack_list.json', 'r') as a:
            data = json.load(a)
            new_data = data.encode('utf-8')  # output type is unicode
            dict_data = ast.literal_eval(new_data) # output type is string

I want output to be dictionary but I didnt get it. Also, json load gives a unicode data so I believe new_data = data.encode('utf-8')is redundant. But if I use ast.literal_eval without encoding I get Malformed string error. In any case, I am not able to get the data type to be dictionary.

Edits:

Error:

Traceback (most recent call last):
  File "openstack_resource_list.py", line 84, in <module>
    output = get_resources()
  File "openstack_resource_list.py", line 47, in get_resources
    dict_data = ast.literal_eval(new_data)
  File "/usr/lib64/python2.7/ast.py", line 80, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib64/python2.7/ast.py", line 63, in _convert
    in zip(node.keys, node.values))
  File "/usr/lib64/python2.7/ast.py", line 62, in <genexpr>
    return dict((_convert(k), _convert(v)) for k, v
  File "/usr/lib64/python2.7/ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

The data before json dump :

"{\n  \"aaa\": null, \n  \"addresses\": \"inner-net=192.168.0.173, x.x.x.x\", \n  \"image\": \"aaa (aaa)\",
    \n  \"aaa:vm_state\": \"active\", \n  \"aaa:launched_at\": \"2017-12-08T08:21:45.000000\", \n  \"flavor\": \"aaa4 (aaa)\",
    \n  \"id\": \"aaa\", \n  \"security_groups\": [\n    {\n      \"name\": \"default\"\n    }\n  ], \n  \"user_id\": \"aaa\",
    \n  \"OS-DCF:diskConfig\": \"MANUAL\", \n  \"accessIPv4\": \"\", \n  \"accessIPv6\": \"\", \n  \"progress\": 0, \n  \"Oaa:power_state\": 1, \n  \"project_id\": \"aaa\",
    \n  \"config_drive\": \"\", \n  \"status\": \"ACTIVE\", \n  \"updated\": \"2017-12-08T08:21:45Z\", \n  \"hostId\": \"aaa\", \n  \"OS-SRV-USG:terminated_at\": null,
    \n  \"key_name\": \"pg_ci\", \n  \"properties\": \"\", \n  \"OS-EXT-AZ:availability_zone\": \"nova\", \n  \"name\": \"taaa\", \n  \"created\": \"2017-12-08T08:21:31Z\", \n
    \"os-extended-volumes:volumes_attached\": [\n    {\n      \"id\": \"aaa\"\n    }\n  ]\n}"

Body:
That data returned by check_output is already JSON, so you should not JSON-ify it again with json.dump. You can just write it to the file as is, and the file will be a valid JSON file. And you can load it into a Python object with json.loads:

import json
from pprint import pprint

s = """{\n  \"aaa\": null, \n  \"addresses\": \"inner-net=192.168.0.173, x.x.x.x\", \n  \"image\": \"aaa (aaa)\",
    \n  \"aaa:vm_state\": \"active\", \n  \"aaa:launched_at\": \"2017-12-08T08:21:45.000000\", \n  \"flavor\": \"aaa4 (aaa)\",
    \n  \"id\": \"aaa\", \n  \"security_groups\": [\n    {\n      \"name\": \"default\"\n    }\n  ], \n  \"user_id\": \"aaa\",
    \n  \"OS-DCF:diskConfig\": \"MANUAL\", \n  \"accessIPv4\": \"\", \n  \"accessIPv6\": \"\", \n  \"progress\": 0, \n  \"Oaa:power_state\": 1, \n  \"project_id\": \"aaa\",
    \n  \"config_drive\": \"\", \n  \"status\": \"ACTIVE\", \n  \"updated\": \"2017-12-08T08:21:45Z\", \n  \"hostId\": \"aaa\", \n  \"OS-SRV-USG:terminated_at\": null,
    \n  \"key_name\": \"pg_ci\", \n  \"properties\": \"\", \n  \"OS-EXT-AZ:availability_zone\": \"nova\", \n  \"name\": \"taaa\", \n  \"created\": \"2017-12-08T08:21:31Z\", \n
    \"os-extended-volumes:volumes_attached\": [\n    {\n      \"id\": \"aaa\"\n    }\n  ]\n}"""

d = json.loads(s)
pprint(d)

output

{'OS-DCF:diskConfig': 'MANUAL',
 'OS-EXT-AZ:availability_zone': 'nova',
 'OS-SRV-USG:terminated_at': None,
 'Oaa:power_state': 1,
 'aaa': None,
 'aaa:launched_at': '2017-12-08T08:21:45.000000',
 'aaa:vm_state': 'active',
 'accessIPv4': '',
 'accessIPv6': '',
 'addresses': 'inner-net=192.168.0.173, x.x.x.x',
 'config_drive': '',
 'created': '2017-12-08T08:21:31Z',
 'flavor': 'aaa4 (aaa)',
 'hostId': 'aaa',
 'id': 'aaa',
 'image': 'aaa (aaa)',
 'key_name': 'pg_ci',
 'name': 'taaa',
 'os-extended-volumes:volumes_attached': [{'id': 'aaa'}],
 'progress': 0,
 'project_id': 'aaa',
 'properties': '',
 'security_groups': [{'name': 'default'}],
 'status': 'ACTIVE',
 'updated': '2017-12-08T08:21:45Z',
 'user_id': 'aaa'}

And if you want to make it into clean JSON, pass that Python object to json.dump or json.dumps

print(json.dumps(d, indent=4))

output

{
    "aaa": null,
    "addresses": "inner-net=192.168.0.173, x.x.x.x",
    "image": "aaa (aaa)",
    "aaa:vm_state": "active",
    "aaa:launched_at": "2017-12-08T08:21:45.000000",
    "flavor": "aaa4 (aaa)",
    "id": "aaa",
    "security_groups": [
        {
            "name": "default"
        }
    ],
    "user_id": "aaa",
    "OS-DCF:diskConfig": "MANUAL",
    "accessIPv4": "",
    "accessIPv6": "",
    "progress": 0,
    "Oaa:power_state": 1,
    "project_id": "aaa",
    "config_drive": "",
    "status": "ACTIVE",
    "updated": "2017-12-08T08:21:45Z",
    "hostId": "aaa",
    "OS-SRV-USG:terminated_at": null,
    "key_name": "pg_ci",
    "properties": "",
    "OS-EXT-AZ:availability_zone": "nova",
    "name": "taaa",
    "created": "2017-12-08T08:21:31Z",
    "os-extended-volumes:volumes_attached": [
        {
            "id": "aaa"
        }
    ]
}

In the original JSON the keys are sorted alphabetically. To do that in the cleaned-up JSON, just pass sort_keys=True to json.dumps.


答:
If you want to select different ids from the same table using one query then you can do something like following:

Model:

```<code>class My_model extends CI_Model{

  public function fun_name($params){
    $this->db->where_in('id', $params);
    return $this->db->get('table');
  }
}
</code>```

Controller:

```<code>class My_controller extends CI_Controller{
   public function get_data(){
       $this->load->model('my_model');
       $params = array('first', 'sec', 'third');
       $data['values'] = $this->my_model->fun_name($params);

       $this->load->view('index', $data);
   }
}
</code>```

You can also see the Codeigniter documentation:
https://www.codeigniter.com/user_guide/database/query_builder.html#selecting-data

Title: PHP Calling a model method multiple times with having different value for parameter in codeiginter

Body:
If you want to select different ids from the same table using one query then you can do something like following:

Model:

class My_model extends CI_Model{

  public function fun_name($params){
    $this->db->where_in('id', $params);
    return $this->db->get('table');
  }
}

Controller:

class My_controller extends CI_Controller{
   public function get_data(){
       $this->load->model('my_model');
       $params = array('first', 'sec', 'third');
       $data['values'] = $this->my_model->fun_name($params);

       $this->load->view('index', $data);
   }
}

You can also see the Codeigniter documentation:
https://www.codeigniter.com/user_guide/database/query_builder.html#selecting-data


问:
iOS Development: What are some reasons I should to use XAuth to authenticate a twitter user?
I see many people using XAuth in their app to authenticate twitter users and I'm wondering what are some situations that I would want to use XAuth in my own apps.

Thanks for your wisdom!

答: If you have spent a lot of time hand crafting your UI, it can suddenly be very jarring to the user to have to goto a different UI to authenticate. For mobile in particular this can be jarring if the authentication page is not optimised for mobile as used to be the case with Twitter</p>


问:
Swap memory pointers atomically on CUDA
I have two pointers in memory and I want to swap it atomically but atomic operation in CUDA support only int types. There is a way to do the following swap?</p>

```<code>classA* a1 = malloc(...);
classA* a2 = malloc(...);
atomicSwap(a1,a2);
</code>```

答:
When writing device-side code...

While CUDA provides atomics, they can't cover multiple (possibly remote) memory locations at once.

To perform this swap, you will need to "protect" access to both these values with something like mutex, and have whoever wants to write values to them take a hold of the mutex for the duration of the critical section (like in C++'s host-side std::lock_guard). This can be done using CUDA's actual atomic facilities, e.g. compare-and-swap, and is the subject of this question:

Implementing a critical section in CUDA

A caveat to the above is mentioned by @RobertCrovella: If you can make do with, say, a pair of 32-bit offsets rather than a 64-bit pointer, then if you were to store them in a 64-bit aligned struct, you could use compare-and-exchange on the whole struct to implement an atomic swap of the whole struct.

... but is it really device side code?

Your code actually doesn't look like something one would run on the device: Memory allocation is usually (though not always) done from the host side before you launch your kernel and do actual work. If you could make sure these alterations only happen on the host side (think CUDA events and callbacks), and that device-side code will not be interfered with by them - you can just use your plain vanilla C++ facilities for concurrent programming (like lock_guard I mentioned above).

Title: Swap memory pointers atomically on CUDA

Body:
I have two pointers in memory and I want to swap it atomically but atomic operation in CUDA support only int types. There is a way to do the following swap?

classA* a1 = malloc(...);
classA* a2 = malloc(...);
atomicSwap(a1,a2);


问:
Change the one progress bar when its corresponding input filed is changed
Currently for both , when one of the input field's value change, two progress bar will change. Can i only change the one progress bar when its corresponding input filed is changed?

$('input').on('keyup', function(){
    var value = this.value;
   var bar =
    $('.progress-bar')
        .css('width', value+'%')
        .attr('aria-valuenow', value);
}).keyup();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<td>
<div class="form-group">
<input type="text" class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td>

<td></td>
<div class="form-group">
<input type="text" class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td></code>```

答:
You could assign IDs to each and use the corresponding jQuery ID selector. Like this:

$('input').on('keyup', function(){
    var value = this.value;
   var bar =
    $('#progress-bar-1')
        .css('width', value+'%')
        .attr('aria-valuenow', value);
}).keyup();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<td>
<div class="form-group">
<input type="text" class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         id="progress-bar-1"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td>

<td></td>
<div class="form-group">
<input type="text" class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         id="progress-bar-2"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td></code>```

Body:
Currently for both , when one of the input field's value change, two progress bar will change. Can i only change the one progress bar when its corresponding input filed is changed?

$('input').on('keyup', function(){
    var value = this.value;
   var bar =
    $('.progress-bar')
        .css('width', value+'%')
        .attr('aria-valuenow', value);
}).keyup();

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

<input type="text" class="form-control"/>

        60% Complete

<input type="text" class="form-control"/>

        60% Complete

Body:
You could assign IDs to each and use the corresponding jQuery ID selector. Like this:

$('input').on('keyup', function(){
    var value = this.value;
   var bar =
    $('#progress-bar-1')
        .css('width', value+'%')
        .attr('aria-valuenow', value);
}).keyup();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<td>
<div class="form-group">
<input type="text" class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         id="progress-bar-1"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td>

<td></td>
<div class="form-group">
<input type="text" class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         id="progress-bar-2"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td>


问:
How do you create an API server based on data from an existing Rails/Postgres web application?
I have an existing web application that's developed with Ruby on Rails and PostgreSQL. I need to create a mobile application (and possibly a separate web application) using the data from that web application, so I'm looking to create an API server. Is it possible to do this without altering the source code from the original Rails/Postgres web application?

Any ideas on the best way to do this? Or can someone point me in the right direction on what to research?

答:
To connect a new application hosted on Heroku to a PostgreSQL database hosted on Heroku just push your new application to Heroku as normal.

Then, under Settings on your new application dashboard, go into Config Variables and add a new config for DATABASE_URL. Put the value of the url for your existing database.

Your new application will need to be under the same account as your existing application. Heroku doesn't allow you to connect across accounts.

You probably want to take a look at this question for additional details.


问:
How can I express `find` conditions in MongoDB accessing document's values?
For example, let's put the case I want all documents inside a collection which are inside a range, whose maximum value is inside the document itself:

```<code>myDocument {
   qty: Number,
   maxValue: Number,
}

db.collection.find( { field: { $gt: 0, $lt: maxValue } } );
</code>```

Is it possible to do something like that in MongoDB?

答:
Yes you can, using $cmp and aggregation https://docs.mongodb.com/v3.4/reference/operator/aggregation/cmp/</p>

```<code>db.col.aggregate([
    {$project: {compareResult: {$cmp: ['$field','$maxValue']}}},
    {$match: {compareResult: -1, field: {$gt: 0}}}
])
</code>```

Body:
For example, let's put the case I want all documents inside a collection which are inside a range, whose maximum value is inside the document itself:

myDocument {
   qty: Number,
   maxValue: Number,
}

db.collection.find( { field: { $gt: 0, $lt: maxValue } } );

Is it possible to do something like that in MongoDB?

Body:
Yes you can, using $cmp and aggregation https://docs.mongodb.com/v3.4/reference/operator/aggregation/cmp/

db.col.aggregate([
    {$project: {compareResult: {$cmp: ['$field','$maxValue']}}},
    {$match: {compareResult: -1, field: {$gt: 0}}}
])


问:
high-order functions in ML
struggling to understand high-order functions in ml.

```<code>> fn a => fn b => fn c => (a c,b c);
val it = fn: ('a -> 'b) -> ('a -> 'c) -> 'a -> 'b * 'c
</code>```

can someone explain to me how this work. I do not understand how "a" goes to "c" for the second part. I believe the output should be:

```<code>val it = fn:  a -> b -> c -> a * c -> b * c
</code>```

?

答:
a and b are clearly functions, so 'a and 'b are too general types for them.

Also, (a c, b c) is a pair, but you've given it the type 'a * 'c -> 'b * 'c - a function from pairs to pairs.

Let's rename things in the function in order to keep the names of the parameters  more easily distinguishable from their types:

```<code>> fn x => fn y => fn z => (x z, y z);
val it = fn: ('a -> 'b) -> ('a -> 'c) -> 'a -> 'b * 'c
</code>```

When you're determining a function's type, it's usually a good idea to start with the result and work your way backwards towards the parameters.

It's pretty obvious that this result, (x z, y z), is a pair.

Let's say its type is P * Q - that is, x z is a P, and y z is a Q.

We know (from x z and y z) that both x and y are functions, and if the type of z is R, we have

```<code>x : R -> P
y : R -> Q
</code>```

Filling this in we have the type

```<code>(R -> P) -> (R -> Q) -> R -> P * Q
   x           y        z    result
</code>```

which we can rename as

```<code>('a -> 'b) -> ('a -> 'c) -> 'a -> 'b * 'c
</code>```

Title: high-order functions in ML

Body:
struggling to understand high-order functions in ml.

> fn a => fn b => fn c => (a c,b c);
val it = fn: ('a -> 'b) -> ('a -> 'c) -> 'a -> 'b * 'c

can someone explain to me how this work. I do not understand how "a" goes to "c" for the second part. I believe the output should be:

val it = fn:  a -> b -> c -> a * c -> b * c

?

Body:
a and b are clearly functions, so 'a and 'b are too general types for them.

Also, (a c, b c) is a pair, but you've given it the type 'a * 'c -> 'b * 'c - a function from pairs to pairs.

Let's rename things in the function in order to keep the names of the parameters  more easily distinguishable from their types:

> fn x => fn y => fn z => (x z, y z);
val it = fn: ('a -> 'b) -> ('a -> 'c) -> 'a -> 'b * 'c

When you're determining a function's type, it's usually a good idea to start with the result and work your way backwards towards the parameters.

It's pretty obvious that this result, (x z, y z), is a pair.

Let's say its type is P * Q - that is, x z is a P, and y z is a Q.

We know (from x z and y z) that both x and y are functions, and if the type of z is R, we have

x : R -> P
y : R -> Q

Filling this in we have the type

(R -> P) -> (R -> Q) -> R -> P * Q
   x           y        z    result

which we can rename as

('a -> 'b) -> ('a -> 'c) -> 'a -> 'b * 'c


问:
InternalError: current transaction is aborted, commands ignored until end of transaction block ,on UNIQUE constraint

I tried to get executed with my except: statement... while attempt to oppose the functionality of UNIQUE constraint..But ended with exceptional error..
The Postgresql database table already contains the row that I have used in

db.insert("The News","AparnaKumar",1995,234569654)

but it works well on inserting unrepeated rows..

```<code>import psycopg2
class database:

    def __init__(self):

        self.con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
        self.cur=self.con.cursor()
        self.cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL UNIQUE,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL UNIQUE)")
        self.con.commit()

    def insert(self,title,author,year,isbn):
      try:
        self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
        self.con.commit()
      except:
          print("already exists..")

    def view(self):
        self.cur.execute("SELECT * FROM books")
        rows=self.cur.fetchall()
        print(rows)

    def search(self,title=None,author=None,year=None,isbn=None):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.fetchall()
        print(row)

db=database()
db.insert("The News","AparnaKumar",1995,234569654)
db.view()
db.search(year=1995)
</code>```

答:
If you want to keep an transaction open, you should use a SAVEPOINT and ROLLBACK to that SAVEPOINT when the exception occurs. But since you use a catchall exception (too broad), this will also happen on other errors. So it gets a bit out of control.

Perhaps a very simple solution is to check using a SELECT if the record you're about to insert already exists.

Body:
I tried to get executed with my except: statement... while attempt to oppose the functionality of UNIQUE constraint..But ended with exceptional error..
The Postgresql database table already contains the row that I have used in

db.insert("The News","AparnaKumar",1995,234569654)

but it works well on inserting unrepeated rows..

import psycopg2
class database:

    def __init__(self):

        self.con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
        self.cur=self.con.cursor()
        self.cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL UNIQUE,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL UNIQUE)")
        self.con.commit()

    def insert(self,title,author,year,isbn):
      try:
        self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
        self.con.commit()
      except:
          print("already exists..")

    def view(self):
        self.cur.execute("SELECT * FROM books")
        rows=self.cur.fetchall()
        print(rows)

    def search(self,title=None,author=None,year=None,isbn=None):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.fetchall()
        print(row)

db=database()
db.insert("The News","AparnaKumar",1995,234569654)
db.view()
db.search(year=1995)


问:
running DOS Debug script
the following script works fine if I type it line-by-line in debug. When I copy it to a file called script.txt, it hangs up after "enter 3 numbers". I run it like so:

D:>debug < script.txt

the file is:

```<code>a
mov cx, 3
jmp 0119
db 0d,0a,"enter 3 numbers",0d,0a,"$"
mov dx, 0105
mov ah, 09
int 21h
mov ah, 01
int 21h
and al, 0f
add bl, al
mov dl, 0a
mov ah, 02
int 21h
loop 0120
jmp 013a
db 0d,0a,"sum: ","$"
mov dx,0132
mov ah, 09
int 21h
or bl, 30
mov dl, bl
mov ah, 02
int 21h
mov ax, 4c00
int 21h

g
</code>```

what am I doing wrong? Any hints or links appreciated.
keith

答:
```<code>enter 3 numbers
</code>```

9
 7
  9

sum: 9

Seam your program not working ... maybe is need to use stack , not regs.

Title: running DOS Debug script

Body:
the following script works fine if I type it line-by-line in debug. When I copy it to a file called script.txt, it hangs up after "enter 3 numbers". I run it like so:

D:>debug < script.txt

the file is:

a
mov cx, 3
jmp 0119
db 0d,0a,"enter 3 numbers",0d,0a,"$"
mov dx, 0105
mov ah, 09
int 21h
mov ah, 01
int 21h
and al, 0f
add bl, al
mov dl, 0a
mov ah, 02
int 21h
loop 0120
jmp 013a
db 0d,0a,"sum: ","$"
mov dx,0132
mov ah, 09
int 21h
or bl, 30
mov dl, bl
mov ah, 02
int 21h
mov ax, 4c00
int 21h

g

what am I doing wrong? Any hints or links appreciated.
keith

Body:
enter 3 numbers

9
 7
  9

sum: 9

Seam your program not working ... maybe is need to use stack , not regs.


问:
Logcat won't display Log.d messages
I'm developing an Android application and I would like to have some way to print debug statements as my code runs. Fortunately for me, Logcat was able to print out Log.d messages when I run my application on an Android 2.3.3 (API 10) emulator.

However, when I tested the same exact application on a physical device (Samsung Galaxy S4 Android 4.2.2) I was unable to see anything other than dalvikvm and AndroidRuntime messages.

```<code>com.android.internal.os.RuntimeInit <<<<<<
07-28 04:49:24.165: DEBUG/AndroidRuntime(6378): CheckJNI is OFF
07-28 04:49:24.165: DEBUG/AndroidRuntime(6378): setted country_code = USA
07-28 04:49:24.165: DEBUG/AndroidRuntime(6378): setted countryiso_code = US
07-28 04:49:24.175: DEBUG/AndroidRuntime(6378): setted sales_code = VZW
07-28 04:49:24.175: DEBUG/AndroidRuntime(6378): readGMSProperty: start
07-28 04:49:24.175: DEBUG/AndroidRuntime(6378): readGMSProperty: already setted!!
07-28 04:49:24.175: DEBUG/AndroidRuntime(6378): readGMSProperty: end
07-28 04:49:24.175: DEBUG/AndroidRuntime(6378): addProductProperty: start
07-28 04:49:24.185: DEBUG/dalvikvm(6378): Trying to load lib libjavacore.so 0x0
07-28 04:49:24.185: DEBUG/dalvikvm(6378): Added shared lib libjavacore.so 0x0
07-28 04:49:24.195: DEBUG/dalvikvm(6378): Trying to load lib libnativehelper.so 0x0
07-28 04:49:24.195: DEBUG/dalvikvm(6378): Added shared lib libnativehelper.so 0x0
07-28 04:49:24.385: DEBUG/AndroidRuntime(6378): Calling main entry com.android.commands.pm.Pm
07-28 04:49:26.978: DEBUG/AndroidRuntime(6378): Shutting down VM
07-28 04:49:26.988: DEBUG/dalvikvm(6378): GC_CONCURRENT freed 157K, 21% free 627K/788K, paused 1ms+0ms, total 4ms
07-28 04:49:26.988: DEBUG/jdwp(6378): Got wake-up signal, bailing out of select
07-28 04:49:26.988: DEBUG/dalvikvm(6378): Debugger has detached; object registry had 1 entries
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): CheckJNI is OFF
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): setted country_code = USA
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): setted countryiso_code = US
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): setted sales_code = VZW
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): readGMSProperty: start
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): readGMSProperty: already setted!!
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): readGMSProperty: end
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): addProductProperty: start
07-28 04:49:27.468: DEBUG/dalvikvm(6420): Trying to load lib libjavacore.so 0x0
07-28 04:49:27.478: DEBUG/dalvikvm(6420): Added shared lib libjavacore.so 0x0
07-28 04:49:27.478: DEBUG/dalvikvm(6420): Trying to load lib libnativehelper.so 0x0
07-28 04:49:27.478: DEBUG/dalvikvm(6420): Added shared lib libnativehelper.so 0x0
07-28 04:49:27.649: DEBUG/AndroidRuntime(6420): Calling main entry com.android.commands.am.Am
07-28 04:49:27.659: DEBUG/dalvikvm(6420): Note: class Landroid/app/ActivityManagerNative; has 169 unimplemented (abstract) methods
07-28 04:49:27.719: DEBUG/AndroidRuntime(6420): Shutting down VM
07-28 04:49:27.729: DEBUG/dalvikvm(6420): GC_CONCURRENT freed 157K, 20% free 666K/828K, paused 0ms+1ms, total 3ms
07-28 04:49:27.729: DEBUG/jdwp(6420): Got wake-up signal, bailing out of select
07-28 04:49:27.729: DEBUG/dalvikvm(6420): Debugger has detached; object registry had 1 entries
</code>```

I'm not exactly sure what is going on since Logcat is correctly targeting my physical device, it shows up on adb devices, and USB Debugging is on.

I've tried using Log.e but that had no effect on the output.

I even set android:debuggable="true" in AndroidManifest.xml.

Is there something I'm missing here? Why won't Logcat display my debug messages when running my app on my physical device?

EDIT: I tried the same app on a Android 4.2.2 emulator and Logcat works as expected with the emulator, but there's still the problem with Logcat through the USB device. Instead of the verbosity of a normal Logcat printout, the block I posted is the only thing I see on the Verbose log level.

答:
Today, I faced the same issue. Nothing worked for me as mentioned solutions. But what worked for me is in Android Studio Right side at the bottom as mentioned in the image. Select the option as mentioned in the image. After that everything was working as expected. Now posting my solution it may help others.

Hope that helps others

Title: Logcat won't display Log.d messages

Body:
I'm developing an Android application and I would like to have some way to print debug statements as my code runs. Fortunately for me, Logcat was able to print out Log.d messages when I run my application on an Android 2.3.3 (API 10) emulator.

However, when I tested the same exact application on a physical device (Samsung Galaxy S4 Android 4.2.2) I was unable to see anything other than dalvikvm and AndroidRuntime messages.

com.android.internal.os.RuntimeInit <<<<<<
07-28 04:49:24.165: DEBUG/AndroidRuntime(6378): CheckJNI is OFF
07-28 04:49:24.165: DEBUG/AndroidRuntime(6378): setted country_code = USA
07-28 04:49:24.165: DEBUG/AndroidRuntime(6378): setted countryiso_code = US
07-28 04:49:24.175: DEBUG/AndroidRuntime(6378): setted sales_code = VZW
07-28 04:49:24.175: DEBUG/AndroidRuntime(6378): readGMSProperty: start
07-28 04:49:24.175: DEBUG/AndroidRuntime(6378): readGMSProperty: already setted!!
07-28 04:49:24.175: DEBUG/AndroidRuntime(6378): readGMSProperty: end
07-28 04:49:24.175: DEBUG/AndroidRuntime(6378): addProductProperty: start
07-28 04:49:24.185: DEBUG/dalvikvm(6378): Trying to load lib libjavacore.so 0x0
07-28 04:49:24.185: DEBUG/dalvikvm(6378): Added shared lib libjavacore.so 0x0
07-28 04:49:24.195: DEBUG/dalvikvm(6378): Trying to load lib libnativehelper.so 0x0
07-28 04:49:24.195: DEBUG/dalvikvm(6378): Added shared lib libnativehelper.so 0x0
07-28 04:49:24.385: DEBUG/AndroidRuntime(6378): Calling main entry com.android.commands.pm.Pm
07-28 04:49:26.978: DEBUG/AndroidRuntime(6378): Shutting down VM
07-28 04:49:26.988: DEBUG/dalvikvm(6378): GC_CONCURRENT freed 157K, 21% free 627K/788K, paused 1ms+0ms, total 4ms
07-28 04:49:26.988: DEBUG/jdwp(6378): Got wake-up signal, bailing out of select
07-28 04:49:26.988: DEBUG/dalvikvm(6378): Debugger has detached; object registry had 1 entries
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): CheckJNI is OFF
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): setted country_code = USA
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): setted countryiso_code = US
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): setted sales_code = VZW
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): readGMSProperty: start
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): readGMSProperty: already setted!!
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): readGMSProperty: end
07-28 04:49:27.458: DEBUG/AndroidRuntime(6420): addProductProperty: start
07-28 04:49:27.468: DEBUG/dalvikvm(6420): Trying to load lib libjavacore.so 0x0
07-28 04:49:27.478: DEBUG/dalvikvm(6420): Added shared lib libjavacore.so 0x0
07-28 04:49:27.478: DEBUG/dalvikvm(6420): Trying to load lib libnativehelper.so 0x0
07-28 04:49:27.478: DEBUG/dalvikvm(6420): Added shared lib libnativehelper.so 0x0
07-28 04:49:27.649: DEBUG/AndroidRuntime(6420): Calling main entry com.android.commands.am.Am
07-28 04:49:27.659: DEBUG/dalvikvm(6420): Note: class Landroid/app/ActivityManagerNative; has 169 unimplemented (abstract) methods
07-28 04:49:27.719: DEBUG/AndroidRuntime(6420): Shutting down VM
07-28 04:49:27.729: DEBUG/dalvikvm(6420): GC_CONCURRENT freed 157K, 20% free 666K/828K, paused 0ms+1ms, total 3ms
07-28 04:49:27.729: DEBUG/jdwp(6420): Got wake-up signal, bailing out of select
07-28 04:49:27.729: DEBUG/dalvikvm(6420): Debugger has detached; object registry had 1 entries

I'm not exactly sure what is going on since Logcat is correctly targeting my physical device, it shows up on adb devices, and USB Debugging is on.

I've tried using Log.e but that had no effect on the output.

I even set android:debuggable="true" in AndroidManifest.xml.

Is there something I'm missing here? Why won't Logcat display my debug messages when running my app on my physical device?

EDIT: I tried the same app on a Android 4.2.2 emulator and Logcat works as expected with the emulator, but there's still the problem with Logcat through the USB device. Instead of the verbosity of a normal Logcat printout, the block I posted is the only thing I see on the Verbose log level.


问:
apply_gradients() function in tensorflow does not update the weight and bias variables
I'm using compute_gradients() and apply_gradients() functions of Tensorflow for back-prop. By printing the gradient values I do see that gradients are getting calculated, but I do not see any change in weights after call to apply_gradients() function. I also do not see that value of global_step variable changing.

Am I doing something wrong?

I'm running the below code in a session and I do see gradient values returned from compute_gradients() function getting printed. But when I pass the list of (gradient, weights variables) tuple to apply_gradients() function I do not see the weights value changing and global_step value does not get updated.

global_step = tf.Variable(0, trainable=False, dtype=tf.int32)
images = tf.placeholder(dtype=tf.float32, shape=[batch_size, None, None, 3])
out_locs = tf.placeholder(dtype=tf.float32, shape=[None, 2])
org_gt_coords = tf.placeholder(dtype=tf.float32, shape=[batch_size, 2])

res_aux = inference(images,out_locs,org_gt_coords)

ret_dict = train(res_aux, global_step)

init = tf.global_variables_initializer()
with tf.Session() as sess:
  writer = tf.summary.FileWriter('./graphs', sess.graph)
  sess.run(init)

  for epoch in xrange(max_steps):
    start_time = time.time()
    anno_file_batch_rows = getImageMetaRecords()
    print('epoch: ', epoch)

    for batch in xrange(len(anno_file_batch_rows)/batch_size):
      distorted_images, meta = cdhd_input.distorted_inputs(stats_dict, batch_size, \
              anno_file_batch_rows[batch * batch_size : (batch * batch_size) + batch_size])

      out_dict = sess.run(ret_dict, feed_dict=
                            {images: distorted_images,
                            out_locs: meta['out_locs'],
                            org_gt_coords: meta['org_gt_coords']})

def inference(images,out_locs,org_gt_coords):
  # conv1
  with tf.variable_scope('conv1') as scope:
    kernel = _variable_with_weight_decay('weights',
                                         shape=[3, 3, 3, 32],
                                         stddev=1,  #check if this is right
                                         wd=0.0)
    kernel = tf.multiply(kernel, 0.2722)        #line 321-325 in warpTrainCNNCDHDCentroidChainGridPredSharedRevFastExp3
    conv = tf.nn.conv2d(images, kernel, [1, 2, 2, 1], padding='VALID')
    biases = _variable_on_cpu('biases', [32], tf.constant_initializer(1.0))
    pre_activation = tf.nn.bias_add(conv, biases)
    conv1 = tf.nn.relu(pre_activation, name=scope.name)

  # conv2
  with tf.variable_scope('conv2') as scope:
    kernel = _variable_with_weight_decay('weights',
                                         shape=[3, 3, 32, 64],
                                         stddev=1,
                                         wd=0.0)
    kernel = tf.multiply(kernel, 0.0833)        #line 321-325 in warpTrainCNNCDHDCentroidChainGridPredSharedRevFastExp3
    conv = tf.nn.conv2d(conv1, kernel, [1, 2, 2, 1], padding='VALID')
    biases = _variable_on_cpu('biases', [64], tf.constant_initializer(1.0))
    pre_activation = tf.nn.bias_add(conv, biases)
    conv2 = tf.nn.relu(pre_activation, name=scope.name)

    ...
    ...
    more layers
    ...
    ...

    return res_aux

def train(res_aux, global_step):
    ...
    ...
    code here to process res_aux and calculate loss
    ...
    ...

    opt = tf.train.GradientDescentOptimizer(learning_rate=0.01)
    grads_and_vars = opt.compute_gradients(loss, tf.get_collection('weights'))
    #printing shows real valued gradient and weight values
    apply_gradients(grads_and_vars, global_step=global_step)
    #printing same weight values shows no change in weight values. Gradients are not applied to the weights
```

答:
This line only defines the op that applies the gradients:

a_optimizer_col_2.apply_gradients(grad_var_2, global_step=global_step)
```

<p>In order to apply it, you should run this op in a session, like this:</p>

<pre class="lang-py prettyprint-override"><code>...
train_step = a_optimizer_col_2.apply_gradients(grad_var_2, global_step=global_step)
...
with tf.Session() as sess:
  sess.run(train_step, feed_dict={...})
</code>```

Body:
This line only defines the op that applies the gradients:

a_optimizer_col_2.apply_gradients(grad_var_2, global_step=global_step)

In order to apply it, you should run this op in a session, like this:

...
train_step = a_optimizer_col_2.apply_gradients(grad_var_2, global_step=global_step)
...
with tf.Session() as sess:
  sess.run(train_step, feed_dict={...})


问:
Xamarin build ERROR : error APT0000: In <declare-styleable> ..., unable to find attribute
I received a project from another developer. I setup my machine. VS-2017 with the required components was already configured.

Android SDK-Manager has the corresponding version installed. Project is configured to compile with Android 7.1 (Nougat).

Starting the build I get one error

```<code>1>ERROR : error APT0000: In <declare-styleable> AppBarLayout, unable to find attribute android:keyboardNavigationCluster
</code>```

It is unclear to me, were I need to set this information, or were this information is needed.

I rececked ERROR: In  MenuView, unable to find attribute android:preserveIconSpacing
 and Error:In  SherlockSpinner, unable to find attribute android:popupPromptView. Both articles don't help.

I rechecked the SDK-Tools, I deleted the folder C:\Users\<user>\AppData\Local\Xamarin.

As far as I understand the message there is an attribute missing, that needs to be set.

In a project file Resource.designer.cs I found

```<code>public const int AppBarLayout_android_keyboardNavigationCluster = 2;
</code>```

The name seams to match exactly.

Can someone explain me this error?

Can someone explain how I get rid of it and how to fix similar problems in future?

答:
In my case I'd moved from Enterprise to Professional and found that there was a mismatch in the Xamarin options (Tools -> Options -> Xamarin) and the android SDK location needed to be changed to "C:\Users\YourMum\AppData\Local\Android\android-sdk".

Can't remember exactly what it was originally but think it was in Programs.

Body:
I received a project from another developer. I setup my machine. VS-2017 with the required components was already configured.

Android SDK-Manager has the corresponding version installed. Project is configured to compile with Android 7.1 (Nougat).

Starting the build I get one error

1>ERROR : error APT0000: In <declare-styleable> AppBarLayout, unable to find attribute android:keyboardNavigationCluster

It is unclear to me, were I need to set this information, or were this information is needed.

I rececked ERROR: In  MenuView, unable to find attribute android:preserveIconSpacing
 and Error:In  SherlockSpinner, unable to find attribute android:popupPromptView. Both articles don't help.

I rechecked the SDK-Tools, I deleted the folder C:\Users\<user>\AppData\Local\Xamarin.

As far as I understand the message there is an attribute missing, that needs to be set.

In a project file Resource.designer.cs I found

public const int AppBarLayout_android_keyboardNavigationCluster = 2;

The name seams to match exactly.

Can someone explain me this error?

Can someone explain how I get rid of it and how to fix similar problems in future?


问:
Formatting location of buttons within JOptionPane
Im trying to format the location of buttons within a JOptionPane. Right now they are side by side, but I would like to put them on top of each other.

I tried making a global configuration but it did not work. How would I achieve this?

```<code>Object[] options = { "Restart Game at Level 1",
                    "Restart and Increase Difficulty (Speed)",
                    "Change Game Map", "Exit Game" };
            int n = JOptionPane.showOptionDialog(gamePanel,
                    "GAME OVER - YouHit a Wall and Died! ",
                    "Game Over!", JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[3]);
</code>```

答:
There is a way, but I wouldn't recommend it since it makes assumptions of internal implementation of JOptionPane. There are 2 things to do:

Create a JOptionPane using directly a constructor to get a reference to it

Change the layout of inner component containing the options (which
is on  position 1)

```<code>JOptionPane op = new JOptionPane("GAME OVER - YouHit a Wall and Died! ");
op.setOptions(options );
((Container)op.getComponent(1)).setLayout(new GridLayout(4, 1));
JDialog dlg = op.createDialog("Game Over!");
dlg.setVisible(true);
</code>```

Body:
Im trying to format the location of buttons within a JOptionPane. Right now they are side by side, but I would like to put them on top of each other.

I tried making a global configuration but it did not work. How would I achieve this?

Object[] options = { "Restart Game at Level 1",
                    "Restart and Increase Difficulty (Speed)",
                    "Change Game Map", "Exit Game" };
            int n = JOptionPane.showOptionDialog(gamePanel,
                    "GAME OVER - YouHit a Wall and Died! ",
                    "Game Over!", JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[3]);

Body:
There is a way, but I wouldn't recommend it since it makes assumptions of internal implementation of JOptionPane. There are 2 things to do:

Create a JOptionPane using directly a constructor to get a reference to it

Change the layout of inner component containing the options (which
is on  position 1)

JOptionPane op = new JOptionPane("GAME OVER - YouHit a Wall and Died! ");
op.setOptions(options );
((Container)op.getComponent(1)).setLayout(new GridLayout(4, 1));
JDialog dlg = op.createDialog("Game Over!");
dlg.setVisible(true);