问:
Android Studio: Failed to load dx.jar
When I run my module in Android Studio I get this error:

Error:Android Dex: [GradleDevBuild] Failed to load dx.jar

I have searched endlessly for a solution online but everything is related to eclipse, there is nothing when it comes to Android Studio.

The path to the dex.jar is C:\AndroidSdk\build-tools\26.0.0\lib\dex.jar
So it does exists, I've moved it out of the folder and was notified that it moved so AS is aware of where it is. I have tried copying it into the root directory and into the platform-tools folder however that did nothing.

This is the full list of errors that all seem to be stemming from this dx.jar error.

```<code>Error:Android Dex: [GradleDevBuild] Failed to load dx.jar
Error:Android Dex: [GradleDevBuild] java.lang.ClassNotFoundException: com.android.dx.command.DxConsole
Error:Android Dex: [GradleDevBuild] at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
Error:Android Dex: [GradleDevBuild] at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
Error:Android Dex: [GradleDevBuild] at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.loadDex(AndroidDxRunner.java:80)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:136)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.main(AndroidDxRunner.java:336)
Error:Android Dex: [GradleDevBuild] Exception in thread "main" java.lang.NullPointerException
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:139)
</code>```

答:
My case:
IntelliJ IDEA,
libgdx - project

In my case my Project was not configured for gradle yet after opening it for the first time. I restarted my IDE and clicked on the "configure gradle" Pop-up on the lower right site and it worked.

see this Thread:
Module ... is not backed by gradle

Title: Android Studio: Failed to load dx.jar

Body:
When I run my module in Android Studio I get this error:

Error:Android Dex: [GradleDevBuild] Failed to load dx.jar

I have searched endlessly for a solution online but everything is related to eclipse, there is nothing when it comes to Android Studio.

The path to the dex.jar is C:\AndroidSdk\build-tools\26.0.0\lib\dex.jar
So it does exists, I've moved it out of the folder and was notified that it moved so AS is aware of where it is. I have tried copying it into the root directory and into the platform-tools folder however that did nothing.

This is the full list of errors that all seem to be stemming from this dx.jar error.

Error:Android Dex: [GradleDevBuild] Failed to load dx.jar
Error:Android Dex: [GradleDevBuild] java.lang.ClassNotFoundException: com.android.dx.command.DxConsole
Error:Android Dex: [GradleDevBuild] at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
Error:Android Dex: [GradleDevBuild] at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
Error:Android Dex: [GradleDevBuild] at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.loadDex(AndroidDxRunner.java:80)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:136)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.main(AndroidDxRunner.java:336)
Error:Android Dex: [GradleDevBuild] Exception in thread "main" java.lang.NullPointerException
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:139)


来源: stackexchange

问:
Is it possible to send an array with the Postman Chrome extension?
I've been using Postman Chrome extension to test out my API and would like to send an array of IDs via post. Is there a way to send something list this as a parameter in Postman?</p>

```<code>{
  user_ids: ["1234", "5678"]
}
</code>```

答: Set Body as raw and form the array as follows:

ContentLicense: CC BY-SA 3.0

Body:
I've been using Postman Chrome extension to test out my API and would like to send an array of IDs via post. Is there a way to send something list this as a parameter in Postman?

{
  user_ids: ["1234", "5678"]
}


问:
Does the number of columns in a Vertica table impact query performance?
We are working with a Vertica 8.1 table containing 500 columns and 100 000 rows.

The following query will take around 1.5 seconds to execute, even when using the vsql client straight on one of the Vertica cluster nodes (to eliminate any network latency issue) :

SELECT COUNT(*) FROM MY_TABLE WHERE COL_132 IS NOT NULL and COL_26 = 'anotherValue'

But when checking the query_requests table, the request_duration_ms is only 98 ms, and the resource_acquisitions table doesn't indicate any delay in resource asquisition. I can't understand where the rest of the time is spent.

If I then export to a new table only the columns used by the query, and run the query on this new, smaller, table, I get a blazing fast response, even though the query_requests table still tells me the request_duration_ms is around 98 ms.

So it seems that the number of columns in the table impacts the execution time of queries, even if most of these columns are not referenced. Am I wrong ? If so, why is it so ?

Thanks by advance

答:
It sounds like your query is running against the (default) superprojection that includes all tables.  Even though Vertica is a columnar database (with associated compression and encoding), your query is probably still touching more data than it needs to.

You can create projections to optimize your queries.  A projection contains a subset of columns; if one is available that has all the columns your query needs, then the query uses that instead of the superprojection.  (It's a little more complicated than that, because physical location is also a factor, but that's the basic idea.)  You can use the Database Designer to create some initial projections based on your schema and sample queries, and iteratively improve it over time.


问:
Inspecting Java threads in Linux using top
I am inspecting a Java process in Linux using

```<code>top -H
</code>```

However, I cannot read the name of the thread in the "COMMAND" column (because it is too long).  If I use 'c' to expand the full name of the process, then it is still to long to fit.

How can I obtain the full name of the command?

答: Threads don't have names as far as the kernel is concerned; they only have ID numbers.  The JVM assigns names to threads, but that's private internal data within the process, which the "top" program can't access (and doesn't know about anyway).</p>

Body:
I am inspecting a Java process in Linux using

top -H

However, I cannot read the name of the thread in the "COMMAND" column (because it is too long).  If I use 'c' to expand the full name of the process, then it is still to long to fit.

How can I obtain the full name of the command?

ContentLicense: CC BY-SA 2.5


问:
My multiplication in python not working
I'm trying to get a multiplication inside a for loop working on the code below:

```<code>#products list and it's values per unity
tomato = 2
potato = 3
carrot = 1
pricePaid = int()

print("Welcome to my grocery shop!\n")

productList = ["Potato", "Tomato", "Carrot"]

print("What will you want today?\n""We have:")
print(*productList, sep=', ')
product = input("What will it be? ")

quantity = int(input("And how many do you want? "))

for productChoice in product:
    if productChoice == "Potato":
        pricePaid = quantity * potato
    elif productChoice == "Tomato":
        pricePaid = quantity * tomato
    elif productChoice == "Carrot":
        pricePaid = quantity * carrot

print("Here's your bag with {0} {1}s. The total is ${2:.2f}.".format(quantity, product, pricePaid))
</code>```

but I'm getting a $0.00 as my results where it should be the quantity * productPrice:

```<code>"Here's your bag with 1 Tomatos. The total is $0.00."
</code>```

Why is it failing? What am I missing here?

I'm using Python 3.x

Thanks in advance!

答:
You are iterating over the letters in producChoice.

Add a print(productChoice) to your loop in order to watch what happens.
Since no single letter equals one of your products, none of the conditional statements will be triggered and pricePaid will stay at its original value of int() == 0.

There's no need for the for loop here at all, so just remove it.

Title: My multiplication in python not working

Body:
I'm trying to get a multiplication inside a for loop working on the code below:

#products list and it's values per unity
tomato = 2
potato = 3
carrot = 1
pricePaid = int()

print("Welcome to my grocery shop!\n")

productList = ["Potato", "Tomato", "Carrot"]

print("What will you want today?\n""We have:")
print(*productList, sep=', ')
product = input("What will it be? ")

quantity = int(input("And how many do you want? "))

for productChoice in product:
    if productChoice == "Potato":
        pricePaid = quantity * potato
    elif productChoice == "Tomato":
        pricePaid = quantity * tomato
    elif productChoice == "Carrot":
        pricePaid = quantity * carrot

print("Here's your bag with {0} {1}s. The total is ${2:.2f}.".format(quantity, product, pricePaid))

but I'm getting a $0.00 as my results where it should be the quantity * productPrice:

"Here's your bag with 1 Tomatos. The total is $0.00."

Why is it failing? What am I missing here?

I'm using Python 3.x

Thanks in advance!


答:
Here an improved code using dictionaries. Dictionaries alone are worth studying to make code much lighter. Basically a dictionary is composed by keys (for instance tomato) holding values (for instance 1). You can get those values by using .get().

```<code>#products list and it's values per unity
prices = dict(tomato=2,potato=3,carrot=1)

product = input('''\
Welcome to my grocery shop!
What will you want today?
We have: {}
What will it be?
'''.format(', '.join(prices.keys()))).lower()

quantity = int(input("And how many do you want? "))

pricePaid = prices.get(product,0) * quantity

if pricePaid:
    print("Here's your bag with {0} {1}s. The total is ${2:.2f}."
          .format(quantity, product, pricePaid))
else:
    print("Error with input!")
</code>```

Title: My multiplication in python not working

Body:
Here an improved code using dictionaries. Dictionaries alone are worth studying to make code much lighter. Basically a dictionary is composed by keys (for instance tomato) holding values (for instance 1). You can get those values by using .get().

#products list and it's values per unity
prices = dict(tomato=2,potato=3,carrot=1)

product = input('''\
Welcome to my grocery shop!
What will you want today?
We have: {}
What will it be?
'''.format(', '.join(prices.keys()))).lower()

quantity = int(input("And how many do you want? "))

pricePaid = prices.get(product,0) * quantity

if pricePaid:
    print("Here's your bag with {0} {1}s. The total is ${2:.2f}."
          .format(quantity, product, pricePaid))
else:
    print("Error with input!")


问:
Sending POST info via PHP (curl) or jQuery - IP problem -
Im sending post info by using php curl. its okay. no problem. however it sends server's IP. this is a problem for me.

jquery is sending post info with user's IP, however jQuery have cross domain problem. it is not sending post info to another domain. It only works for same domain.

I wanna send post info (to another domain) + user ip (not server ip). Id like to learn your advices... Well, is there any other ways to make this job?

Thanks, Regards.

答:
The only way to do this is to have a form on the web page that points to the specified resource, give it a POST method, and submit it.

If you don't want the entire page to reload, use an iframe.

```<code><iframe id="myiframe"></iframe>

<form action="http://some-other-site.com/page.php" method="post" target="myiframe">
....
</code>```

You will, however, not be able to access the results the site outputs - again due to the cross domain / single origin policy.

Body:
The only way to do this is to have a form on the web page that points to the specified resource, give it a POST method, and submit it.

If you don't want the entire page to reload, use an iframe.

<iframe id="myiframe"></iframe>

<form action="http://some-other-site.com/page.php" method="post" target="myiframe">
....

You will, however, not be able to access the results the site outputs - again due to the cross domain / single origin policy.


问:
SQL statement inside an SQL statement
I want this statement to return the systems where there are more than two stations, I got this far but I don't know what to do next. All this does it return every system with a regionID less than 1100001. Am I onto the right idea at least? </p>

