问:
Changing Mac volume to a variable in terminal
I'm trying to create a shell script in which I change the volume to max, use the Say command and then change the volume back. So far I'm able to save the old volume as a variable, change the volume to maximum and use the say command. The only trouble I'm having is changing the volume to the variable value.

What I have:

```<code>#!/bin/bash

VOL=$(osascript -e 'output volume of (get volume settings)')
osascript -e 'set Volume 100'
say Hello
osascript -e "set Volume $VOL"
</code>```

答:
For some reason, set Volume x uses a volume scale of 0 to 7, while output volume of (get volume settings) uses a scale of 0 to 100. You could multiply by 0.07, but there's an easier solution, pointed out by Antal Spector-Zabusky: use set volume output volume n, which uses the 0-100 scale.

```<code>vol=$(osascript -e 'output volume of (get volume settings)')
osascript -e "set volume output volume 100"
#say "Hello"
osascript -e "set volume output volume $vol"
</code>```

Body:
I'm trying to create a shell script in which I change the volume to max, use the Say command and then change the volume back. So far I'm able to save the old volume as a variable, change the volume to maximum and use the say command. The only trouble I'm having is changing the volume to the variable value.

What I have:

#!/bin/bash

VOL=$(osascript -e 'output volume of (get volume settings)')
osascript -e 'set Volume 100'
say Hello
osascript -e "set Volume $VOL"

Body:
For some reason, set Volume x uses a volume scale of 0 to 7, while output volume of (get volume settings) uses a scale of 0 to 100. You could multiply by 0.07, but there's an easier solution, pointed out by Antal Spector-Zabusky: use set volume output volume n, which uses the 0-100 scale.

vol=$(osascript -e 'output volume of (get volume settings)')
osascript -e "set volume output volume 100"
#say "Hello"
osascript -e "set volume output volume $vol"


来源: stackexchange

问:
Web Scraping a Table Over Many Days
I've been webscraping using XML::readHTMLTable, and I'm now trying to learn how to scrape on a more granular level. My motivation came from trying to scrape a table on a website over multiple days that changes positions (e.g. yesterday it was 4th table on the page, today it was 2nd table on the page, etc.). I'm going to use a website which posts vegas-odds for various sports as an example, I will specifically be trying to pull NBA data.

```<code>URL1 = "http://www.scoresandodds.com/grid_20161123.html"
URL2 = "http://www.scoresandodds.com/grid_20161125.html"
</code>```

You'll notice that the NBA table is the first table in URL1 and it's the second table in URL2. Recognizing that NBA is the first table, here's how I would pull it for the first URL:

```<code>library(XML)

URL1 = "http://www.scoresandodds.com/grid_20161123.html"
exTable = readHTMLTable(URL1)[[1]] %>%
# Find first blank, since NBA is the first table #
  head(which(exTable[,1] == "")[1] - 1)
</code>```

Then I would clean it up from there. I know that this is not the best way to do it, before even considering that I'd want to loop over many days, due to all the cleaning that needs to take place. It would be better to learn how to grab specific objects within a webpage table.

I've played around with rvest some and I know I can get nodes that look like "td.line" for Vegas lines, but I get lost trying to select the nodes for specific tables (css = "#nba > div.sport" or something?). I don't necessarily want the answer to this specific example, but learning how to do this example would allow me to apply the skills to many other cases. Thanks in advance for your help.

答:
You're on a good track here; you need a more apt CSS or XPath selector. Using rvest, you can grab both with the same code if your selector is good enough:

library(rvest)

URL1 = "http://www.scoresandodds.com/grid_20161123.html"
URL2 = "http://www.scoresandodds.com/grid_20161125.html"

html1 <- URL1 %>% read_html()
df1 <- html1 %>% html_node('#nba ~ div table') %>% html_table()

html2 <- URL2 %>% read_html()
df2 <- html2 %>% html_node('#nba ~ div table') %>% html_table()

str(df1)
#> 'data.frame':    65 obs. of  7 variables:
#>  $ Team          : chr  "7:05 PM EST" "701 PHOENIX SUNS" "702 ORLANDO MAGIC" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Open          : chr  "7:05 PM EST" "206.5" "-4.5" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Line Movements: chr  "7:05 PM EST" "207.5 / 208 / 209.5" "-4 -15 / -4.5  / -4.5 -05" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Current       : chr  "7:05 PM EST" "210" "-4" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Moneyline     : chr  "7:05 PM EST" "+155" "-175" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Halftime      : chr  "7:05 PM EST" "109" "-4" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Scores        : chr  "7:05 PM EST" "92Under 210" "87final" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...

str(df2)
#> 'data.frame':    75 obs. of  7 variables:
#>  $ Team          : chr  "1:05 PM EST" "701 SAN ANTONIO SPURS" "702 BOSTON CELTICS" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Open          : chr  "1:05 PM EST" "-2.5" "203.5" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Line Movements: chr  "1:05 PM EST" "-3  / -3.5 -15 / -3.5" "199 / 200 / 201" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Current       : chr  "1:05 PM EST" "-3.5 -05" "201.5" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Moneyline     : chr  "1:05 PM EST" "-155" "+135" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Halftime      : chr  "1:05 PM EST" "-4.5" "106" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Scores        : chr  "1:05 PM EST" "109Over 201.5" "103final" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
```

In this case, the CSS selector

looks for a node with an ID of nba, then

looks for a div after that, then

selects the table node inside of it.

You can write the same thing in XPath, if you like, which would let you use the XML package, if you really like. If you want to up your CSS selector skills, the tutorial linked in ?rvest::html_node is fun and efficient.

If you want to scrape a lot of similar URLs at once, you can put them in a vector and iterate over it with lapply, or more conveniently purrr::map_df. Scrape responsibly; it's kind to put a Sys.sleep call in the anonymous function so as to behave more like a normal site visitor.

ContentLicense: CC BY-SA 3.0

Title: Web Scraping a Table Over Many Days

Body:
I've been webscraping using XML::readHTMLTable, and I'm now trying to learn how to scrape on a more granular level. My motivation came from trying to scrape a table on a website over multiple days that changes positions (e.g. yesterday it was 4th table on the page, today it was 2nd table on the page, etc.). I'm going to use a website which posts vegas-odds for various sports as an example, I will specifically be trying to pull NBA data.

URL1 = "http://www.scoresandodds.com/grid_20161123.html"
URL2 = "http://www.scoresandodds.com/grid_20161125.html"

You'll notice that the NBA table is the first table in URL1 and it's the second table in URL2. Recognizing that NBA is the first table, here's how I would pull it for the first URL:

library(XML)

URL1 = "http://www.scoresandodds.com/grid_20161123.html"
exTable = readHTMLTable(URL1)[[1]] %>%
# Find first blank, since NBA is the first table #
  head(which(exTable[,1] == "")[1] - 1)

Then I would clean it up from there. I know that this is not the best way to do it, before even considering that I'd want to loop over many days, due to all the cleaning that needs to take place. It would be better to learn how to grab specific objects within a webpage table.

I've played around with rvest some and I know I can get nodes that look like "td.line" for Vegas lines, but I get lost trying to select the nodes for specific tables (css = "#nba > div.sport" or something?). I don't necessarily want the answer to this specific example, but learning how to do this example would allow me to apply the skills to many other cases. Thanks in advance for your help.

Body:
You're on a good track here; you need a more apt CSS or XPath selector. Using rvest, you can grab both with the same code if your selector is good enough:

library(rvest)

URL1 = "http://www.scoresandodds.com/grid_20161123.html"
URL2 = "http://www.scoresandodds.com/grid_20161125.html"

html1 <- URL1 %>% read_html()
df1 <- html1 %>% html_node('#nba ~ div table') %>% html_table()

html2 <- URL2 %>% read_html()
df2 <- html2 %>% html_node('#nba ~ div table') %>% html_table()

str(df1)
#> 'data.frame':    65 obs. of  7 variables:
#>  $ Team          : chr  "7:05 PM EST" "701 PHOENIX SUNS" "702 ORLANDO MAGIC" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Open          : chr  "7:05 PM EST" "206.5" "-4.5" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Line Movements: chr  "7:05 PM EST" "207.5 / 208 / 209.5" "-4 -15 / -4.5  / -4.5 -05" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Current       : chr  "7:05 PM EST" "210" "-4" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Moneyline     : chr  "7:05 PM EST" "+155" "-175" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Halftime      : chr  "7:05 PM EST" "109" "-4" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...
#>  $ Scores        : chr  "7:05 PM EST" "92Under 210" "87final" "PHO-F-T.J. Warren-? | TV: FS-Florida, DTV: 654" ...

str(df2)
#> 'data.frame':    75 obs. of  7 variables:
#>  $ Team          : chr  "1:05 PM EST" "701 SAN ANTONIO SPURS" "702 BOSTON CELTICS" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Open          : chr  "1:05 PM EST" "-2.5" "203.5" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Line Movements: chr  "1:05 PM EST" "-3  / -3.5 -15 / -3.5" "199 / 200 / 201" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Current       : chr  "1:05 PM EST" "-3.5 -05" "201.5" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Moneyline     : chr  "1:05 PM EST" "-155" "+135" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Halftime      : chr  "1:05 PM EST" "-4.5" "106" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...
#>  $ Scores        : chr  "1:05 PM EST" "109Over 201.5" "103final" "TV: CSN-New England, FS-Southwest, DTV: 642, 676" ...

In this case, the CSS selector

looks for a node with an ID of nba, then

looks for a div after that, then

selects the table node inside of it.

You can write the same thing in XPath, if you like, which would let you use the XML package, if you really like. If you want to up your CSS selector skills, the tutorial linked in ?rvest::html_node is fun and efficient.

If you want to scrape a lot of similar URLs at once, you can put them in a vector and iterate over it with lapply, or more conveniently purrr::map_df. Scrape responsibly; it's kind to put a Sys.sleep call in the anonymous function so as to behave more like a normal site visitor.


问:
How to access variables from base workspace within function?
I am a nested function inside a function and I am calling variables from base workspace. Note that guiel is in base workspace.

```<code>function callback(~,~)
    vars.dropheight = str2num(get(edit(2),'String'));
    vars.armradius = str2num(get(edit(1),'String'));
    kiddies = get(guiel.hAX(3),'Children');
    delete(kiddies);
    clear kiddies;
    set(guiel.tfPanel,'Visible','off','Position',cnst.tfPanelpos);
    set(guiel.hAX(1),'Position',cnst.axpos1);
    if ishandle(guiel.hAX(2))
    set(guiel.hAX(2),'Position',cnst.axpos2);
    end
    eval(get(guiel.hPB(4),'Callback'));
