问:
Sending array along with javascript call to the Driver class in java -rest
I am trying to add an array of four items to a call of a driver class. My JavaScript code works like this:

```<code>request.open("GET","rest/ds/acceptInput?UserInput="+document.getElementById('text').value, async=true);
request.send()
</code>```

I use this to send the user input to the driver, AND THIS WORKS with an annotated driver (seen below).

```<code>@Test
@Path("acceptInput")
@GET
@Consumes("text/plain")
@Produces(MediaType.APPLICATION_JSON)
public String acceptInput(@QueryParam("UserInput") String input{
</code>```

NOW I would like to be able to send an array (attained by user checkboxes in JavaScript) along with my call to the driver. I've tried a few ways, but what makes sense to me is this:

JavaScript code like this:

```<code>request.open("GET","rest/ds/acceptInput?UserInput="+document.getElementById('text').value + checked[0],checked[1],checked[2],checked[3], async=true);
request.send()
</code>```

And the driver accepting it like this:

```<code>    @Test
    @Path("acceptInput")
    @GET
    @Consumes("text/plain")
    @Produces(MediaType.APPLICATION_JSON)
    public String acceptInput(@QueryParam("UserInput") String input, @QueryParam("po") boolean Po, @QueryParam("cl") boolean Cl, @QueryParam("ac") boolean Ac, @QueryParam("qu") boolean Qu) {
</code>```

But now I end up not returning ANY results. Any ideas why this would happen?

答:
Change your JavaScript code to this:

```<code>request.open("GET","rest/ds/acceptInput?UserInput="+document.getElementById('text').value + "&po="+ checked[0]+"&cl="+checked[1]+"&ac="+checked[2]+"&qu="+checked[3], true);
</code>```

You weren't giving any parameter names to the checkbox values in your GET request.

Also, instead of async = true parameter shouldn't it just be true?

Body:
I am trying to add an array of four items to a call of a driver class. My JavaScript code works like this:

request.open("GET","rest/ds/acceptInput?UserInput="+document.getElementById('text').value, async=true);
request.send()

I use this to send the user input to the driver, AND THIS WORKS with an annotated driver (seen below).

@Test
@Path("acceptInput")
@GET
@Consumes("text/plain")
@Produces(MediaType.APPLICATION_JSON)
public String acceptInput(@QueryParam("UserInput") String input{

NOW I would like to be able to send an array (attained by user checkboxes in JavaScript) along with my call to the driver. I've tried a few ways, but what makes sense to me is this:

JavaScript code like this:

request.open("GET","rest/ds/acceptInput?UserInput="+document.getElementById('text').value + checked[0],checked[1],checked[2],checked[3], async=true);
request.send()

And the driver accepting it like this:

    @Test
    @Path("acceptInput")
    @GET
    @Consumes("text/plain")
    @Produces(MediaType.APPLICATION_JSON)
    public String acceptInput(@QueryParam("UserInput") String input, @QueryParam("po") boolean Po, @QueryParam("cl") boolean Cl, @QueryParam("ac") boolean Ac, @QueryParam("qu") boolean Qu) {

But now I end up not returning ANY results. Any ideas why this would happen?

Body:
Change your JavaScript code to this:

request.open("GET","rest/ds/acceptInput?UserInput="+document.getElementById('text').value + "&po="+ checked[0]+"&cl="+checked[1]+"&ac="+checked[2]+"&qu="+checked[3], true);

You weren't giving any parameter names to the checkbox values in your GET request.

Also, instead of async = true parameter shouldn't it just be true?


来源: stackexchange

问:
python phanthomjs is not working with nohup
I'm running selenium  using phanthomjs, the script is running perfectly if when I trigger it as:

```<code>python my_script.py
</code>```

But when I try to using nohup:

```<code>nohup python my_script.py &
</code>```

I got the following error:

```<code>selenium.common.exceptions.WebDriverException: Message: Service phantomjs unexpectedly exited. Status code was: 8
</code>```

答:
It's probably too late but I just met similar error just with another code and I've found a solution. So, when you run nohup your program's output is redirected to nohup.out, and the file for me was like this:

```<code>Traceback (most recent call last):
me/fanar/.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 109, in assert_process_still_running

  File "main.py", line 51, in <module>
    Work()
  File "main.py", line 41, in Work
    TakeImage() # start o 16
  File "main.py", line 9, in TakeImage
    driver = webdriver.PhantomJS()
  File "/home/fanar/.local/lib/python2.7/site-packages/selenium/webdriver/phantomjs/webdriver.py", line 52, in __init__
    self.service.start()
  File "/home/fanar/.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 96, in start
    self.assert_process_still_running()
  File "/home/fanar/.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 109, in assert_process_still_running
    % (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service phantomjs unexpectedly exited. Status code was: 1
</code>```

The workaround was to go to the

```<code>.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py
</code>```

and comment out line

```<code>self.assert_process_still_running()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm running selenium  using phanthomjs, the script is running perfectly if when I trigger it as:

python my_script.py

But when I try to using nohup:

nohup python my_script.py &

I got the following error:

selenium.common.exceptions.WebDriverException: Message: Service phantomjs unexpectedly exited. Status code was: 8

Body:
It's probably too late but I just met similar error just with another code and I've found a solution. So, when you run nohup your program's output is redirected to nohup.out, and the file for me was like this:

Traceback (most recent call last):
me/fanar/.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 109, in assert_process_still_running

  File "main.py", line 51, in <module>
    Work()
  File "main.py", line 41, in Work
    TakeImage() # start o 16
  File "main.py", line 9, in TakeImage
    driver = webdriver.PhantomJS()
  File "/home/fanar/.local/lib/python2.7/site-packages/selenium/webdriver/phantomjs/webdriver.py", line 52, in __init__
    self.service.start()
  File "/home/fanar/.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 96, in start
    self.assert_process_still_running()
  File "/home/fanar/.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 109, in assert_process_still_running
    % (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service phantomjs unexpectedly exited. Status code was: 1

The workaround was to go to the

.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py

and comment out line

self.assert_process_still_running()


问:
With onclick show hidden div in other html file
I use Javascript and 'onclick' to show hidden div's in a large database, when I use onclick it shows as a popup. It works fine in the same html-file, but I cannot get an id openend in another html file. How can I do this?

I use this javascript code (sh = show):

```<code> var divState = {}; function sh(id) {
if (document.getElementById) {
    var divid = document.getElementById(id);
divState[id] = (divState[id]) ? false : true;
 //close others
 for (var div in divState){
    if (divState[div] && div != id){
        document.getElementById(div).style.visibility = 'hidden';
        divState[div] = false;
    }
}
divid.style.visibility = (divid.style.visibility == 'visible' ? 'hidden' : 'visible'); } }
</code>```

And I call the item with this code (id=1):

```<code> <a class=w onclick="sh('1');">asdfasdf asdasdfds</a>
</code>```

I tried onclick="window.location.href='../A/index.html?id=0174' "> but it does not "open" or rather show id=0174, only opens index.html in the A-directory. How can I make id 0174 in A/index.html visible when clicked on some item in E/index.html?

Many thanks!

答:
You can use the :target CSS pseudo-class to show or hide elements with the id specified as the hash in the url.

For example: Link to div #0174 on other page

.show-when-target {
  visibility: hidden;
}

.show-when-target:target {
  visibility: visible;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="1" class="show-when-target">
  Hello from div 1!
</div>

<div id="2" class="show-when-target">
  Hello from div 2!
</div>

<div id="3" class="show-when-target">
  Hello from div 3!
</div>

Show Div 1
Show Div 2
Show Div 3</code>```

Body:
I use Javascript and 'onclick' to show hidden div's in a large database, when I use onclick it shows as a popup. It works fine in the same html-file, but I cannot get an id openend in another html file. How can I do this?

I use this javascript code (sh = show):

 var divState = {}; function sh(id) {
if (document.getElementById) {
    var divid = document.getElementById(id);
divState[id] = (divState[id]) ? false : true;
 //close others
 for (var div in divState){
    if (divState[div] && div != id){
        document.getElementById(div).style.visibility = 'hidden';
        divState[div] = false;
    }
}
divid.style.visibility = (divid.style.visibility == 'visible' ? 'hidden' : 'visible'); } }

And I call the item with this code (id=1):

 asdfasdf asdasdfds

I tried  but it does not "open" or rather show id=0174, only opens index.html in the A-directory. How can I make id 0174 in A/index.html visible when clicked on some item in E/index.html?

Many thanks!

Body:
You can use the :target CSS pseudo-class to show or hide elements with the id specified as the hash in the url.

For example: <a href="../A/index.html#0174">Link to div #0174 on other page</a>

.show-when-target {
  visibility: hidden;
}

.show-when-target:target {
  visibility: visible;
}

<div id="1" class="show-when-target">
  Hello from div 1!
</div>

<div id="2" class="show-when-target">
  Hello from div 2!
</div>

<div id="3" class="show-when-target">
  Hello from div 3!
</div>

<a href="#1">Show Div 1</a>
<a href="#2">Show Div 2</a>
<a href="#3">Show Div 3</a>


问:
Add class to empty elements only
The problem is that I have multiple instances of .Prodotto but I would like to add the class only to the empty .Prodotto. How can I specify only the empty '.Prodotto' ? My jQuery attempt is this one:

```<code>if ($('.Prodotto').is(':empty')){
  $('.Prodotto').addClass('empty-content');
}
</code>```

答:
Your question is too vague, if you give a bit more details, but I assume that you have a click event somewhere?
If that is the case, assuming you have something like:

```<code>    $("body").on("click", ".Prodotto", function(){
    if($(this).is(":empty")){
            $(this).addClass("empty-content");
    }
    });
</code>```

Hope this helps!

Title: Add class to empty elements only

Body:
The problem is that I have multiple instances of .Prodotto but I would like to add the class only to the empty .Prodotto. How can I specify only the empty '.Prodotto' ? My jQuery attempt is this one:

if ($('.Prodotto').is(':empty')){
  $('.Prodotto').addClass('empty-content');
}

Body:
Your question is too vague, if you give a bit more details, but I assume that you have a click event somewhere?
If that is the case, assuming you have something like:

    $("body").on("click", ".Prodotto", function(){
    if($(this).is(":empty")){
            $(this).addClass("empty-content");
    }
    });

Hope this helps!


问:
Selenium can't find element by id
I'm trying to create a simple test with Selenium. I used this code before and it worked fine. Somehow it stopped working when I changed to a new machine. I tried adding some code to wait until the element is visible, but it didn't work out.

I just try to find an element by its id, move to this element and click it. Somehow the code doesn't find the element at all.

Here is my code:

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SeleniumBasicTest {

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

    DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
    caps.setCapability("ignoreZoomSetting", true);
    WebDriver driver = new InternetExplorerDriver(caps);

    driver.get("http://www.store.demoqa.com");

    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("menu-item-33")));

    System.out.println("Successfully opened the website www.Store.Demoqa.com");

    WebElement producCategorytMenu = driver.findElement(By.id("menu-item-33"));

    Actions builder = new Actions(driver);
    builder.moveToElement(producCategorytMenu).perform();
    builder.click(producCategorytMenu).perform();

    Thread.sleep(5000);

    System.out.println("quiting test...");
    driver.quit();
  }

}
</code>```

This is the exception I'm receiving:

```<code>Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with id == menu-item-33 (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 315 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.3.0', revision: 'b526bd5b41', time: '2017-03-07 19:26:04 +0000'
System info: host: 'CMTCLX62137', ip: '53.19.245.167', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_31'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{se:ieOptions={browserAttachTimeout=0, ie.enableFullPageScreenshot=true, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.forceShellWindowsApi=false, ignoreZoomSetting=true, ie.fileUploadDialogTimeout=3000, ie.useLegacyFileUploadDialogHandling=false, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, initialBrowserUrl=http://localhost:37146/, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true}, browserName=internet explorer, pageLoadStrategy=normal, javascriptEnabled=true, version=11, platform=WINDOWS, unexpectedAlertBehaviour=dismiss}]
Session ID: 1e1740a9-00a2-4b92-814a-1979cfcef8e0
*** Element info: {Using=id, value=menu-item-33}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:371)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:420)
    at org.openqa.selenium.By$ById.findElement(By.java:218)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
    at com.mytest.SeleniumBasicTest.main(SeleniumBasicTest.java:22)