```<code>SELECT DISTINCT mapSolarSystems.regionID,solarSystemID,solarSystemName,x,z,security
FROM mapSolarSystems
WHERE mapSolarSystems.regionID <11000001
AND
2 < (SELECT COUNT(*) FROM stations,mapSolarSystems
 WHERE mapSolarSystems.solarSystemID=stations.systemid)
</code>```

答: SELECT DISTINCT m.regionID,solarSystemID,solarSystemName,x,z,security FROM mapSolarSystems m join stations s on m.solarSystemID = s.systemid WHERE m.regionID <11000001 AND (SELECT COUNT(*) FROM stations) >2 </p>

Title: SQL statement inside an SQL statement

Body:
I want this statement to return the systems where there are more than two stations, I got this far but I don't know what to do next. All this does it return every system with a regionID less than 1100001. Am I onto the right idea at least?

SELECT DISTINCT mapSolarSystems.regionID,solarSystemID,solarSystemName,x,z,security
FROM mapSolarSystems
WHERE mapSolarSystems.regionID <11000001
AND
2 < (SELECT COUNT(*) FROM stations,mapSolarSystems
 WHERE mapSolarSystems.solarSystemID=stations.systemid)


问:
JavaFX TableView CellFactory
I have a TableView with some records and want to set the background color of a cell depending on a property (eg. set color if ID == 5).

Basically that works.

See Image 1

```<code>public class CustomCell extends TableCell<Person, String> {

@Override
protected void updateItem(String item, boolean empty){
    super.updateItem(item, empty);

    if (item != null && !empty){

        setText(item);

        if (getTableRow() != null && getTableRow().getItem() != null){
            Person p = (Person) getTableRow().getItem();

            if (p.getId() == 5){
                setStyle("-fx-background-color: #CBDBD7;");
            }
        }
    }else{
        setText(null);
    }
}
</code>```

But when i start to scroll up and down a few times,
different cells get the background color as well.
This is not the behavior i want.

Wrong cells with background color

I tested this on macOS 10.13.1 / Java 1.8.0_151
and Debian with OpenJDK.

https://github.com/glueckandi/test_fx.git

What am I doing wrong?

答:
Try setting the style to null or "" empty string.

```<code>if (p.getId() == 5)
{
    setStyle("-fx-background-color: #CBDBD7;");
}
else
{
    setStyle("");
}
</code>```

and

```<code>else
{
    setText(null);
    setStyle("");
}
</code>```

Title: JavaFX TableView CellFactory

Body:
I have a TableView with some records and want to set the background color of a cell depending on a property (eg. set color if ID == 5).

Basically that works.

See Image 1

public class CustomCell extends TableCell<Person, String> {

@Override
protected void updateItem(String item, boolean empty){
    super.updateItem(item, empty);

    if (item != null && !empty){

        setText(item);

        if (getTableRow() != null && getTableRow().getItem() != null){
            Person p = (Person) getTableRow().getItem();

            if (p.getId() == 5){
                setStyle("-fx-background-color: #CBDBD7;");
            }
        }
    }else{
        setText(null);
    }
}

But when i start to scroll up and down a few times,
different cells get the background color as well.
This is not the behavior i want.

Wrong cells with background color

I tested this on macOS 10.13.1 / Java 1.8.0_151
and Debian with OpenJDK.

https://github.com/glueckandi/test_fx.git

What am I doing wrong?

Body:
Try setting the style to null or "" empty string.

if (p.getId() == 5)
{
    setStyle("-fx-background-color: #CBDBD7;");
}
else
{
    setStyle("");
}

and

else
{
    setText(null);
    setStyle("");
}


问:
Selenium WD | Trying to use an 'If' statement with logical 'or'
I have a step in my test that goes into several html pages and looks for an element on the screen. That element can have 2 different CSS class names while looking the same in the website (visually speaking) , I have to use an if statement with a logical 'or' to identify them

```<code>if (Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2")) || Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-1")));
System.out.println("Stock is closed");)
</code>```

I expected that if one of the 2 elements would appear, the Eclipse would

recognize it. Well - The second element out of the 2 appeared - and for some reason I've got an exception error. The if statement gave attention only to the first condition in the if, and ignored the second.

org.openqa.selenium.NoSuchElementException: no such element:

locate element: {"method":"css
  selector","selector":".inlineblock.redClockBigIcon.middle.isOpenExchBig-2"}Unable to

How can I make the || to work in this 'if' statement?
Thanks

Screenshots of the elements

答:
You can try using try catch block:

```<code>boolean isFirstElemPresent = true;

try{
      driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-1"));
}catch (NoSuchElementException e){
    isFirstElemPresent = false;
}

if(isFirstElemPresent == false)
     driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2"));
</code>```

Or

To avoid try catch block, use below code snap:

```<code>List<WebElement> elements = driver.findElements(By.className("redClockBigIcon"));

if (elements.size() == 0) {
    System.out.println("Element is not present");
} else {
    System.out.println("Element is present");
}
</code>```

Body:
I have a step in my test that goes into several html pages and looks for an element on the screen. That element can have 2 different CSS class names while looking the same in the website (visually speaking) , I have to use an if statement with a logical 'or' to identify them

if (Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2")) || Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-1")));
System.out.println("Stock is closed");)

I expected that if one of the 2 elements would appear, the Eclipse would

recognize it. Well - The second element out of the 2 appeared - and for some reason I've got an exception error. The if statement gave attention only to the first condition in the if, and ignored the second.

org.openqa.selenium.NoSuchElementException: no such element:

locate element: {"method":"css
  selector","selector":".inlineblock.redClockBigIcon.middle.isOpenExchBig-2"}Unable to

How can I make the || to work in this 'if' statement?
Thanks

Screenshots of the elements

Body:
You can try using try catch block:

boolean isFirstElemPresent = true;

try{
      driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-1"));
}catch (NoSuchElementException e){
    isFirstElemPresent = false;
}

if(isFirstElemPresent == false)
     driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2"));

Or

To avoid try catch block, use below code snap:

List<WebElement> elements = driver.findElements(By.className("redClockBigIcon"));

if (elements.size() == 0) {
    System.out.println("Element is not present");
} else {
    System.out.println("Element is present");
}


问:
django-decouple throws an error whenever it encounters '.'
django-decouple throws an error

```<code>'tuple' object has no attribute 'rsplit'
module_path, class_name = dotted_path.rsplit('.', 1)
AttributeError: 'tuple' object has no attribute 'rsplit'
</code>```

whenever it encounters '.' e.g django.core.mail.backends.smtp.EmailBackend, smtp.gmail.com

Kindly help

答: I think dotted_path is not a string, it's a tuple as said in the error message. you probably need to do something like dotted_path[0].rsplit('.', 1)

Body:
django-decouple throws an error

'tuple' object has no attribute 'rsplit'
module_path, class_name = dotted_path.rsplit('.', 1)
AttributeError: 'tuple' object has no attribute 'rsplit'

whenever it encounters '.' e.g django.core.mail.backends.smtp.EmailBackend, smtp.gmail.com

Kindly help


问:
How to add a caption to a resized table with scalebox in xtable?
I'm working on a R Markdown document. I've got a dataframe of this kind:

```<code>library(tidyverse)
library(xtable)

df <- tibble(a = 1:10, b = 1:10, c = 1:10, d = 1:10, e = 1:10, f =1:10,
g = 1:10, h = 1:10, i = 1:10)
</code>```

I'm using the xtable package to create display a table. Since the table is too wide, I scale the table with the scalebox parameter

```<code>xt <- xtable(df, caption = "Table 1")
print(xt, type = "latex", comment = FALSE,floating = F,
include.rownames = F, scalebox = 0.50)
</code>```

However, the caption is not displayed on the document. What can I do?

答:
If you are not limited to using xtable, I would recommend making the switch to knitr::kable and kableExtra.

```<code>---
output: pdf_document
---

```{r setup, include=FALSE}
library(tidyverse)
library(knitr)
library(kableExtra)

df <- tibble(a = 1:10, b = 1:10, c = 1:10, d = 1:10, e = 1:10, f =1:10,
g = 1:10, h = 1:10, i = 1:10)
```

```{r table, results='asis'}
df %>%
  kable("latex", caption = "Table 1", booktabs = TRUE) %>%
  kable_styling(latex_options = c("striped", "hold_position"))
```
</code>```

Produces...

In addition, there is an equivalent scale_down option available to latex_options. However, as noted in the vignette it will fit to page width and therefore also scale up if the table is not sufficiently wide.

Body:
I'm working on a R Markdown document. I've got a dataframe of this kind:

library(tidyverse)
library(xtable)

df <- tibble(a = 1:10, b = 1:10, c = 1:10, d = 1:10, e = 1:10, f =1:10,
g = 1:10, h = 1:10, i = 1:10)

I'm using the xtable package to create display a table. Since the table is too wide, I scale the table with the scalebox parameter

xt <- xtable(df, caption = "Table 1")
print(xt, type = "latex", comment = FALSE,floating = F,
include.rownames = F, scalebox = 0.50)

However, the caption is not displayed on the document. What can I do?

Body:
If you are not limited to using xtable, I would recommend making the switch to knitr::kable and kableExtra.

---
output: pdf_document
---

```{r setup, include=FALSE}
library(tidyverse)
library(knitr)
library(kableExtra)

df <- tibble(a = 1:10, b = 1:10, c = 1:10, d = 1:10, e = 1:10, f =1:10,
g = 1:10, h = 1:10, i = 1:10)
```

```{r table, results='asis'}
df %>%
  kable("latex", caption = "Table 1", booktabs = TRUE) %>%
  kable_styling(latex_options = c("striped", "hold_position"))
```

Produces...

In addition, there is an equivalent scale_down option available to latex_options. However, as noted in the vignette it will fit to page width and therefore also scale up if the table is not sufficiently wide.


问:
Whatever the username, Hyperledger Fabric Sample App, Balance Transfer, log in successfully
I am playing around with hyperledger fabric sample apps. In "Balance transfer" app, they have provided sample requests to login user, create channel and more.....
 But whatever the username i provide, it logged it in successfully.
Request:

```<code>curl -s -X POST \
  http://localhost:4000/users \
  -H "content-type: application/x-www-form-urlencoded" \
  -d 'username=Jim&orgName=org1'
</code>```

Response

```<code>{
    "success": true,
    "secret": "GSHPwdfBQyzB",
    "message": "Jim enrolled Successfully",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTI0MjkxNzYsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzIiLCJpYXQiOjE1MTIzOTMxNzZ9.AAH5A9V08QfMvPmsDpoHVkYsFNbQX-nRMU025NziZRc"
}
</code>```

No matter what username i provide it log it in successfully.
Can anyone explain, what is actually going on.

答:
The command

curl -s -X POST \
  http://localhost:4000/users \
  -H "content-type: application/x-www-form-urlencoded" \
  -d 'username=Jim&orgName=org1'

registers and enrolls a user. You are sending the POST request as an admin with registration privileges.

Body:
I am playing around with hyperledger fabric sample apps. In "Balance transfer" app, they have provided sample requests to login user, create channel and more.....
 But whatever the username i provide, it logged it in successfully.
Request:

curl -s -X POST \
  http://localhost:4000/users \
  -H "content-type: application/x-www-form-urlencoded" \
  -d 'username=Jim&orgName=org1'

Response

{
    "success": true,
    "secret": "GSHPwdfBQyzB",
    "message": "Jim enrolled Successfully",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTI0MjkxNzYsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzIiLCJpYXQiOjE1MTIzOTMxNzZ9.AAH5A9V08QfMvPmsDpoHVkYsFNbQX-nRMU025NziZRc"
}

No matter what username i provide it log it in successfully.
Can anyone explain, what is actually going on.


问:
Run terminal inside VS Code for python script?
I'm on Linux Mint running VSCode and I was somehow able to run a terminal not as a separate window but right below an open Python file.  Seems to be easy on Win/OSX (Ctrl/Cmd+J and select Terminal tab) but not specifically a feature that I can choose when I'm on a Linux machine.  Any special keys to bring it back?</p>

答: In general, Ctrl-` opens the integrated terminal in VS Code. Otherwise look under the View menu for the Integrated Terminal option. If you're looking for Python-specific options, there are Run Python File in Terminal and Run Python Selection/Line in Terminal commands from the command palette.


问:
what's wrong with string contains match
Sorry, I don't want to post this question here. Other questions like mine have been posted before, but I haven't found an answer yet.

I am trying to do a simple string match using string.contains

```<code> If Not dataRow("Name").ToString().Contains(UserName) Then
  --do something--
End If
</code>```

but that's not working in my condition

```<code>dataRow("Name").ToString()= "Steve Cook"
UserName="Cook Steve"
</code>```

I want to find the %like match (like SQL) but .contains not what I was expecting it to do?

答:
A simple Comparer Class.

If the strings differ in length or not all parts are equal, returns false

```<code>Dim names As Names = New Names
names.CompareName = "Steve Cook"
names.ToName = "Cook steve"

If names.Compare(True) = True Then
 Console.Write("Same guy")
End If

Public Class Names
  Public Property CompareName() As String
  Public Property ToName() As String

  Public Function Compare(ByVal IgnoreCase As Boolean) As Boolean
     If CompareName.Length <> ToName.Length Then Return False

     Dim TypeOfComparison As StringComparison =
         If(IgnoreCase, StringComparison.InvariantCultureIgnoreCase,
                        StringComparison.InvariantCulture)
     Dim _All As Boolean = True
     Dim _parts As String() = ToName.Split(" "c)
     For Each _part As String In _parts
        If CompareName.IndexOf(_part, 0, TypeOfComparison) < 0 Then
           _All = False
           Exit For
        End If
     Next
     Return _All
  End Function
End Class
</code>```

Or with a Join-Split-Reverse:

```<code>Dim Name1 As String = "Steve Cook"
Dim Name2 As String = "Cook Steve"

If StringCompare(Name1, Name2) Then
    Console.Write("Same guy")
End If

Public Function StringCompare(ByVal CompName As String, ByVal ToName As String) As Boolean
   If CompName.Equals(ToName, StringComparison.InvariantCultureIgnoreCase) Then
       Return True
   End If
   If CompName.Equals(String.Join(" ", ToName.Split(" "c).AsEnumerable.Reverse()),
                      StringComparison.InvariantCultureIgnoreCase) Then
      Return True
   End If
   Return False
End Function
</code>```

Title: what's wrong with string contains match

Body:
Sorry, I don't want to post this question here. Other questions like mine have been posted before, but I haven't found an answer yet.

I am trying to do a simple string match using string.contains

 If Not dataRow("Name").ToString().Contains(UserName) Then
  --do something--
End If

but that's not working in my condition

dataRow("Name").ToString()= "Steve Cook"
UserName="Cook Steve"

I want to find the %like match (like SQL) but .contains not what I was expecting it to do?

Body:
A simple Comparer Class.

If the strings differ in length or not all parts are equal, returns false

Dim names As Names = New Names
names.CompareName = "Steve Cook"
names.ToName = "Cook steve"

If names.Compare(True) = True Then
 Console.Write("Same guy")
End If

Public Class Names
  Public Property CompareName() As String
  Public Property ToName() As String

  Public Function Compare(ByVal IgnoreCase As Boolean) As Boolean
     If CompareName.Length <> ToName.Length Then Return False

     Dim TypeOfComparison As StringComparison =
         If(IgnoreCase, StringComparison.InvariantCultureIgnoreCase,
                        StringComparison.InvariantCulture)
     Dim _All As Boolean = True
     Dim _parts As String() = ToName.Split(" "c)
     For Each _part As String In _parts
        If CompareName.IndexOf(_part, 0, TypeOfComparison) < 0 Then
           _All = False
           Exit For
        End If
     Next
     Return _All
  End Function
End Class

Or with a Join-Split-Reverse:

Dim Name1 As String = "Steve Cook"
Dim Name2 As String = "Cook Steve"

If StringCompare(Name1, Name2) Then
    Console.Write("Same guy")
End If

Public Function StringCompare(ByVal CompName As String, ByVal ToName As String) As Boolean
   If CompName.Equals(ToName, StringComparison.InvariantCultureIgnoreCase) Then
       Return True
   End If
   If CompName.Equals(String.Join(" ", ToName.Split(" "c).AsEnumerable.Reverse()),
                      StringComparison.InvariantCultureIgnoreCase) Then
      Return True
   End If
   Return False
End Function

ContentLicense: CC BY-SA 4.0


问:
Pandas rank method dense but skip a number
I have a sample data set that i'm trying to rank based on the values in the column 'HP':

```<code>import pandas as pd

d = {
 'unit': ['UD', 'UD', 'UD' ,'UC','UC', 'UC','UA','UA','UA','UB','UB','UB'],
 'N-D': [ 'C1', 'C2', 'C3','Q1', 'Q2', 'Q3','D1','D2','D3','E1','E2','E3'],
 'HP': [24, 24, 24,7,7,7,7,7,7,5,5,5]
}
df = pd.DataFrame(d)

df['rank']=df['HP'].rank(ascending=False, method='dense')

df
</code>```

it looks like:

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   3.0
10   5  E2   UB   3.0
11   5  E3   UB   3.0
</code>```

the 'HP' is a calculated column based on other columns (i won't show it here, but it's necessary in my real dataset)

I also tried the method='min' but the outcome looks like this:

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   4.0
4    7  Q2   UC   4.0
5    7  Q3   UC   4.0
6    7  D1   UA   4.0
7    7  D2   UA   4.0
8    7  D3   UA   4.0
9    5  E1   UB  10.0
10   5  E2   UB  10.0
11   5  E3   UB  10.0
</code>```

Units 'UC' and 'UA' tie for 2nd rank, what i'm looking for is to have the next rank which is unit 'UB' to be '4' instead of '3'. :

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   4.0
10   5  E2   UB   4.0
11   5  E3   UB   4.0
</code>```

答:
Let us try this factorize

```<code>#df['rank']=pd.factorize(df.unit)[0]+1
df['rank']=pd.factorize(df.unit+df.HP.astype(str))[0]+1

df['rank']=df.groupby('HP').rank.transform('min')
df
Out[335]:
    HP N-D unit  rank
0   24  C1   UD     1
1   24  C2   UD     1
2   24  C3   UD     1
3    7  Q1   UC     2
4    7  Q2   UC     2
5    7  Q3   UC     2
6    7  D1   UA     2
7    7  D2   UA     2
8    7  D3   UA     2
9    5  E1   UB     4
10   5  E2   UB     4
11   5  E3   UB     4
</code>```

Body:
I have a sample data set that i'm trying to rank based on the values in the column 'HP':

import pandas as pd

d = {
 'unit': ['UD', 'UD', 'UD' ,'UC','UC', 'UC','UA','UA','UA','UB','UB','UB'],
 'N-D': [ 'C1', 'C2', 'C3','Q1', 'Q2', 'Q3','D1','D2','D3','E1','E2','E3'],
 'HP': [24, 24, 24,7,7,7,7,7,7,5,5,5]
}
df = pd.DataFrame(d)

df['rank']=df['HP'].rank(ascending=False, method='dense')

df

it looks like:

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   3.0
10   5  E2   UB   3.0
11   5  E3   UB   3.0

the 'HP' is a calculated column based on other columns (i won't show it here, but it's necessary in my real dataset)

I also tried the method='min' but the outcome looks like this:

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   4.0
4    7  Q2   UC   4.0
5    7  Q3   UC   4.0
6    7  D1   UA   4.0
7    7  D2   UA   4.0
8    7  D3   UA   4.0
9    5  E1   UB  10.0
10   5  E2   UB  10.0
11   5  E3   UB  10.0

Units 'UC' and 'UA' tie for 2nd rank, what i'm looking for is to have the next rank which is unit 'UB' to be '4' instead of '3'. :

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   4.0
10   5  E2   UB   4.0
11   5  E3   UB   4.0

Body:
Let us try this factorize

#df['rank']=pd.factorize(df.unit)[0]+1
df['rank']=pd.factorize(df.unit+df.HP.astype(str))[0]+1

df['rank']=df.groupby('HP').rank.transform('min')
df
Out[335]:
    HP N-D unit  rank
0   24  C1   UD     1
1   24  C2   UD     1
2   24  C3   UD     1
3    7  Q1   UC     2
4    7  Q2   UC     2
5    7  Q3   UC     2
6    7  D1   UA     2
7    7  D2   UA     2
8    7  D3   UA     2
9    5  E1   UB     4
10   5  E2   UB     4
11   5  E3   UB     4


问:
Angular 4 project too large on disk
I found out that my Angular 4 project is around 300 MB on disk. I also figured out that the folder node_modules is the culprit for this size. Should I keep this folder out of the repository to save repository space and avoid long data traffic when updating source files on a repository?
Thanks a lot.

答:
node_modules should be ignored when the project is uploaded to CVS, doing the opposite defies the purpose of a package manager.

While package-lock.json (introduced in NPM 5) should be commited, it locks currently installed dependencies and allows to replicate the state of node_modules on npm i.

Title: Angular 4 project too large on disk


问:
Clearing activity from history unloads application
I've been playing arround with using the camera flashlight from many interfaces, Activities, Widgets and Notifications, and to coordinate all interfaces I'm using a static initialization block in a random class to instance all needed components, widgets and notifications work fine, but when launcher apps are cleared from recent apps it seems that my random class gets unloaded for some reason I dont understand.

I dont want this class to get unloaded, am I doing something wrong?

Here is my manifest:
(I've changed some stuff when I started testing what was going on)

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

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

<!--
    <uses-feature android:name="android.hardware.camera" android:required="false" />
    <uses-feature android:name="android.hardware.camera.flash" android:required="false" />
-->

<application
    android:allowBackup="true"
    android:icon="@mipmap/icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/icon_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".activity.FlashlightActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".widget.FlashlightWidget">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/flashlight_widget_info" />
    </receiver>

    <receiver android:name=".widget.WidgetReceiver" />
</application>
</code>```

This is my random class:

```<code>public class Flashlight {

    public static final Flasher FLASHER;
    public static final FlashlightActivityList ACTIVITY_LIST;
    public static final FlashlightWidgetList WIDGET_LIST;
    public static final UI UI;

    static {
        Log.d("Flashlight", "initialization");
        FLASHER = new Flasher();
        UI = new UI();
        ACTIVITY_LIST = UI.getActivityList();
        WIDGET_LIST = UI.getWidgetList();
    }
}
</code>```

The activity class does nothing weird on onCreate and onDelete events

Whenever the activity is cleared from recent apps, the next thing starting prints

```<code>"... D/Flashlight: initialization"
</code>```

and then probably crashes because there is a thread in the background switching the flash on and off, and gets created twice.

答:
but when launcher apps are cleared from recent apps it seems that my random class gets unloaded for some reason I dont understand

Your process is terminated. This can happen at any time when your app is not in the foreground.

I dont want this class to get unloaded

You do not have much of a choice. Your app's process will not run forever. You need to be able to gracefully handle this scenario.

Body:
I've been playing arround with using the camera flashlight from many interfaces, Activities, Widgets and Notifications, and to coordinate all interfaces I'm using a static initialization block in a random class to instance all needed components, widgets and notifications work fine, but when launcher apps are cleared from recent apps it seems that my random class gets unloaded for some reason I dont understand.

I dont want this class to get unloaded, am I doing something wrong?

Here is my manifest:
(I've changed some stuff when I started testing what was going on)

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

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/icon_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".activity.FlashlightActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".widget.FlashlightWidget">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/flashlight_widget_info" />
    </receiver>

    <receiver android:name=".widget.WidgetReceiver" />
</application>

This is my random class:

public class Flashlight {

    public static final Flasher FLASHER;
    public static final FlashlightActivityList ACTIVITY_LIST;
    public static final FlashlightWidgetList WIDGET_LIST;
    public static final UI UI;

    static {
        Log.d("Flashlight", "initialization");
        FLASHER = new Flasher();
        UI = new UI();
        ACTIVITY_LIST = UI.getActivityList();
        WIDGET_LIST = UI.getWidgetList();
    }
}

The activity class does nothing weird on onCreate and onDelete events

Whenever the activity is cleared from recent apps, the next thing starting prints

"... D/Flashlight: initialization"

and then probably crashes because there is a thread in the background switching the flash on and off, and gets created twice.


问:
Merge arrays inside an array in javascript
Going through the link Merge/flatten an array of arrays in JavaScript? is somewhat what i need. But with that link and many other links shows merging of arrays of two arrays. What I have is as follows

```<code>[
   {
      "setter":[
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":1
         }
      ]
   },
   {
      "setter":[
         {
            "joinedcond":"and"
         },
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":2
         }
      ]
   }
]
</code>```

That is I have an array and inside that array I have an array "setter".
What I want is actually merging all setter array as a single array. Having said the merge should produce below output

```<code>[
   {
      "setter":[
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":1
         },
         {
            "joinedcond":"and"
         },
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":2
         }
      ]
   }
]
</code>```

Help would be appreciated. Thanks

答:
Using ES6 Rest and Spread operators we can achieve the same with a recursive function call:</p>

```<code>let cdata= data.slice();//Copy the data
let condensedArray=[];