end
</code>```

答:
The best way, in my opinion, is to store guiel into guidata.

```<code>guidata(hFig, guiel); % hFig can be gcf for top figure
</code>```

and access it in callback by

```<code>guiel = guidata(hFig);
</code>```

One of the alternatives is to pass the variable as input to callback by defining it as

```<code>{@callback, guiel}
</code>```

The callback function definition will be

```<code>function callback(~, ~, guiel)
</code>```

If you really hate these methods, a simple way is to define it as global in base and your callback. But this is something one tries to avoid for both performance and code maintainability consideration.

Body:
I am a nested function inside a function and I am calling variables from base workspace. Note that guiel is in base workspace.

function callback(~,~)
    vars.dropheight = str2num(get(edit(2),'String'));
    vars.armradius = str2num(get(edit(1),'String'));
    kiddies = get(guiel.hAX(3),'Children');
    delete(kiddies);
    clear kiddies;
    set(guiel.tfPanel,'Visible','off','Position',cnst.tfPanelpos);
    set(guiel.hAX(1),'Position',cnst.axpos1);
    if ishandle(guiel.hAX(2))
    set(guiel.hAX(2),'Position',cnst.axpos2);
    end
    eval(get(guiel.hPB(4),'Callback'));
end

Body:
The best way, in my opinion, is to store guiel into guidata.

guidata(hFig, guiel); % hFig can be gcf for top figure

and access it in callback by

guiel = guidata(hFig);

One of the alternatives is to pass the variable as input to callback by defining it as

{@callback, guiel}

The callback function definition will be

function callback(~, ~, guiel)

If you really hate these methods, a simple way is to define it as global in base and your callback. But this is something one tries to avoid for both performance and code maintainability consideration.


问:
Chaining callsArgWith on stub
I have gone through the documentation understand what exactly is stub.callsArgWith here:
    http://sinonjs.org/releases/v1.17.7/stubs/

But I could not not understand what it makes sense when we chain it like below:

```<code>stub.callsArgWith(1, null, "ok")
    .callsArgWith(1, new Error("Error!"));
</code>```

So, basically what it mean is param at index 1 is a callback function and it should be called with first param = null and 2nd param as "ok". But what I could not understand is in what situation we do chaining of callsArgWith and in what sequence are they get used.
Please help me in understanding what exactly is the meaning of above two lines how they will be executed, mean when will it take 'Ok' and when will it return an error.

答:
In older versions of Sinon (specifically versions 1.5 - 1.7), this was how you described behaviour for consecutive calls.

Otherwise, the second callsArgWith call replaces the behaviour of the first callsArgWith.

So in the your example (and assuming the version of Sinon is v1.5 - 1.7):

```<code>stub.callsArgWith(1, null, "ok")
    .callsArgWith(1, new Error("Error!"));
</code>```

When the stubbed function is called for the first time,
it will call the 2nd parameter of the stubbed function with the parameters null and "ok".

The second time the stubbed function is called, it will call the 2nd parameter of the stubbed function with an Error object.

So in the your example (and assuming the version of Sinon is NOT v1.5 - 1.7):

```<code>stub.callsArgWith(1, null, "ok")
    .callsArgWith(1, new Error("Error!"));