</code>```

And here is the part of the HTML that has the menu:

```<code>    <nav class="group" id="main-nav">
            <ul id="menu-main-menu" class="menu"><li id="menu-item-15" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-11 current_page_item menu-item-15"><span class="before"> </span><a href="http://store.demoqa.com/"><span></span>Home</a></li>
<li id="menu-item-33" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-has-children menu-item-33 has_children"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/"><span></span>Product Category</a>
<ul class="sub-menu">
    <li id="menu-item-34" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-34"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/accessories/"><span></span>Accessories</a></li>
    <li id="menu-item-35" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-35"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/imacs/"><span></span>iMacs</a></li>
    <li id="menu-item-36" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-36"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/ipads/"><span></span>iPads</a></li>
    <li id="menu-item-37" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-37"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/iphones/"><span></span>iPhones</a></li>
    <li id="menu-item-38" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-38"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/ipods/"><span></span>iPods</a></li>
    <li id="menu-item-39" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-39"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/macbooks/"><span></span>MacBooks</a></li>
</ul>
</li>
<li id="menu-item-16" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-16 has_children"><span class="before"> </span><a><span></span>#0 (no title)</a>
<ul class="sub-menu">
    <li id="menu-item-17" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-17"><span class="before"> </span><a><span></span>#0 (no title)</a></li>
    <li id="menu-item-18" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-18"><span class="before"> </span><a><span></span>#0 (no title)</a></li>
</ul>
</li>
<li id="menu-item-72" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-72"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/"><span></span>All Product</a></li>
</ul>
</code>```

Source: http://store.demoqa.com/

Anyone knows what might be happening?
I've read all the similar questions here on StackOverflow, tried every single option and still it doesn't find an element that is clearly there.

答:
Here is the Answer to your Question:

I don't see any errors in your code block. But you may consider to use elementToBeClickable method instead of visibilityOfElementLocated while you induce ExplicitWait. Additionally, instead of locating the li element with id as menu-item-33, you can consider to locate the a tag of the element. Finally, the a tag will receive the normal Java click and you won't be needing to use Actions class. Here is your own code with some simple tweaks:

```<code>    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.ie.InternetExplorerDriver;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class Q44952318 {

        public static void main(String[] args) {

            System.setProperty("webdriver.ie.driver","C:\\Utility\\BrowserDrivers\\IEDriverServer_32.exe");
            DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
            cap.setCapability("ignoreZoomSetting", true);
            cap.setCapability("platform", "WIN8");
            cap.setCapability("version", "11");
            cap.setCapability("browserName", "internet explorer");
            cap.setCapability("ignoreProtectedModeSettings",1);
            cap.setCapability("nativeEvents","false");
            cap.setCapability("requireWindowFocus","true");
            cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
            WebDriver driver = new InternetExplorerDriver(cap);
            driver.get("http://www.store.demoqa.com");
            System.out.println("Successfully opened the website www.Store.Demoqa.com");
            WebDriverWait wait = new WebDriverWait(driver, 20);
            WebElement product = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//li[@id='menu-item-33']/a")));
            product.click();
            System.out.println("quiting test...");
            driver.quit();

        }

    }