function flatten(data, ...rest){
    let [{ setter }] = data;
    condensedArray = [...condensedArray, ...setter];
    data.splice(0,1);
    data.length>0?flatten(data, ...data):console.log('Complete');
}

flatten(cdata, ...cdata);
console.log(condensedArray);
</code>```

Body:
Going through the link Merge/flatten an array of arrays in JavaScript? is somewhat what i need. But with that link and many other links shows merging of arrays of two arrays. What I have is as follows

[
   {
      "setter":[
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":1
         }
      ]
   },
   {
      "setter":[
         {
            "joinedcond":"and"
         },
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":2
         }
      ]
   }
]

That is I have an array and inside that array I have an array "setter".
What I want is actually merging all setter array as a single array. Having said the merge should produce below output

[
   {
      "setter":[
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":1
         },
         {
            "joinedcond":"and"
         },
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":2
         }
      ]
   }
]

Help would be appreciated. Thanks

Body:
Using ES6 Rest and Spread operators we can achieve the same with a recursive function call:

let cdata= data.slice();//Copy the data
let condensedArray=[];

function flatten(data, ...rest){
    let [{ setter }] = data;
    condensedArray = [...condensedArray, ...setter];
    data.splice(0,1);
    data.length>0?flatten(data, ...data):console.log('Complete');
}

flatten(cdata, ...cdata);
console.log(condensedArray);


问:
How to ignore unpacked parts of a tuple as argument of a lambda?
In Python, by convention, the underscore (_) is often used to throw away parts of an unpacked tuple, like so

```<code>>>> tup = (1,2,3)
>>> meaningfulVariableName,_,_ = tup
>>> meaningfulVariableName
1
</code>```

I'm trying to do the same for a tuple argument of a lambda. It seems unfair that it can only be done with 2-tuples...

```<code>>>> map(lambda (meaningfulVariableName,_): meaningfulVariableName*2, [(1,10), (2,20), (3,30)]) # This is fine
[2, 4, 6]