</code>```

Every time the stubbed function is called it will call the 2nd parameter of the stubbed function with an Error object.

Documentation Link: http://sinonjs.org/releases/v1.17.7/stubs/#defining-stub-behavior-on-consecutive-calls

Title: Chaining callsArgWith on stub

Body:
I have gone through the documentation understand what exactly is stub.callsArgWith here:
    http://sinonjs.org/releases/v1.17.7/stubs/

But I could not not understand what it makes sense when we chain it like below:

stub.callsArgWith(1, null, "ok")
    .callsArgWith(1, new Error("Error!"));

So, basically what it mean is param at index 1 is a callback function and it should be called with first param = null and 2nd param as "ok". But what I could not understand is in what situation we do chaining of callsArgWith and in what sequence are they get used.
Please help me in understanding what exactly is the meaning of above two lines how they will be executed, mean when will it take 'Ok' and when will it return an error.

Body:
In older versions of Sinon (specifically versions 1.5 - 1.7), this was how you described behaviour for consecutive calls.

Otherwise, the second callsArgWith call replaces the behaviour of the first callsArgWith.

So in the your example (and assuming the version of Sinon is v1.5 - 1.7):

stub.callsArgWith(1, null, "ok")
    .callsArgWith(1, new Error("Error!"));

When the stubbed function is called for the first time,
it will call the 2nd parameter of the stubbed function with the parameters null and "ok".

The second time the stubbed function is called, it will call the 2nd parameter of the stubbed function with an Error object.

So in the your example (and assuming the version of Sinon is NOT v1.5 - 1.7):

stub.callsArgWith(1, null, "ok")
    .callsArgWith(1, new Error("Error!"));

Every time the stubbed function is called it will call the 2nd parameter of the stubbed function with an Error object.

Documentation Link: http://sinonjs.org/releases/v1.17.7/stubs/#defining-stub-behavior-on-consecutive-calls


问:
Spring JMS : Configure Multi Consumer client
I am developing a Spring JMS based client, which connects to an IBM MQ.

This part is working fine !!

Scenario:

The MQ client can get a request from multiple Spring "@Components". Considering, JMSTemplate's "send" and "receive" are completely different methods -

Question:

How do we co-relate the response from component-one to only its request ? e.g.

A sends request-A

B sends request-B

How will SpringListener know to respond the response-A to A, and response-B to B ?

Does spring provide an out of box functionality to handle such a scenario ?

Thanks in advance !!

Sample Listener :

```<code>public class MessageReceiver implements MessageListener {

    @Override
    public void onMessage(Message message) {

        if(message instanceof TextMessage){
            System.out.println(message.toString());
        }
    }
}
</code>```

Sample Sender :

```<code>public class App
{
    public static void main( String[] args )
    {

        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JmsTemplate jmsTemplate = (JmsTemplate)context.getBean("jmsTemplate");

        jmsTemplate.send(s -> s.createTextMessage("TestingAMQ"));
    }
}
</code>```

答:
Found this to be the approach of 'setProperty' -

https://codedependents.com/2010/03/04/synchronous-request-response-with-activemq-and-spring/

Body:
I am developing a Spring JMS based client, which connects to an IBM MQ.

This part is working fine !!

Scenario:

The MQ client can get a request from multiple Spring "@Components". Considering, JMSTemplate's "send" and "receive" are completely different methods -

Question:

How do we co-relate the response from component-one to only its request ? e.g.

A sends request-A

B sends request-B

How will SpringListener know to respond the response-A to A, and response-B to B ?

Does spring provide an out of box functionality to handle such a scenario ?

Thanks in advance !!

Sample Listener :

public class MessageReceiver implements MessageListener {

    @Override
    public void onMessage(Message message) {

        if(message instanceof TextMessage){
            System.out.println(message.toString());
        }
    }
}

Sample Sender :

public class App
{
    public static void main( String[] args )
    {

        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JmsTemplate jmsTemplate = (JmsTemplate)context.getBean("jmsTemplate");

        jmsTemplate.send(s -> s.createTextMessage("TestingAMQ"));
    }
}


问:
How does a computer reproduce the SIFT paper method on its own in deep learning
Let me begin by saying that I am struggling to understand what is going on in deep learning. From what I gather, it is an approach to try to have a computer engineer different layers  of representations and features to enable it learn stuff on its own.  SIFT seems to be a common way to sort of detect things by tagging and hunting for scale invariant things in some representation. Again I am completely stupid and in awe and wonder about how this magic is achieved. How does one have a computer do this by itself? I have looked at this paper https://www.cs.ubc.ca/~lowe/papers/ijcv04.pdf and I must say at this point I think it is magic. Can somebody help me distill the main points of how this works and why a computer can do it on its own? </p>

答:
SIFT and CNN are both methods to extract features from images in different ways and outputs.

SIFT/SURF/ORB or any similar feature extraction algorithms are "Hand-made" feature extraction algorithms. It means, independent from the real world cases, they are aiming to extract some meaningful features. This approach has some advantages and disadvantages.

Advantages :

You don't have to care about input image conditions and probably you don't need any pre-processing step to extract those features.

You can directly get SIFT implementation and integrate it to your application

With GPU based implementations (i.e. GPU-SIFT), you can achieve high inference speed.

Disadvantages:

It has limitation about finding the features. You will have trouble about getting features over quite plain surfaces.

SIFT/SURF/ORB cannot solve all problems that requires feature classification / matching. Think face recognition problem. Do you think that extracting & classifying SIFT features over face will be enough to recognize people?

Those are hand-made feature extraction techniques, they cannot be improved over time (of course unless a better technique is being introduced)

Developing such a feature extraction technique requires a lot of research work

In the other hand, in deep learning, you can start analyzing much complex features which are impossible by human to recognize. CNNs are perfect approach as today to analyze hierarchical filter responses and much complex features which are created by combining those filter responses (going deeper).
The main power of CNNs are coming from not extracting features by hand. We only define "how" PC has to look for features. Of course this method has some pros and cons too.

Advantages :

More data, better success! It is all depending on data. If you have enough data to explain your case, DL outperforms hand-made feature extraction techniques.

As soon as you extract the features from image, you can use it for many purposes like to segment image, to create description words, to detect objects inside image, to recognize them. The better part is, all of them can be obtained in one shot, rather than complex sequential processes.

Disadvantages:

You need data. Probably a lot.

It is better to use supervised or reinforcement learning methods in these days. As unsupervised learning is still not good enough yet.

It takes time and resource to train a good neural net. A complex hierarchy like Google Inception took 2 weeks to be trained on 8 GPU server rack. Of course not all the networks are so hard to train.

It has some learning curve. You don't have to know how SIFT is working to use it for your application but you have to know how CNNs are working to use them in your custom purposes.


问:
SQL group by and aggregation in two columns
This is a follow up on my previous question, kindly answered by @Barmar:
When using MYSQL GROUP BY WITH ROLLUP on Year(date) and Month(date) i am not able to change Null to 'Total'

I have a SQL query which gets data from my transaction, subkategori, and kategori tables and this works fine. But now I want to add budget table and sum the budgeted amount. My approach is as below:

```<code>$stmt = $dbh->prepare("
                SELECT IFNULL(Year, 'All') AS Year,
                       IFNULL(Month, 'All') AS Month,
                       IFNULL(Kategori,'All') AS Kategori,
                       IFNULL(Subkategori,'All') AS Subkategori,
                       Belopp,
                       Budget
                FROM (
                      SELECT YEAR(transaktioner.datum) AS Year,
                             MONTH(transaktioner.datum) AS Month,
                             kategori.kat_namn AS Kategori,
                             subkategori.subkat_namn AS Subkategori,
                             SUM(transaktioner.belopp)  AS Belopp,
                             SUM(budget.budgetedAmmount) AS Budget

                      FROM subkategori
                      LEFT JOIN transaktioner
                            ON subkategori.subkat_id=transaktioner.subkat_id
                      LEFT JOIN kategori
                            ON subkategori.kat_id = kategori.kat_id
                      LEFT JOIN budget
                            ON subkategori.subkat_id = budget.subkat_id

                      GROUP BY Year, Month, Kategori, Subkategori
                      WITH ROLLUP

                    ) AS x

                    WHERE Year =".$year."

                    ");
</code>```

It gives me a null output.  Can somebody help me with this one?

Tables are as follows:

transaktioner

```<code>id
datum
beskrivning
overforing
belopp
balans
subkat_id
konto_id
latest_update
</code>```

kategori

```<code>kat_id
kat_namn
type
latest_update
</code>```

subkategori

```<code>subkat_id
subkat_namn
kat_id
latest_update
</code>```

Budget table

```<code>budget_id
subkat_id
budgetedAmmount
user_id
year
</code>```

DESIRED Result table

```<code>Year    Month   Kategory    Subkategory     Spent   Budget
2017    1       Kat1        Subkat1         1000    500
2017    1       Kat1        Subkat2         500     250
2017    1       kat1        ALL             1500    750
2017    1       Kat2        Subkat1         2000    1000
2017    1       Kat2        Subkat2         450     500
2017    1       kat2        ALL             2450    1500
2017    1        ALL        ALL             3950    2250
ALL     ALL      ALL        ALL             3950    2250
</code>```

See fiddle: http://sqlfiddle.com/#!9/35a778/2

答:
With some transactions monthly, and budget annually, there hs to be some method to spread he budget "per month". Also to ensure all sub categories and all months are reported create a "Cartesian product" of those, then left join the data to that. Finally in addition you need to include a way to sort the data sensibly. I hope that from this example you can adapt it to your specific needs.

SQL Fiddle

MySQL 5.6 Schema Setup:

```<code>-- Create transaktioner
  CREATE TABLE transaktioner
      (`id` varchar(4),
      `datum` date,
      `beskrivning` varchar(8),
      `overforing` varchar(8),
      `belopp` varchar(8),
      `balans` varchar(8),
      `subkat_id` varchar(8),
      `konto_id` varchar(8)
       );

  INSERT INTO transaktioner
      ( `datum`,`beskrivning`,`overforing`,`belopp`,`balans`,`subkat_id`,`konto_id`)
  VALUES
      ("2017-01-01","Test1","Yes",'1000','1200','1','1111'),
      ("2016-01-01","Test1","Yes",'1000','1200','2','1111');

-- Create Kategori Table
  CREATE TABLE kategori
      (`kat_id` varchar(4),`kat_namn` varchar(10));

  INSERT INTO kategori
      ( `kat_id`,`kat_namn`)
  VALUES
      ('1',"Kat1"),
      ('2',"Kat2"),
      ('3',"Kat3"),
      ('4',"Kat4");

-- Create Subkategori Table
  CREATE TABLE subkategori
      (`subkat_id` varchar(4),`kat_id` varchar(4),`subkat_namn` varchar(10));

  INSERT INTO subkategori
      ( `subkat_id`,`kat_id`,`subkat_namn`)
  VALUES
      ('1','1',"subKat1"),
      ('2','1',"subKat2"),
      ('3','1',"subKat3"),
      ('4','1',"subKat4");

-- Create budget Table
  CREATE TABLE budget
      (`budget_id` varchar(4),`subkat_id` varchar(4),`budgetedAmmount` varchar(10), `year` varchar(4));

  INSERT INTO budget
      ( `budget_id`,`subkat_id`,`budgetedAmmount`,`year`)
  VALUES
      ('1','1',"111",'2017'),
      ('2','2',"222",'2017'),
      ('3','3',"333",'2017'),
      ('4','4',"444",'2017'),
      ('1','1',"111",'2016'),
      ('2','2',"222",'2016'),
      ('3','3',"333",'2016'),
      ('4','4',"444",'2016');
</code>```

Query 1:

```<code>SELECT
      IFNULL(Year, 'All')       AS Year
    , IFNULL(Month, 'All')      AS Month
    , IFNULL(Kategori,'All')    AS Kategori
    , IFNULL(Subkategori,'All') AS Subkategori
    , IFNULL(Belopp,0)          AS Belopp
    , IFNULL(Budget,0)          AS Budget
FROM (
      SELECT
            y.year                         AS year
          , m.n                            AS month
          , kategori.kat_namn              AS kategori
          , subkategori.subkat_namn                  AS subkategori
          , SUM(IFNULL(transaktioner.belopp,0))      AS belopp
          , SUM(IFNULL(b.budgetedAmmount,0))         AS budget
      FROM subkategori
      INNER JOIN kategori ON subkategori.kat_id = kategori.kat_id
      CROSS JOIN (
            SELECT 2017 year
            ) y
      CROSS JOIN (
            SELECT 1 n union all SELECT 2 n union all SELECT 3 n union all SELECT 4 n union all
            SELECT 5 n union all SELECT 6 n union all SELECT 7 n union all SELECT 8 n union all
            SELECT 9 n union all SELECT 10  union all SELECT 11  union all SELECT 12
            ) m
      LEFT JOIN transaktioner ON subkategori.subkat_id = transaktioner.subkat_id
            AND y.year = YEAR(transaktioner.datum)
            AND m.n = MONTH(transaktioner.datum)
      LEFT JOIN (
                SELECT subkat_id, Year, budgetedAmmount/12 as budgetedAmmount
                FROM budget
                ) b ON subkategori.subkat_id = b.subkat_id
                    AND y.year = b.year
      GROUP BY
            y.year
          , m.n
          , kategori.kat_namn
          , subkategori.subkat_namn
      WITH ROLLUP
      ) d
ORDER BY
      IFNULL(Year, 9999)
    , IFNULL(Month, 13)
    , IFNULL(Kategori,'zzzzzzzzz')
    , IFNULL(Subkategori,'zzzzzzzzzzz')
;
</code>```

Results:

```<code>| Year | Month | Kategori | Subkategori | Belopp | Budget |
|------|-------|----------|-------------|--------|--------|
| 2017 |     1 |     Kat1 |     subKat1 |   1000 |   9.25 |
| 2017 |     1 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     1 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     1 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     1 |     Kat1 |         All |   1000 |   92.5 |
| 2017 |     1 |      All |         All |   1000 |   92.5 |
| 2017 |     2 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     2 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     2 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     2 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     2 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     2 |      All |         All |      0 |   92.5 |
| 2017 |     3 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     3 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     3 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     3 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     3 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     3 |      All |         All |      0 |   92.5 |
| 2017 |     4 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     4 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     4 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     4 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     4 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     4 |      All |         All |      0 |   92.5 |
| 2017 |     5 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     5 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     5 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     5 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     5 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     5 |      All |         All |      0 |   92.5 |
| 2017 |     6 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     6 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     6 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     6 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     6 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     6 |      All |         All |      0 |   92.5 |
| 2017 |     7 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     7 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     7 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     7 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     7 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     7 |      All |         All |      0 |   92.5 |
| 2017 |     8 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     8 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     8 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     8 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     8 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     8 |      All |         All |      0 |   92.5 |
| 2017 |     9 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     9 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     9 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     9 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     9 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     9 |      All |         All |      0 |   92.5 |
| 2017 |    10 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |    10 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |    10 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |    10 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |    10 |     Kat1 |         All |      0 |   92.5 |
| 2017 |    10 |      All |         All |      0 |   92.5 |
| 2017 |    11 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |    11 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |    11 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |    11 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |    11 |     Kat1 |         All |      0 |   92.5 |
| 2017 |    11 |      All |         All |      0 |   92.5 |
| 2017 |    12 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |    12 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |    12 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |    12 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |    12 |     Kat1 |         All |      0 |   92.5 |
| 2017 |    12 |      All |         All |      0 |   92.5 |
| 2017 |   All |      All |         All |   1000 |   1110 |
|  All |   All |      All |         All |   1000 |   1110 |
</code>```

Body:
This is a follow up on my previous question, kindly answered by @Barmar:
When using MYSQL GROUP BY WITH ROLLUP on Year(date) and Month(date) i am not able to change Null to 'Total'

I have a SQL query which gets data from my transaction, subkategori, and kategori tables and this works fine. But now I want to add budget table and sum the budgeted amount. My approach is as below:

$stmt = $dbh->prepare("
                SELECT IFNULL(Year, 'All') AS Year,
                       IFNULL(Month, 'All') AS Month,
                       IFNULL(Kategori,'All') AS Kategori,
                       IFNULL(Subkategori,'All') AS Subkategori,
                       Belopp,
                       Budget
                FROM (
                      SELECT YEAR(transaktioner.datum) AS Year,
                             MONTH(transaktioner.datum) AS Month,
                             kategori.kat_namn AS Kategori,
                             subkategori.subkat_namn AS Subkategori,
                             SUM(transaktioner.belopp)  AS Belopp,
                             SUM(budget.budgetedAmmount) AS Budget

                      FROM subkategori
                      LEFT JOIN transaktioner
                            ON subkategori.subkat_id=transaktioner.subkat_id
                      LEFT JOIN kategori
                            ON subkategori.kat_id = kategori.kat_id
                      LEFT JOIN budget
                            ON subkategori.subkat_id = budget.subkat_id

                      GROUP BY Year, Month, Kategori, Subkategori
                      WITH ROLLUP

                    ) AS x

                    WHERE Year =".$year."

                    ");

It gives me a null output.  Can somebody help me with this one?

Tables are as follows:

transaktioner

id
datum
beskrivning
overforing
belopp
balans
subkat_id
konto_id
latest_update

kategori

kat_id
kat_namn
type
latest_update

subkategori

subkat_id
subkat_namn
kat_id
latest_update

Budget table

budget_id
subkat_id
budgetedAmmount
user_id
year

DESIRED Result table

Year    Month   Kategory    Subkategory     Spent   Budget
2017    1       Kat1        Subkat1         1000    500
2017    1       Kat1        Subkat2         500     250
2017    1       kat1        ALL             1500    750
2017    1       Kat2        Subkat1         2000    1000
2017    1       Kat2        Subkat2         450     500
2017    1       kat2        ALL             2450    1500
2017    1        ALL        ALL             3950    2250
ALL     ALL      ALL        ALL             3950    2250

See fiddle: http://sqlfiddle.com/#!9/35a778/2

Body:
With some transactions monthly, and budget annually, there hs to be some method to spread he budget "per month". Also to ensure all sub categories and all months are reported create a "Cartesian product" of those, then left join the data to that. Finally in addition you need to include a way to sort the data sensibly. I hope that from this example you can adapt it to your specific needs.

SQL Fiddle

MySQL 5.6 Schema Setup:

-- Create transaktioner
  CREATE TABLE transaktioner
      (`id` varchar(4),
      `datum` date,
      `beskrivning` varchar(8),
      `overforing` varchar(8),
      `belopp` varchar(8),
      `balans` varchar(8),
      `subkat_id` varchar(8),
      `konto_id` varchar(8)
       );

  INSERT INTO transaktioner
      ( `datum`,`beskrivning`,`overforing`,`belopp`,`balans`,`subkat_id`,`konto_id`)
  VALUES
      ("2017-01-01","Test1","Yes",'1000','1200','1','1111'),
      ("2016-01-01","Test1","Yes",'1000','1200','2','1111');

-- Create Kategori Table
  CREATE TABLE kategori
      (`kat_id` varchar(4),`kat_namn` varchar(10));

  INSERT INTO kategori
      ( `kat_id`,`kat_namn`)
  VALUES
      ('1',"Kat1"),
      ('2',"Kat2"),
      ('3',"Kat3"),
      ('4',"Kat4");

-- Create Subkategori Table
  CREATE TABLE subkategori
      (`subkat_id` varchar(4),`kat_id` varchar(4),`subkat_namn` varchar(10));

  INSERT INTO subkategori
      ( `subkat_id`,`kat_id`,`subkat_namn`)
  VALUES
      ('1','1',"subKat1"),
      ('2','1',"subKat2"),
      ('3','1',"subKat3"),
      ('4','1',"subKat4");

-- Create budget Table
  CREATE TABLE budget
      (`budget_id` varchar(4),`subkat_id` varchar(4),`budgetedAmmount` varchar(10), `year` varchar(4));

  INSERT INTO budget
      ( `budget_id`,`subkat_id`,`budgetedAmmount`,`year`)
  VALUES
      ('1','1',"111",'2017'),
      ('2','2',"222",'2017'),
      ('3','3',"333",'2017'),
      ('4','4',"444",'2017'),
      ('1','1',"111",'2016'),
      ('2','2',"222",'2016'),
      ('3','3',"333",'2016'),
      ('4','4',"444",'2016');

Query 1:

SELECT
      IFNULL(Year, 'All')       AS Year
    , IFNULL(Month, 'All')      AS Month
    , IFNULL(Kategori,'All')    AS Kategori
    , IFNULL(Subkategori,'All') AS Subkategori
    , IFNULL(Belopp,0)          AS Belopp
    , IFNULL(Budget,0)          AS Budget
FROM (
      SELECT
            y.year                         AS year
          , m.n                            AS month
          , kategori.kat_namn              AS kategori
          , subkategori.subkat_namn                  AS subkategori
          , SUM(IFNULL(transaktioner.belopp,0))      AS belopp
          , SUM(IFNULL(b.budgetedAmmount,0))         AS budget
      FROM subkategori
      INNER JOIN kategori ON subkategori.kat_id = kategori.kat_id
      CROSS JOIN (
            SELECT 2017 year
            ) y
      CROSS JOIN (
            SELECT 1 n union all SELECT 2 n union all SELECT 3 n union all SELECT 4 n union all
            SELECT 5 n union all SELECT 6 n union all SELECT 7 n union all SELECT 8 n union all
            SELECT 9 n union all SELECT 10  union all SELECT 11  union all SELECT 12
            ) m
      LEFT JOIN transaktioner ON subkategori.subkat_id = transaktioner.subkat_id
            AND y.year = YEAR(transaktioner.datum)
            AND m.n = MONTH(transaktioner.datum)
      LEFT JOIN (
                SELECT subkat_id, Year, budgetedAmmount/12 as budgetedAmmount
                FROM budget
                ) b ON subkategori.subkat_id = b.subkat_id
                    AND y.year = b.year
      GROUP BY
            y.year
          , m.n
          , kategori.kat_namn
          , subkategori.subkat_namn
      WITH ROLLUP
      ) d
ORDER BY
      IFNULL(Year, 9999)
    , IFNULL(Month, 13)
    , IFNULL(Kategori,'zzzzzzzzz')
    , IFNULL(Subkategori,'zzzzzzzzzzz')
;

Results:

| Year | Month | Kategori | Subkategori | Belopp | Budget |
|------|-------|----------|-------------|--------|--------|
| 2017 |     1 |     Kat1 |     subKat1 |   1000 |   9.25 |
| 2017 |     1 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     1 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     1 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     1 |     Kat1 |         All |   1000 |   92.5 |
| 2017 |     1 |      All |         All |   1000 |   92.5 |
| 2017 |     2 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     2 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     2 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     2 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     2 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     2 |      All |         All |      0 |   92.5 |
| 2017 |     3 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     3 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     3 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     3 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     3 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     3 |      All |         All |      0 |   92.5 |
| 2017 |     4 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     4 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     4 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     4 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     4 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     4 |      All |         All |      0 |   92.5 |
| 2017 |     5 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     5 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     5 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     5 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     5 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     5 |      All |         All |      0 |   92.5 |
| 2017 |     6 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     6 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     6 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     6 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     6 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     6 |      All |         All |      0 |   92.5 |
| 2017 |     7 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     7 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     7 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     7 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     7 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     7 |      All |         All |      0 |   92.5 |
| 2017 |     8 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     8 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     8 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     8 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     8 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     8 |      All |         All |      0 |   92.5 |
| 2017 |     9 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |     9 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |     9 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |     9 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |     9 |     Kat1 |         All |      0 |   92.5 |
| 2017 |     9 |      All |         All |      0 |   92.5 |
| 2017 |    10 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |    10 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |    10 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |    10 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |    10 |     Kat1 |         All |      0 |   92.5 |
| 2017 |    10 |      All |         All |      0 |   92.5 |
| 2017 |    11 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |    11 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |    11 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |    11 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |    11 |     Kat1 |         All |      0 |   92.5 |
| 2017 |    11 |      All |         All |      0 |   92.5 |
| 2017 |    12 |     Kat1 |     subKat1 |      0 |   9.25 |
| 2017 |    12 |     Kat1 |     subKat2 |      0 |   18.5 |
| 2017 |    12 |     Kat1 |     subKat3 |      0 |  27.75 |
| 2017 |    12 |     Kat1 |     subKat4 |      0 |     37 |
| 2017 |    12 |     Kat1 |         All |      0 |   92.5 |
| 2017 |    12 |      All |         All |      0 |   92.5 |
| 2017 |   All |      All |         All |   1000 |   1110 |
|  All |   All |      All |         All |   1000 |   1110 |


问:
How to Multiply Two textfield values Without converting the text into integer or Number
I have two text fields and user entered the values. I can get the values of textFields like below

```<code>NSString *number1 = firstTextField.text;
NSString *number2 = secondTextField.text;
</code>```

I want to multiply number1 and number2 without converting them into integer or number.I am doing like below

```NSExpression *expression = [NSExpression expressionWithFormat:[NSString stringWithFormat:@"%@*%@",number1,number2]];<br/>NSLog(@"Multiplication result is----%@",[expression expressionValueWithObject:nil context:nil]);```

I don't know if it is correct or not. If it is not correct please give me the suggestions how it can be possible.

答:
I simply used textfields... and used the values that the user input into those textfields... here is one calculation example that has worked for me... in this example the user is trying to find the volume of beachstone they would need to order... the formula is pretty straight forward. Make sure you use the math brackets () to distinguish order of operations...

```<code>-(IBAction)calculate_beachstone:(id)sender {

float floatanswer =

   ([area1.text floatValue])+([area2.text floatValue])+([area3.text floatValue])+([area4.text floatValue])+([area5.text floatValue])+([area6.text floatValue])+([area7.text floatValue])+([area8.text floatValue])+([area9.text floatValue])+([area10.text floatValue]))

  *([beachstone_depth.text floatValue])/12)/27);