</code>```

Let me know if this Answers your Question.

Title: Selenium can't find element by id

Body:
I'm trying to create a simple test with Selenium. I used this code before and it worked fine. Somehow it stopped working when I changed to a new machine. I tried adding some code to wait until the element is visible, but it didn't work out.

I just try to find an element by its id, move to this element and click it. Somehow the code doesn't find the element at all.

Here is my code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SeleniumBasicTest {

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

    DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
    caps.setCapability("ignoreZoomSetting", true);
    WebDriver driver = new InternetExplorerDriver(caps);

    driver.get("http://www.store.demoqa.com");

    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("menu-item-33")));

    System.out.println("Successfully opened the website www.Store.Demoqa.com");

    WebElement producCategorytMenu = driver.findElement(By.id("menu-item-33"));

    Actions builder = new Actions(driver);
    builder.moveToElement(producCategorytMenu).perform();
    builder.click(producCategorytMenu).perform();

    Thread.sleep(5000);

    System.out.println("quiting test...");
    driver.quit();
  }

}

This is the exception I'm receiving:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with id == menu-item-33 (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 315 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.3.0', revision: 'b526bd5b41', time: '2017-03-07 19:26:04 +0000'
System info: host: 'CMTCLX62137', ip: '53.19.245.167', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_31'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{se:ieOptions={browserAttachTimeout=0, ie.enableFullPageScreenshot=true, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.forceShellWindowsApi=false, ignoreZoomSetting=true, ie.fileUploadDialogTimeout=3000, ie.useLegacyFileUploadDialogHandling=false, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, initialBrowserUrl=http://localhost:37146/, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true}, browserName=internet explorer, pageLoadStrategy=normal, javascriptEnabled=true, version=11, platform=WINDOWS, unexpectedAlertBehaviour=dismiss}]
Session ID: 1e1740a9-00a2-4b92-814a-1979cfcef8e0
*** Element info: {Using=id, value=menu-item-33}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:371)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:420)
    at org.openqa.selenium.By$ById.findElement(By.java:218)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
    at com.mytest.SeleniumBasicTest.main(SeleniumBasicTest.java:22)

And here is the part of the HTML that has the menu:

 Home

 Product Category

 Accessories

 iMacs

 iPads

 iPhones

 iPods

 MacBooks

 #0 (no title)

 #0 (no title)

 #0 (no title)

 All Product

Source: http://store.demoqa.com/

Anyone knows what might be happening?
I've read all the similar questions here on StackOverflow, tried every single option and still it doesn't find an element that is clearly there.

Body:
Here is the Answer to your Question:

I don't see any errors in your code block. But you may consider to use elementToBeClickable method instead of visibilityOfElementLocated while you induce ExplicitWait. Additionally, instead of locating the li element with id as menu-item-33, you can consider to locate the a tag of the element. Finally, the a tag will receive the normal Java click and you won't be needing to use Actions class. Here is your own code with some simple tweaks:

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.ie.InternetExplorerDriver;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class Q44952318 {

        public static void main(String[] args) {

            System.setProperty("webdriver.ie.driver","C:\\Utility\\BrowserDrivers\\IEDriverServer_32.exe");
            DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
            cap.setCapability("ignoreZoomSetting", true);
            cap.setCapability("platform", "WIN8");
            cap.setCapability("version", "11");
            cap.setCapability("browserName", "internet explorer");
            cap.setCapability("ignoreProtectedModeSettings",1);
            cap.setCapability("nativeEvents","false");
            cap.setCapability("requireWindowFocus","true");
            cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
            WebDriver driver = new InternetExplorerDriver(cap);
            driver.get("http://www.store.demoqa.com");
            System.out.println("Successfully opened the website www.Store.Demoqa.com");
            WebDriverWait wait = new WebDriverWait(driver, 20);
            WebElement product = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//li[@id='menu-item-33']/a")));
            product.click();
            System.out.println("quiting test...");
            driver.quit();

        }

    }

Let me know if this Answers your Question.


问:
EmberJS Model Iteration by Value
I am working on a restaurant's website as my first ember project and I am having a hard time trying to figure out how to handle the menu model.

currently the models/menu.js file reads like this:

import DS from 'ember-data';

```<code>export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  price: DS.attr('number'),
  soyFree: DS.attr('string'),
  glutenFree: DS.attr('string'),
  addOnName: DS.attr('string'),
  addOnPrice: DS.attr('number'),
  type: DS.attr('string'),
  isAppetizer: Ember.computed('type', function(){
    return this.get('type') == 'Appetizer';
  }),
  isBreakfast: Ember.computed('type', function(){
    return this.get('type') == 'Breakfast';
  })
});
</code>```

My menu template file is:

```<code><div class="col-md-8 col-md-offset-2 text-center">
  <h2>Menu</h2>
  <h2 class="text-center">Appetizers</h2>
  {{#each model as |menu|}}
    {{#if menu.isAppetizer}}

      <p>
        <span><strong>{{menu.name}}</strong> - <em>{{menu.description}}</em> - {{menu.price}}</span>
        {{#if session.isAuthenticated}}<button class="btn btn-danger" {{action "deleteMenuItem" menu}}>Delete</button>{{/if}}
      </p>
    {{/if}}

  {{/each}}
  <h2 class="text-center">Breakfast</h2>
  {{#each model as |menu|}}
    {{#if menu.isBreakfast}}

      <p>
        <span><strong>{{menu.name}}</strong> - <em>{{menu.description}}</em> - {{menu.price}}</span>
        {{#if session.isAuthenticated}}<button class="btn btn-danger" {{action "deleteMenuItem" menu}}>Delete</button>{{/if}}
      </p>
    {{/if}}

  {{/each}}
</div>
{{outlet}}
</code>```

As you can see I am having to reiterate through all of the menu model entries for each section (Appetizers / Breakfast). Is there a way with ember that I can only iterate over the specific item type for each #each block.
ie.,

```<code>{{#each model.type == 'Appetizer'}}
  Fill the appetizer section
 {{/each}}
</code>```

Here is my route file is:

```<code>import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return this.store.findAll('menu');
  }
});
</code>```

答:
You can return the required value from model hook and access it using model.appetizerMenu for Appetizer menu.

```
    model() {
        return this.store.findAll('menu').then((result) => {
            return {
                appetizerMenu: result.filterBy('isAppetizer', true),
                breakFastMenu: result.filterBy('isBreakfast', true),
            }
        });
    }
```

2.you can have computed property in controller.

```<code>appetizerMenu: Ember.computed.filterBy('model','isAppetizer',true),
breakFastMenu: Ember.computed.filterBy('model','isBreakfast',true),
</code>```

3.Further you can simplify that you dont need computed property in the model for every type like currently you are having.
You can use type attribute alone for filtering whenever is required.

```
    appetizerMenu: Ember.computed.filterBy('model','type','Appetizer'),
    breakFastMenu: Ember.computed.filterBy('model','type','Breakfast'),
```

4.If you want more shopisticated helper like you suggested {{#each model.type == 'Appetizer'}} then you might be interested in ember-composable-helpers

Title: EmberJS Model Iteration by Value

Body:
I am working on a restaurant's website as my first ember project and I am having a hard time trying to figure out how to handle the menu model.

currently the models/menu.js file reads like this:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  price: DS.attr('number'),
  soyFree: DS.attr('string'),
  glutenFree: DS.attr('string'),
  addOnName: DS.attr('string'),
  addOnPrice: DS.attr('number'),
  type: DS.attr('string'),
  isAppetizer: Ember.computed('type', function(){
    return this.get('type') == 'Appetizer';
  }),
  isBreakfast: Ember.computed('type', function(){
    return this.get('type') == 'Breakfast';
  })
});

My menu template file is:

Menu

Appetizers

  {{#each model as |menu|}}
    {{#if menu.isAppetizer}}

        {{menu.name}} - {{menu.description}} - {{menu.price}}
        {{#if session.isAuthenticated}}<button class="btn btn-danger" {{action "deleteMenuItem" menu}}>Delete</button>{{/if}}

    {{/if}}

  {{/each}}

Breakfast

  {{#each model as |menu|}}
    {{#if menu.isBreakfast}}

        {{menu.name}} - {{menu.description}} - {{menu.price}}
        {{#if session.isAuthenticated}}<button class="btn btn-danger" {{action "deleteMenuItem" menu}}>Delete</button>{{/if}}

    {{/if}}

  {{/each}}

{{outlet}}

As you can see I am having to reiterate through all of the menu model entries for each section (Appetizers / Breakfast). Is there a way with ember that I can only iterate over the specific item type for each #each block.
ie.,

{{#each model.type == 'Appetizer'}}
  Fill the appetizer section
 {{/each}}

Here is my route file is:

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return this.store.findAll('menu');
  }
});

Body:
You can return the required value from model hook and access it using model.appetizerMenu for Appetizer menu.

    model() {
        return this.store.findAll('menu').then((result) => {
            return {
                appetizerMenu: result.filterBy('isAppetizer', true),
                breakFastMenu: result.filterBy('isBreakfast', true),
            }
        });
    }

2.you can have computed property in controller.

appetizerMenu: Ember.computed.filterBy('model','isAppetizer',true),
breakFastMenu: Ember.computed.filterBy('model','isBreakfast',true),

3.Further you can simplify that you dont need computed property in the model for every type like currently you are having.
You can use type attribute alone for filtering whenever is required.

    appetizerMenu: Ember.computed.filterBy('model','type','Appetizer'),
    breakFastMenu: Ember.computed.filterBy('model','type','Breakfast'),

4.If you want more shopisticated helper like you suggested {{#each model.type == 'Appetizer'}} then you might be interested in ember-composable-helpers


问:
Can i select the second link inside my navigation link
I am working on a sharepoint 2013 site, and I want to force my second link inside the Quick Edit link (left side navigation) to always be Blue & Bold. currently the markup looks as follow:-

so i want the "test new project er" link to always appear as Blue & bold .so can this be achieved? of course on other sites the site name will be different, but will always be placed second. Thanks

答:
From this exact markup, I'd say :</p>

```<code>#zz15_RootAspMenu li:nth-child(2) a {
    color : blue;
    font-weight : bold;
}
</code>```

Body:
From this exact markup, I'd say :

#zz15_RootAspMenu li:nth-child(2) a {
    color : blue;
    font-weight : bold;
}


问:
Resizing a grid control programatically over a period of time
G'day,

I am attempting to simulate the old XBox 360 GUI with the sliding tabs (Remember, you'd press left or right and the content would slide in depending on the tab?) Anyways, at the moment, I have this working well, however I cannot get the "animation" working.

When the user presses left arrow or right arrow, my OpenWindow(int iIndex) method will be called, where iIndex is the index to the next or previous "window" to be slid in. (Not a window... each "Window" is a struct with a parent grid control containing a button and a smaller grid control that contains the windows contents.)

Now, my problem lies with resizing the parent grid control. When it is slid in, it is resized by calling mygrid.Width += 1; That works, but I don't see it happen over a determined period of time, it just lags a bit and then resizes to the required width. Whereas if I call this.Width += 1 in the same method, (this being the main program window) the window resizes how I want the grid control to resize. I've tried UpdateLayout() but to no avail. This tells me my timing is okay.

If anyone could be of assistance, it would be greatly appreciated.

Here is my OpenWindow method...

```<code>public void OpenWindow(int iIndex)
    {
        int iInterval = 1;
        for (int i = (int)myDict[iIndex].Shell.Width; i < (int)stack_outter.Width; i += iInterval)
        {
            myDict[iIndex].Shell.Width += 1;
            myDict[iIndex].Shell.UpdateLayout();
            System.Threading.Thread.Sleep(1);

        }

        myDict[iIndex].Shell.Width = stack_outter.Width - (BUTTON_WIDTH * (myDict.Count - 1));
    }
</code>```

myDict is a Dictionary, Shell is the grid that I am attempting to animate when resizing. Sorry about the code, it's messy, my code is always hacked when I am trying to get stuff working :)

Thanks,

Ash

Neried Web Solutions

答:
Your OpenWindow method is happening on the Dispatcher thread. That's also the thread responsible for rendering, so as long as your OpenWindow method doesn't return, nothing gets rendered.

The proper way to fix this would be to animate the Width property. I don't have any experience in starting animations from code (I've only used them in the past for things like a fade-in button highlight on mouse over, which is more easily done from WPF), but I took a quick read-through this page, Animation Overview on MSDN, and I think you'll want something like this:

```<code>        DoubleAnimation myDoubleAnimation = new DoubleAnimation();
        myDoubleAnimation.From = myDict[iIndex].Shell.Width;
        myDoubleAnimation.To = stack_outter.Width;
        myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
        myDoubleAnimation.AutoReverse = false;
        myDoubleAnimation.RepeatBehavior = new RepeatBehavior(1.0);

        myStoryboard = new Storyboard();
        myStoryboard.Children.Add(myDoubleAnimation);
        Storyboard.SetTarget(myDoubleAnimation, myDict[iIndex].Shell);
        Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(FrameworkElement.WidthProperty));
        myStoryboard.Begin(myDict[iIndex].Shell);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
G'day,

I am attempting to simulate the old XBox 360 GUI with the sliding tabs (Remember, you'd press left or right and the content would slide in depending on the tab?) Anyways, at the moment, I have this working well, however I cannot get the "animation" working.

When the user presses left arrow or right arrow, my OpenWindow(int iIndex) method will be called, where iIndex is the index to the next or previous "window" to be slid in. (Not a window... each "Window" is a struct with a parent grid control containing a button and a smaller grid control that contains the windows contents.)

Now, my problem lies with resizing the parent grid control. When it is slid in, it is resized by calling mygrid.Width += 1; That works, but I don't see it happen over a determined period of time, it just lags a bit and then resizes to the required width. Whereas if I call this.Width += 1 in the same method, (this being the main program window) the window resizes how I want the grid control to resize. I've tried UpdateLayout() but to no avail. This tells me my timing is okay.

If anyone could be of assistance, it would be greatly appreciated.

Here is my OpenWindow method...

public void OpenWindow(int iIndex)
    {
        int iInterval = 1;
        for (int i = (int)myDict[iIndex].Shell.Width; i < (int)stack_outter.Width; i += iInterval)
        {
            myDict[iIndex].Shell.Width += 1;
            myDict[iIndex].Shell.UpdateLayout();
            System.Threading.Thread.Sleep(1);

        }

        myDict[iIndex].Shell.Width = stack_outter.Width - (BUTTON_WIDTH * (myDict.Count - 1));
    }

myDict is a Dictionary, Shell is the grid that I am attempting to animate when resizing. Sorry about the code, it's messy, my code is always hacked when I am trying to get stuff working :)

Thanks,

Ash

Neried Web Solutions

Body:
Your OpenWindow method is happening on the Dispatcher thread. That's also the thread responsible for rendering, so as long as your OpenWindow method doesn't return, nothing gets rendered.

The proper way to fix this would be to animate the Width property. I don't have any experience in starting animations from code (I've only used them in the past for things like a fade-in button highlight on mouse over, which is more easily done from WPF), but I took a quick read-through this page, Animation Overview on MSDN, and I think you'll want something like this:

        DoubleAnimation myDoubleAnimation = new DoubleAnimation();
        myDoubleAnimation.From = myDict[iIndex].Shell.Width;
        myDoubleAnimation.To = stack_outter.Width;
        myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
        myDoubleAnimation.AutoReverse = false;
        myDoubleAnimation.RepeatBehavior = new RepeatBehavior(1.0);

        myStoryboard = new Storyboard();
        myStoryboard.Children.Add(myDoubleAnimation);
        Storyboard.SetTarget(myDoubleAnimation, myDict[iIndex].Shell);
        Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(FrameworkElement.WidthProperty));
        myStoryboard.Begin(myDict[iIndex].Shell);


问:
Open text file not in current folder in MATLAB
I would like to open a text file using uigetfile but it gives me an error when I open a text file other from the current folder. Is there a way to fix this?

I wrote:

```<code>FileName = uigetfile('*.txt', 'Open text file');
file = load(FileName);
</code>```

答:
You need to get the complete path:</p>

```<code>[FileName,PathName] = uigetfile('*.txt', 'Open text file');
file = load(fullfile(PathName,FileName));
</code>```

Body:
I would like to open a text file using uigetfile but it gives me an error when I open a text file other from the current folder. Is there a way to fix this?

I wrote:

FileName = uigetfile('*.txt', 'Open text file');
file = load(FileName);

Body:
You need to get the complete path:

[FileName,PathName] = uigetfile('*.txt', 'Open text file');
file = load(fullfile(PathName,FileName));


问:
@Transient @RestController not being mapped by ServletDispatcher in Spring MVC
I'm currently facing an issue with Spring MVC: if I create a rest controller and mark it as @Transient it's not being mapped by the ServletDispatcher (404 if called), if I remove the annotation the controller is mapped correctly and everything is fine. If I mark a service as transactional and invoke it from inside the controller, everything is fine (the transaction starts and finishes correctly). Unfortunately marking my services as transactional right now is not viable (I'm working on a legacy system). At the time of writing I'm using the latest spring version (4.3.9).

My current configs:

```<code>    <servlet>
        <servlet-name>api</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/api-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>api</servlet-name>
        <url-pattern>/v2/*</url-pattern>
    </servlet-mapping>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</code>```

Transaction manager configuration (the resources are defined in my applicationContext.xml):

```<code>@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = "my.package")
public class TransactionManagerConfiguration {

    @Resource(name = "entityManager")
    private EntityManagerFactory entityManager;

    @Resource(name = "dataSource")
    private DataSource dataSource;

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManager);
        tm.setDataSource(dataSource);
        return tm;
    }

}
</code>```

My Controller:

```<code>    @RestController
    @RequestMapping("/accounts")
    public class AccountsController {

    @GetMapping
    @Transactional
        public List<Account> doStuff() {

            //stuff...
            return stuff;
        }

    }
</code>```

My api-servlet.xml:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:sec="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/security/oauth2
                        http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.2.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
                        http://www.springframework.org/schema/security
                        http://www.springframework.org/schema/security/spring-security-4.1.xsd">

    <context:component-scan base-package="my.package"/>

</beans>
</code>```

I'm omitting my applicationContext.xml since it doesn't have anything significant in it (just a bunch of BL beans and a package scan).

答:
Found a solution thanks to M. Deinum's comment. In my case I had to add the set proxy target class as true

@EnableTransactionManagement(proxyTargetClass = true)

You can find more details here: https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping-proxying

Body:
I'm currently facing an issue with Spring MVC: if I create a rest controller and mark it as @Transient it's not being mapped by the ServletDispatcher (404 if called), if I remove the annotation the controller is mapped correctly and everything is fine. If I mark a service as transactional and invoke it from inside the controller, everything is fine (the transaction starts and finishes correctly). Unfortunately marking my services as transactional right now is not viable (I'm working on a legacy system). At the time of writing I'm using the latest spring version (4.3.9).

My current configs:

    <servlet>
        <servlet-name>api</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/api-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>api</servlet-name>
        <url-pattern>/v2/*</url-pattern>
    </servlet-mapping>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

Transaction manager configuration (the resources are defined in my applicationContext.xml):

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = "my.package")
public class TransactionManagerConfiguration {

    @Resource(name = "entityManager")
    private EntityManagerFactory entityManager;

    @Resource(name = "dataSource")
    private DataSource dataSource;

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManager);
        tm.setDataSource(dataSource);
        return tm;
    }

}

My Controller:

    @RestController
    @RequestMapping("/accounts")
    public class AccountsController {

    @GetMapping
    @Transactional
        public List<Account> doStuff() {

            //stuff...
            return stuff;
        }

    }

My api-servlet.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:sec="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/security/oauth2
                        http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.2.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
                        http://www.springframework.org/schema/security
                        http://www.springframework.org/schema/security/spring-security-4.1.xsd">

    <context:component-scan base-package="my.package"/>

</beans>

I'm omitting my applicationContext.xml since it doesn't have anything significant in it (just a bunch of BL beans and a package scan).


问:
Using program variables in python logging configuration file
I am trying to enable my python logging using the following:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.config
import os
test_filename = 'my_log_file.txt'
try:
    logging.config.fileConfig('loggingpy.conf', disable_existing_loggers=False)
except Exception as e:
    # try to set up a default logger
    logging.error("No loggingpy.conf to parse", exc_info=e)
    logging.basicConfig(level=logging.WARNING, format="%(asctime)-15s %(message)s")
test1_log = logging.getLogger("test1")
test1_log.critical("test1_log crit")
test1_log.error("test1_log error")
test1_log.warning("test1_log warning")
test1_log.info("test1_log info")
test1_log.debug("test1_log debug")
</code>```

I would like to use a loggingpy.conf file to control the logging like the following:

```<code>[loggers]
keys=root

[handlers]
keys=handRoot

[formatters]
keys=formRoot

[logger_root]
level=INFO
handlers=handRoot

[handler_handRoot]
class=FileHandler
level=INFO
formatter=formRoot
args=(test_filename,)

[formatter_formRoot]
format=%(asctime)s:%(name)s:%(process)d:%(lineno)d %(levelname)s %(message)s
datefmt=
class=logging.Formatter
</code>```

Here I am trying to route the logging to the file named by the local "test_filename".  When I run this, I get:

```<code>ERROR:root:No loggingpy.conf to parse
Traceback (most recent call last):
  File "logging_test.py", line 8, in <module>
    logging.config.fileConfig('loggingpy.conf', disable_existing_loggers=False)
  File "/usr/lib/python2.7/logging/config.py", line 85, in fileConfig
    handlers = _install_handlers(cp, formatters)
  File "/usr/lib/python2.7/logging/config.py", line 162, in _install_handlers
    args = eval(args, vars(logging))
  File "<string>", line 1, in <module>
NameError: name 'test_filename' is not defined
CRITICAL:test1:test1_log crit
ERROR:test1:test1_log error
WARNING:test1:test1_log warning
</code>```

Reading the docs, it seems that the "args" value in the config is eval'd in the context of the logging package namespace rather than the context when fileConfig is called.  Is there any decent way to try to get the logging to behave this way through a configuration file so I can configure a dynamic log filename (usually like "InputFile.log"), but still have the flexibility to use the logging config file to change it?

答:
Even though it's an old question, I think this still has relevance. An alternative to the above mentioned solutions would be to use logging.config.dictConfig(...) and manipulating the dictionary.

MWE:

log_config.yml

```<code>version: 1
disable_existing_loggers: false
formatters:
  default:
    format: "%(asctime)s:%(name)s:%(process)d:%(lineno)d %(levelname)s %(message)s"
handlers:
  console:
    class: logging.StreamHandler
    formatter: default
    stream: ext://sys.stdout
    level: DEBUG
  file:
    class: logging.FileHandler
    formatter: default
    filename: "{path}/service.log"
    level: DEBUG
root:
  level: DEBUG
  handlers:
  - file
  - console
</code>```

example.py

```<code>import logging.config
import sys
import yaml

log_output_path = sys.argv[1]

log_config = yaml.load(open("log_config.yml"))
log_config["handlers"]["file"]["filename"] = log_config["handlers"]["file"]["filename"].format(path = log_output_path)
logging.config.dictConfig(log_config)

logging.debug("test")
</code>```

Executable as follows:

python example.py .

Result:

service.log file in current working directory contains one line of log message.

Console outputs one line of log message.

Both state something like this:

2016-06-06 20:56:56,450:root:12232:11 DEBUG test

Body:
I am trying to enable my python logging using the following:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.config
import os
test_filename = 'my_log_file.txt'
try:
    logging.config.fileConfig('loggingpy.conf', disable_existing_loggers=False)
except Exception as e:
    # try to set up a default logger
    logging.error("No loggingpy.conf to parse", exc_info=e)
    logging.basicConfig(level=logging.WARNING, format="%(asctime)-15s %(message)s")
test1_log = logging.getLogger("test1")
test1_log.critical("test1_log crit")
test1_log.error("test1_log error")
test1_log.warning("test1_log warning")
test1_log.info("test1_log info")
test1_log.debug("test1_log debug")

I would like to use a loggingpy.conf file to control the logging like the following:

[loggers]
keys=root

[handlers]
keys=handRoot

[formatters]
keys=formRoot

[logger_root]
level=INFO
handlers=handRoot

[handler_handRoot]
class=FileHandler
level=INFO
formatter=formRoot
args=(test_filename,)

[formatter_formRoot]
format=%(asctime)s:%(name)s:%(process)d:%(lineno)d %(levelname)s %(message)s
datefmt=
class=logging.Formatter

Here I am trying to route the logging to the file named by the local "test_filename".  When I run this, I get:

ERROR:root:No loggingpy.conf to parse
Traceback (most recent call last):
  File "logging_test.py", line 8, in <module>
    logging.config.fileConfig('loggingpy.conf', disable_existing_loggers=False)
  File "/usr/lib/python2.7/logging/config.py", line 85, in fileConfig
    handlers = _install_handlers(cp, formatters)
  File "/usr/lib/python2.7/logging/config.py", line 162, in _install_handlers
    args = eval(args, vars(logging))
  File "<string>", line 1, in <module>
NameError: name 'test_filename' is not defined
CRITICAL:test1:test1_log crit
ERROR:test1:test1_log error
WARNING:test1:test1_log warning

Reading the docs, it seems that the "args" value in the config is eval'd in the context of the logging package namespace rather than the context when fileConfig is called.  Is there any decent way to try to get the logging to behave this way through a configuration file so I can configure a dynamic log filename (usually like "InputFile.log"), but still have the flexibility to use the logging config file to change it?

Body:
Even though it's an old question, I think this still has relevance. An alternative to the above mentioned solutions would be to use logging.config.dictConfig(...) and manipulating the dictionary.

MWE:

log_config.yml

version: 1
disable_existing_loggers: false
formatters:
  default:
    format: "%(asctime)s:%(name)s:%(process)d:%(lineno)d %(levelname)s %(message)s"
handlers:
  console:
    class: logging.StreamHandler
    formatter: default
    stream: ext://sys.stdout
    level: DEBUG
  file:
    class: logging.FileHandler
    formatter: default
    filename: "{path}/service.log"
    level: DEBUG
root:
  level: DEBUG
  handlers:
  - file
  - console

example.py

import logging.config
import sys
import yaml

log_output_path = sys.argv[1]

log_config = yaml.load(open("log_config.yml"))
log_config["handlers"]["file"]["filename"] = log_config["handlers"]["file"]["filename"].format(path = log_output_path)
logging.config.dictConfig(log_config)

logging.debug("test")

Executable as follows:

python example.py .

Result:

service.log file in current working directory contains one line of log message.

Console outputs one line of log message.

Both state something like this:

2016-06-06 20:56:56,450:root:12232:11 DEBUG test


问:
Lambda Expression: How to map to a List rather than IEnumerable?
I am using the following code to avoid repetition:

```<code> private static Expression<Func<Incident_Log, IncidentVM>> mappingIncidentVM()
        {
            return x => new IncidentVM
            {
                incident_ID = x.incident_id,
                incident_description = x.incident_description,
                file_names = x.file_names,
                location = x.location,

                Actions =
                    x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
                {
                    incident_ID = z.incident_id,
                    action_ID = z.action_id,
                    action_description = z.action_description

                })
                //actionList = new List<ActionVM>(d => mappingActionVM)

            };
        }
</code>```

Then I can do the following:

List<IncidentVM> incidents = db.Incident_Log.Select(mappingIncidentVM).ToList();

And it maps the Incident_Log entity to my viewModel IncidentVM.
My problem is that I wish I could map directly to a list rather than an IEnumerable.Something like this:

```<code>  private static Expression<Func<Incident_Log, IncidentVM>> mappingIncidentVM()
        {
            return x => new IncidentVM
            {
                incident_ID = x.incident_id,
                incident_description = x.incident_description,
                file_names = x.file_names,
                location = x.location,

                actionList =
                    x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
                    {
                        incident_ID = z.incident_id,
                        action_ID = z.action_id,
                        action_description = z.action_description

                    }).ToList()

            };
        }
</code>```

But that is throwing an error:

LINQ to Entities does not recognize the method System.Collections.Generic.List[ViewModel.ActionVM] ToList[ActionVM](System.Collections.Generic.IEnumerable([ViewModel.ActionVM]) method, and this method cannot be translated into a store expression.

The ToList() is not recognised.

Here is my ViewModel:

```<code> public class IncidentVM
    {

        public int incident_ID { set; get; }

        [Display(Name = "Description*")]
        [Required]
        public string incident_description { get; set; }

        [Display(Name = "Specific Location*")]
        [Required]
        public string location { set; get; }

        public string file_names { set; get; }

//Here is the problem, I 'd like to have only actionList
        public IEnumerable<ActionVM> Actions { get; set; }
        public List<ActionVM> actionList { get; set; }
</code>```

And here is the model for the Action_Log Object:

```<code>public partial class Action_Log
{
    public int action_id { get; set; }
    public int incident_id { get; set; }
    public string action_description { get; set; }

    public virtual Incident_Log Incident_Log { get; set; }
}
</code>```

Is it possible to map directly to a List in this case?

答:
Try</p>

```<code>actionList =
      x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
      {
          incident_ID = z.incident_id,
          action_ID = z.action_id,
          action_description = z.action_description

       }).ToList<ActionVM>()
</code>```

Body:
I am using the following code to avoid repetition:

 private static Expression<Func<Incident_Log, IncidentVM>> mappingIncidentVM()
        {
            return x => new IncidentVM
            {
                incident_ID = x.incident_id,
                incident_description = x.incident_description,
                file_names = x.file_names,
                location = x.location,

                Actions =
                    x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
                {
                    incident_ID = z.incident_id,
                    action_ID = z.action_id,
                    action_description = z.action_description

                })
                //actionList = new List<ActionVM>(d => mappingActionVM)

            };
        }

Then I can do the following:

List<IncidentVM> incidents = db.Incident_Log.Select(mappingIncidentVM).ToList();

And it maps the Incident_Log entity to my viewModel IncidentVM.
My problem is that I wish I could map directly to a list rather than an IEnumerable.Something like this:

  private static Expression<Func<Incident_Log, IncidentVM>> mappingIncidentVM()
        {
            return x => new IncidentVM
            {
                incident_ID = x.incident_id,
                incident_description = x.incident_description,
                file_names = x.file_names,
                location = x.location,

                actionList =
                    x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
                    {
                        incident_ID = z.incident_id,
                        action_ID = z.action_id,
                        action_description = z.action_description

                    }).ToList()

            };
        }

But that is throwing an error:

LINQ to Entities does not recognize the method System.Collections.Generic.List[ViewModel.ActionVM] ToList[ActionVM](System.Collections.Generic.IEnumerable([ViewModel.ActionVM]) method, and this method cannot be translated into a store expression.

The ToList() is not recognised.

Here is my ViewModel:

 public class IncidentVM
    {

        public int incident_ID { set; get; }

        [Display(Name = "Description*")]
        [Required]
        public string incident_description { get; set; }

        [Display(Name = "Specific Location*")]
        [Required]
        public string location { set; get; }

        public string file_names { set; get; }

//Here is the problem, I 'd like to have only actionList
        public IEnumerable<ActionVM> Actions { get; set; }
        public List<ActionVM> actionList { get; set; }

And here is the model for the Action_Log Object:

public partial class Action_Log
{
    public int action_id { get; set; }
    public int incident_id { get; set; }
    public string action_description { get; set; }

    public virtual Incident_Log Incident_Log { get; set; }
}

Is it possible to map directly to a List in this case?

Body:
Try

actionList =
      x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
      {
          incident_ID = z.incident_id,
          action_ID = z.action_id,
          action_description = z.action_description

       }).ToList<ActionVM>()


问:
Splitting a project VB/C#, and References
I've inherited a project written mostly in VB. I'd like to maintain what I have in VB while slowly converting to C# when I can. The only way I've found to do this is to create a separate C# project. However, this causes problems because of dependencies and references. I can't have VBProject reference CSharpProject and vice versa because it creates a circular reference. This is a problem because I need both projects to be able to reference the other. Is there a better way to do this, or am I stuck writing in VB (or completely translating to C#)?

Also, these projects are in the same solution. Shouldn't I be able to import/use them without creating a reference or some other easier way?

答:
Inversion of Control will help you greatly in performing a migration like this. I recently tackled a similar problem when asked to add significant functionality to untested duct-tape VB.Net code. I wanted to extract the existing affected functionality out of VB.Net and put it in a unit tested C# assembly.

In cases where you want to extract a class to a new assembly but would lead to dependencies back in the original assembly you can negate this by defining a contract interface in the new assembly which is implemented by dependencies from the original assembly.

For example, given classes Alpha, Bravo, and Charlie in the VB.Net assembly, where Alpha has a reference to Bravo. You want to extract Bravo, but it has a reference to Charlie. Define an interface called ICharlie in the C# project which contains the members in Charlie that Bravo cares about. In the VB.Net project, modify Charlie : ICharlie. When you construct Bravo, it will accept a dependency of type ICharlie.

The benefit of this approach, even within the same project or set of projects, is testability. Dependencies between classes are well known and can be substituted out with mocks/stubs so that classes like Bravo can be tested without needing to worry about setting it up with a real ICharlie implementation.


问:
Python OpenCV2 SVM get scores instead of yes/no responses
I want to train a RBF kernel SVM for a 2-class problem. At the moment the SVM predicts only 0 or 1, but I want it to return the distance to the decision boundary. How can I achieve this?

```<code>self.svm = cv2.ml.SVM_create()
self.svm.setKernel(cv2.ml.SVM_RBF)
self.svm.train(features, cv2.ml.ROW_SAMPLE, labels)
res = svm.predict(testdata, True)
</code>```

My features are np.arrays with dtype=np.float32, my labels are np.arrays with dtype=np.int and values are 0 for class "no", 1 for class "yes"

The documentation says that svm.predict returns scores for the second parameter being True, but I only get results like this:

(0.0, array([[ 0.],
         [ 0.],
         [ 0.],
         ...,
         [ 0.],
         [ 0.],
         [ 0.]], dtype=float32))

Do I have to change the SVM type? If so, which should I choose?

答:
You could use the scikit-learn package to generate your svm.

To train:

```<code>from sklearn.svm import LinearSVC
clf=LinearSVC(C=1.0,  class_weight='balanced')
clf.fit(features, labels)
svm_w = clf.coef_[0]
svm_intercept = clf.intercept_[0]
</code>```

To test:

```<code>response_list = list()
for ft in feature_list:
    val = (sum(p*q for p,q in zip(ft,svm_w)) + svm_intercept)[0]
    response_list.append(val)
</code>```

This gives you the SVM response for the feature in terms of the distance from the hyperplane.

Body:
I want to train a RBF kernel SVM for a 2-class problem. At the moment the SVM predicts only 0 or 1, but I want it to return the distance to the decision boundary. How can I achieve this?

self.svm = cv2.ml.SVM_create()
self.svm.setKernel(cv2.ml.SVM_RBF)
self.svm.train(features, cv2.ml.ROW_SAMPLE, labels)
res = svm.predict(testdata, True)

My features are np.arrays with dtype=np.float32, my labels are np.arrays with dtype=np.int and values are 0 for class "no", 1 for class "yes"

The documentation says that svm.predict returns scores for the second parameter being True, but I only get results like this:

(0.0, array([[ 0.],
         [ 0.],
         [ 0.],
         ...,
         [ 0.],
         [ 0.],
         [ 0.]], dtype=float32))

Do I have to change the SVM type? If so, which should I choose?

Body:
You could use the scikit-learn package to generate your svm.

To train:

from sklearn.svm import LinearSVC
clf=LinearSVC(C=1.0,  class_weight='balanced')
clf.fit(features, labels)
svm_w = clf.coef_[0]
svm_intercept = clf.intercept_[0]

To test:

response_list = list()
for ft in feature_list:
    val = (sum(p*q for p,q in zip(ft,svm_w)) + svm_intercept)[0]
    response_list.append(val)

This gives you the SVM response for the feature in terms of the distance from the hyperplane.


问:
Making API call before closing tab to store dashboard widgets data
There are widgets in dashboard page which be can sorted(draggable and droppable). We want the order of widgets to be preserved when user revisits our page, so we have API to dump all widgets to DB. But the problem is whether we should make an API call on every drag-drop of widget or before window close/unload?
Having read around, got to know that doing API at window unload is not recommended. So is there any other approach to tackle this? I don't want to make API call on every drag-drop of widget.

Thanks in advance for help.

答:
We figured out a way. Using navigator.sendBeacon() -
(https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon)

Thanks to Jaromanda X.


问:
JLabel: load HTML images asynchronously
A JLabel allows HTML contents, which can contain an image among the contents:

```<code>String html = "<html><body>...<img src=\"http://some_url/image.png\"/>...</body></html>";
JLabel label = new JLabel(html);
</code>```

Note that I use the JLabel for rendering images in a JXTreeTable, so the updating of the text of the JLabel is done on the EDT in the renderer.

The problem is that the image gets loaded synchronously. With a slow server, the EDT can be blocked for multiple seconds while the image is being loaded.

I already discovered why the image gets loaded synchronously, and which class I need to modify to switch to async loading of images.

The loading of the image is done by the javax.swing.text.html.ImageView class, which has a method setLoadsSynchronously.

The problem is that I have no clue how I can easily adjust the HTMLFactory / HTMLEditorKit which is responsible for creating that ImageView, and which is used internally by the JLabel .
To make matters even more complicated, I need a solution which works for all Look and Feels.

In case the above is not clear, the following thread dump shows on what the EDT is blocked during the image retrieval:

```<code>"AWT-EventQueue-0@999" prio=6 tid=0x10 nid=NA waiting
  java.lang.Thread.State: WAITING
      at java.lang.Object.wait(Object.java:-1)
      at java.awt.MediaTracker.waitForID(MediaTracker.java:677)
      at javax.swing.ImageIcon.loadImage(ImageIcon.java:314)
      at javax.swing.ImageIcon.setImage(ImageIcon.java:381)
      at javax.swing.text.html.ImageView.loadImage(ImageView.java:704)
      at javax.swing.text.html.ImageView.refreshImage(ImageView.java:673)
      at javax.swing.text.html.ImageView.sync(ImageView.java:645)
      at javax.swing.text.html.ImageView.getPreferredSpan(ImageView.java:443)
      at javax.swing.text.FlowView$LogicalView.getPreferredSpan(FlowView.java:732)
      at javax.swing.text.FlowView.calculateMinorAxisRequirements(FlowView.java:233)
      at javax.swing.text.ParagraphView.calculateMinorAxisRequirements(ParagraphView.java:717)
      at javax.swing.text.html.ParagraphView.calculateMinorAxisRequirements(ParagraphView.java:157)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.ParagraphView.getMinimumSpan(ParagraphView.java:270)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.BlockView.getMinimumSpan(BlockView.java:378)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.BlockView.getMinimumSpan(BlockView.java:378)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getPreferredSpan(BoxView.java:545)
      at javax.swing.text.html.BlockView.getPreferredSpan(BlockView.java:362)
      at javax.swing.plaf.basic.BasicHTML$Renderer.<init>(BasicHTML.java:383)
      at javax.swing.plaf.basic.BasicHTML.createHTMLView(BasicHTML.java:67)
      at javax.swing.plaf.basic.BasicHTML.updateRenderer(BasicHTML.java:207)
      at javax.swing.plaf.basic.BasicLabelUI.propertyChange(BasicLabelUI.java:417)
      at javax.swing.plaf.synth.SynthLabelUI.propertyChange(SynthLabelUI.java:296)
      at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:335)
      at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:327)
      at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:263)
      at java.awt.Component.firePropertyChange(Component.java:8428)
      at org.jdesktop.swingx.renderer.JRendererLabel.firePropertyChange(JRendererLabel.java:292)
      at javax.swing.JLabel.setText(JLabel.java:330)
</code>```

答:
Using SwingWorkers (as suggested bytrashgod) is the best solution. An alternative would be something like that:
Create an asynch method that donwload the image:

```<code>new Thread(new Runnable() {
    public void run() {
       //download the image
       BufferedImage image = ImageIO.read(url);
       //update the label
       updateLabel(image)
    }
}).start();
</code>```

that calls another method that updates the label in the EDT

```<code>private void updateLabel(final BufferedImage image) {
  SwingUtilities.invokeLater(new Runnable() {
    public void run(){
      // fine updating here... event dispatch thread
      label.setIcon(new ImageIcon(image));
    }
  });
}
</code>```

Title: JLabel: load HTML images asynchronously

Body:
A JLabel allows HTML contents, which can contain an image among the contents:

String html = "......";
JLabel label = new JLabel(html);

Note that I use the JLabel for rendering images in a JXTreeTable, so the updating of the text of the JLabel is done on the EDT in the renderer.

The problem is that the image gets loaded synchronously. With a slow server, the EDT can be blocked for multiple seconds while the image is being loaded.

I already discovered why the image gets loaded synchronously, and which class I need to modify to switch to async loading of images.

The loading of the image is done by the javax.swing.text.html.ImageView class, which has a method setLoadsSynchronously.

The problem is that I have no clue how I can easily adjust the HTMLFactory / HTMLEditorKit which is responsible for creating that ImageView, and which is used internally by the JLabel .
To make matters even more complicated, I need a solution which works for all Look and Feels.

In case the above is not clear, the following thread dump shows on what the EDT is blocked during the image retrieval:

"AWT-EventQueue-0@999" prio=6 tid=0x10 nid=NA waiting
  java.lang.Thread.State: WAITING
      at java.lang.Object.wait(Object.java:-1)
      at java.awt.MediaTracker.waitForID(MediaTracker.java:677)
      at javax.swing.ImageIcon.loadImage(ImageIcon.java:314)
      at javax.swing.ImageIcon.setImage(ImageIcon.java:381)
      at javax.swing.text.html.ImageView.loadImage(ImageView.java:704)
      at javax.swing.text.html.ImageView.refreshImage(ImageView.java:673)
      at javax.swing.text.html.ImageView.sync(ImageView.java:645)
      at javax.swing.text.html.ImageView.getPreferredSpan(ImageView.java:443)
      at javax.swing.text.FlowView$LogicalView.getPreferredSpan(FlowView.java:732)
      at javax.swing.text.FlowView.calculateMinorAxisRequirements(FlowView.java:233)
      at javax.swing.text.ParagraphView.calculateMinorAxisRequirements(ParagraphView.java:717)
      at javax.swing.text.html.ParagraphView.calculateMinorAxisRequirements(ParagraphView.java:157)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.ParagraphView.getMinimumSpan(ParagraphView.java:270)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.BlockView.getMinimumSpan(BlockView.java:378)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.BlockView.getMinimumSpan(BlockView.java:378)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getPreferredSpan(BoxView.java:545)
      at javax.swing.text.html.BlockView.getPreferredSpan(BlockView.java:362)
      at javax.swing.plaf.basic.BasicHTML$Renderer.<init>(BasicHTML.java:383)
      at javax.swing.plaf.basic.BasicHTML.createHTMLView(BasicHTML.java:67)
      at javax.swing.plaf.basic.BasicHTML.updateRenderer(BasicHTML.java:207)
      at javax.swing.plaf.basic.BasicLabelUI.propertyChange(BasicLabelUI.java:417)
      at javax.swing.plaf.synth.SynthLabelUI.propertyChange(SynthLabelUI.java:296)
      at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:335)
      at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:327)
      at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:263)
      at java.awt.Component.firePropertyChange(Component.java:8428)
      at org.jdesktop.swingx.renderer.JRendererLabel.firePropertyChange(JRendererLabel.java:292)
      at javax.swing.JLabel.setText(JLabel.java:330)

Body:
Using SwingWorkers (as suggested bytrashgod) is the best solution. An alternative would be something like that:
Create an asynch method that donwload the image:

new Thread(new Runnable() {
    public void run() {
       //download the image
       BufferedImage image = ImageIO.read(url);
       //update the label
       updateLabel(image)
    }
}).start();

that calls another method that updates the label in the EDT

private void updateLabel(final BufferedImage image) {
  SwingUtilities.invokeLater(new Runnable() {
    public void run(){
      // fine updating here... event dispatch thread
      label.setIcon(new ImageIcon(image));
    }
  });
}


问:
htaccess configuration - With CodeIgniter - A3M library
I downloaded a3m, it comes packaged with CI 1.7.2 but I went ahead and removed all of the files it needed to run and put them in my pre-existing installation. After going to the a3m controller on my site I received:
Message: Undefined property: CI::$session

So I assume it’s because of htaccess looking for a3m files in an a3m folder, here’s the a3m htaccess:

```<code>RewriteEngine on
RewriteRule ^$ /a3m/index.php [L]
RewriteCond $1 !^(index\.php|css|img|js|scripts|system|uploads|robots\.txt|favicon\.ico)
RewriteRule ^(.*)$ /a3m/index.php/$1 [L]
</code>```

And my already existing htaccess for mod rewrite is as follows:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /beta/

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #When your application folder isn't in the system folder
    #This snippet prevents user access to the application folder
    #Submitted by: Fabdrol
    #Rename 'application' to your applications folder name.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>
</code>```

As the commenting shows, I used it from a site a while back, so how can I combine the two I guess is what I’m trying to ask as I’m quite enthused about using a3m.

Thanks guys.

答:
It doesn't look like you've loaded the session library.

Check in system\application\config\autoload.php if you have the library loaded:
[42] $autoload['libraries'] = array('database', 'session');

You can do this from the controller:
$this->load->library('session');

http://codeigniter.com/user_guide/libraries/sessions.html

Body:
I downloaded a3m, it comes packaged with CI 1.7.2 but I went ahead and removed all of the files it needed to run and put them in my pre-existing installation. After going to the a3m controller on my site I received:
Message: Undefined property: CI::$session

So I assume it’s because of htaccess looking for a3m files in an a3m folder, here’s the a3m htaccess:

RewriteEngine on
RewriteRule ^$ /a3m/index.php [L]
RewriteCond $1 !^(index\.php|css|img|js|scripts|system|uploads|robots\.txt|favicon\.ico)
RewriteRule ^(.*)$ /a3m/index.php/$1 [L]

And my already existing htaccess for mod rewrite is as follows:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /beta/

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #When your application folder isn't in the system folder
    #This snippet prevents user access to the application folder
    #Submitted by: Fabdrol
    #Rename 'application' to your applications folder name.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>

As the commenting shows, I used it from a site a while back, so how can I combine the two I guess is what I’m trying to ask as I’m quite enthused about using a3m.

Thanks guys.


问:
Can't install required packages for Ubuntu to build Android Open Source Project
I'm build Android Open Source Project on Ubuntu 10.0.4. I try to install required packages by execute below command (coppied from http://source.android.com/source/initializing.html) but I can't.

```<code>    sudo apt-get install git-core gnupg flex bison gperf build-essential \
  zip curl zlib1g-dev libc6-dev lib32ncurses5-dev ia32-libs \
  x11proto-core-dev libx11-dev lib32readline5-dev lib32z-dev \
  libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown \
  libxml2-utils xsltproc
</code>```

The error message:

E: Couldn't find package lib32ncurses5-dev

E: Couldn't find package lib32readline5-dev

E: Couldn't find package lib32z-dev

E: Couldn't find package mingw32

答:
I'm not sure if he meant 14.04, but for 10.04 list would be for a 32-bit OS:</p>

```<code>$  sudo apt-get install git gnupg flex bison gperf build-essential zip curl zlib1g-dev libc6-dev libncurses5-dev x11proto-core-dev libx11-dev libreadline5-dev libz-dev libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown libxml2-utils xsltproc
</code>```

Body:
I'm build Android Open Source Project on Ubuntu 10.0.4. I try to install required packages by execute below command (coppied from http://source.android.com/source/initializing.html) but I can't.

    sudo apt-get install git-core gnupg flex bison gperf build-essential \
  zip curl zlib1g-dev libc6-dev lib32ncurses5-dev ia32-libs \
  x11proto-core-dev libx11-dev lib32readline5-dev lib32z-dev \
  libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown \
  libxml2-utils xsltproc

The error message:

E: Couldn't find package lib32ncurses5-dev

E: Couldn't find package lib32readline5-dev

E: Couldn't find package lib32z-dev

E: Couldn't find package mingw32

Body:
I'm not sure if he meant 14.04, but for 10.04 list would be for a 32-bit OS:

$  sudo apt-get install git gnupg flex bison gperf build-essential zip curl zlib1g-dev libc6-dev libncurses5-dev x11proto-core-dev libx11-dev libreadline5-dev libz-dev libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown libxml2-utils xsltproc


问:
JS Bitwise Operator to Java
I'm trying to convert a js function to Java but i don't know how to work with JS Bitwise operator in java.

I need to translate this:

var r = '0x' + a.substring(j, 2) | 0     and
('0x' + a.substr(j, 2) ^ r)

Has anyone ever done that?

Thanks!

答:
Java's bitwise operators are explained here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

Basically ^ is XOR, & is AND and | is OR.

You can find the specification here:
http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22

However they cannot be applied to strings (thank god!).

Title: JS Bitwise Operator to Java


问:
Not getting toast in clicking an item in spinner
```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Spinner s = new Spinner(this);

        RelativeLayout rl = (RelativeLayout)
        findViewById(R.id.activity_main);

        String ss[] = {"--Select Item--", "Item1", "Item2", "Item3",
                       "Item4", "Item5"};

        ArrayAdapter<String> ad = new ArrayAdapter<String>(this,
                           android.R.layout.simple_dropdown_item_1line, ss);

        s.setAdapter(ad);

        rl.addView(s);

        s.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                TextView t = (TextView) v;
                Toast.makeText(MainActivity.this, t.getText().toString(),
                               Toast.LENGTH_SHORT).show();
                return true;
            }
        });
}

}
</code>```

When i am long pressing on an item in spinner I am not  getting any Toast which  should come as the  code specifies it so above. Also, when long pressing the spinner itself (not the item in the dropdown list in the spinner) then the app is crashing. Why is that so?

Edit 1:

```<code>s.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                TextView t = (TextView) view;
                Toast.makeText(MainActivity.this, t.getText().toString(), Toast.LENGTH_SHORT).show();
                return true;
            }
        });