>>> map(lambda (meaningfulVariableName,_,_): meaningfulVariableName*2, [(1,10,100), (2,20,200), (3,30,300)]) # But I need this!
SyntaxError: duplicate argument '_' in function definition (<pyshell#24>, line 1)
</code>```

Any ideas why, and what the best way to achieve this is?

答:
Tuples are immutable in Python so you won't be able to "throw away" (modify) the extraneous values.

Additionally, since you don't care about what those values are, there is absolutely no need to assign them to variables.

What I would do, is to simply index the tuple at the index you are interested in, like so:

```<code>>>> list(map(lambda x: x[0] * 2, [(1,10,100), (2,20,200), (3,30,300)]))
[2, 4, 6]
</code>```

No need for *args or dummy variables.

Body:
In Python, by convention, the underscore (_) is often used to throw away parts of an unpacked tuple, like so

>>> tup = (1,2,3)
>>> meaningfulVariableName,_,_ = tup
>>> meaningfulVariableName
1

I'm trying to do the same for a tuple argument of a lambda. It seems unfair that it can only be done with 2-tuples...

>>> map(lambda (meaningfulVariableName,_): meaningfulVariableName*2, [(1,10), (2,20), (3,30)]) # This is fine
[2, 4, 6]

>>> map(lambda (meaningfulVariableName,_,_): meaningfulVariableName*2, [(1,10,100), (2,20,200), (3,30,300)]) # But I need this!
SyntaxError: duplicate argument '_' in function definition (<pyshell#24>, line 1)

Any ideas why, and what the best way to achieve this is?

Body:
Tuples are immutable in Python so you won't be able to "throw away" (modify) the extraneous values.

Additionally, since you don't care about what those values are, there is absolutely no need to assign them to variables.

What I would do, is to simply index the tuple at the index you are interested in, like so:

>>> list(map(lambda x: x[0] * 2, [(1,10,100), (2,20,200), (3,30,300)]))
[2, 4, 6]

No need for *args or dummy variables.


问:
is it possible to find and change color of the text in excel
I have two columns, the first column has a list of city names which are included next cell's text.

I want to check the second column for the city names. To make it easier I want to highlight city names in the second column's text.

I don't think it is possible to highlight a single word in text in Excel. I want to change the colour of the text, for easy recognition. I tried some highlight text rules but did not achieve what I want.

Is it possible, and if so, how can I do it?

答:
You can certainly search for the string in column A inside of Column B.

Are you any good with VBA code?  This is more of a VBA project.

Here is the core code for selection and color change, but you could loop through your target cells and look at the cell range where they could be located each time.

```<code>Sub test4String2color()
Dim strTest As String
Dim strLen As Integer
 strTest = Range("F1")
 strLen = Len(strTest)
For Each cell In Range("A1:D100")
 If InStr(cell, strTest) > 0 Then
  cell.Characters(InStr(cell, strTest), strLen).Font.Color = vbRed
 End If
Next
End Sub
</code>```

This was taken from:
https://stackoverflow.com/a/11676031/8716187

Do you know how to make a range to loop through for the text to find targets?  Really that is what would need to be added to this function which you can link to a button or something easy to call.

Body:
You can certainly search for the string in column A inside of Column B.

Are you any good with VBA code?  This is more of a VBA project.

Here is the core code for selection and color change, but you could loop through your target cells and look at the cell range where they could be located each time.

Sub test4String2color()
Dim strTest As String
Dim strLen As Integer
 strTest = Range("F1")
 strLen = Len(strTest)
For Each cell In Range("A1:D100")
 If InStr(cell, strTest) > 0 Then
  cell.Characters(InStr(cell, strTest), strLen).Font.Color = vbRed
 End If
Next
End Sub

This was taken from:
https://stackoverflow.com/a/11676031/8716187

Do you know how to make a range to loop through for the text to find targets?  Really that is what would need to be added to this function which you can link to a button or something easy to call.


问:
Hibernate design pattern question
Im working with Hibernate. It works great. However, say that I have a class that corresponds to a database table with only getters and setters and toString, equal methods. Now I would like to add some more methods for helping purpose, for example, say that I would like to get the creationdate with some added description text as shown below.

```<code>public class Client {
        private long id;
        private Calendar creationDate;
        protected String password;

            public long getId() {
            return id;
        }

        @SuppressWarnings("unused")
        private void setId(long id) {
            this.id = id;
        }

        public Calendar getCreationDate() {
            return creationDate;
        }

        public void setCreationDate(Calendar creationDate) {
            this.creationDate = creationDate;
        }

        ..
        .. some other getters and setters that corresponding to SQL columns

        //Here I would like to have some help methods. Is it recommended to put it here?
        public String getCreationDateInSecs() {
            return "Date in secs: " + creationDate.getTimeInMillis * 1000;
        }
    }
</code>```

The question is: Where should I place this method?

Should I add it in the same class as the Value Object or should I place it somewhere else? I would like to know the best practice if you know what I mean =)

Best regards

答:
Absolutely no problem in adding the method in the entity. It is where it belongs, because it operates on the internal state of the object.

You can make an utility method, like ClientUtils.getCreationDateInSeconds(client), but that's rather non-OOP.

Title: Hibernate design pattern question

Body:
Im working with Hibernate. It works great. However, say that I have a class that corresponds to a database table with only getters and setters and toString, equal methods. Now I would like to add some more methods for helping purpose, for example, say that I would like to get the creationdate with some added description text as shown below.

public class Client {
        private long id;
        private Calendar creationDate;
        protected String password;

            public long getId() {
            return id;
        }

        @SuppressWarnings("unused")
        private void setId(long id) {
            this.id = id;
        }

        public Calendar getCreationDate() {
            return creationDate;
        }

        public void setCreationDate(Calendar creationDate) {
            this.creationDate = creationDate;
        }

        ..
        .. some other getters and setters that corresponding to SQL columns

        //Here I would like to have some help methods. Is it recommended to put it here?
        public String getCreationDateInSecs() {
            return "Date in secs: " + creationDate.getTimeInMillis * 1000;
        }
    }

The question is: Where should I place this method?

Should I add it in the same class as the Value Object or should I place it somewhere else? I would like to know the best practice if you know what I mean =)

Best regards


问:
TSQL turning these multiple CASE queries into one query
I have the following CASE queries that return 1 if they find anything, and 0 otherwise. I would like to turn these into a single query that returns 1 if any of them are true, or 0 otherwise. How can I acomplish this?</p>

```<code>SELECT CASE WHEN count(PLACE.CODE) > 0 THEN 1 ELSE 0 END
FROM PLACE
WHERE STYLE = 'RED'
AND RULES = 'NO'

SELECT CASE WHEN count(GARDEN.AREA) > 0 THEN 1 ELSE 0 END
FROM GARDEN
WHERE PLACE = 'GROUND'
AND MAZE = '1'

SELECT CASE WHEN count(place_area.AVAILABLE_AREA) > 0 THEN 1 ELSE 0 END
FROM PLACE_AREA as place_area
INNER JOIN USED_PLACE as used_place
    ON used_place.COLOR = 'RED'
    AND used_place.MAKE = 'INDUSTRY'
WHERE place_area.CODE = 'FLOOR'
AND place_area.DANCE = '0'
</code>```

答:
```<code>SELECT
CASE
    WHEN
            EXISTS(
                SELECT TOP 1 1
                FROM PLACE
                WHERE STYLE = 'RED'
                AND RULES = 'NO'
                AND count(PLACE.CODE) > 0
            )
            OR EXISTS (
                SELECT TOP 1 1
                FROM GARDEN
                WHERE PLACE = 'GROUND'
                AND MAZE = '1'
                AND count(GARDEN.AREA) > 0
            )
            OR EXISTS (
                SELECT TOP 1 1
                FROM PLACE_AREA as place_area
                INNER JOIN USED_PLACE as used_place
                    ON used_place.COLOR = 'RED'
                    AND used_place.MAKE = 'INDUSTRY'
                WHERE place_area.CODE = 'FLOOR'
                AND place_area.DANCE = '0'
                AND count(place_area.AVAILABLE_AREA) > 0
                )
    THEN 1
    ELSE 0
END
</code>```

Body:
I have the following CASE queries that return 1 if they find anything, and 0 otherwise. I would like to turn these into a single query that returns 1 if any of them are true, or 0 otherwise. How can I acomplish this?

SELECT CASE WHEN count(PLACE.CODE) > 0 THEN 1 ELSE 0 END
FROM PLACE
WHERE STYLE = 'RED'
AND RULES = 'NO'

SELECT CASE WHEN count(GARDEN.AREA) > 0 THEN 1 ELSE 0 END
FROM GARDEN
WHERE PLACE = 'GROUND'
AND MAZE = '1'

SELECT CASE WHEN count(place_area.AVAILABLE_AREA) > 0 THEN 1 ELSE 0 END
FROM PLACE_AREA as place_area
INNER JOIN USED_PLACE as used_place
    ON used_place.COLOR = 'RED'
    AND used_place.MAKE = 'INDUSTRY'
WHERE place_area.CODE = 'FLOOR'
AND place_area.DANCE = '0'


问:
MS- Access VBA Converting multiple characters to Asc
For a homework project I am trying to enter characters in a single textbox as (eg:"AbC" no spaces) and have the output in a captioned label as the corresponding ASCII value written out with commas and spaces. (eg: 65, 98, 67)

```<code>Private Sub cmdCode_Click()
Dim codeInt As Integer
strInput = txtInput.value
codeInt = Asc(strInput)
lblAnswer.Caption = codeInt & ", "
End Sub
</code>```

I would like the result to look like: 65, 98, 67

I'm getting no errors but only receiving "65," as my output.

答:
Here is my solution. It assumes that the input is always going to be three (3) characters long:</p>

```<code>Private Sub cmdCode_Click()
Dim x As String
Dim y As String
Dim z As String
strInput = txtInput.value
x = Asc(Left(strInput, 1))
y = Asc(Mid(strInput, 2, 1))
z = Asc(Right(strInput, 1))
lblAnswer.Caption = x & ", " & y & ", " & z
End Sub
</code>```

Body:
For a homework project I am trying to enter characters in a single textbox as (eg:"AbC" no spaces) and have the output in a captioned label as the corresponding ASCII value written out with commas and spaces. (eg: 65, 98, 67)

Private Sub cmdCode_Click()
Dim codeInt As Integer
strInput = txtInput.value
codeInt = Asc(strInput)
lblAnswer.Caption = codeInt & ", "
End Sub

I would like the result to look like: 65, 98, 67

I'm getting no errors but only receiving "65," as my output.

Body:
Here is my solution. It assumes that the input is always going to be three (3) characters long:

Private Sub cmdCode_Click()
Dim x As String
Dim y As String
Dim z As String
strInput = txtInput.value
x = Asc(Left(strInput, 1))
y = Asc(Mid(strInput, 2, 1))
z = Asc(Right(strInput, 1))
lblAnswer.Caption = x & ", " & y & ", " & z
End Sub


问:
Eclipse Oomph windows 64 bit installer downloading linux tools
I am installing eclipse using the Oomph installer tool.

I am seeing in the logs that linux tools are getting downloaded, which is taking time as well.

I would like to understand the reason. If we are installing Eclipse using Oomph we are not sure of what plugins and jars will be downloaded. How does this work?

Collecting 1 artifacts from
  http://download.eclipse.org/linuxtools/updates-docker-nightly/

Downloading org.bouncycastle.bcprov

Fetching org.bouncycastle.bcprov_1.52.0.v20160915-1535.jar from
  http://download.eclipse.org/linuxtools/updates-docker-nightly/plugins/

答:
Any Eclipse installation based on Oomph uses a "Set Up Model" which is just a declarative description of which Eclipse plugins from which "p2 repositories" (= URLs of site that offer Eclipse plugins) are downloaded.

Are you by any chance seeing this problem when using (my...) https://github.com/vorburger/opendaylight-eclipse-setup ? ;-)  I used to include "http://download.eclipse.org/linuxtools/updates-docker-nightly/, but have long since removed it again.


问:
Check if data was updated in database
When i update data in a database is there a way to check if the value stayed the same or if a new value was entered.

```<code>  $update_email = User::find(Auth::user()->id)->update($request->all());
</code>```

The above will return true even if the data is the same or not.

答:
Start by using fill instead of update:

```<code>$user = User::find(Auth::user()->id)->fill($request->all());
</code>```

Then you will have to check each attribute to see if changed:

```<code>$emailChanged = $user->email !== $user->getOriginal('email')
</code>```

Then save before you finish up:

```<code>$user->save();
</code>```

You may be able to use a for loop to iterate through the attributes rather than hard code email like I did.  Either way the gist of the answer is, this isn't built in to eloquent and you will have to manage it yourself more or less.

Edit after seeing the other answer, there is actually a method getDirty() which will return the attributes that have changed:  https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html#method_getDirty

Title: Check if data was updated in database

Body:
When i update data in a database is there a way to check if the value stayed the same or if a new value was entered.

  $update_email = User::find(Auth::user()->id)->update($request->all());

The above will return true even if the data is the same or not.

Body:
Start by using fill instead of update:

$user = User::find(Auth::user()->id)->fill($request->all());

Then you will have to check each attribute to see if changed:

$emailChanged = $user->email !== $user->getOriginal('email')

Then save before you finish up:

$user->save();

You may be able to use a for loop to iterate through the attributes rather than hard code email like I did.  Either way the gist of the answer is, this isn't built in to eloquent and you will have to manage it yourself more or less.

Edit after seeing the other answer, there is actually a method getDirty() which will return the attributes that have changed:  https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html#method_getDirty


问:
How to compile srlua?
I made a program today, and I was wondering on how exactly to make it an executable. I've researched and I've came up with using srlua. I've asked this previously, but I usually mess up on the same instruction. I was told to 'compile srlua' While I know exactly what to do right after I compile srlua, I don't know how to compile them right now.

I've gone through a few YouTube tutorials, and I managed to find one but only in Spanish. I was able to slightly follow along until he downloaded a precompiled version of srlua, where the download link is no longer there at the same page he was at.

Would anyone be able to explain what they're trying to say?

答:
You need to tell CMake where the Lua files it needs are.

For me, the Lua includes are in /usr/include/luaX.X, where X.X is your version number, e.g. 5.3. The Lua libraries may be in /usr/lib (with filenames like libluaX.X.so).

If the locations differ for you, you can try find / | grep "lua.h" and find / | grep "liblua".

Once you've located the folder which lua.h is in, and the appropriate library file like liblua5.3.so, you need to add these to the CMakeLists.txt file in the srlua folder.
For example, using lua5.3, you might replace this line:

```<code>include_directories(${LUA_INCLUDE_DIR})
</code>```

with this one:

```<code>include_directories(/usr/include/lua5.3)
</code>```

And for the libraries, you might replace this:

```<code>target_link_libraries(glue ${LUA_LIBRARIES})
target_link_libraries(srlua ${LUA_LIBRARIES})
</code>```

with this:

```<code>target_link_libraries(glue /usr/lib/liblua5.3.so)
target_link_libraries(srlua /usr/lib/liblua5.3.so)
</code>```

After this, run cmake ./ in  the srlua folder, then run make. srlua should be built.

Note: you may also have to remove the line find_package ( Lua REQUIRED ), it was a false error for me (it only built when I removed that line).

Title: How to compile srlua?

Body:
You need to tell CMake where the Lua files it needs are.

For me, the Lua includes are in /usr/include/luaX.X, where X.X is your version number, e.g. 5.3. The Lua libraries may be in /usr/lib (with filenames like libluaX.X.so).

If the locations differ for you, you can try find / | grep "lua.h" and find / | grep "liblua".

Once you've located the folder which lua.h is in, and the appropriate library file like liblua5.3.so, you need to add these to the CMakeLists.txt file in the srlua folder.
For example, using lua5.3, you might replace this line:

include_directories(${LUA_INCLUDE_DIR})

with this one:

include_directories(/usr/include/lua5.3)

And for the libraries, you might replace this:

target_link_libraries(glue ${LUA_LIBRARIES})
target_link_libraries(srlua ${LUA_LIBRARIES})

with this:

target_link_libraries(glue /usr/lib/liblua5.3.so)
target_link_libraries(srlua /usr/lib/liblua5.3.so)

After this, run cmake ./ in  the srlua folder, then run make. srlua should be built.

Note: you may also have to remove the line find_package ( Lua REQUIRED ), it was a false error for me (it only built when I removed that line).


问:
node.js npm package installation error: ENOENT: no such file or directory
In the c9.io IDE I'm attempting to install the faker npm package with node. I appear to have successfully installed the npm but encounter errors both when installing and running.

After hitting npm install faker it appears to have successfully installed but with errors:

```<code>└── faker@4.1.0

npm WARN enoent ENOENT: no such file or directory, open '/home/ubuntu/workspace/IntroToNPM/MyShop/package.json'
npm WARN MyShop No description
npm WARN MyShop No repository field.
npm WARN MyShop No README data
npm WARN MyShop No license field.
</code>```

However the node_modules directory is there and appears to have the package components. When I try to execute my .js file using the npm I get:

```<code>/home/ubuntu/workspace/IntroToNPM/MyShop/listProducts.js:3
var randomName = faker.name.findName(); // Rowan Nikolaus
                            ^

ReferenceError: faker is not defined
    at Object.<anonymous> (/home/ubuntu/workspace/IntroToNPM/MyShop/listProducts.js:3:29)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3
</code>```

I've read through troubleshooting
and
update-node-js-version-inside-cloud-9-ide
, From what I read it seems to want me to roll back my version of node to be compatible with this npm package but that doesn't seem right.

答: I resolved this by deleting my work space and starting over. Not much of an 'answer' I know.</p>

Body:
In the c9.io IDE I'm attempting to install the faker npm package with node. I appear to have successfully installed the npm but encounter errors both when installing and running.

After hitting npm install faker it appears to have successfully installed but with errors:

└── faker@4.1.0

npm WARN enoent ENOENT: no such file or directory, open '/home/ubuntu/workspace/IntroToNPM/MyShop/package.json'
npm WARN MyShop No description
npm WARN MyShop No repository field.
npm WARN MyShop No README data
npm WARN MyShop No license field.

However the node_modules directory is there and appears to have the package components. When I try to execute my .js file using the npm I get:

/home/ubuntu/workspace/IntroToNPM/MyShop/listProducts.js:3
var randomName = faker.name.findName(); // Rowan Nikolaus
                            ^

ReferenceError: faker is not defined
    at Object.<anonymous> (/home/ubuntu/workspace/IntroToNPM/MyShop/listProducts.js:3:29)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3

I've read through troubleshooting
and
update-node-js-version-inside-cloud-9-ide
, From what I read it seems to want me to roll back my version of node to be compatible with this npm package but that doesn't seem right.


问:
WinAPI - Problem to append text to an editbox
I created a simple window with a multiline Edit Control:

```<code>Edit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), NULL,
                    WS_CHILD | WS_VISIBLE | ES_MULTILINE,
                    20, 200, 200, 200,
                    hWnd, (HMENU)EDIT, GetModuleHandle(NULL), NULL);