NSString *stringRectResult=[[NSString alloc]
                            initWithFormat:@"%.1f",floatanswer];

answer_beachstone.text=stringRectResult;
}
</code>```

I am adding the text found in the textfield (which user can only use numbers for input - custom keyboard)... in this example I have up to 10 fields which can be added together... then I use the * (multiply)  to apply a depth in this example, and convert it back to a text string so I can display the result somewhere else...
In fact, if you write this part answer_beachstone to NSUserDefaults, you can use the result anywhere in different controllers, by calling it back.

If you're interested, here is how I did that...

```<code>-(IBAction)save_answer_beachstone:(id)sender {

save_answer_beachstone = [[NSString alloc] initWithString:answer_beachstone.text];
[answer_beachstone setText:save_answer_beachstone];
NSUserDefaults *save = [NSUserDefaults standardUserDefaults];
[save setObject:save_answer_beachstone forKey:@"save_answer_beachstone"];
</code>```

}

Then I can use the resulting "answer" in any controller inside viewDidLoad...

```<code>[answer_beachstone setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"save_answer_beachstone"]];
</code>```

I know the question was asked 4 years ago, but this formula syntax works for me in a number of ways, in various apps...

Body:
I have two text fields and user entered the values. I can get the values of textFields like below

NSString *number1 = firstTextField.text;
NSString *number2 = secondTextField.text;

I want to multiply number1 and number2 without converting them into integer or number.I am doing like below

NSExpression *expression = [NSExpression expressionWithFormat:[NSString stringWithFormat:@"%@*%@",number1,number2]];
NSLog(@"Multiplication result is----%@",[expression expressionValueWithObject:nil context:nil]);

I don't know if it is correct or not. If it is not correct please give me the suggestions how it can be possible.

Body:
I simply used textfields... and used the values that the user input into those textfields... here is one calculation example that has worked for me... in this example the user is trying to find the volume of beachstone they would need to order... the formula is pretty straight forward. Make sure you use the math brackets () to distinguish order of operations...

-(IBAction)calculate_beachstone:(id)sender {

float floatanswer =

   ([area1.text floatValue])+([area2.text floatValue])+([area3.text floatValue])+([area4.text floatValue])+([area5.text floatValue])+([area6.text floatValue])+([area7.text floatValue])+([area8.text floatValue])+([area9.text floatValue])+([area10.text floatValue]))

  *([beachstone_depth.text floatValue])/12)/27);

NSString *stringRectResult=[[NSString alloc]
                            initWithFormat:@"%.1f",floatanswer];

answer_beachstone.text=stringRectResult;
}

I am adding the text found in the textfield (which user can only use numbers for input - custom keyboard)... in this example I have up to 10 fields which can be added together... then I use the * (multiply)  to apply a depth in this example, and convert it back to a text string so I can display the result somewhere else...
In fact, if you write this part answer_beachstone to NSUserDefaults, you can use the result anywhere in different controllers, by calling it back.

If you're interested, here is how I did that...

-(IBAction)save_answer_beachstone:(id)sender {

save_answer_beachstone = [[NSString alloc] initWithString:answer_beachstone.text];
[answer_beachstone setText:save_answer_beachstone];
NSUserDefaults *save = [NSUserDefaults standardUserDefaults];
[save setObject:save_answer_beachstone forKey:@"save_answer_beachstone"];

}

Then I can use the resulting "answer" in any controller inside viewDidLoad...

[answer_beachstone setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"save_answer_beachstone"]];

I know the question was asked 4 years ago, but this formula syntax works for me in a number of ways, in various apps...


问:
Tomcat & Eclipse integration
I'm developing on a Ubuntu 8.04 machine using Eclipse Ganymede. I installed Tomcat 5.5 using sudo apt-get install tomcat5.5 tomcat5.5-admin and using an Ant script I deploy my WAR file by copying it to $CATALINA_HOME/webapps.

I then created an Eclipse project and I have it output compiled source in a similar but separate directory structure under $PROJECT_ROOT/target/. I still deploy the WAR file by right clicking on the build.xml and choosing my deploy-war task.

As Tomcat is running as a deamon, automatically started up on booting, I'm not instructing it when to start or exit.

My problems with this setup are:

Using this approach I do not get any output to the Eclipse console, as Tomcat is running under the tomcat55 user and I have a different login and no access to Stdout of tomcat55.

The logging which occurs is also directed to Stdout at the moment, which I find pretty nice during development. But it's not nice when I can't see it. :-)

I don't have any servers under the Server tab and no Run configurations. This makes it impossible for me to use the Debug mode of Eclipse, which otherwise is quite convenient.

What do you think I should do to integrate them and in turn make my development environment much better?

答:
I never cared about 1 and 2, so I can't really help you with them.

regarding 3:
You don't need any servers under the server tab for debugging to work. Just start tomcat with these environment variables

```<code>export JPDA_ADDRESS=8000
export JPDA_TRANSPORT=dt_socket</code>```

and configure eclipse accordingly: run - open debug dialog - select remote java app and create a new configuration.

ContentLicense: CC BY-SA 2.5

Title: Tomcat & Eclipse integration

Body:
I never cared about 1 and 2, so I can't really help you with them.

regarding 3:
You don't need any servers under the server tab for debugging to work. Just start tomcat with these environment variables

export JPDA_ADDRESS=8000
export JPDA_TRANSPORT=dt_socket

and configure eclipse accordingly: run - open debug dialog - select remote java app and create a new configuration.

OwnerDisplayName: Kim


问:
C++ loop stack allocation
While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I'm aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I'm puzzeled about.

Lets say you have a for loop:

```<code>for(int i = 0; i < 10; i++)
{
   MyObject obj(file);
   obj.doSomething();
}
</code>```

Now the problem is that if the Object contains state, it keeps it state (stays the same object) while iterating through the iterations from 1 til 10. Maybe coming from a Java/C# background gets me on the wrong path. But I only see two ways of solving this:

Using dynamic memory.

Not giving file to the constructor but instead to the method doSomething(file) but this isn't very nice if you have more than one method manipulating the file object e.g. doSomethingElse(file).

So what do you guys do in such a situation, or do you never get yourself in such a situation at all?

Update:
Turns out i misunderstood and it is working as expected. Check the awnsers below! Thanks everyone

答:
In the code you have posted, obj does not maintain any state between iterations.

```<code>for(int i = 0; i < 10; i++)
{
  MyObject obj(file); //obj enters scope, constructor is called with 'file'
  obj.doSomething();
}  //obj loses scope, destructor is called
</code>```

In that example, obj is a different object every time.  It may be using the same 'stack' memory location as the previous object, but the class destructor and constructor are called between iterations.

If you wish to have the object only be constructed once and used repeatedly, construct before the loop.

```<code>function(file)
{
    MyObject obj(file); //obj enters scope, constructor is called with 'file'

    for(int i = 0; i < 10; i++)
    {
      obj.doSomething(); //Same object used every iteration
    }

}  //obj loses scope, destructor is called
</code>```

Title: C++ loop stack allocation

Body:
While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I'm aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I'm puzzeled about.

Lets say you have a for loop:

for(int i = 0; i < 10; i++)
{
   MyObject obj(file);
   obj.doSomething();
}

Now the problem is that if the Object contains state, it keeps it state (stays the same object) while iterating through the iterations from 1 til 10. Maybe coming from a Java/C# background gets me on the wrong path. But I only see two ways of solving this:

Using dynamic memory.

Not giving file to the constructor but instead to the method doSomething(file) but this isn't very nice if you have more than one method manipulating the file object e.g. doSomethingElse(file).

So what do you guys do in such a situation, or do you never get yourself in such a situation at all?

Update:
Turns out i misunderstood and it is working as expected. Check the awnsers below! Thanks everyone

Body:
In the code you have posted, obj does not maintain any state between iterations.

for(int i = 0; i < 10; i++)
{
  MyObject obj(file); //obj enters scope, constructor is called with 'file'
  obj.doSomething();
}  //obj loses scope, destructor is called

In that example, obj is a different object every time.  It may be using the same 'stack' memory location as the previous object, but the class destructor and constructor are called between iterations.

If you wish to have the object only be constructed once and used repeatedly, construct before the loop.

function(file)
{
    MyObject obj(file); //obj enters scope, constructor is called with 'file'

    for(int i = 0; i < 10; i++)
    {
      obj.doSomething(); //Same object used every iteration
    }

}  //obj loses scope, destructor is called


问:
Advice for interpreting an assembly function's behavior
I am relatively new to assembly and came across a function that has me stumped. In the course of debugging I found the $rdi register was initially set to 0x55555575a1b8. Essentially, I am looking to return a value of anything, but a negative value or zero. Originally, it seemed like setting the $esi to 0x5575a1b8 would return 0x1. In reality it returned -1. Further inspection shows that there are several two recursive function calls, which each save the return value into a register for later comparison:

```<code>r12 = Find(*(rdi + 0x8), rsi);
rax = Find(*(rdi + 0x10), rsi);
</code>```

After this, I get lost in the code...

```<code>0000000000001b62 <Find>:
1b62:   48 85 ff                test   %rdi,%rdi
1b65:   74 3c                   je     1ba3 <Find+0x41>
1b67:   39 37                   cmp    %esi,(%rdi)
1b69:   74 3e                   je     1ba9 <Find+0x47>
1b6b:   41 54                   push   %r12
1b6d:   55                      push   %rbp
1b6e:   53                      push   %rbx
1b6f:   89 f5                   mov    %esi,%ebp
1b71:   48 89 fb                mov    %rdi,%rbx
1b74:   48 8b 7f 08             mov    0x8(%rdi),%rdi
1b78:   e8 e5 ff ff ff          callq  1b62 <Find>
1b7d:   41 89 c4                mov    %eax,%r12d
1b80:   48 8b 7b 10             mov    0x10(%rbx),%rdi
1b84:   89 ee                   mov    %ebp,%esi
1b86:   e8 d7 ff ff ff          callq  1b62 <Find>
1b8b:   45 85 e4                test   %r12d,%r12d
1b8e:   7e 09                   jle    1b99 <Find+0x37>
1b90:   43 8d 04 24             lea    (%r12,%r12,1),%eax
1b94:   5b                      pop    %rbx
1b95:   5d                      pop    %rbp
1b96:   41 5c                   pop    %r12
1b98:   c3                      retq
1b99:   85 c0                   test   %eax,%eax
1b9b:   7e 12                   jle    1baf <Find+0x4d>
1b9d:   8d 44 00 01             lea    0x1(%rax,%rax,1),%eax
1ba1:   eb f1                   jmp    1b94 <Find+0x32>
1ba3:   b8 ff ff ff ff          mov    $0xffffffff,%eax
1ba8:   c3                      retq
1ba9:   b8 01 00 00 00          mov    $0x1,%eax
1bae:   c3                      retq
1baf:   b8 ff ff ff ff          mov    $0xffffffff,%eax
1bb4:   eb de                   jmp    1b94 <Find+0x32>
</code>```

Any insight into the behavior of the method is greatly appreciated.

答:
```<code>0000000000001b62 <Find>:
; if (null == rdi) return -1;
1b62:   48 85 ff                test   %rdi,%rdi
1b65:   74 3c                   je     1ba3 <Find+0x41>
; if (esi == *rdi) return 1;
1b67:   39 37                   cmp    %esi,(%rdi)
1b69:   74 3e                   je     1ba9 <Find+0x47>
; preserving r12, rbp, rbx
1b6b:   41 54                   push   %r12
1b6d:   55                      push   %rbp
1b6e:   53                      push   %rbx
; r12d = Find( *(rdi+8), esi );
1b6f:   89 f5                   mov    %esi,%ebp
1b71:   48 89 fb                mov    %rdi,%rbx
1b74:   48 8b 7f 08             mov    0x8(%rdi),%rdi
1b78:   e8 e5 ff ff ff          callq  1b62 <Find>
1b7d:   41 89 c4                mov    %eax,%r12d
; eax = Find( *(rdi_orig+16), esi_orig)
1b80:   48 8b 7b 10             mov    0x10(%rbx),%rdi
1b84:   89 ee                   mov    %ebp,%esi
1b86:   e8 d7 ff ff ff          callq  1b62 <Find>
; if (r12d <= 0 && eax <= 0) return -1; (with restoring regs)
; if (r12d <= 0 && 0 < eax) return 2*eax + 1; (with restoring regs)
1b8b:   45 85 e4                test   %r12d,%r12d
1b8e:   7e 09                   jle    1b99 <Find+0x37>
; return 2*r12d; with restoring regs
1b90:   43 8d 04 24             lea    (%r12,%r12,1),%eax
1b94:   5b                      pop    %rbx
1b95:   5d                      pop    %rbp
1b96:   41 5c                   pop    %r12
1b98:   c3                      retq
1b99:   85 c0                   test   %eax,%eax
1b9b:   7e 12                   jle    1baf <Find+0x4d>
1b9d:   8d 44 00 01             lea    0x1(%rax,%rax,1),%eax
1ba1:   eb f1                   jmp    1b94 <Find+0x32>
1ba3:   b8 ff ff ff ff          mov    $0xffffffff,%eax
1ba8:   c3                      retq
1ba9:   b8 01 00 00 00          mov    $0x1,%eax
1bae:   c3                      retq
1baf:   b8 ff ff ff ff          mov    $0xffffffff,%eax
1bb4:   eb de                   jmp    1b94 <Find+0x32>
</code>```

So in C-like code I think (didn't verify or debug, or even just compile):

```<code>struct node_s {
    int32_t value;
    int32_t _padding; // left starts at offset 8
    node_s* left;
    node_s* right;
};