</code>```

When using setOnItemLongClickListener instead of setOnLongClickListener then when long pressing an item in dropdown list of spinner should generate a toast but it is not giving so?

答:
The longClickListener is set on a Spinner class and you are casting that view to a TextView inside the listener. That is why the app crashes.

Spinner.setOnLongClickListener is not the listener for each of the adapter items.

What you are looking for is  Spinner.setOnItemSelectedListener(new OnItemSelectedListener())

Body:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Spinner s = new Spinner(this);

        RelativeLayout rl = (RelativeLayout)
        findViewById(R.id.activity_main);

        String ss[] = {"--Select Item--", "Item1", "Item2", "Item3",
                       "Item4", "Item5"};

        ArrayAdapter<String> ad = new ArrayAdapter<String>(this,
                           android.R.layout.simple_dropdown_item_1line, ss);

        s.setAdapter(ad);

        rl.addView(s);

        s.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                TextView t = (TextView) v;
                Toast.makeText(MainActivity.this, t.getText().toString(),
                               Toast.LENGTH_SHORT).show();
                return true;
            }
        });
}

}

When i am long pressing on an item in spinner I am not  getting any Toast which  should come as the  code specifies it so above. Also, when long pressing the spinner itself (not the item in the dropdown list in the spinner) then the app is crashing. Why is that so?

Edit 1:

s.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                TextView t = (TextView) view;
                Toast.makeText(MainActivity.this, t.getText().toString(), Toast.LENGTH_SHORT).show();
                return true;
            }
        });

When using setOnItemLongClickListener instead of setOnLongClickListener then when long pressing an item in dropdown list of spinner should generate a toast but it is not giving so?


问:
Deleting unwanted columns starting at a specific row - excel vba
For some reason I can't figure out how to do this... it seems so basic:

Trying to delete unwanted columns starting at a specific row.

Example:
Want to delete Columns C, D, E, M, N and L all starting at row 10 of Wsh2.

```<code>'deleting columns that are unwanted
Cells(wsh2.Cells("C10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("D10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("E10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("M10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("N10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("L10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
End Sub
</code>```

I've adapted a previous code that I found on here that used Range. I've also attempted using Union and Range but cant seem to figure it out.

Basically: Trying to delete only specific columns starting at a particular row after I've copied a range of rows from a previous worksheet.

Any help would be great. Thank you!

答:
if you use EntireColumn.Delete it will delete the entire column, you need to get the range and delete that instead, eg.</p>

```<code>Range("C10:C" & Rows.Count).Delete
</code>```

Body:
For some reason I can't figure out how to do this... it seems so basic:

Trying to delete unwanted columns starting at a specific row.

Example:
Want to delete Columns C, D, E, M, N and L all starting at row 10 of Wsh2.

'deleting columns that are unwanted
Cells(wsh2.Cells("C10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("D10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("E10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("M10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("N10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("L10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
End Sub

I've adapted a previous code that I found on here that used Range. I've also attempted using Union and Range but cant seem to figure it out.

Basically: Trying to delete only specific columns starting at a particular row after I've copied a range of rows from a previous worksheet.

Any help would be great. Thank you!

Body:
if you use EntireColumn.Delete it will delete the entire column, you need to get the range and delete that instead, eg.

Range("C10:C" & Rows.Count).Delete


问:
Avoiding XSS Vulnerability with single quotes, but allow users to use them in input?
This may be a more basic question, but I am accessing a JSON string from my controller, which accesses the database, on my JavaScript page. I do {!JSENCODE(jsonString)} to be wary of XSS vulnerability with this as users get to specify a name for the objects in the JSON.

The issue is... when doing JSENCODE, it escapes single quotes. Then if I try to JSON.parse() it, the \' throws an error as an invalid character. Replacing \' with \' prevents errors, but then it shows up as \' in the list of object names instead of the single quote (used for apostrophes).

What would be the best course of action to allow users to use single quotes in the names of these objects while avoiding XSS vulnerabilities?

答:
It sounds like you are taking data, converting it to JSON, then injecting it into a string literal in a
```

Body:
It sounds like you are taking data, converting it to JSON, then injecting it into a string literal in a <script> element, and then trying to parse the resulting string as JSON.

The problem is that special characters in JSON are also special characters in JavaScript.

The good news is that JSON is a subset of JavaScript, so you can just use it as if it were a JavaScript literal.

<script>
    var data =  {!JSENCODE(jsonString)};
    console.log(data);
</script>


问:
How can I access a constraint throughout my class not just where I set it?
So my first thought was to make it an instance property of the class, and then set it in one method and access it in another. This didn't really work as nicely as I hoped it would so I am wondering how I can set an identifier for a constraint so I can access it where ever I need to in my class? I am not using storyboards. So I cannot use outlets and set the identifier in the GUI.

```<code>iconOne.heightAnchor.constraint(equalToConstant: 25.0).isActive = true
</code>```

I want to be able to access the above constraint so I can later on update the constant what is the best way to go about this? If it is not identifiers please let me know as I open to any suggestions.

答:
iconOne.heightAnchor.constraint(equalToConstant: 25.0) will return an NSLayoutConstraint. Store this in a variable.

```<code>class TestViewController: UIViewController {

var iconOne: UIImageView!

var heightConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    heightConstraint = iconOne.heightAnchor.constraint(equalToConstant: 25.0)
    heightConstraint.isActive = true

}

}
</code>```

Or make an outlet via IB.

```<code>class TestViewController: UIViewController {

@IBOutlet weak var iconOne: UIImageView!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!

}
</code>```

Body:
So my first thought was to make it an instance property of the class, and then set it in one method and access it in another. This didn't really work as nicely as I hoped it would so I am wondering how I can set an identifier for a constraint so I can access it where ever I need to in my class? I am not using storyboards. So I cannot use outlets and set the identifier in the GUI.

iconOne.heightAnchor.constraint(equalToConstant: 25.0).isActive = true

I want to be able to access the above constraint so I can later on update the constant what is the best way to go about this? If it is not identifiers please let me know as I open to any suggestions.

Body:
iconOne.heightAnchor.constraint(equalToConstant: 25.0) will return an NSLayoutConstraint. Store this in a variable.

class TestViewController: UIViewController {

var iconOne: UIImageView!

var heightConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    heightConstraint = iconOne.heightAnchor.constraint(equalToConstant: 25.0)
    heightConstraint.isActive = true

}

}

Or make an outlet via IB.

class TestViewController: UIViewController {

@IBOutlet weak var iconOne: UIImageView!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!

}


问:
creating symbolic link of file in a different directory in linux
trying to create a symbolic link to an xml file in a different directory. I am using the command in the current file directory.

```<code>ln -s file_name.xml /home/path_to_desired_symbolic_link_location/file_name.xml
</code>```

The symbolic link is created but it is empty.

答:
It's safe to use the absolute address if you want to link to the file in another directory. Like this:</p>

```<code>ln -s /path a/file_name.xml /path b/file_name.xml
</code>```

Body:
trying to create a symbolic link to an xml file in a different directory. I am using the command in the current file directory.

ln -s file_name.xml /home/path_to_desired_symbolic_link_location/file_name.xml

The symbolic link is created but it is empty.

Body:
It's safe to use the absolute address if you want to link to the file in another directory. Like this:

ln -s /path a/file_name.xml /path b/file_name.xml


问:
Ext Js Grid Column
My grid needs to have 2 columns and second column needs to have a progress bar , status of progress bar and also radio buttons. How do we achieve this in Extjs.

Should this be a component column or a widget column.

I also need to handle json events so that I can change the progress of the progress bar and also set the radio buttons.

答:
Checkout the widget grid in the Kitchen Sink examples:
http://examples.sencha.com/extjs/6.5.0/examples/kitchensink/?classic#widget-grid

You can always bind your progress bar to a viewmodel data value or formula and update it with an interval or web socket.

Title: Ext Js Grid Column