</code>```

If I set text using a WM_SETTEXT message, I don't get errorrs, but if I use EM_REPLACESEL
I get Error 5 (ERROR_ACCESS_DENIED):

```<code>SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}
</code>```

Same problem with EM_SETSEL:

```<code>SendMessage(GetDlgItem(hWnd, EDIT), EM_SETSEL, (WPARAM)(0),(LPARAM)(-1));
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}
</code>```

I noticed that if I send a WM_SETFOCUS message before the EM_REPLACESEL there are no error:

```<code>SendMessage(GetDlgItem(hWnd, EDIT), WM_SETFOCUS, (WPARAM)GetDlgItem(hWnd, EDIT), 0);
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* NO ERRORS */
}
</code>```

How can I resolve this problem?
Do I have to send a WM_SETFOCUS message before the EM_REPLACESEL one every time I want to append some text to my Editbox?

Thanks for help!

答:
Unfortunately GetLastError is not documented as supported for EM_REPLACESEL meaning you will have to devise some alternate strategy for catching failures.  Maybe some text length calculations would work.

Having said that, I was curious about why the access denied error was being returned.  I set a data break point on the address where SetLastError/GetLastError store the error code and found that it was deep within GDI, not directly from the edit control.  Not very helpful but at least an interesting tidbit.

Body:
I created a simple window with a multiline Edit Control:

Edit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), NULL,
                    WS_CHILD | WS_VISIBLE | ES_MULTILINE,
                    20, 200, 200, 200,
                    hWnd, (HMENU)EDIT, GetModuleHandle(NULL), NULL);

If I set text using a WM_SETTEXT message, I don't get errorrs, but if I use EM_REPLACESEL
I get Error 5 (ERROR_ACCESS_DENIED):

SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}

Same problem with EM_SETSEL:

SendMessage(GetDlgItem(hWnd, EDIT), EM_SETSEL, (WPARAM)(0),(LPARAM)(-1));
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}

I noticed that if I send a WM_SETFOCUS message before the EM_REPLACESEL there are no error:

SendMessage(GetDlgItem(hWnd, EDIT), WM_SETFOCUS, (WPARAM)GetDlgItem(hWnd, EDIT), 0);
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* NO ERRORS */
}

How can I resolve this problem?
Do I have to send a WM_SETFOCUS message before the EM_REPLACESEL one every time I want to append some text to my Editbox?

Thanks for help!


问:
Run Length Encoding in Python with List Comprehension
I have a more basic Run Length Encoding question compared to many of the questions about this topic that have already been answered. Essentially, I'm trying to take the string

```<code>string = 'aabccccaaa'
</code>```

and have it return

```<code>a2b1c4a3
</code>```

I thought that if I can manage to get all the information into a list like I have illustrated below, I would easily be able to return a2b1c4a3

```<code>test = [['a','a'], ['b'], ['c','c','c','c'], ['a','a','a']]
</code>```

I came up with the following code so far, but was wondering if someone would be able to help me figure out how to make it create the output I illustrated above.

```<code>def string_compression():
    for i in xrange(len(string)):
        prev_item, current_item = string[i-1], string[i]
        print prev_item, current_item
        if prev_item == current_item:
            <HELP>
</code>```

If anyone has any additional comments regarding more efficient ways to go about solving a question like this I am all ears!

答:
Consider using the more_itertools.run_length tool.

Demo

```<code>import more_itertools as mit

iterable = "aabccccaaa"
list(mit.run_length.encode(iterable))
# [('a', 2), ('b', 1), ('c', 4), ('a', 3)]
</code>```

Code

```<code>"".join(f"{x[0]}{x[1]}" for x in mit.run_length.encode(iterable))  # python 3.6
# 'a2b1c4a3'
</code>```

```<code>"".join(x[0] + str(x[1]) for x in mit.run_length.encode(iterable))
# 'a2b1c4a3'
</code>```

Alternative itertools/functional style:

```<code>"".join(map(str, it.chain.from_iterable(x for x in mit.run_length.encode(iterable))))
# 'a2b1c4a3'
</code>```

Note: more_itertools is a third-party library that installable via pip install more_itertools.

Body:
I have a more basic Run Length Encoding question compared to many of the questions about this topic that have already been answered. Essentially, I'm trying to take the string

string = 'aabccccaaa'

and have it return

a2b1c4a3

I thought that if I can manage to get all the information into a list like I have illustrated below, I would easily be able to return a2b1c4a3

test = [['a','a'], ['b'], ['c','c','c','c'], ['a','a','a']]

I came up with the following code so far, but was wondering if someone would be able to help me figure out how to make it create the output I illustrated above.

def string_compression():
    for i in xrange(len(string)):
        prev_item, current_item = string[i-1], string[i]
        print prev_item, current_item
        if prev_item == current_item:
            <HELP>

If anyone has any additional comments regarding more efficient ways to go about solving a question like this I am all ears!

Body:
Consider using the more_itertools.run_length tool.

Demo

import more_itertools as mit

iterable = "aabccccaaa"
list(mit.run_length.encode(iterable))
# [('a', 2), ('b', 1), ('c', 4), ('a', 3)]

Code

"".join(f"{x[0]}{x[1]}" for x in mit.run_length.encode(iterable))  # python 3.6
# 'a2b1c4a3'

"".join(x[0] + str(x[1]) for x in mit.run_length.encode(iterable))
# 'a2b1c4a3'

Alternative itertools/functional style:

"".join(map(str, it.chain.from_iterable(x for x in mit.run_length.encode(iterable))))
# 'a2b1c4a3'

Note: more_itertools is a third-party library that installable via pip install more_itertools.


问:
XSLT: node()? vs node()*
I've been working through some legacy code in XSLT in order to replace it with something in a more widely used language, and I've hit something about which I can't find a reference.

What's the difference between

```<code><xsl:variable name="following_actions" as="node()*">
</code>```

and

```<code><xsl:variable name="following_actions" as="node()?">
</code>```

I'm accustomed to seeing the asterisk version give me a list of records matching some condition specified in the body of the xsl:variable block, but I don't think I've seen the question-mark version before.

Directly relevant remedial references happily accepted.  I believe I'm operating on XSLT 2.0, FWIW.

答:
Like with regular expressions, ?, *, and + designate optionality and multiplicity:

node() means 1 node.

node()? means 0 or 1 nodes.

node()+ means 1 or more nodes.

node()* means 0 or more nodes.

Title: XSLT: node()? vs node()*

Body:
I've been working through some legacy code in XSLT in order to replace it with something in a more widely used language, and I've hit something about which I can't find a reference.

What's the difference between

<xsl:variable name="following_actions" as="node()*">

and

<xsl:variable name="following_actions" as="node()?">

I'm accustomed to seeing the asterisk version give me a list of records matching some condition specified in the body of the xsl:variable block, but I don't think I've seen the question-mark version before.

Directly relevant remedial references happily accepted.  I believe I'm operating on XSLT 2.0, FWIW.


答:
You can check it before:</p>

```<code>$user = User::find(Auth::user()->id);