int32_t Find(node_s* node, int32_t i) {
    if (nullptr == node) return -1;
    if (i == node->value) return 1;
    int32_t f1 = Find( node->left, i);
    int32_t f2 = Find( node->right, i);
    if (0 < f1) return 2 * f1;
    if (0 < f2) return 2 * f2 + 1;
    return -1;
}
</code>```

It looks to me as unoptimized way to return kind-of-position of particular value in binary tree.

Let's say you have tree like this:

```<code>n0: {10, n1, n2}
n1: {11, n3, n4}
n2: {12, n5, n6}
n3: {13, nullptr, n7}
n4: {14, nullptr, nullptr}
n5: {15, nullptr, n8}
n6: {16, nullptr, nullptr}
n7: {17, nullptr, nullptr}
n8: {18, nullptr, nullptr}
</code>```

i.e.

```<code>           10
        /      \
     11            12
  /    \        /    \
13      14    15      16
  \             \
   17            18
</code>```

Then I guess:

```<code>Find(n0, 99) = -1
Find(n0, 10) = 1
Find(n0, 11) = 2
Find(n0, 12) = 3
Find(n1, 11) = 1
Find(n0, 17) = 12
Find(n1, 17) = 6
Find(n3, 17) = 3
Find(n7, 17) = 1
...
</code>```

Or when searching for particular value from n0 node, the return values will be (I hope I didn't do mistake):

```<code>           1
        /      \
     2             3
  /    \        /    \
 4       6     5       7
  \             \
   12             13
</code>```

So it's returning whole "floor" (depth of linking) as some range i .. i+f_n-1 (f_n = amount of max nodes on floor possible in BT), where first half of range are left nodes and second half of range are right nodes.

Now if you have that code in machine, you can try to recreate such tree struct for input and let me know, if I did guess it correctly.. :)

EDIT: nope, didn't. That bottom would be then 12, 14, not 12, 13, so the order is somewhat more tricky than nice left/right split... too tired to think how to name this. Looks like some kind of lexicographic ordering when you have path from root to value (but the sort is backwards like reversed string, or path from value to top):

```<code>1 : ""
2 : L
3 : R
4 : LL
5 : RL
6 : LR
7 : RR
8 : LLL
9 : RLL
10: LRL
11: RRL
12: LLR
13: RLR
14: LRR
15: RRR
16: LLLL
17: RLLL
18: LRLL
...
</code>```

Body:
I am relatively new to assembly and came across a function that has me stumped. In the course of debugging I found the $rdi register was initially set to 0x55555575a1b8. Essentially, I am looking to return a value of anything, but a negative value or zero. Originally, it seemed like setting the $esi to 0x5575a1b8 would return 0x1. In reality it returned -1. Further inspection shows that there are several two recursive function calls, which each save the return value into a register for later comparison:

r12 = Find(*(rdi + 0x8), rsi);
rax = Find(*(rdi + 0x10), rsi);

After this, I get lost in the code...

0000000000001b62 <Find>:
1b62:   48 85 ff                test   %rdi,%rdi
1b65:   74 3c                   je     1ba3 <Find+0x41>
1b67:   39 37                   cmp    %esi,(%rdi)
1b69:   74 3e                   je     1ba9 <Find+0x47>
1b6b:   41 54                   push   %r12
1b6d:   55                      push   %rbp
1b6e:   53                      push   %rbx
1b6f:   89 f5                   mov    %esi,%ebp
1b71:   48 89 fb                mov    %rdi,%rbx
1b74:   48 8b 7f 08             mov    0x8(%rdi),%rdi
1b78:   e8 e5 ff ff ff          callq  1b62 <Find>
1b7d:   41 89 c4                mov    %eax,%r12d
1b80:   48 8b 7b 10             mov    0x10(%rbx),%rdi
1b84:   89 ee                   mov    %ebp,%esi
1b86:   e8 d7 ff ff ff          callq  1b62 <Find>
1b8b:   45 85 e4                test   %r12d,%r12d
1b8e:   7e 09                   jle    1b99 <Find+0x37>
1b90:   43 8d 04 24             lea    (%r12,%r12,1),%eax
1b94:   5b                      pop    %rbx
1b95:   5d                      pop    %rbp
1b96:   41 5c                   pop    %r12
1b98:   c3                      retq
1b99:   85 c0                   test   %eax,%eax
1b9b:   7e 12                   jle    1baf <Find+0x4d>
1b9d:   8d 44 00 01             lea    0x1(%rax,%rax,1),%eax
1ba1:   eb f1                   jmp    1b94 <Find+0x32>
1ba3:   b8 ff ff ff ff          mov    $0xffffffff,%eax
1ba8:   c3                      retq
1ba9:   b8 01 00 00 00          mov    $0x1,%eax
1bae:   c3                      retq
1baf:   b8 ff ff ff ff          mov    $0xffffffff,%eax
1bb4:   eb de                   jmp    1b94 <Find+0x32>

Any insight into the behavior of the method is greatly appreciated.

Body:
0000000000001b62 <Find>:
; if (null == rdi) return -1;
1b62:   48 85 ff                test   %rdi,%rdi
1b65:   74 3c                   je     1ba3 <Find+0x41>
; if (esi == *rdi) return 1;
1b67:   39 37                   cmp    %esi,(%rdi)
1b69:   74 3e                   je     1ba9 <Find+0x47>
; preserving r12, rbp, rbx
1b6b:   41 54                   push   %r12
1b6d:   55                      push   %rbp
1b6e:   53                      push   %rbx
; r12d = Find( *(rdi+8), esi );
1b6f:   89 f5                   mov    %esi,%ebp
1b71:   48 89 fb                mov    %rdi,%rbx
1b74:   48 8b 7f 08             mov    0x8(%rdi),%rdi
1b78:   e8 e5 ff ff ff          callq  1b62 <Find>
1b7d:   41 89 c4                mov    %eax,%r12d
; eax = Find( *(rdi_orig+16), esi_orig)
1b80:   48 8b 7b 10             mov    0x10(%rbx),%rdi
1b84:   89 ee                   mov    %ebp,%esi
1b86:   e8 d7 ff ff ff          callq  1b62 <Find>
; if (r12d <= 0 && eax <= 0) return -1; (with restoring regs)
; if (r12d <= 0 && 0 < eax) return 2*eax + 1; (with restoring regs)
1b8b:   45 85 e4                test   %r12d,%r12d
1b8e:   7e 09                   jle    1b99 <Find+0x37>
; return 2*r12d; with restoring regs
1b90:   43 8d 04 24             lea    (%r12,%r12,1),%eax
1b94:   5b                      pop    %rbx
1b95:   5d                      pop    %rbp
1b96:   41 5c                   pop    %r12
1b98:   c3                      retq
1b99:   85 c0                   test   %eax,%eax
1b9b:   7e 12                   jle    1baf <Find+0x4d>
1b9d:   8d 44 00 01             lea    0x1(%rax,%rax,1),%eax
1ba1:   eb f1                   jmp    1b94 <Find+0x32>
1ba3:   b8 ff ff ff ff          mov    $0xffffffff,%eax
1ba8:   c3                      retq
1ba9:   b8 01 00 00 00          mov    $0x1,%eax
1bae:   c3                      retq
1baf:   b8 ff ff ff ff          mov    $0xffffffff,%eax
1bb4:   eb de                   jmp    1b94 <Find+0x32>

So in C-like code I think (didn't verify or debug, or even just compile):

struct node_s {
    int32_t value;
    int32_t _padding; // left starts at offset 8
    node_s* left;
    node_s* right;
};

int32_t Find(node_s* node, int32_t i) {
    if (nullptr == node) return -1;
    if (i == node->value) return 1;
    int32_t f1 = Find( node->left, i);
    int32_t f2 = Find( node->right, i);
    if (0 < f1) return 2 * f1;
    if (0 < f2) return 2 * f2 + 1;
    return -1;
}

It looks to me as unoptimized way to return kind-of-position of particular value in binary tree.

Let's say you have tree like this:

n0: {10, n1, n2}
n1: {11, n3, n4}
n2: {12, n5, n6}
n3: {13, nullptr, n7}
n4: {14, nullptr, nullptr}
n5: {15, nullptr, n8}
n6: {16, nullptr, nullptr}
n7: {17, nullptr, nullptr}
n8: {18, nullptr, nullptr}

i.e.

           10
        /      \
     11            12
  /    \        /    \
13      14    15      16
  \             \
   17            18

Then I guess:

Find(n0, 99) = -1
Find(n0, 10) = 1
Find(n0, 11) = 2
Find(n0, 12) = 3
Find(n1, 11) = 1
Find(n0, 17) = 12
Find(n1, 17) = 6
Find(n3, 17) = 3
Find(n7, 17) = 1
...

Or when searching for particular value from n0 node, the return values will be (I hope I didn't do mistake):

           1
        /      \
     2             3
  /    \        /    \
 4       6     5       7
  \             \
   12             13

So it's returning whole "floor" (depth of linking) as some range i .. i+f_n-1 (f_n = amount of max nodes on floor possible in BT), where first half of range are left nodes and second half of range are right nodes.

Now if you have that code in machine, you can try to recreate such tree struct for input and let me know, if I did guess it correctly.. :)

EDIT: nope, didn't. That bottom would be then 12, 14, not 12, 13, so the order is somewhat more tricky than nice left/right split... too tired to think how to name this. Looks like some kind of lexicographic ordering when you have path from root to value (but the sort is backwards like reversed string, or path from value to top):

1 : ""
2 : L
3 : R
4 : LL
5 : RL
6 : LR
7 : RR
8 : LLL
9 : RLL
10: LRL
11: RRL
12: LLR
13: RLR
14: LRR
15: RRR
16: LLLL
17: RLLL
18: LRLL
...


问:
How can I construct an enum.Enum from a dictionary of values?
I'd like to generate some types at runtime from a config file. For simplity, let's assume I already have the data loaded as a python dictionary:

```<code>color_values = dict(RED = 1, YELLOW = 2, GREEN = 3)
</code>```

How can I transform this into the type (using enum)

```<code>class Color(enum.Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3
</code>```

The following doesn't work

```<code>def make_enum(name, values):
    return type(name, (enum.Enum,), values)
</code>```

```<code>>>> Color = make_enum('Color', color_values)
AttributeError: 'dict' object has no attribute '_member_names'
</code>```

答:
```<code>Color = Enum('Color', color_values)
</code>```

Tada! There's a provided API for that. You can also give it an iterable of name-value pairs, or an iterable of just names (in which case the values will be auto-filled starting from 1), or a whitespace- or comma-separated string of names (which will also auto-fill values).

Body:
I'd like to generate some types at runtime from a config file. For simplity, let's assume I already have the data loaded as a python dictionary:

color_values = dict(RED = 1, YELLOW = 2, GREEN = 3)

How can I transform this into the type (using enum)

class Color(enum.Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3

The following doesn't work

def make_enum(name, values):
    return type(name, (enum.Enum,), values)

>>> Color = make_enum('Color', color_values)
AttributeError: 'dict' object has no attribute '_member_names'

Body:
Color = Enum('Color', color_values)

Tada! There's a provided API for that. You can also give it an iterable of name-value pairs, or an iterable of just names (in which case the values will be auto-filled starting from 1), or a whitespace- or comma-separated string of names (which will also auto-fill values).


问:
Why is display=grid not working in IE?
I am using display = grid in CSS. It's works fine for Chrome & Firefox, but it's not working on IE. Any CSS tricks or any other solution?

答:
Specifying e.g.:

```<code>#grid_container {
    display: -ms-grid
    display: grid
    ...
}
<div id="grid_container">
    ...