$user->fill(request()->all();

if($user->isDirty()) {
    // update happened
}

$user->save();
</code>```

Title: Check if data was updated in database

Body:
You can check it before:

$user = User::find(Auth::user()->id);

$user->fill(request()->all();

if($user->isDirty()) {
    // update happened
}

$user->save();


问:
Tracking how many times an image loads and gets clicked
A client asked me to create an image for him, and he wants me to set up a script that will track how many times the image is clicked AND how many times the image is loaded. He wants this displayed for him in the WP dashboard so I don't think I can use the servers access logs. I have never done anything like this, so I turn to the stackoverflow community. :)

Can somebody just point me in the right direction? Thanks a million.

答:
The easiest way is probably just to use to the access logs of your web server (for Apache, the most common one, check: http://httpd.apache.org/docs/2.0/logs.html). Here every hit (both the link page and the image) is logged, so you can get the information from that.

Most web servers have some tools available that can make this a bit easier than counting by hand (or with grep); just search the web for your web server + log analyzer (e.g. http://awstats.sourceforge.net/ for Apache). If you're not hosting the site yourself, chances are that your web host has pre-installed such a tool for you already.


问:
Always get previous state in React app
In relation to my previous question, I'm doing this to store the right state:

```<code>if (value === 'checkpoint')
{
  if (checked1)
  {
    this.setState({checked1 : false})
    localStorage.setObject('checked1', false)
  }
  else
  {
    this.setState({checked1 : true})
    localStorage.setObject('checked1', true)
  }
}
</code>```

Now I have multiple checkboxes (let's say I have four). One for ALL checkboxes, and the other 3 for categories. I want my app to detect when the three category checkboxes are checked, and check the ALL checkbox automatically. When any of the category checkboxes are unchecked, the ALL checkbox will uncheck itself.

I tried this code:

```<code>  if (checked1 && checked2 && checked3) {
    this.setState({checkedAll: true})
  } else {
    this.setState({checkedAll: false})
  }
</code>```

But the other 3 checkbox (checked1, checked2, checked3) will always get a previous state.

How do I get the right state so that my checkedAll functions correctly?

答:
I think it's more about where in the lifecycle you place this code. componentDidUpdate seems like a resonable candidate. For example:

```<code>componentDidUpdate () {
  const { checked1, checked2, checked3 } = this.state
  const checkedAll = checked1 && checked2 && checked3
  if (checkedAll === this.state.checkedAll) {
    return
  }
  this.setState({ checkedAll })
}
</code>```

In other words, as soon as the boxes all update their state, checkAll naturally will too.

Title: Always get previous state in React app

Body:
In relation to my previous question, I'm doing this to store the right state:

if (value === 'checkpoint')
{
  if (checked1)
  {
    this.setState({checked1 : false})
    localStorage.setObject('checked1', false)
  }
  else
  {
    this.setState({checked1 : true})
    localStorage.setObject('checked1', true)
  }
}

Now I have multiple checkboxes (let's say I have four). One for ALL checkboxes, and the other 3 for categories. I want my app to detect when the three category checkboxes are checked, and check the ALL checkbox automatically. When any of the category checkboxes are unchecked, the ALL checkbox will uncheck itself.

I tried this code:

  if (checked1 && checked2 && checked3) {
    this.setState({checkedAll: true})
  } else {
    this.setState({checkedAll: false})
  }

But the other 3 checkbox (checked1, checked2, checked3) will always get a previous state.

How do I get the right state so that my checkedAll functions correctly?

Body:
I think it's more about where in the lifecycle you place this code. componentDidUpdate seems like a resonable candidate. For example:

componentDidUpdate () {
  const { checked1, checked2, checked3 } = this.state
  const checkedAll = checked1 && checked2 && checked3
  if (checkedAll === this.state.checkedAll) {
    return
  }
  this.setState({ checkedAll })
}

In other words, as soon as the boxes all update their state, checkAll naturally will too.


问:
Bitbake's order of execution of Python-based run files?
I'm looking at run. files for a recipe under Yocto 2.2.  Some of the Python ones have the following structure:

```<code>def do_whatever(d):
   # [...]
   bb.build.exec_func("sub_function_foo", d)
   bb.build.exec_func("sub_function_bar", d)

do_whatever(d)

def sub_function_foo(d):
   [...]

def sub_function_bar(d):
   [...]
</code>```

The executed functions seem to be forward-referenced. If this is run like normal Python, then at the time do_whatever is executed, the sub_function_foo and sub_function_bar are not yet defined.

How is this supposed to work?

Is the bitbake exec_func mechanism just queuing jobs to be run later, which happens after this file is processed?

Or else, is this processed by a custom loader rather than Python, which puts definitions before top-level calls? (If so, why do that rather than simply generate the code in the proper order in the first place and hand it off to Python?)

答:
The python run files themselves are debug output generated by bitbake with the function contents contained within them, they are not actually executed. So you can use them for debugging but they're not executable in their current form. This is something I've thought about fixing but its not been a priority right now. It would also mean dumping a static copy of the datastore into the file to construct objects like 'd'.

Just for reference, the shell script run files are actually executed.

Body:
I'm looking at run. files for a recipe under Yocto 2.2.  Some of the Python ones have the following structure:

def do_whatever(d):
   # [...]
   bb.build.exec_func("sub_function_foo", d)
   bb.build.exec_func("sub_function_bar", d)

do_whatever(d)

def sub_function_foo(d):
   [...]

def sub_function_bar(d):
   [...]

The executed functions seem to be forward-referenced. If this is run like normal Python, then at the time do_whatever is executed, the sub_function_foo and sub_function_bar are not yet defined.

How is this supposed to work?

Is the bitbake exec_func mechanism just queuing jobs to be run later, which happens after this file is processed?

Or else, is this processed by a custom loader rather than Python, which puts definitions before top-level calls? (If so, why do that rather than simply generate the code in the proper order in the first place and hand it off to Python?)


问:
Bootstrap issue with Wordpress Menu
I have integrated the bootstrap Navbar with my Wordpress theme I am developing. However my menu is squished together and there is no spacing or design within the ul & li tags. I have tried everything possible to make this work properly with bootstrap but I am lost.

Can anyone point me in the right direction to fix this issue or possibly give me a solution? Thank you for any help.

live site: https://publifiedlabs.com/sandbox-theme/

Here is my block of code

```<code>           <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container-fluid">
                <div class="navbar-header">
                    <a class="navbar-brand" href="<?php echo home_url( '/' ); ?>">
                    <img src="https://publifiedlabs.com/wp-content/uploads/2016/04/main-logo.png" alt="<?php //get alt tag for image ?>">
                    </a>
                </div> <!-- ./navbar-header -->
                    <div class="search-form-container">
                    <?php get_search_form(); ?>
                </div>
                <!-- Begin wp_nav_menu -->
                        <div class="navbar navbar-nav float-md-right" id="navbarSupportedContent">
                        <?php   // This brings in the menu in the proper style with bootstrap
                                    wp_nav_menu( array(
                                        'theme_location'    =>'primary',
                                        //'depth'             => 2,
                                        'container'         => '',
                                        'fallback_cb'       => '',
                                        //'menu_class'        => 'navbar-nav mr-auto',
                                        'items_wrap'        => '<ul class="navbar-nav">%3$s</ul>',
                                        'walker'            => new pbf_walker_nav_primary(),
                                        'echo'              => true
                                        )
                                    ); ?>
            </div> <!-- /.container-fluid -->
        </nav>
</code>```

Here is the outputed HTML:

```<code><nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                    <div class="container-fluid">
                        <div class="navbar-header">
                            <a class="navbar-brand" href="https://publifiedlabs.com/sandbox-theme/">
                            <img src="https://publifiedlabs.com/wp-content/uploads/2016/04/main-logo.png" alt="">
                            </a>
                        </div> <!-- ./navbar-header -->
                            <div class="search-form-container">
                            <form role="search" method="get" action="https://publifiedlabs.com/sandbox-theme/">
    <input type="search" class="form-control" placeholder="Search" value="" name="s" title="Search">
</form>                        </div>
                        <!-- Begin wp_nav_menu -->
                                <div class="navbar navbar-nav float-md-right" id="navbarSupportedContent">
                                    <ul class="navbar-nav"><li id="menu-item-16" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-6 current_page_item active menu-item-16 nav-item"><a href="https://publifiedlabs.com/sandbox-theme/">Home</a></li>
    <li id="menu-item-15" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children dropdown menu-item-15 nav-item"><a href="https://publifiedlabs.com/sandbox-theme/about-us/" class="dropdown-toggle" data-toggle="dropdown">About <b class="caret"></b></a>
    <ul class="dropdown-menu depth_0 nav navbar-nav">
        <li id="menu-item-35" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-35 nav-item"><a href="#">Contact</a></li>
    </ul>
    </li>
    <li id="menu-item-32" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-32 nav-item"><a href="https://publifiedlabs.com/sandbox-theme/blog/">Blog</a></li>
    </ul>                    </div> <!-- /.container-fluid -->
                    </div></nav>
</code>```

Image of Menu Issue:

答:
In your first code example delete navbar-expand-lg from this

```<code><nav class="navbar navbar-expand-lg navbar-dark bg-dark">
</code>```

Title: Bootstrap issue with Wordpress Menu

Body:
I have integrated the bootstrap Navbar with my Wordpress theme I am developing. However my menu is squished together and there is no spacing or design within the ul & li tags. I have tried everything possible to make this work properly with bootstrap but I am lost.

Can anyone point me in the right direction to fix this issue or possibly give me a solution? Thank you for any help.

live site: https://publifiedlabs.com/sandbox-theme/

Here is my block of code

                    <a class="navbar-brand" href="<?php echo home_url( '/' ); ?>">
                    <img src="https://publifiedlabs.com/wp-content/uploads/2016/04/main-logo.png" alt="<?php //get alt tag for image ?>">

                    <?php get_search_form(); ?>

                        <?php   // This brings in the menu in the proper style with bootstrap
                                    wp_nav_menu( array(
                                        'theme_location'    =>'primary',
                                        //'depth'             => 2,
                                        'container'         => '',
                                        'fallback_cb'       => '',
                                        //'menu_class'        => 'navbar-nav mr-auto',
                                        'items_wrap'        => '
%3$s
',
                                        'walker'            => new pbf_walker_nav_primary(),
                                        'echo'              => true
                                        )
                                    ); ?>

Here is the outputed HTML:

                            <form role="search" method="get" action="https://publifiedlabs.com/sandbox-theme/">
    <input type="search" class="form-control" placeholder="Search" value="" name="s" title="Search">
</form>

Home

About

Contact

Blog

Image of Menu Issue:

Body:
In your first code example delete navbar-expand-lg from this

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">


问:
My multiplication in python not working
I'm trying to get a multiplication inside a for loop working on the code below:

```<code>#products list and it's values per unity
tomato = 2
potato = 3
carrot = 1
pricePaid = int()

print("Welcome to my grocery shop!\n")

productList = ["Potato", "Tomato", "Carrot"]

print("What will you want today?\n""We have:")
print(*productList, sep=', ')
product = input("What will it be? ")

quantity = int(input("And how many do you want? "))

for productChoice in product:
    if productChoice == "Potato":
        pricePaid = quantity * potato
    elif productChoice == "Tomato":
        pricePaid = quantity * tomato
    elif productChoice == "Carrot":
        pricePaid = quantity * carrot

print("Here's your bag with {0} {1}s. The total is ${2:.2f}.".format(quantity, product, pricePaid))
</code>```

but I'm getting a $0.00 as my results where it should be the quantity * productPrice:

```<code>"Here's your bag with 1 Tomatos. The total is $0.00."
</code>```

Why is it failing? What am I missing here?

I'm using Python 3.x

Thanks in advance!

答:
This is causing your issues:

```<code>for productChoice in product:
    if productChoice == "Potato":
        pricePaid = quantity * potato
    elif productChoice == "Tomato":
        pricePaid = quantity * tomato
    elif productChoice == "Carrot":
        pricePaid = quantity * carrot
</code>```

If we changed that to this quickly we can see why

```<code>for productChoice in product:
    print(productChoice)
</code>```

The output to that with product being "Tomato"

```<code>T
o
m
a
t
o
</code>```

What you are doing here is iterating over each character in the string product, when you don't actually want this behavior. The fix to your problem is just removing the for loop, keeping the selection only.

This is all you need:

```<code>if product == "Potato":
    pricePaid = quantity * potato
elif product == "Tomato":
    pricePaid = quantity * tomato
elif product == "Carrot":
    pricePaid = quantity * carrot
</code>```

Hope this helps!

Title: My multiplication in python not working

Body:
I'm trying to get a multiplication inside a for loop working on the code below:

#products list and it's values per unity
tomato = 2
potato = 3
carrot = 1
pricePaid = int()

print("Welcome to my grocery shop!\n")

productList = ["Potato", "Tomato", "Carrot"]

print("What will you want today?\n""We have:")
print(*productList, sep=', ')
product = input("What will it be? ")

quantity = int(input("And how many do you want? "))

for productChoice in product:
    if productChoice == "Potato":
        pricePaid = quantity * potato
    elif productChoice == "Tomato":
        pricePaid = quantity * tomato
    elif productChoice == "Carrot":
        pricePaid = quantity * carrot

print("Here's your bag with {0} {1}s. The total is ${2:.2f}.".format(quantity, product, pricePaid))

but I'm getting a $0.00 as my results where it should be the quantity * productPrice:

"Here's your bag with 1 Tomatos. The total is $0.00."

Why is it failing? What am I missing here?

I'm using Python 3.x

Thanks in advance!

Body:
This is causing your issues:

for productChoice in product:
    if productChoice == "Potato":
        pricePaid = quantity * potato
    elif productChoice == "Tomato":
        pricePaid = quantity * tomato
    elif productChoice == "Carrot":
        pricePaid = quantity * carrot

If we changed that to this quickly we can see why

for productChoice in product:
    print(productChoice)

The output to that with product being "Tomato"

T
o
m
a
t
o

What you are doing here is iterating over each character in the string product, when you don't actually want this behavior. The fix to your problem is just removing the for loop, keeping the selection only.

This is all you need:

if product == "Potato":
    pricePaid = quantity * potato
elif product == "Tomato":
    pricePaid = quantity * tomato
elif product == "Carrot":
    pricePaid = quantity * carrot

Hope this helps!


问:
User string input to go until \0 in c
I am trying to simply get a user input string. The string is saved (scanf) when the person hits enter or the string hits the NULL character. Yet, when I run my program, and type in the string, it continues input until I type \n or \0 (whichever I have in my if statement. Here's my code:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MSL 30

char intersperse(char);
char widen_stars(char);

int main(int argc, char *argv[])
{
    char *p, *q, *str1[MSL], *str2[MSL];

    if(str1[MSL+1] != '\0'){
    printf("Please enter a string of maximum 30 characters: ");
    scanf("%s\n", str1[MSL]);

    }
    printf("%s\n", str1[MSL]);

}
</code>```

This is by no means finished code, i'm just in the process of writing my program when I snagged this annoying bug. The +1 on my MSL is to make sure the NULL character is read so my string doesn't yell at me, idk if it's necessary, but it's a precaution. Thank you answerers.

答:
There are various problems with your code, not just a simple bug. I'll try to describe some of them here.

Turn on compiler warnings. For example, if your array is size 30, there is no element at index 30 (indexes would go from 0 to 29). Your compiler could have warned you about that and other problems.

Store a string in a char array or pointer, but not in a char pointers array. When you wrote:

```<code>char *str1[MSL]
</code>```

You are creating an array of pointers to char, or an array of strings. However, since you're dealing with pointers to char as strings, you'd need to allocate space for them yourself. That's another concept. You probably meant to write an array of char like this:

```<code>char str1[MSL]
char *p, *q, str1[MSL], str2[MSL]; /* in your declaration */
</code>```

Enter at maximum 29 characters. If your string holds 30 char, and you need 1 to mark the null at the end, you've got 29 remaining usable chars. Or… change MSL to 31.

Consider dropping the \n from your scanf format. It will make it read all whitespace (which is what \n represents in a format) waiting for the next non-whitespace. Thus, the input somestring<enter> for example won't be sent directly to your program until the next non-whitespace or EOF.

Give scanf an address. That could be just the array name (which translates to the first element address) or a pointer if you were working with them.

```<code>scanf("%s", str1);
scanf("%s", strptr); /* strptr is a char pointer pointing
                          to previously allocated space */
</code>```

You can limit the length of what scanf reads. To be safe:

```<code>scanf("%29s", str1);
</code>```

Don't use uninitialised data in comparisons. When you wrote if(str1[MSL+1] != '\0'), what did you expect str1 to contain if you had never stored anything yet?

```<code>int
main(int argc, char **argv)
{
    char *p, *q, str1[31], str2[31]; /* a lot of unused variables */

    printf("Please enter a string of maximum 30 characters: ");
    scanf("%30s", str1);

    printf("%s\n", str1);

    return 0;
}
</code>```

Title: User string input to go until \0 in c

Body:
I am trying to simply get a user input string. The string is saved (scanf) when the person hits enter or the string hits the NULL character. Yet, when I run my program, and type in the string, it continues input until I type \n or \0 (whichever I have in my if statement. Here's my code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MSL 30

char intersperse(char);
char widen_stars(char);

int main(int argc, char *argv[])
{
    char *p, *q, *str1[MSL], *str2[MSL];

    if(str1[MSL+1] != '\0'){
    printf("Please enter a string of maximum 30 characters: ");
    scanf("%s\n", str1[MSL]);

    }
    printf("%s\n", str1[MSL]);

}

This is by no means finished code, i'm just in the process of writing my program when I snagged this annoying bug. The +1 on my MSL is to make sure the NULL character is read so my string doesn't yell at me, idk if it's necessary, but it's a precaution. Thank you answerers.

Body:
There are various problems with your code, not just a simple bug. I'll try to describe some of them here.

Turn on compiler warnings. For example, if your array is size 30, there is no element at index 30 (indexes would go from 0 to 29). Your compiler could have warned you about that and other problems.

Store a string in a char array or pointer, but not in a char pointers array. When you wrote:

char *str1[MSL]

You are creating an array of pointers to char, or an array of strings. However, since you're dealing with pointers to char as strings, you'd need to allocate space for them yourself. That's another concept. You probably meant to write an array of char like this:

char str1[MSL]
char *p, *q, str1[MSL], str2[MSL]; /* in your declaration */

Enter at maximum 29 characters. If your string holds 30 char, and you need 1 to mark the null at the end, you've got 29 remaining usable chars. Or… change MSL to 31.

Consider dropping the \n from your scanf format. It will make it read all whitespace (which is what \n represents in a format) waiting for the next non-whitespace. Thus, the input somestring<enter> for example won't be sent directly to your program until the next non-whitespace or EOF.

Give scanf an address. That could be just the array name (which translates to the first element address) or a pointer if you were working with them.

scanf("%s", str1);
scanf("%s", strptr); /* strptr is a char pointer pointing
                          to previously allocated space */

You can limit the length of what scanf reads. To be safe:

scanf("%29s", str1);

Don't use uninitialised data in comparisons. When you wrote if(str1[MSL+1] != '\0'), what did you expect str1 to contain if you had never stored anything yet?

int
main(int argc, char **argv)
{
    char *p, *q, str1[31], str2[31]; /* a lot of unused variables */

    printf("Please enter a string of maximum 30 characters: ");
    scanf("%30s", str1);

    printf("%s\n", str1);

    return 0;
}