</div>
</code>```

will currently, as of 2017-11-14, work for Internet Explorer and Edge on Windows, as well as other browsers in Windows and other platforms.

The new style display property will take effect for other browsers, and the original Grid element with the vendor prefix  from the March 2012 W3 Working Draft will be used by Internet Explorer and Edge browsers in Windows.

This is current as of:
2017-11-14:

IE 11.726.15063.0 Update 11.0.48

Edge 40.15063.674.0

Windows 1703 Build 15063.726.

and tested in:

Chrome, Firefox, Safari, and Vivaldi in High Sierra;

Chrome, Firefox, and Samsung Cloud (mobile browser) in an Android phone; and

Chrome, Firefox, Internet Explorer, and Edge in Windows 10.

I am also still using e.g.:

```<code>-ms-grid-column: 2;
-ms-grid-column-span: 1;
-ms-grid-row: 1;
grid-column: 2 / 3;
grid-row: 1;
</code>```

per prior research, i.e. Rachel Andrew

I realize this is a little old given the pace of things, but I hope it helps someone.

Title: Why is display=grid not working in IE?

Body:
Specifying e.g.:

#grid_container {
    display: -ms-grid
    display: grid
    ...
}
<div id="grid_container">
    ...
</div>

will currently, as of 2017-11-14, work for Internet Explorer and Edge on Windows, as well as other browsers in Windows and other platforms.

The new style display property will take effect for other browsers, and the original Grid element with the vendor prefix  from the March 2012 W3 Working Draft will be used by Internet Explorer and Edge browsers in Windows.

This is current as of:
2017-11-14:

IE 11.726.15063.0 Update 11.0.48

Edge 40.15063.674.0

Windows 1703 Build 15063.726.

and tested in:

Chrome, Firefox, Safari, and Vivaldi in High Sierra;

Chrome, Firefox, and Samsung Cloud (mobile browser) in an Android phone; and

Chrome, Firefox, Internet Explorer, and Edge in Windows 10.

I am also still using e.g.:

-ms-grid-column: 2;
-ms-grid-column-span: 1;
-ms-grid-row: 1;
grid-column: 2 / 3;
grid-row: 1;

per prior research, i.e. Rachel Andrew

I realize this is a little old given the pace of things, but I hope it helps someone.


问:
multiple alter table in execute immediate
```<code>BEGIN
  execute immediate '
    BEGIN
        ALTER TABLE EMPRESA ADD CONSTRAINT pk_empresa_id PRIMARY KEY (EMPRESA_ID);

        ALTER TABLE CLIENTE ADD CONSTRAINT pk_cliente_id PRIMARY KEY (CLIENTE_ID);
    END';
END;
</code>```

I want to do something like this in PL/SQL, but it throws me an error.

How should I do it?

答:
Problem is that you can't run DDL directly in PLSQL. You can run them in separate execute immediates:</p>

```<code>BEGIN
    execute immediate 'ALTER TABLE EMPRESA ADD CONSTRAINT pk_empresa_id PRIMARY KEY (EMPRESA_ID)';
    execute immediate 'ALTER TABLE CLIENTE ADD CONSTRAINT pk_cliente_id PRIMARY KEY (CLIENTE_ID)';
END;
/
</code>```

Body:
BEGIN
  execute immediate '
    BEGIN
        ALTER TABLE EMPRESA ADD CONSTRAINT pk_empresa_id PRIMARY KEY (EMPRESA_ID);

        ALTER TABLE CLIENTE ADD CONSTRAINT pk_cliente_id PRIMARY KEY (CLIENTE_ID);
    END';
END;

I want to do something like this in PL/SQL, but it throws me an error.

How should I do it?

Body:
Problem is that you can't run DDL directly in PLSQL. You can run them in separate execute immediates:

BEGIN
    execute immediate 'ALTER TABLE EMPRESA ADD CONSTRAINT pk_empresa_id PRIMARY KEY (EMPRESA_ID)';
    execute immediate 'ALTER TABLE CLIENTE ADD CONSTRAINT pk_cliente_id PRIMARY KEY (CLIENTE_ID)';
END;
/


问:
How do I repeat a parenthesized group n times using a Python regular expression?
I'm trying to get pairs of |<digit><whitespace> out of a string with many of them. I'm using the regex (\|\d+\s+){2} to do this, i.e.:

```<code>>>> import re
>>> s = '|11 |22    |\n|33  |444 |\n'
>>> re.findall('(\|\d+\s+){2}', s)
['|22    ', '|444 ']
</code>```

I expected instead is:

```<code>['|11 |22    |', '|33  |444 |']
</code>```

because () should define a group and {2} should repeat it twice. Why doesn't it do that, and what's a better way of doing it?

答:
Turn the capturing group to non-capturing group and add a \| at the last in your regex. Because re.findall will return the captured characters if there any capturing group else it would return all the matched characters. since your regex contain one greedy capturing group, it  captures only the last repeat but matches all the previous repeats.

```<code>>>> s = '|11 |22    |\n|33  |444 |\n'
>>> re.findall('(?:\|\d+\s+){2}\|', s)
['|11 |22    |', '|33  |444 |']
</code>```

Body:
I'm trying to get pairs of |<digit><whitespace> out of a string with many of them. I'm using the regex (\|\d+\s+){2} to do this, i.e.:

>>> import re
>>> s = '|11 |22    |\n|33  |444 |\n'
>>> re.findall('(\|\d+\s+){2}', s)
['|22    ', '|444 ']

I expected instead is:

['|11 |22    |', '|33  |444 |']

because () should define a group and {2} should repeat it twice. Why doesn't it do that, and what's a better way of doing it?

Body:
Turn the capturing group to non-capturing group and add a \| at the last in your regex. Because re.findall will return the captured characters if there any capturing group else it would return all the matched characters. since your regex contain one greedy capturing group, it  captures only the last repeat but matches all the previous repeats.

>>> s = '|11 |22    |\n|33  |444 |\n'
>>> re.findall('(?:\|\d+\s+){2}\|', s)
['|11 |22    |', '|33  |444 |']


问:
How do I calculate the area of a projection created by the command "view"?
How do I calculate the area of a projection? For example, using the following code, I get a projection on the X-Z plane.

```<code>[x,y,z]=peaks;
surf(x,y,z);
xlabel('x');ylabel('y');zlabel('z')
view([0,0])
</code>```

X-Z Plane Projection

I want to be able to determine the area of the projection of any surf plot that I create. Is there a command or function for this?

答:
If you want to get the projection area at an arbitrary view angle, you can use the viewmtx function to project the surface onto the viewing plane, and then use boundary and polyarea to extract the boundary and calculate the area. Something like this:

```<code> % draw your surface
 [x,y,z]=peaks;
 surf(x,y,z);
 xlabel('x');ylabel('y');zlabel('z')
 axis equal;
 %extract the viewing angle, and calculate the resulting transformation matrix
 [az,el]=view(gca);
 T= viewmtx(az,el);
 % transform the surface points by this transformation matrix
 pts= [x(:),y(:),z(:),ones(numel(x),1)]';
 tpts= T*pts;
 tpts=(tpts(1:3,:))';
 % now "tpts" has the surface points projected onto the viewing plane
 figure, plot( tpts(:,1), tpts(:,2), 'bo'); axis equal;
 % calculate the border of this region, and calculate its area.
 border = boundary(tpts(:,1), tpts(:,2));
 projectedArea = polyarea(tpts(border,1), tpts(border,2));
</code>```

This approach is based off of the help for viewmtx.

Body:
How do I calculate the area of a projection? For example, using the following code, I get a projection on the X-Z plane.

[x,y,z]=peaks;
surf(x,y,z);
xlabel('x');ylabel('y');zlabel('z')
view([0,0])

X-Z Plane Projection

I want to be able to determine the area of the projection of any surf plot that I create. Is there a command or function for this?

Body:
If you want to get the projection area at an arbitrary view angle, you can use the viewmtx function to project the surface onto the viewing plane, and then use boundary and polyarea to extract the boundary and calculate the area. Something like this:

 % draw your surface
 [x,y,z]=peaks;
 surf(x,y,z);
 xlabel('x');ylabel('y');zlabel('z')
 axis equal;
 %extract the viewing angle, and calculate the resulting transformation matrix
 [az,el]=view(gca);
 T= viewmtx(az,el);
 % transform the surface points by this transformation matrix
 pts= [x(:),y(:),z(:),ones(numel(x),1)]';
 tpts= T*pts;
 tpts=(tpts(1:3,:))';
 % now "tpts" has the surface points projected onto the viewing plane
 figure, plot( tpts(:,1), tpts(:,2), 'bo'); axis equal;
 % calculate the border of this region, and calculate its area.
 border = boundary(tpts(:,1), tpts(:,2));
 projectedArea = polyarea(tpts(border,1), tpts(border,2));

This approach is based off of the help for viewmtx.


问:
Multiple query Joins in windows form application C# with MS Access not working
I have three tables in MS Access database

users,
  rooms,
  room_history

room_history contains both users,rooms id. when I try to join users with room_history data successfully retrieve same goes with rooms and room_history.
Here is my query for joining all three tables.

```<code>"SELECT users.*,rooms.room_id,rooms.room_name,rooms.type,room_history.start_date,room_history.end_date FROM users " +
                "LEFT JOIN room_history ON room_history.user_id= users.user_id " +
                "LEFT JOIN rooms ON room_history.room_id = rooms.room_id";
</code>```

Using above query following error occurs.

syntax error (missing operator) in query expression 'room_history.user_id = users.user_id LEFT JOIN rooms on room_history.room_id = rooms.room_i'

I check/change my database tables name, compact the database.

答:
Your problem is your naming convention.

You used

```<code>rooms.type
</code>```

where type is a reserved word of your database.

the error you receive

```<code>syntax error (missing operator) in query expression 'room_history.user_id = users.user_id LEFT JOIN rooms on room_history.room_id = rooms.room_i'
</code>```

pertains to naming conventions which below link discusses.

https://support.microsoft.com/en-ph/help/932994/you-receive-an-error-message-when-you-run-a-query-in-microsoft-access

If you would insist to use your query "as is" you may simply put brackets ([]) on all of your table names that are reserve words, (e.g [type], [start_date],[user_id])

Body:
I have three tables in MS Access database

users,
  rooms,
  room_history

room_history contains both users,rooms id. when I try to join users with room_history data successfully retrieve same goes with rooms and room_history.
Here is my query for joining all three tables.

"SELECT users.*,rooms.room_id,rooms.room_name,rooms.type,room_history.start_date,room_history.end_date FROM users " +
                "LEFT JOIN room_history ON room_history.user_id= users.user_id " +
                "LEFT JOIN rooms ON room_history.room_id = rooms.room_id";

Using above query following error occurs.

syntax error (missing operator) in query expression 'room_history.user_id = users.user_id LEFT JOIN rooms on room_history.room_id = rooms.room_i'

I check/change my database tables name, compact the database.

Body:
Your problem is your naming convention.

You used

rooms.type

where type is a reserved word of your database.

the error you receive

syntax error (missing operator) in query expression 'room_history.user_id = users.user_id LEFT JOIN rooms on room_history.room_id = rooms.room_i'

pertains to naming conventions which below link discusses.

https://support.microsoft.com/en-ph/help/932994/you-receive-an-error-message-when-you-run-a-query-in-microsoft-access

If you would insist to use your query "as is" you may simply put brackets ([]) on all of your table names that are reserve words, (e.g [type], [start_date],[user_id])


问:
Querying a database in node.js asynchronously
I am trying to figure out the proper way to call a function asynchronously if it is also making asynchronous calls to the database.

In my code I call a function called 'check_foods()` which will query a database up to two times if it has not been called already. The database queries will populate the two variables vegetables and fruit (assuming they haven't been populated already). Once the function returns I want to make use of those variables.

However, I assume that the way my code is now that it will try to begin processing the two console lines even if it hasn't pulled the data from the database yet. Am I correct in this assumption? If so, what should I do to implement this correctly?

A simplified version of my code looks like this:

```<code>var vegetables = {};
var fruit = {};

async function starter (){
    sql = "select growth_items from garden where room_id = ?";
    db_connection.query(sql, [socket.room], function (err, result){
        if (err){
            console.log("Garden Error: " + err);
            return;
        }

        console.log(result);

        check_foods();

        //Should not get to this point until variables have been populated
        //However, due to the async nature of the code this does not seem to be implemented correctly.
        //process vegetables[socket.room] and fruit[socket.room]
        console.log(vegetables[socket.room]);
        console.log(fruit[socket.room]);
    });
}

async function check_foods(){
       //Check to see if vegetables[socket.room] already exists, otherwise load it from the database
       if (typeof vegetables[socket.room] !== "undefined"){
            sql = "select name, qty from vegetables where room_id = ?";
            db_connection.query(sql, [socket.room], function (err, result){
                if (err){
                    console.log("An vegetable error has occurred: " + err);
                    return;
                }

                vegetables[socket.room] = result;
            });
        };

        //Check to see if fruit already exists before looking up again

        if (typeof fruit[socket.room] !== "undefined"){
            sql = "select name, qty from fruit where room_id = ?";
            db_connection.query(sql, [socket.room], function (err, result){
                if (err){
                    console.log("An fruit error has occurred: " + err);
                    return;
                }

                fruit[socket.room] = result;
            });
        };

}
</code>```

答:
You can use promisify to convert callback to promise and then use await

sample code should be like this

```<code>const vegetables = {};
const fruit = {};
const Promise = require('bluebird'); // or you can use node utility module as well
const db = Promise.promisifyAll(require('YOUR DB LIB'));
const db_connection = 'YOUR DB CONNECTION'

async function starter (){
  const SQL = "select growth_items from garden where room_id = ?";
  try {
    const result = await db_connection.query(SQL);
    console.log(result);
    check_foods();
  } catch(err) {
    console.log("Garden Error: " + err);
  }
}

async function check_foods(){
  //Check to see if vegetables[socket.room] already exists, otherwise load it from the database
  if (typeof vegetables[socket.room] !== "undefined"){
    const SQL = "select name, qty from vegetables where room_id = ?";
    try {
      const result = await db_connection.query(SQL);
      vegetables[socket.room] = result;
    } catch(err) {
      console.log("An vegetable error has occurred: " + err);
      return;
    }
  }

  //Check to see if fruit already exists before looking up again
  if (typeof fruit[socket.room] !== "undefined"){
      const SQL = "select name, qty from fruit where room_id = ?";
      try {
        const result = await db_connection.query(SQL);
        fruit[socket.room] = result;
      } catch(err) {
        console.log("An fruit error has occurred: " + err);
        return;
      }
  };
}
</code>```

Body:
I am trying to figure out the proper way to call a function asynchronously if it is also making asynchronous calls to the database.

In my code I call a function called 'check_foods()` which will query a database up to two times if it has not been called already. The database queries will populate the two variables vegetables and fruit (assuming they haven't been populated already). Once the function returns I want to make use of those variables.

However, I assume that the way my code is now that it will try to begin processing the two console lines even if it hasn't pulled the data from the database yet. Am I correct in this assumption? If so, what should I do to implement this correctly?

A simplified version of my code looks like this:

var vegetables = {};
var fruit = {};

async function starter (){
    sql = "select growth_items from garden where room_id = ?";
    db_connection.query(sql, [socket.room], function (err, result){
        if (err){
            console.log("Garden Error: " + err);
            return;
        }

        console.log(result);

        check_foods();

        //Should not get to this point until variables have been populated
        //However, due to the async nature of the code this does not seem to be implemented correctly.
        //process vegetables[socket.room] and fruit[socket.room]
        console.log(vegetables[socket.room]);
        console.log(fruit[socket.room]);
    });
}

async function check_foods(){
       //Check to see if vegetables[socket.room] already exists, otherwise load it from the database
       if (typeof vegetables[socket.room] !== "undefined"){
            sql = "select name, qty from vegetables where room_id = ?";
            db_connection.query(sql, [socket.room], function (err, result){
                if (err){
                    console.log("An vegetable error has occurred: " + err);
                    return;
                }

                vegetables[socket.room] = result;
            });
        };

        //Check to see if fruit already exists before looking up again

        if (typeof fruit[socket.room] !== "undefined"){
            sql = "select name, qty from fruit where room_id = ?";
            db_connection.query(sql, [socket.room], function (err, result){
                if (err){
                    console.log("An fruit error has occurred: " + err);
                    return;
                }

                fruit[socket.room] = result;
            });
        };

}

Body:
You can use promisify to convert callback to promise and then use await

sample code should be like this

const vegetables = {};
const fruit = {};
const Promise = require('bluebird'); // or you can use node utility module as well
const db = Promise.promisifyAll(require('YOUR DB LIB'));
const db_connection = 'YOUR DB CONNECTION'

async function starter (){
  const SQL = "select growth_items from garden where room_id = ?";
  try {
    const result = await db_connection.query(SQL);
    console.log(result);
    check_foods();
  } catch(err) {
    console.log("Garden Error: " + err);
  }
}

async function check_foods(){
  //Check to see if vegetables[socket.room] already exists, otherwise load it from the database
  if (typeof vegetables[socket.room] !== "undefined"){
    const SQL = "select name, qty from vegetables where room_id = ?";
    try {
      const result = await db_connection.query(SQL);
      vegetables[socket.room] = result;
    } catch(err) {
      console.log("An vegetable error has occurred: " + err);
      return;
    }
  }

  //Check to see if fruit already exists before looking up again
  if (typeof fruit[socket.room] !== "undefined"){
      const SQL = "select name, qty from fruit where room_id = ?";
      try {
        const result = await db_connection.query(SQL);
        fruit[socket.room] = result;
      } catch(err) {
        console.log("An fruit error has occurred: " + err);
        return;
      }
  };
}


问:
Can't Deploy Asp.Net Core 2.0 app to Azure app services
Due to my limited reputation point (as I am still new to StackOverflow), I am unable to comment on other posts, so I have to create a new question. However, this does not appear to be the same problem indicated in the post .net-core-2.0 azure app service 502.5 error. I am not getting the 502.5 error but rather this message:

I did perform the steps in the other post anyway to no success. I am still getting the same problem shown above. I even completely deleted my Asp.Net Core 1.1 app service and related SQL database and then re-created a new one to host my Asp.Net Core 2.0 app service. Still, no success.

Does anybody have any fresh ideas about how to fix this problem?

Thank you for your feedback.

UPDATE:

I got the following error:

SqlException: Login failed for user 'null'. System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, object providerInfo, bool redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, bool applyTransientFaultHandling)

答:
I just did a migration for our Azure web app from ASP.Net Core 1 to 2.0. It also uses Azure SQL. Interestingly it didn't throw any SQL related errors as you experienced. Here are some note hopefully helpful to you:

use 'Tools|Nuget package manager' to update all components to the latest 2.0 version, including ASP.Net Core and EF Core.

fix errors shown after the updates. Some are easy to fix simply following the visual studio suggestions. Some might be tricky, and needs a lot of googling and researching. the key places needs to be careful are shown below:

in Program.cs:

```<code>public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args)
{
   return  WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                config.AddEnvironmentVariables();
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            })
            .UseSetting("detailErrors", "true")
            .UseStartup<Startup>()
            .UseSetting("DesignTime", "true")
            .CaptureStartupErrors(true)
            .Build();
}
</code>```

startup constructor becomes:

```<code>public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}
</code>```

in ConfigureServices methods,

```<code>        // authentication cookie
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = "/"; //new Microsoft.AspNetCore.Http.PathString("/");
            options.AccessDeniedPath = "/"; //new Microsoft.AspNetCore.Http.PathString("/");
        });

    // Add EntityFramework's Identity support.
    services.AddEntityFrameworkSqlServer();

    // Add ApplicationDbContext.
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])
        );
</code>```

In Configure method, I added this for server side debugging:

```<code> public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
    }
</code>```

on Azure web portal, add a new setting key/value pair, Hosting:Environment   Development:

Note: this is for debugging purpose (server-side mainly), and can be removed from production version.

during publishing, check the box to remove additional files at destination:

Here are my lessons learned while upgrading to ASP.Net Core 2.0. If you start from your original project again, the SQL bug might not be there by following one or two points mentioned above.

Body:
I just did a migration for our Azure web app from ASP.Net Core 1 to 2.0. It also uses Azure SQL. Interestingly it didn't throw any SQL related errors as you experienced. Here are some note hopefully helpful to you:

use 'Tools|Nuget package manager' to update all components to the latest 2.0 version, including ASP.Net Core and EF Core.

fix errors shown after the updates. Some are easy to fix simply following the visual studio suggestions. Some might be tricky, and needs a lot of googling and researching. the key places needs to be careful are shown below:

in Program.cs:

public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args)
{
   return  WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                config.AddEnvironmentVariables();
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            })
            .UseSetting("detailErrors", "true")
            .UseStartup<Startup>()
            .UseSetting("DesignTime", "true")
            .CaptureStartupErrors(true)
            .Build();
}

startup constructor becomes:

public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

in ConfigureServices methods,

        // authentication cookie
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = "/"; //new Microsoft.AspNetCore.Http.PathString("/");
            options.AccessDeniedPath = "/"; //new Microsoft.AspNetCore.Http.PathString("/");
        });

    // Add EntityFramework's Identity support.
    services.AddEntityFrameworkSqlServer();

    // Add ApplicationDbContext.
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])
        );

In Configure method, I added this for server side debugging:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
    }

on Azure web portal, add a new setting key/value pair, Hosting:Environment   Development:

Note: this is for debugging purpose (server-side mainly), and can be removed from production version.

during publishing, check the box to remove additional files at destination:

Here are my lessons learned while upgrading to ASP.Net Core 2.0. If you start from your original project again, the SQL bug might not be there by following one or two points mentioned above.