问:
Case expressions may only be nested to level 10 error in SQL query
I have original query on server1 and need to create it on server 2. I am able to create the View but while executing it I am getting error at CASE statement as below:

```<code>Error:

    Msg 8180, Level 16, State 1, Line 1
    Statement(s) could not be prepared.
    Msg 102, Level 15, State 1, Line 1
    Incorrect syntax near 'Qry1097'.
    Msg 125, Level 15, State 4, Line 1
    Case expressions may only be nested to level 10.
</code>```

Query:
    SELECT

```<code>ID, Forename, Surname,

Code, Description,

Grade, Dept,

Course, Title,

CASE WHEN Code IN ('VJ028') THEN 'FUNCTIONAL SKILLS - LEVEL 1 & LEVEL 2'

WHEN Code IN ('VE203', '22877C')  THEN 'WRITING - LEVEL 2'

WHEN Code IN ('VE202', 'VE201')  THEN 'READING - LEVEL 2'

WHEN Code = 'VE201'  THEN 'SPEAKING & LISTENING'

WHEN Code = 'RU243'  THEN 'ENTRY LEVEL'

WHEN Code IN ('22875C') THEN 'E2 FUNCTIONAL SKILLS SPEAKING & LISTENING'

WHEN Code IN ('22876C', '22879C')  THEN 'E2 FUNCTIONAL SKILLS READING'

WHEN Code = '22877C'  THEN 'E2 FUNCTIONAL SKILLS WRITING'

WHEN Code = '22878C'  THEN 'E3 FUNCTIONAL SKILLS SPEAKING & LISTENING'

WHEN Code = '22880C'  THEN 'E3 FUNCTIONAL SKILLS WRITING'

WHEN Code= '22879C' THEN  'E3 FUNCTIONAL SKILLS READING'

WHEN Code = 'VE102'  THEN 'READING-LEVEL 1'

WHEN Code = 'VE103'  THEN 'WRITING-LEVEL 1'

WHEN Code = '3748-01'  THEN 'FUNCTIONAL SKILLS ENGLISH'

WHEN Code = 'VE101'  THEN 'SPEAKING & LISTENING-LEVEL 1'

END AS SubjectCode,

CASE

WHEN Description = 'FUNCTIONAL SKILLS - ENGLISH (LEVEL 1 & LEVEL  2)' THEN 'Overall'

WHEN Description = 'ENGLISH (ENTRY LEVEL)' THEN 'Overall'

WHEN Description = 'FUNCTIONAL SKILLS ENGLISH' THEN 'Overall'

WHEN Description = 'READING -ENGLISH LEVEL 2' THEN 'Reading'

WHEN Description = 'READING- ENGLISH (LEVEL 1 )' THEN 'Reading'

WHEN Description = 'E2 ENGLISH FUNTIONAL SKILLS READING' THEN 'Reading'

WHEN Description = 'E3 ENGLISH FUNTIONAL SKILLS READING' THEN 'Reading'

WHEN Description = 'WRITING- ENGLISH (LEVEL 1 )' THEN 'Writing'

WHEN Description = 'WRITING- ENGLISH LEVEL  2' THEN 'Writing'

WHEN Description = 'E2 ENGLISH FUNCTIONAL SKILLS WRITING' THEN 'Writing'

WHEN Description = 'E3 ENGLISH FUNCTIONAL SKILLS WRITING' THEN 'Writing'

WHEN Description = 'SPEAKING & LISTENING- ENGLISH LEVEL 2' THEN 'Speaking & Listening'

WHEN Description = 'SPEAKING & LISTENING- ENGLISH (LEVEL 1)' THEN 'Speaking & Listening'

WHEN Description = 'E3 ENGLISH FUNCTIONAL SKILLS SPEAKING AND LISTENING' THEN 'Speaking & Listening'

WHEN Description = 'E2 ENGLISH FUNCTIONAL SKILLS SPEAKING AND LISTENING' THEN 'Speaking & Listening'

END AS CourseType,

CASE WHEN Act_Grade  = 'PA' THEN 'Pass'

WHEN e.EXSS_Act_Grade = 'FL'  THEN 'Fail'

WHEN e.EXSS_Act_Grade = 'XA'  THEN 'Not Attended'

END AS Grade

FROM Table
</code>```

Error:

Case expressions may only be nested to level 10.

How can I correct this?

答:
If the values are numeric another work around would be to simply add multiple case statements together. See below example.</p>

```<code>select
case when @Period=1 then Bal01 else 0 end +
case when @Period=2 then Bal02 else 0 end +
case when @Period=3 then Bal03 else 0 end +
case when @Period=4 then Bal04 else 0 end +
case when @Period=5 then Bal05 else 0 end +
case when @Period=6 then Bal06 else 0 end +
case when @Period=7 then Bal07 else 0 end +
case when @Period=8 then Bal08 else 0 end +
case when @Period=9 then Bal09 else 0 end +
case when @Period=10 then Bal10 else 0 end +
case when @Period=11 then Bal11 else  0 end +
case when @Period=12 then Bal12 else  0 end

from VendorHistory
where Vendor = 'Staples'
</code>```

Body:
I have original query on server1 and need to create it on server 2. I am able to create the View but while executing it I am getting error at CASE statement as below:

Error:

    Msg 8180, Level 16, State 1, Line 1
    Statement(s) could not be prepared.
    Msg 102, Level 15, State 1, Line 1
    Incorrect syntax near 'Qry1097'.
    Msg 125, Level 15, State 4, Line 1
    Case expressions may only be nested to level 10.

Query:
    SELECT

ID, Forename, Surname,

Code, Description,

Grade, Dept,

Course, Title,

CASE WHEN Code IN ('VJ028') THEN 'FUNCTIONAL SKILLS - LEVEL 1 & LEVEL 2'

WHEN Code IN ('VE203', '22877C')  THEN 'WRITING - LEVEL 2'

WHEN Code IN ('VE202', 'VE201')  THEN 'READING - LEVEL 2'

WHEN Code = 'VE201'  THEN 'SPEAKING & LISTENING'

WHEN Code = 'RU243'  THEN 'ENTRY LEVEL'

WHEN Code IN ('22875C') THEN 'E2 FUNCTIONAL SKILLS SPEAKING & LISTENING'

WHEN Code IN ('22876C', '22879C')  THEN 'E2 FUNCTIONAL SKILLS READING'

WHEN Code = '22877C'  THEN 'E2 FUNCTIONAL SKILLS WRITING'

WHEN Code = '22878C'  THEN 'E3 FUNCTIONAL SKILLS SPEAKING & LISTENING'

WHEN Code = '22880C'  THEN 'E3 FUNCTIONAL SKILLS WRITING'

WHEN Code= '22879C' THEN  'E3 FUNCTIONAL SKILLS READING'

WHEN Code = 'VE102'  THEN 'READING-LEVEL 1'

WHEN Code = 'VE103'  THEN 'WRITING-LEVEL 1'

WHEN Code = '3748-01'  THEN 'FUNCTIONAL SKILLS ENGLISH'

WHEN Code = 'VE101'  THEN 'SPEAKING & LISTENING-LEVEL 1'

END AS SubjectCode,

CASE

WHEN Description = 'FUNCTIONAL SKILLS - ENGLISH (LEVEL 1 & LEVEL  2)' THEN 'Overall'

WHEN Description = 'ENGLISH (ENTRY LEVEL)' THEN 'Overall'

WHEN Description = 'FUNCTIONAL SKILLS ENGLISH' THEN 'Overall'

WHEN Description = 'READING -ENGLISH LEVEL 2' THEN 'Reading'

WHEN Description = 'READING- ENGLISH (LEVEL 1 )' THEN 'Reading'

WHEN Description = 'E2 ENGLISH FUNTIONAL SKILLS READING' THEN 'Reading'

WHEN Description = 'E3 ENGLISH FUNTIONAL SKILLS READING' THEN 'Reading'

WHEN Description = 'WRITING- ENGLISH (LEVEL 1 )' THEN 'Writing'

WHEN Description = 'WRITING- ENGLISH LEVEL  2' THEN 'Writing'

WHEN Description = 'E2 ENGLISH FUNCTIONAL SKILLS WRITING' THEN 'Writing'

WHEN Description = 'E3 ENGLISH FUNCTIONAL SKILLS WRITING' THEN 'Writing'

WHEN Description = 'SPEAKING & LISTENING- ENGLISH LEVEL 2' THEN 'Speaking & Listening'

WHEN Description = 'SPEAKING & LISTENING- ENGLISH (LEVEL 1)' THEN 'Speaking & Listening'

WHEN Description = 'E3 ENGLISH FUNCTIONAL SKILLS SPEAKING AND LISTENING' THEN 'Speaking & Listening'

WHEN Description = 'E2 ENGLISH FUNCTIONAL SKILLS SPEAKING AND LISTENING' THEN 'Speaking & Listening'

END AS CourseType,

CASE WHEN Act_Grade  = 'PA' THEN 'Pass'

WHEN e.EXSS_Act_Grade = 'FL'  THEN 'Fail'

WHEN e.EXSS_Act_Grade = 'XA'  THEN 'Not Attended'

END AS Grade

FROM Table

Error:

Case expressions may only be nested to level 10.

How can I correct this?

Body:
If the values are numeric another work around would be to simply add multiple case statements together. See below example.

select
case when @Period=1 then Bal01 else 0 end +
case when @Period=2 then Bal02 else 0 end +
case when @Period=3 then Bal03 else 0 end +
case when @Period=4 then Bal04 else 0 end +
case when @Period=5 then Bal05 else 0 end +
case when @Period=6 then Bal06 else 0 end +
case when @Period=7 then Bal07 else 0 end +
case when @Period=8 then Bal08 else 0 end +
case when @Period=9 then Bal09 else 0 end +
case when @Period=10 then Bal10 else 0 end +
case when @Period=11 then Bal11 else  0 end +
case when @Period=12 then Bal12 else  0 end

from VendorHistory
where Vendor = 'Staples'


来源: stackexchange

问:
Getting the source code of a page from a googlechrome extension
I am writting an extension for googlechrome to display a list of items from a website. The problem I have is that I cannot get the source code of the page I am looking for. When I tried putting it in an iframe, it had code that would change the location of the window. XMLhttpRequest is also only allowed on your own domain. Is there any way I can get the source code for a site from a googlechrome extension through javascript?

here is the manifest:

```<code>{
  "name": "My First Extension",
  "version": "1.0",
  "description": "The first extension that I made.",
  "browser_action": {
    "default_icon": "icon.png",
    "popup": "popup.html"
  },
  "permissions": [
    "http://api.flickr.com/",
    "http://search.twitter.com/"
  ]
 }
</code>```

答:
can you run the site in an iframe and then use some javascript to run:

```<code>sourceCode=[iframename].document.body.parentNode.innerHTML;
sourceCode='<html>'+sourceCode+'</html>'
</code>```

I don't know if this works across domains

ContentLicense: CC BY-SA 2.5

Body:
I am writting an extension for googlechrome to display a list of items from a website. The problem I have is that I cannot get the source code of the page I am looking for. When I tried putting it in an iframe, it had code that would change the location of the window. XMLhttpRequest is also only allowed on your own domain. Is there any way I can get the source code for a site from a googlechrome extension through javascript?

here is the manifest:

{
  "name": "My First Extension",
  "version": "1.0",
  "description": "The first extension that I made.",
  "browser_action": {
    "default_icon": "icon.png",
    "popup": "popup.html"
  },
  "permissions": [
    "http://api.flickr.com/",
    "http://search.twitter.com/"
  ]
 }

Body:
can you run the site in an iframe and then use some javascript to run:

sourceCode=[iframename].document.body.parentNode.innerHTML;
sourceCode='<html>'+sourceCode+'</html>'

I don't know if this works across domains


问:
How to average several readings in python?
A sensor generates an reading every one second for five seconds. I was trying to use the function np.mean to calculate the average of five sensor readings (i.e., sensor1_t1 to sensor1_t5), however it doesn't work.

Can you please help me on this?

Thanks.

```<code>sensor1_t1 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t2 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t3 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t4 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t5 = BridgeValue(0) * 274.0 - 2.1
sleep(1)

# my code - not working
#avg_sensor1 = np.mean(sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5)
</code>```

答:
You need to pass an array-like object to the a parameter of np.mean.  Try:

```<code>avg_sensor1 = np.mean([sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5])
</code>```

You're currently passing 5 arguments when you need to pass them as one array-like object.

In other words, the syntax for np.mean is:

numpy.mean(a, axis=None, dtype=None, out=None, ...

The way you currently are calling the function, you're passing 5 positional arguments.  These get interpreted as separate parameters:

sensor1_t1 is passed to a

sensor1_t2 is passed to axis

sensor1_t3 is passed to dtype

...and so on.

Note that the syntax I suggested passes a list, which is one of the structures that's considered "array-like."  More on that here if you are interested.

ContentLicense: CC BY-SA 3.0

Body:
A sensor generates an reading every one second for five seconds. I was trying to use the function np.mean to calculate the average of five sensor readings (i.e., sensor1_t1 to sensor1_t5), however it doesn't work.

Can you please help me on this?

Thanks.

sensor1_t1 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t2 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t3 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t4 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t5 = BridgeValue(0) * 274.0 - 2.1
sleep(1)

# my code - not working
#avg_sensor1 = np.mean(sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5)

Body:
You need to pass an array-like object to the a parameter of np.mean.  Try:

avg_sensor1 = np.mean([sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5])

You're currently passing 5 arguments when you need to pass them as one array-like object.

In other words, the syntax for np.mean is:

numpy.mean(a, axis=None, dtype=None, out=None, ...

The way you currently are calling the function, you're passing 5 positional arguments.  These get interpreted as separate parameters:

sensor1_t1 is passed to a

sensor1_t2 is passed to axis

sensor1_t3 is passed to dtype

...and so on.

Note that the syntax I suggested passes a list, which is one of the structures that's considered "array-like."  More on that here if you are interested.


问:
socket.to(roomId).emit not working after reconnect
I'd like to explain a problem I've been facing the last days and I'm not able to solve. I'm working with socket.io, using rooms to emit to multiple clients. I am testing the situation in which one reconnects (due to wi-fi connection failure for example).

The situation is the following:
Client side:

```<code>socket.on('reconnect', function () {
    var socketId = socket.id;
    socket.emit('reconnectAttempt',{
        id: $matchId,
        username: $username,
        socketId: socketId
    });
    log("you were reconnected");
});
</code>```

Server Side:

```<code>socket.on('reconnectAttempt',function(data){
    listClientsInRoom(data.id);
    socket.join(data.id); // Since socket.id changes after reconnect
    listClientsInRoom(data.id);
    socket.to(data.id).emit('reconnect attempt succeeded');
};
</code>```

Where:

```<code>function listClientsInRoom(key){
    var clients = io.sockets.adapter.rooms[key].sockets;
    console.log('___Clients in room:'+JSON.stringify(clients));
}
</code>```

and the output is something like (In this case only one client which reconnects):

```<code>___Clients in room:{"mfA-h4IkTtUMgPNsAAAD":true}
___Clients in room:{"mfA-
h4IkTtUMgPNsAAAD":true,"ShdVRVzVr4x4WCggAAAE":true}
</code>```

In this case, being ShdVRVzVr4x4WCggAAAE the socket.id after the reconnect event.
Then, with this situation, it seems that the socket has been properly added
to the room, but as you can see, after joining, i do :

```<code>socket.to(data.id).emit('reconnect attempt succeeded');
</code>```

This should just do a log in the client side (In all the room), and works in all clients except the one that reconnected. If i do :

```<code>socket.emit('reconnect attempt succeeded');
</code>```

instead, I will see the log correctly.

Can somebody help me please?

Thanks

答:
Stupid mistake, was just trying with this 'reconnect attempt succeeded' event, which as can be seen in the question is wrong called.

Question:

```<code>socket.to(data.id).emit('reconnect attempt succeeded');
</code>```

Correct way

```<code>io.to(data.id).emit('reconnect attempt succeeded');
</code>```

Body:
I'd like to explain a problem I've been facing the last days and I'm not able to solve. I'm working with socket.io, using rooms to emit to multiple clients. I am testing the situation in which one reconnects (due to wi-fi connection failure for example).

The situation is the following:
Client side:

socket.on('reconnect', function () {
    var socketId = socket.id;
    socket.emit('reconnectAttempt',{
        id: $matchId,
        username: $username,
        socketId: socketId
    });
    log("you were reconnected");
});

Server Side:

socket.on('reconnectAttempt',function(data){
    listClientsInRoom(data.id);
    socket.join(data.id); // Since socket.id changes after reconnect
    listClientsInRoom(data.id);
    socket.to(data.id).emit('reconnect attempt succeeded');
};

Where:

function listClientsInRoom(key){
    var clients = io.sockets.adapter.rooms[key].sockets;
    console.log('___Clients in room:'+JSON.stringify(clients));
}

and the output is something like (In this case only one client which reconnects):

___Clients in room:{"mfA-h4IkTtUMgPNsAAAD":true}
___Clients in room:{"mfA-
h4IkTtUMgPNsAAAD":true,"ShdVRVzVr4x4WCggAAAE":true}

In this case, being ShdVRVzVr4x4WCggAAAE the socket.id after the reconnect event.
Then, with this situation, it seems that the socket has been properly added
to the room, but as you can see, after joining, i do :

socket.to(data.id).emit('reconnect attempt succeeded');

This should just do a log in the client side (In all the room), and works in all clients except the one that reconnected. If i do :

socket.emit('reconnect attempt succeeded');

instead, I will see the log correctly.

Can somebody help me please?

Thanks

Body:
Stupid mistake, was just trying with this 'reconnect attempt succeeded' event, which as can be seen in the question is wrong called.

Question:

socket.to(data.id).emit('reconnect attempt succeeded');

Correct way

io.to(data.id).emit('reconnect attempt succeeded');


问:
Ibpy: how to capture data returned from reqAccountSummary
I'm using ibapi from interactive brokers and I got stuck on how to capture the returned data, generally.  For example, according to api docs, when I request reqAccountSummary(), the method delivered the data via accountSummary().  But their example only print the data. I've tried capturing the data or assign it to a variable, but no where in their docs shows how to do this.  I've also google search and only find register() and registerAll() but that is from ib.opt which isn't in the latest working ibapi package.  </p>

<p>Here is my code.  Could you show me how to modify accountSummary() to capture the data?  </p>

```<code>from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
class TestApp(EWrapper,EClient):
    def __init__(self):
        EClient.__init__(self,self)

    # request account data:
    def my_reqAccountSummary1(self, reqId:int, groupName:str, tags:str):
        self.reqAccountSummary(reqId, "All", "TotalCashValue")

    # The received data is passed to accountSummary()
    def accountSummary(self, reqId: int, account: str, tag: str, value: str, currency: str):
        super().accountSummary(reqId, account, tag, value, currency)
        print("Acct# Summary. ReqId>:", reqId, "Acct:", account, "Tag: ", tag, "Value:", value, "Currency:", currency)
        return value  #This is my attempt which doesn't work

def main():
    app = TestApp()
    app.connect("127.0.0.1",7497,clientId=0)

    app.my_reqAccountSummary1(8003, "All", "TotalCashValue")  #"This works, but the data is print to screen. I don't know how to assign the received TotalCashValue to a variable"

    # myTotalCashValue=app.my_reqAccountSummary1(8003, "All", "TotalCashValue")  #"My attempt doesn't work"
    # more code to stop trading if myTotalCashValue is low

    app.run()

if __name__=="__main__":
    main()
</code>```

答:
You cannot do this in the main function, since app.run listens to responses from the TWS. Once you have set up all the callbacks as you correctly did, the main function will be looping forever in app.run.

You have to put your code directly into the accountSummary function. This is how these kind of programs work, you put your logic directly into
 the callback functions. You can always assign self.myTotalCashValue = value to make it available to other parts of your class, or even to another thread.

-- OR --

You run app.run in a thread and wait for the value to return, e.g.

add self._myTotalCashValue = value to  accountSummary, import threading and time and then add something like this in main:

```<code>t = threading.Thread(target=app.run)
t.daemon = True
t.start()
while not hasattr(app,"_myTotalCashValue"):
    time.sleep(1)
print(app._myTotalCashValue)
</code>```

As usual with threads, you have to be a bit careful with shared memory between app and main.

Body:
I'm using ibapi from interactive brokers and I got stuck on how to capture the returned data, generally.  For example, according to api docs, when I request reqAccountSummary(), the method delivered the data via accountSummary().  But their example only print the data. I've tried capturing the data or assign it to a variable, but no where in their docs shows how to do this.  I've also google search and only find register() and registerAll() but that is from ib.opt which isn't in the latest working ibapi package.

Here is my code.  Could you show me how to modify accountSummary() to capture the data?

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
class TestApp(EWrapper,EClient):
    def __init__(self):
        EClient.__init__(self,self)

    # request account data:
    def my_reqAccountSummary1(self, reqId:int, groupName:str, tags:str):
        self.reqAccountSummary(reqId, "All", "TotalCashValue")

    # The received data is passed to accountSummary()
    def accountSummary(self, reqId: int, account: str, tag: str, value: str, currency: str):
        super().accountSummary(reqId, account, tag, value, currency)
        print("Acct# Summary. ReqId>:", reqId, "Acct:", account, "Tag: ", tag, "Value:", value, "Currency:", currency)
        return value  #This is my attempt which doesn't work

def main():
    app = TestApp()
    app.connect("127.0.0.1",7497,clientId=0)

    app.my_reqAccountSummary1(8003, "All", "TotalCashValue")  #"This works, but the data is print to screen. I don't know how to assign the received TotalCashValue to a variable"

    # myTotalCashValue=app.my_reqAccountSummary1(8003, "All", "TotalCashValue")  #"My attempt doesn't work"
    # more code to stop trading if myTotalCashValue is low

    app.run()

if __name__=="__main__":
    main()

Body:
You cannot do this in the main function, since app.run listens to responses from the TWS. Once you have set up all the callbacks as you correctly did, the main function will be looping forever in app.run.

You have to put your code directly into the accountSummary function. This is how these kind of programs work, you put your logic directly into
 the callback functions. You can always assign self.myTotalCashValue = value to make it available to other parts of your class, or even to another thread.

-- OR --

You run app.run in a thread and wait for the value to return, e.g.

add self._myTotalCashValue = value to  accountSummary, import threading and time and then add something like this in main:

t = threading.Thread(target=app.run)
t.daemon = True
t.start()
while not hasattr(app,"_myTotalCashValue"):
    time.sleep(1)
print(app._myTotalCashValue)

As usual with threads, you have to be a bit careful with shared memory between app and main.


答: Because numpy is mainly used with arrays (especially numpy.ndarray) numpy.mean expects an array as it's first argument. But you don't need to create an ndarray you can simply change np.mean(sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5) to np.mean([sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5]) and numpy will take care of the rest.

Title: How to average several readings in python?


问:
What are your experiences with Windows Workflow Foundation?
I am evaluating WF for use in line of business applications on the web, and I would love to hear some recent first-hand accounts of this technology.

My main interest here is in improving the maintainability of projects and maybe in increasing developer productivity when working on complex processes that change frequently.

I really like the idea of WF, however it seems to be relatively unknown and many older comments I've come across mention that it's overwhelmingly complex once you get into it.

If it's overdesigned to the point that it's unusable (or a bad tradeoff) for a small to medium-sized project, that's something that I need to know.

Of course, it has been out since late 2006, so perhaps it has matured. If that's the case, that's another piece of information that would be very helpful!

Thanks in advance!

答:
Last year we completed a working application with WF, now used as the backbone of an unbelievably huge system which is used by a very big bank for its mortgage process. The pe process has many steps starting from customer application to approval of credit.

Although it was a success, there were so many problems and crisis all along the way. And it wont worth the trouble for any smaller size projects.

OwnerDisplayName: Brian MacKay

OwnerDisplayName: Orkun Balkancı

LastEditorDisplayName: Orkun Balkancı


问:
Mysql Query Slow on large table
Trying to run the following query on a mysql table that has over 3 million rows. Its very slow to the point it pretty much hangs until the script times out. Below is the query and the explain from that query, any suggestions?

```<code>SELECT SQL_CALC_FOUND_ROWS
listing_track.listingid,
listing_track.commid,
listing.listingname,
listing_package.packagename,
listing.active,
community.commname,
SUM( listing_track.impression ) AS listing_impressions,
SUM( listing_track.view ) AS listing_views,
SUM( listing_track.phone ) AS listing_phones,
SUM( listing_track.forward ) AS listing_forward,
SUM( listing_track.coupon ) AS listing_coupons,
SUM( listing_track.email ) AS listing_emails
FROM listing_track
INNER JOIN listing ON listing_track.listingid = listing.id
INNER JOIN community ON listing_track.commid = community.id
INNER JOIN listing_package ON listing.packageid = listing_package.id
WHERE listing_track.commid =2
GROUP BY listing_track.commid, listing_track.listingid, listing_track.trackip
LIMIT 0 , 25
</code>```

Here is the explain:

答:
Without knowing a lot more about the structure of the data its impossible to say, however given the available informnation, the system seems to be making a reasonable attempt at the query. If you really want to process millions of rows i a single select, it is going to take time. However if the relationships are strictly 1:N you could easily drop the lookup to the other tables - and just count the records in the listng table without changing the results:

```<code>SELECT SQL_CALC_FOUND_ROWS *
FROM listing
WHERE commid=2
</code>```

What is the purpose of a query which returns a million rows?

It's possible that there's some scope for tunng the DBMS - particularly the join buffer - try running mysqltuner against it.

The plan does seem to suggest that the only filtering you've applied (listing_track.commid =2) is best served by an index lookup on the table returning in the region of a million rows - If there are only 3 million rows in the database, then a full table scan would probably be faster.

Title: Mysql Query Slow on large table

Body:
Trying to run the following query on a mysql table that has over 3 million rows. Its very slow to the point it pretty much hangs until the script times out. Below is the query and the explain from that query, any suggestions?

SELECT SQL_CALC_FOUND_ROWS
listing_track.listingid,
listing_track.commid,
listing.listingname,
listing_package.packagename,
listing.active,
community.commname,
SUM( listing_track.impression ) AS listing_impressions,
SUM( listing_track.view ) AS listing_views,
SUM( listing_track.phone ) AS listing_phones,
SUM( listing_track.forward ) AS listing_forward,
SUM( listing_track.coupon ) AS listing_coupons,
SUM( listing_track.email ) AS listing_emails
FROM listing_track
INNER JOIN listing ON listing_track.listingid = listing.id
INNER JOIN community ON listing_track.commid = community.id
INNER JOIN listing_package ON listing.packageid = listing_package.id
WHERE listing_track.commid =2
GROUP BY listing_track.commid, listing_track.listingid, listing_track.trackip
LIMIT 0 , 25

Here is the explain:

Body:
Without knowing a lot more about the structure of the data its impossible to say, however given the available informnation, the system seems to be making a reasonable attempt at the query. If you really want to process millions of rows i a single select, it is going to take time. However if the relationships are strictly 1:N you could easily drop the lookup to the other tables - and just count the records in the listng table without changing the results:

SELECT SQL_CALC_FOUND_ROWS *
FROM listing
WHERE commid=2

What is the purpose of a query which returns a million rows?

It's possible that there's some scope for tunng the DBMS - particularly the join buffer - try running mysqltuner against it.

The plan does seem to suggest that the only filtering you've applied (listing_track.commid =2) is best served by an index lookup on the table returning in the region of a million rows - If there are only 3 million rows in the database, then a full table scan would probably be faster.


问:
Insert into table the outcome of a select on that table using Row_Number
I am creating a query where in I select data on a table, then select a number of rows from that table, to then insert those rows into another identical table in another Database, and then repeat the proces to select the next number of rows from the orignal table.

For Reference, this is what i try to do (already build it for Oracle):

```<code>$" INSERT INTO {destination-table}
     SELECT * FROM {original-table}
     WHERE ROWID IN (SELECT B.RID
          FROM  (SELECT ROWID AS RID, rownum as RID2
                   FROM {original-table}
                   WHERE {Where Claus}
                   AND ROWNUM <= {recordsPerStatement * iteration}
) B WHERE RID2 > {recordsPerStatement * (iteration - 1)})"
</code>```

This is put through a loop in .net

For SQL server however I fail to get this done. The data i retrieve with:

```<code>$" Select B.* from (Select A.* from (Select Row_NUMBER()
       OVER (order by %%physloc%%) As RowID, {original-table}.* FROM
{original-table} where {where-claus})
A Where A.RowID between {recordsPerStatement * (iteration - 1)}
AND {recordsPerStatement * iteration} B"
</code>```

The problem here is that above select produces an extra column (ROWID) which prevents me from inserting the above data into the destination-table

I have been looking at ways to get rid of the ROWID column in the top select or to insert data from original-table based on the data retrieved
(something like insert into destination-table select * from original-table where exists in (rest of select query)..... but to no avail

TLDR = Get rid of a ROWID column used in calculations to then be able to insert rows into an identical table

specifications:

A LOT (millions of rows) of data (therefor processing it in bits)

Unknown tables (so i cannot call on specific column names, as they are unknown)

needs to have an order (thus the row_number) so the same data is not copied twice.

insert using a select query (as first retrieving it and doing some magic locally would severly impact performance)

If necessary additional variables can be added in here (like an order claus variable) however, any reference to data in the query will ALWAYS be a variable + If I can find a way to not add more varriables in the query then that would be preferable

I hope that someone would have an idea on what i could look at further.

答:
The solution i came up with:

First reading the column_names from the database and storing them locally, to then use them again in building up the insert / select query and only select those columns from the view (which are all apart from ROWID).

```<code>commandText = $"SELECT column_name
               FROM INFORMATION_SCHEMA.COLUMNS
               WHERE TABLE_NAME = N'{table}'"

columnNames = "executionfunction with commandText"
columnNamesCount = columnNames.Rows.Count

Dim counter As Int16 = 0
commandText = String.Empty
commandText = $"INSERT INTO {destination} SELECT "

    For Each row As DataRow In columnNames.Rows

         If counter = columnNamesCount - 1 Then
              commandText += $"B.{row("column_name")} "
         Else
              commandText += $"B.{row("column_name")}, "
         End If

         counter = counter + 1
    Next

    commandText += $"FROM
                   (Select A.* FROM (Select Row_NUMBER()
                   OVER(order by %%physloc%%) AS RowID, {table}.*
                   FROM {table} where {filter}) A
                   WHERE A.RowID between ({recordsPerStatement} * ({iteration}-1)) + 1
                   AND ({recordsPerStatement} * {iteration})) B"
</code>```

EDIT: To remove the %%physloc%% clause AN OFFSET FETCH NEXT part has been build in. new approach:

```<code>commandText += $"INSERT INTO {destination} SELECT * FROM {table} WHERE {filter}"

    For i As Int16 = 1 To columnNamesCount

        If i = 1 Then
            commandText += $"ORDER BY {columnNames.Rows(i - 1)("column_name")} ASC"
        Else
            commandText += $"{columnNames.Rows(i - 1)("column_name")} ASC"
        End If

        If i <> columnNamesCount Then
            commandText += ", "
        End If
    Next

commandText += $" OFFSET ({recordsPerStatement} * ({iteration} -1)) ROWS FETCH Next {recordsPerStatement} ROWS ONLY"
</code>```

Body:
I am creating a query where in I select data on a table, then select a number of rows from that table, to then insert those rows into another identical table in another Database, and then repeat the proces to select the next number of rows from the orignal table.

For Reference, this is what i try to do (already build it for Oracle):

$" INSERT INTO {destination-table}
     SELECT * FROM {original-table}
     WHERE ROWID IN (SELECT B.RID
          FROM  (SELECT ROWID AS RID, rownum as RID2
                   FROM {original-table}
                   WHERE {Where Claus}
                   AND ROWNUM <= {recordsPerStatement * iteration}
) B WHERE RID2 > {recordsPerStatement * (iteration - 1)})"

This is put through a loop in .net

For SQL server however I fail to get this done. The data i retrieve with:

$" Select B.* from (Select A.* from (Select Row_NUMBER()
       OVER (order by %%physloc%%) As RowID, {original-table}.* FROM
{original-table} where {where-claus})
A Where A.RowID between {recordsPerStatement * (iteration - 1)}
AND {recordsPerStatement * iteration} B"

The problem here is that above select produces an extra column (ROWID) which prevents me from inserting the above data into the destination-table

I have been looking at ways to get rid of the ROWID column in the top select or to insert data from original-table based on the data retrieved
(something like insert into destination-table select * from original-table where exists in (rest of select query)..... but to no avail

TLDR = Get rid of a ROWID column used in calculations to then be able to insert rows into an identical table

specifications:

A LOT (millions of rows) of data (therefor processing it in bits)

Unknown tables (so i cannot call on specific column names, as they are unknown)

needs to have an order (thus the row_number) so the same data is not copied twice.

insert using a select query (as first retrieving it and doing some magic locally would severly impact performance)

If necessary additional variables can be added in here (like an order claus variable) however, any reference to data in the query will ALWAYS be a variable + If I can find a way to not add more varriables in the query then that would be preferable

I hope that someone would have an idea on what i could look at further.

Body:
The solution i came up with:

First reading the column_names from the database and storing them locally, to then use them again in building up the insert / select query and only select those columns from the view (which are all apart from ROWID).

commandText = $"SELECT column_name
               FROM INFORMATION_SCHEMA.COLUMNS
               WHERE TABLE_NAME = N'{table}'"

columnNames = "executionfunction with commandText"
columnNamesCount = columnNames.Rows.Count

Dim counter As Int16 = 0
commandText = String.Empty
commandText = $"INSERT INTO {destination} SELECT "

    For Each row As DataRow In columnNames.Rows

         If counter = columnNamesCount - 1 Then
              commandText += $"B.{row("column_name")} "
         Else
              commandText += $"B.{row("column_name")}, "
         End If

         counter = counter + 1
    Next

    commandText += $"FROM
                   (Select A.* FROM (Select Row_NUMBER()
                   OVER(order by %%physloc%%) AS RowID, {table}.*
                   FROM {table} where {filter}) A
                   WHERE A.RowID between ({recordsPerStatement} * ({iteration}-1)) + 1
                   AND ({recordsPerStatement} * {iteration})) B"

EDIT: To remove the %%physloc%% clause AN OFFSET FETCH NEXT part has been build in. new approach:

commandText += $"INSERT INTO {destination} SELECT * FROM {table} WHERE {filter}"

    For i As Int16 = 1 To columnNamesCount

        If i = 1 Then
            commandText += $"ORDER BY {columnNames.Rows(i - 1)("column_name")} ASC"
        Else
            commandText += $"{columnNames.Rows(i - 1)("column_name")} ASC"
        End If

        If i <> columnNamesCount Then
            commandText += ", "
        End If
    Next

commandText += $" OFFSET ({recordsPerStatement} * ({iteration} -1)) ROWS FETCH Next {recordsPerStatement} ROWS ONLY"


问:
group numbers in an array by step value changes
i have an array like [101, 107, 106, 199, 204, 205, 207, 306, 310, 312, 312, 314, 317, 318, 380, 377, 379, 382, 466, 469, 471, 472, 557, 559, 562, 566, 569...]

In this array, after a few integers, there will be a step change in value.(like between [101,107,106] and [199,204,...])
Or put it in another way, the array is made up of groups of integers, each group with values centered around an unknown mean.
But i won't know how many groups are there in total ,and the number of integers in each is uncertain.

How could i group those integers in each step change into different arrays.

Thanks

Body:
It seems from your posted code that a step occurs when abs(array[i]-array[i+1]) > 6. You can use this:

final = []
current = []
arr = [101, 107, 106, 199, 204, 205, 207, 306, 310, 312, 312, 314, 317, 318, 380, 377, 379, 382, 466, 469, 471, 472, 557, 559, 562, 566, 569]
for i in range(len(arr)-1):
   if abs(arr[i] - arr[i+1]) > 6:
      current.append(arr[i])
      final.append(current)
      current = []
   else:
       current.append(arr[i])

Output:

[[101, 107, 106], [199, 204, 205, 207], [306, 310, 312, 312, 314, 317, 318], [380, 377, 379, 382], [466, 469, 471, 472]]


问:
Server access Error: java.security.cert.CertificateException: No subject alternative DNS name matching repo1.maven.org found
I am doing: sbt clean and I started getting the following errors:

Server access Error: java.security.cert.CertificateException: No subject alternative DNS name matching repo1.maven.org found

This worked as recently as a few hours back. How do I fix this issue? I cannot do a build.

答:
I have spent a day working on this problem, and finally found out it is a recent problem mentioned by @mienaikoe. my workaround here is to create in file ~/.sbt/repositories url link </p>

```<code>[repositories]
local
secured-central: http://repo1.maven.org/maven2
</code>```

Body:
I have spent a day working on this problem, and finally found out it is a recent problem mentioned by @mienaikoe. my workaround here is to create in file ~/.sbt/repositories url link

[repositories]
local
secured-central: http://repo1.maven.org/maven2


问:
How to create a link with parameter in django
Hi I am trying to create a link with paremeter but I am getting an error (Page not found)

error

```<code>Reverse for 'hexcode' with arguments '('#d4cbd0',)' not found. 1 pattern(s) tried: ['hexcode/(?P<color>\\w)$']
</code>```

template

```<code>{% for color in palette_dominant_color %}
<a href="{% url 'brandcolors:hexcode' color %}" style="text-decoration:none;color:inherit">
  {{color}}
</a>
<br>
{% endfor %}
</code>```

urls.py

```<code>url(r'^hexcode/(?P<color>\w)/$', ThemeView.as_view(), name="hexcode"),
</code>```

views.py

```<code>class ThemeView(TemplateView):
    template_name='fabric/theme.html'

    def get_context_data(self, **kwargs):
        context = super(ThemeView, self).get_context_data(**kwargs)
        colors = Color.objects.filter(color=kwargs['color']).all()
        return context
</code>```

答: Your regex expects a single alphanumeric character, not a hash followed by several characters.</p>

Body:
Hi I am trying to create a link with paremeter but I am getting an error (Page not found)

error

Reverse for 'hexcode' with arguments '('#d4cbd0',)' not found. 1 pattern(s) tried: ['hexcode/(?P<color>\\w)$']

template

{% for color in palette_dominant_color %}

  {{color}}

{% endfor %}

urls.py

url(r'^hexcode/(?P<color>\w)/$', ThemeView.as_view(), name="hexcode"),

views.py

class ThemeView(TemplateView):
    template_name='fabric/theme.html'

    def get_context_data(self, **kwargs):
        context = super(ThemeView, self).get_context_data(**kwargs)
        colors = Color.objects.filter(color=kwargs['color']).all()
        return context


问:
Unhandled promise rejection (rejection id: 1): Error: kill ESRCH
I've made some research on the Web and SOF, but found nothing really helpful on that error.

I installed Node and Puppeteer with Windows 10 Ubuntu Bash, but didn't manage to make it work, yet I manage to make it work on Windows without Bash on an other machine.

My command is :

```<code>    node index.js
</code>```

My index.js tries to take a screenshot of a page :

```<code>    const puppeteer = require('puppeteer');

    async function run() {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('https://github.com');
    await page.screenshot({ path: 'screenshots/github.png' });

    browser.close();
    }

    run();
</code>```

Does anybody know the way I could fix this "Error: kill ESRCH" error?

答:
Points no consider:

Windows bash is not a complete drop-in replacement for Ubuntu bash (yet). There are many cases where different GUI based apps did not work properly. Also, the script might be confused by bash on windows 10. It could think that the os is linux instead of windows.

Windows 10 bash only supports 64-bit binaries, so make sure the node and the chrome version that's used inside is pretty much 64-bit. Puppeteer is using -child.pid to kill the child processes instead of child.pid on windows version. Make sure puppeteer is not getting confused by all these bash/windows thing.

Back to your case.

You are using browser.close() in the function, but it should be await browser.close(), otherwise it's not executing in proper order.

Also, You should try to add await page.close(); before browser.close();.

So the code should be,

```<code>await page.close();
await browser.close();
</code>```

Body:
I've made some research on the Web and SOF, but found nothing really helpful on that error.

I installed Node and Puppeteer with Windows 10 Ubuntu Bash, but didn't manage to make it work, yet I manage to make it work on Windows without Bash on an other machine.

My command is :

    node index.js

My index.js tries to take a screenshot of a page :

    const puppeteer = require('puppeteer');

    async function run() {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('https://github.com');
    await page.screenshot({ path: 'screenshots/github.png' });

    browser.close();
    }

    run();

Does anybody know the way I could fix this "Error: kill ESRCH" error?

Body:
Points no consider:

Windows bash is not a complete drop-in replacement for Ubuntu bash (yet). There are many cases where different GUI based apps did not work properly. Also, the script might be confused by bash on windows 10. It could think that the os is linux instead of windows.

Windows 10 bash only supports 64-bit binaries, so make sure the node and the chrome version that's used inside is pretty much 64-bit. Puppeteer is using -child.pid to kill the child processes instead of child.pid on windows version. Make sure puppeteer is not getting confused by all these bash/windows thing.

Back to your case.

You are using browser.close() in the function, but it should be await browser.close(), otherwise it's not executing in proper order.

Also, You should try to add await page.close(); before browser.close();.

So the code should be,

await page.close();
await browser.close();


问:
App crashes in ios simulator when trying to use Phone auth in react-native firebase
I've followed the docs and did the necessary settings but the app crashes while launch. I'm not able to figure out the problem as to why this is occurring. any one who worked with rnfirebase? facing this issue?

```<code>import React, { Component } from 'react';
import { View, Button, Text, TextInput, Image } from 'react-native';

import firebase from 'react-native-firebase';

const successImageUri = 'https://cdn.pixabay.com/photo/2015/06/09/16/12/icon-803718_1280.png';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.unsubscribe = null;
    this.state = {
      user: null,
      message: '',
      codeInput: '',
      phoneNumber: '+44',
      confirmResult: null
    };
    firebase.initializeApp({
      apiKey: 'AIzaSyAvKPtsqqqGjkGLkXD8BeqOR6GwJaI2AcE',
      appId: '1:170852024080:ios:9bb19d2f74715186',
      messagingSenderId: '170852024080',
      projectId: 'chatapp-7c693',
      authDomain: 'chatapp-7c693.firebaseapp.com',
      databaseURL: 'https://chatapp-7c693.firebaseio.com',
      storageBucket: 'chatapp-7c693.appspot.com'
    });
  }

  componentDidMount() {
    this.unsubscribe = firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({ user: user.toJSON() });
      } else {
        // User has been signed out, reset the state
        this.setState({
          user: null,
          message: '',
          codeInput: '',
          phoneNumber: '+44',
          confirmResult: null
        });
      }
    });
  }

//This is the example from the docs, so it must work

  componentWillUnmount() {
    if (this.unsubscribe) this.unsubscribe();
  }

  signIn = () => {
    const { phoneNumber } = this.state;
    this.setState({ message: 'Sending code ...' });

    firebase
      .auth()
      .signInWithPhoneNumber(phoneNumber)
      .then(confirmResult => this.setState({ confirmResult, message: 'Code has been sent!' }))
      .catch(error =>
        this.setState({ message: `Sign In With Phone Number Error: ${error.message}` })
      );
  };

  confirmCode = () => {
    const { codeInput, confirmResult } = this.state;

    if (confirmResult && codeInput.length) {
      confirmResult
        .confirm(codeInput)
        .then(user => {
          this.setState({ message: 'Code Confirmed!' });
        })
        .catch(error => this.setState({ message: `Code Confirm Error: ${error.message}` }));
    }
  };

  signOut = () => {
    firebase.auth().signOut();
  };

  renderPhoneNumberInput() {
    const { phoneNumber } = this.state;

    return (
      <View style={{ padding: 25 }}>
        <Text>Enter phone number:</Text>
        <TextInput
          autoFocus
          style={{ height: 40, marginTop: 15, marginBottom: 15 }}
          onChangeText={value => this.setState({ phoneNumber: value })}
          placeholder={'Phone number ... '}
          value={phoneNumber}
        />
        <Button title="Sign In" color="green" onPress={this.signIn} />
      </View>
    );
  }

  renderMessage() {
    const { message } = this.state;

    if (message.length) return null;

    return <Text style={{ padding: 5, backgroundColor: '#000', color: '#fff' }}>{message}</Text>;
  }

  renderVerificationCodeInput() {
    const { codeInput } = this.state;

    return (
      <View style={{ marginTop: 25, padding: 25 }}>
        <Text>Enter verification code below:</Text>
        <TextInput
          autoFocus
          style={{ height: 40, marginTop: 15, marginBottom: 15 }}
          onChangeText={value => this.setState({ codeInput: value })}
          placeholder={'Code ... '}
          value={codeInput}
        />
        <Button title="Confirm Code" color="#841584" onPress={this.confirmCode} />
      </View>
    );
  }

  render() {
    const { user, confirmResult } = this.state;
    return (
      <View style={{ flex: 1 }}>
        {!user && !confirmResult && this.renderPhoneNumberInput()}

        {this.renderMessage()}

        {!user && confirmResult && this.renderVerificationCodeInput()}

        {user && (
          <View
            style={{
              padding: 15,
              justifyContent: 'center',
              alignItems: 'center',
              backgroundColor: '#77dd77',
              flex: 1
            }}
          >
            <Image
              source={{ uri: successImageUri }}
              style={{ width: 100, height: 100, marginBottom: 25 }}
            />
            <Text style={{ fontSize: 25 }}>Signed In!</Text>
            <Text>{JSON.stringify(user)}</Text>
            <Button title="Sign Out" color="red" onPress={this.signOut} />
          </View>
        )}
      </View>
    );
  }
}
</code>```

can someone help? ive checked the docs again ..but no help ?idk
  what more details I should add..this is my first question on stack
  over flow..didnt know it was this annoying to ask a question...
      I tried the web firebase sdk and can use the anonymous signin.. but I need phone auth which I'm not able to accomplish as it has different setups for ios and android ...rnfirebase is suppose to same as the web sdk

答:
One of the few tricks will do

1. Add custom URL schemes to your Xcode project:

Open your project configuration: double-click the project name in
the left tree view. Select your app from the TARGETS section, then
select the Info tab, and expand the URL Types section.

Click the + button, and add a URL scheme for your reversed client ID.
To find this value, open the GoogleService-Info.plist configuration
file, and look for the REVERSED_CLIENT_ID key. Copy the value of that
key, and paste it into the URL Schemes box on the configuration page.
Leave the other fields blank.

more info here https://developers.google.com/identity/sign-in/ios/start-integrating

2. Run project from xcode then get back to terminal

Using Xcode, make sure you are opening the workspace file and not the project file. Run the it, once successfully built close Xcode get back to terminal react-native run-ios

Body:
I've followed the docs and did the necessary settings but the app crashes while launch. I'm not able to figure out the problem as to why this is occurring. any one who worked with rnfirebase? facing this issue?

import React, { Component } from 'react';
import { View, Button, Text, TextInput, Image } from 'react-native';

import firebase from 'react-native-firebase';

const successImageUri = 'https://cdn.pixabay.com/photo/2015/06/09/16/12/icon-803718_1280.png';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.unsubscribe = null;
    this.state = {
      user: null,
      message: '',
      codeInput: '',
      phoneNumber: '+44',
      confirmResult: null
    };
    firebase.initializeApp({
      apiKey: 'AIzaSyAvKPtsqqqGjkGLkXD8BeqOR6GwJaI2AcE',
      appId: '1:170852024080:ios:9bb19d2f74715186',
      messagingSenderId: '170852024080',
      projectId: 'chatapp-7c693',
      authDomain: 'chatapp-7c693.firebaseapp.com',
      databaseURL: 'https://chatapp-7c693.firebaseio.com',
      storageBucket: 'chatapp-7c693.appspot.com'
    });
  }

  componentDidMount() {
    this.unsubscribe = firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({ user: user.toJSON() });
      } else {
        // User has been signed out, reset the state
        this.setState({
          user: null,
          message: '',
          codeInput: '',
          phoneNumber: '+44',
          confirmResult: null
        });
      }
    });
  }

//This is the example from the docs, so it must work

  componentWillUnmount() {
    if (this.unsubscribe) this.unsubscribe();
  }

  signIn = () => {
    const { phoneNumber } = this.state;
    this.setState({ message: 'Sending code ...' });

    firebase
      .auth()
      .signInWithPhoneNumber(phoneNumber)
      .then(confirmResult => this.setState({ confirmResult, message: 'Code has been sent!' }))
      .catch(error =>
        this.setState({ message: `Sign In With Phone Number Error: ${error.message}` })
      );
  };

  confirmCode = () => {
    const { codeInput, confirmResult } = this.state;

    if (confirmResult && codeInput.length) {
      confirmResult
        .confirm(codeInput)
        .then(user => {
          this.setState({ message: 'Code Confirmed!' });
        })
        .catch(error => this.setState({ message: `Code Confirm Error: ${error.message}` }));
    }
  };

  signOut = () => {
    firebase.auth().signOut();
  };

  renderPhoneNumberInput() {
    const { phoneNumber } = this.state;

    return (
      <View style={{ padding: 25 }}>
        <Text>Enter phone number:</Text>
        <TextInput
          autoFocus
          style={{ height: 40, marginTop: 15, marginBottom: 15 }}
          onChangeText={value => this.setState({ phoneNumber: value })}
          placeholder={'Phone number ... '}
          value={phoneNumber}
        />
        <Button title="Sign In" color="green" onPress={this.signIn} />
      </View>
    );
  }

  renderMessage() {
    const { message } = this.state;

    if (message.length) return null;

    return <Text style={{ padding: 5, backgroundColor: '#000', color: '#fff' }}>{message}</Text>;
  }

  renderVerificationCodeInput() {
    const { codeInput } = this.state;

    return (
      <View style={{ marginTop: 25, padding: 25 }}>
        <Text>Enter verification code below:</Text>
        <TextInput
          autoFocus
          style={{ height: 40, marginTop: 15, marginBottom: 15 }}
          onChangeText={value => this.setState({ codeInput: value })}
          placeholder={'Code ... '}
          value={codeInput}
        />
        <Button title="Confirm Code" color="#841584" onPress={this.confirmCode} />
      </View>
    );
  }

  render() {
    const { user, confirmResult } = this.state;
    return (
      <View style={{ flex: 1 }}>
        {!user && !confirmResult && this.renderPhoneNumberInput()}

        {this.renderMessage()}

        {!user && confirmResult && this.renderVerificationCodeInput()}

        {user && (
          <View
            style={{
              padding: 15,
              justifyContent: 'center',
              alignItems: 'center',
              backgroundColor: '#77dd77',
              flex: 1
            }}
          >
            <Image
              source={{ uri: successImageUri }}
              style={{ width: 100, height: 100, marginBottom: 25 }}
            />
            <Text style={{ fontSize: 25 }}>Signed In!</Text>
            <Text>{JSON.stringify(user)}</Text>
            <Button title="Sign Out" color="red" onPress={this.signOut} />
          </View>
        )}
      </View>
    );
  }
}

can someone help? ive checked the docs again ..but no help ?idk
  what more details I should add..this is my first question on stack
  over flow..didnt know it was this annoying to ask a question...
      I tried the web firebase sdk and can use the anonymous signin.. but I need phone auth which I'm not able to accomplish as it has different setups for ios and android ...rnfirebase is suppose to same as the web sdk


问:
Modulo and order of operation in Python
In Zed Shaw's Learn Python the Hard Way (page 15-16), he has an example exercise

```<code> 100 - 25 * 3 % 4
</code>```

the result is 97 (try it!)

I cannot see the order of operations that could do this..

100 - 25 = 75

3 % 4 = 0

or (100-25*3) =225 % 4 = ???   but anyhow not 97 I don't think...

A similar example is 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 which yields 7

In what order are the operations done?

答:
Here's how it goes:

'*' and '%' have the same precendence, so evaluate those from left to right.

25*3 = 75

75 % 4 = 3 (4*18 = 72; remainder is 3)

100 - 3 = 97

Q.E.D.

Title: Modulo and order of operation in Python

Body:
In Zed Shaw's Learn Python the Hard Way (page 15-16), he has an example exercise

 100 - 25 * 3 % 4

the result is 97 (try it!)

I cannot see the order of operations that could do this..

100 - 25 = 75

3 % 4 = 0

or (100-25*3) =225 % 4 = ???   but anyhow not 97 I don't think...

A similar example is 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 which yields 7

In what order are the operations done?


问:
OpenCV Python : rotate image without cropping sides
Imagine I have these images :

I want the image from left to be rotated like the image of the middle, not the right one. How do I do this using Python and OpenCV. I looked at getRotationMatrix2D and warpAffine but the examples about it transform my image to the right one.

答:
You can also use padding as well, that is, add borders to the sides of the image, then rotate it to avoid cropping from the original image.</p>

```<code>def rotate_im(image, angle)
    image_height = image.shape[0]
    image_width = image.shape[1]
    diagonal_square = (image_width*image_width) + (
        image_height* image_height
    )
    #
    diagonal = round(sqrt(diagonal_square))
    padding_top = round((diagonal-image_height) / 2)
    padding_bottom = round((diagonal-image_height) / 2)
    padding_right = round((diagonal-image_width) / 2)
    padding_left = round((diagonal-image_width) / 2)
    padded_image = cv2.copyMakeBorder(image,
                                      top=padding_top,
                                      bottom=padding_bottom,
                                      left=padding_left,
                                      right=padding_right,
                                      borderType=cv2.BORDER_CONSTANT,
                                      value=0
            )
    padded_height = padded_image.shape[0]
    padded_width = padded_image.shape[1]
    transform_matrix = cv2.getRotationMatrix2D(
                (padded_height/2,
                 padded_width/2), # center
                angle, # angle
      1.0) # scale
    rotated_image = cv2.warpAffine(padded_image,
                                   transform_matrix,
                                   (diagonal, diagonal),
                                   flags=cv2.INTER_LANCZOS4)
    return rotated_image
</code>```

Body:
You can also use padding as well, that is, add borders to the sides of the image, then rotate it to avoid cropping from the original image.

def rotate_im(image, angle)
    image_height = image.shape[0]
    image_width = image.shape[1]
    diagonal_square = (image_width*image_width) + (
        image_height* image_height
    )
    #
    diagonal = round(sqrt(diagonal_square))
    padding_top = round((diagonal-image_height) / 2)
    padding_bottom = round((diagonal-image_height) / 2)
    padding_right = round((diagonal-image_width) / 2)
    padding_left = round((diagonal-image_width) / 2)
    padded_image = cv2.copyMakeBorder(image,
                                      top=padding_top,
                                      bottom=padding_bottom,
                                      left=padding_left,
                                      right=padding_right,
                                      borderType=cv2.BORDER_CONSTANT,
                                      value=0
            )
    padded_height = padded_image.shape[0]
    padded_width = padded_image.shape[1]
    transform_matrix = cv2.getRotationMatrix2D(
                (padded_height/2,
                 padded_width/2), # center
                angle, # angle
      1.0) # scale
    rotated_image = cv2.warpAffine(padded_image,
                                   transform_matrix,
                                   (diagonal, diagonal),
                                   flags=cv2.INTER_LANCZOS4)
    return rotated_image


问:
Bing Custom Search using PHP
I'm in the process of testing the new Bing Custom Search using below PHP code. The result is a blank white screen with no errors. Is it because this service is still in beta mode?

```<code><?php
$sURL = "https://api.cognitive.microsoft.com/bingcustomsearch/v5.0/search?q=dogs&customconfig=[mycustomconfigvalue]&responseFilter=Webpages&mkt=en-us&safesearch=Moderate";
$key = "[myPrimaryKey]";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);

echo $content;
?>
</code>```

When I try to verify if API keys are working for me using Postman, I get an error saying "Could n ot get any response".

However, if I try the same values in https://customsearch.ai under endpoint section, it works perfectly by displaying the response.

Can anyone please let me know I can't run the code using my own PHP code?

Thanks

答:
I replied this somewhere. Here is a working php snippet. Just replace YOUR_QUERY, YOUR_KEY, and YOUR_CUSTOMCONFIG.</p>

```<code>$endpoint = 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search';
$term = 'YOUR_QUERY';
$headers = "Ocp-Apim-Subscription-Key: YOUR_KEY\r\n";
$options = array ('http' => array (
                      'header' => $headers,
                       'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&customconfig=YOUR_CUSTOMCONFIG&responseFilter=Webpages&mkt=en-us&safesearch=Moderate", false, $context);
</code>```

Title: Bing Custom Search using PHP

Body:
I'm in the process of testing the new Bing Custom Search using below PHP code. The result is a blank white screen with no errors. Is it because this service is still in beta mode?

<?php
$sURL = "https://api.cognitive.microsoft.com/bingcustomsearch/v5.0/search?q=dogs&customconfig=[mycustomconfigvalue]&responseFilter=Webpages&mkt=en-us&safesearch=Moderate";
$key = "[myPrimaryKey]";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);

echo $content;
?>

When I try to verify if API keys are working for me using Postman, I get an error saying "Could n ot get any response".

However, if I try the same values in https://customsearch.ai under endpoint section, it works perfectly by displaying the response.

Can anyone please let me know I can't run the code using my own PHP code?

Thanks

Body:
I replied this somewhere. Here is a working php snippet. Just replace YOUR_QUERY, YOUR_KEY, and YOUR_CUSTOMCONFIG.

$endpoint = 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search';
$term = 'YOUR_QUERY';
$headers = "Ocp-Apim-Subscription-Key: YOUR_KEY\r\n";
$options = array ('http' => array (
                      'header' => $headers,
                       'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&customconfig=YOUR_CUSTOMCONFIG&responseFilter=Webpages&mkt=en-us&safesearch=Moderate", false, $context);


问:
Getting all Named Parameters from Powershell including empty and set ones
I'm trying to find a way to get all parameter information from a powershell script. Ex script:

```<code>function test()
{
    Param(
        [string]$foo,
        [string]$bar,
        [string]$baz = "baz"
    )

    foreach ($key in $MyInvocation.BoundParameters.keys)
    {
        write-host "Parameter: $($key) -> $($MyInvocation.BoundParameters[$key])"
    }
}
test -foo "foo!"
</code>```

I'd like to get the values of $bar and $baz in a dynamic way without knowing the names of the parameters ahead of time.

I've looked through $MyInvocation properties and methods but I don't see anything besides parameters that are set/passed.

Update 1:

I'm close to getting it with:

```<code>function test()
{
    Param(
        [string]$foo,
        [string]$bar,
        [string]$baz = "baz"
    )
    foreach($var in (get-variable -scope private))
    {
        write-host "$($var.name) -> $($var.value)"
    }
}
test -foo "foo!"
</code>```

If i could filter out the script parameters vs the default parameters I would be good to go.

Update 2:
The final working solution looks like this:

```<code>function test {
    param (
          [string] $Bar = 'test'
        , [string] $Baz
        , [string] $Asdf
    )
    $ParameterList = (Get-Command -Name $MyInvocation.InvocationName).Parameters;
    foreach ($key in $ParameterList.keys)
    {
        $var = Get-Variable -Name $key -ErrorAction SilentlyContinue;
        if($var)
        {
            write-host "$($var.name) > $($var.value)"
        }
    }
}

test -asdf blah;
</code>```

答:
Hopefully, some may find this one-liner useful:

```<code>function test()
{
    Param(
        [string]$foo,
        [string]$bar,
        [string]$baz = "baz"
    )

    $MyInvocation.MyCommand.Parameters | Format-Table -AutoSize @{ Label = "Key"; Expression={$_.Key}; }, @{ Label = "Value"; Expression={(Get-Variable -Name $_.Key -EA SilentlyContinue).Value}; }
}
test -foo "foo!"
</code>```

Result

```<code>Keys Value
---- -----
foo  foo!
bar
baz  baz
</code>```

Body:
I'm trying to find a way to get all parameter information from a powershell script. Ex script:

function test()
{
    Param(
        [string]$foo,
        [string]$bar,
        [string]$baz = "baz"
    )

    foreach ($key in $MyInvocation.BoundParameters.keys)
    {
        write-host "Parameter: $($key) -> $($MyInvocation.BoundParameters[$key])"
    }
}
test -foo "foo!"

I'd like to get the values of $bar and $baz in a dynamic way without knowing the names of the parameters ahead of time.

I've looked through $MyInvocation properties and methods but I don't see anything besides parameters that are set/passed.

Update 1:

I'm close to getting it with:

function test()
{
    Param(
        [string]$foo,
        [string]$bar,
        [string]$baz = "baz"
    )
    foreach($var in (get-variable -scope private))
    {
        write-host "$($var.name) -> $($var.value)"
    }
}
test -foo "foo!"

If i could filter out the script parameters vs the default parameters I would be good to go.

Update 2:
The final working solution looks like this:

function test {
    param (
          [string] $Bar = 'test'
        , [string] $Baz
        , [string] $Asdf
    )
    $ParameterList = (Get-Command -Name $MyInvocation.InvocationName).Parameters;
    foreach ($key in $ParameterList.keys)
    {
        $var = Get-Variable -Name $key -ErrorAction SilentlyContinue;
        if($var)
        {
            write-host "$($var.name) > $($var.value)"
        }
    }
}

test -asdf blah;

Body:
Hopefully, some may find this one-liner useful:

function test()
{
    Param(
        [string]$foo,
        [string]$bar,
        [string]$baz = "baz"
    )

    $MyInvocation.MyCommand.Parameters | Format-Table -AutoSize @{ Label = "Key"; Expression={$_.Key}; }, @{ Label = "Value"; Expression={(Get-Variable -Name $_.Key -EA SilentlyContinue).Value}; }
}
test -foo "foo!"

Result

Keys Value
---- -----
foo  foo!
bar
baz  baz


问:
Behaviour of actionButton if called from server
Calling actionButton with NULL as button ID works fine in console (it just doesn't create an id):

```<code>> library(shiny)
> actionButton(NULL, "Label1")
<button type="button" class="btn btn-default action-button">Label1</button>
</code>```

But calling it from server causes error:

```<code>Browse[1]> actionButton(NULL, "label1")
Error in exists(name, envir = private$values) : invalid first argument
</code>```

example app:

```<code>ui <- function() {
  fluidPage()
  }

server <- function(input, output, session) {
  browser()
  }
runApp(list(ui = ui, server = server))
</code>```

Can someone explain me this behaviour?

答:
my best guess is that it is connected with exists function, that is called by the server on inputId parameter of actionButton function.

Look on error, please:

```<code>Listening on http://127.0.0.1:5515
Warning: Error in exists: invalid first argument
Stack trace (innermost first):
87: exists
86: self$exists
85: oldInputs$available
84: restoreInput
83: actionButton
82: renderUI [#10]
81: func
80: origRenderFunc
79: output$moreControls
 4: <Anonymous>
 3: do.call
 2: print.shiny.appobj
 1: <Promise>
</code>```

and if you call:

```<code>> exists( NULL)
Error in exists(NULL) : invalid first argument
</code>```

I used this code to generate aforementioned error message:

```<code> if (interactive()) {

  ui <- fluidPage(
    uiOutput("moreControls")
  )

  server <- function(input, output) {
    output$moreControls <- renderUI({

        actionButton( NULL, "label1")

    })
  }
  shinyApp(ui, server)
}
</code>```

Body:
Calling actionButton with NULL as button ID works fine in console (it just doesn't create an id):

> library(shiny)
> actionButton(NULL, "Label1")
<button type="button" class="btn btn-default action-button">Label1</button>

But calling it from server causes error:

Browse[1]> actionButton(NULL, "label1")
Error in exists(name, envir = private$values) : invalid first argument

example app:

ui <- function() {
  fluidPage()
  }

server <- function(input, output, session) {
  browser()
  }
runApp(list(ui = ui, server = server))

Can someone explain me this behaviour?

Body:
my best guess is that it is connected with exists function, that is called by the server on inputId parameter of actionButton function.

Look on error, please:

Listening on http://127.0.0.1:5515
Warning: Error in exists: invalid first argument
Stack trace (innermost first):
87: exists
86: self$exists
85: oldInputs$available
84: restoreInput
83: actionButton
82: renderUI [#10]
81: func
80: origRenderFunc
79: output$moreControls
 4: <Anonymous>
 3: do.call
 2: print.shiny.appobj
 1: <Promise>

and if you call:

> exists( NULL)
Error in exists(NULL) : invalid first argument

I used this code to generate aforementioned error message:

 if (interactive()) {

  ui <- fluidPage(
    uiOutput("moreControls")
  )

  server <- function(input, output) {
    output$moreControls <- renderUI({

        actionButton( NULL, "label1")

    })
  }
  shinyApp(ui, server)
}


问:
I want google map like this Multiple Polyline, can Multiple select
I want  google map like this Multiple Polyline, can Multiple select.

Multiple Polyline

var geocoder;
var map;
var polyline;

positions = [new google.maps.LatLng(37.441883,-122.143019),
             new google.maps.LatLng(37.45296,-122.181725)];
function initialize() {
    var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
        center: new google.maps.LatLng(37.4419, -122.1419),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    $("#chkRouteLines").click(function () {
        if (!polyline || !polyline.setMap) {
          polyline = new google.maps.Polyline({
            path: positions,
            strokeColor: "#FF0000",
            strokeOpacity: 1.0,
            strokeWeight: 2,
            visible: true
          });
        }

    if ($(this).is(':checked')) {
        polyline.setMap(map);
    } else {
        polyline.setMap(null);
    }
})

}
google.maps.event.addDomListener(window, "load", initialize);
```

<pre class="lang-css prettyprint-override"><code>html, body, #map_canvas {
    height: 90%;
    width: 100%;
    margin: 0px;
    padding: 0px
</code>```

<input id="chkRouteLines" value="click" type="checkbox" />
```

答:
you can google developers documents.For example this link:
https://developers.google.com/maps/documentation/javascript/examples/polyline-complex</p>

```<code><html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Complex Polylines</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

      // This example creates an interactive map which constructs a polyline based on
      // user clicks. Note that the polyline only appears once its path property
      // contains two LatLng coordinates.

      var poly;
      var map;

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 7,
          center: {lat: 41.879, lng: -87.624}  // Center the map on Chicago, USA.
        });

        poly = new google.maps.Polyline({
          strokeColor: '#000000',
          strokeOpacity: 1.0,
          strokeWeight: 3
        });
        poly.setMap(map);

        // Add a listener for the click event
        map.addListener('click', addLatLng);
      }

      // Handles click events on a map, and adds a new point to the Polyline.
      function addLatLng(event) {
        var path = poly.getPath();

        // Because path is an MVCArray, we can simply append a new coordinate
        // and it will automatically appear.
        path.push(event.latLng);

        // Add a new marker at the new plotted point on the polyline.
        var marker = new google.maps.Marker({
          position: event.latLng,
          title: '#' + path.getLength(),
          map: map
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>
</code>```

Body:
I want  google map like this Multiple Polyline, can Multiple select.

Multiple Polyline

var geocoder;
var map;
var polyline;

positions = [new google.maps.LatLng(37.441883,-122.143019),
             new google.maps.LatLng(37.45296,-122.181725)];
function initialize() {
    var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
        center: new google.maps.LatLng(37.4419, -122.1419),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    $("#chkRouteLines").click(function () {
        if (!polyline || !polyline.setMap) {
          polyline = new google.maps.Polyline({
            path: positions,
            strokeColor: "#FF0000",
            strokeOpacity: 1.0,
            strokeWeight: 2,
            visible: true
          });
        }

    if ($(this).is(':checked')) {
        polyline.setMap(map);
    } else {
        polyline.setMap(null);
    }
})

}
google.maps.event.addDomListener(window, "load", initialize);

html, body, #map_canvas {
    height: 90%;
    width: 100%;
    margin: 0px;
    padding: 0px

<input id="chkRouteLines" value="click" type="checkbox" />

Body:
you can google developers documents.For example this link:
https://developers.google.com/maps/documentation/javascript/examples/polyline-complex

<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Complex Polylines</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

      // This example creates an interactive map which constructs a polyline based on
      // user clicks. Note that the polyline only appears once its path property
      // contains two LatLng coordinates.

      var poly;
      var map;

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 7,
          center: {lat: 41.879, lng: -87.624}  // Center the map on Chicago, USA.
        });

        poly = new google.maps.Polyline({
          strokeColor: '#000000',
          strokeOpacity: 1.0,
          strokeWeight: 3
        });
        poly.setMap(map);

        // Add a listener for the click event
        map.addListener('click', addLatLng);
      }

      // Handles click events on a map, and adds a new point to the Polyline.
      function addLatLng(event) {
        var path = poly.getPath();

        // Because path is an MVCArray, we can simply append a new coordinate
        // and it will automatically appear.
        path.push(event.latLng);

        // Add a new marker at the new plotted point on the polyline.
        var marker = new google.maps.Marker({
          position: event.latLng,
          title: '#' + path.getLength(),
          map: map
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>


问:
Value not accessible outside valuechangelistener of Inputfile during fileupload in Oracle ADF
I am creating a form in Oracle ADF in which i am using inputfile to upload a file to db. When i select a file through input file value is recieved in the ValueChangeListener but if i try to access that value outside the valuchangelistener function through public variables or getter , setter functions the value recieved is null.

```<code>// Value Change Listener for inputFileComponent
    public void onFileUploadVCL(ValueChangeEvent valueChangeEvent) {
        file=(UploadedFile)valueChangeEvent.getNewValue();
        // get the file name
        uploadedFileName=file.getFilename();
        // get the mime type
        contentType = file.getContentType();
        // get blob
        blob=getBlob(file);
    }

  //submit function where i need to use values

   public void onSubmit(ActionEvent actionEvent) {
        // Add event code here...
        System.out.println("String:"+inEmpCode+"#"+outDesignation+"#"+inFromDate+"#"+inToDate+"#"+uploadedFileName+"$$"+blob);
        insertRow(inEmpCode,inFromDate,inToDate,uploadedFileName,blob);
    }
</code>```

// Code from its view

```<code>                            <af:selectOneChoice value="#{AddReviewBean.inEmpCode}"
                                                label="#{bindings.Empcode.label}"
                                                required="#{bindings.Empcode.hints.mandatory}"
                                                shortDesc="#{bindings.Empcode.hints.tooltip}" id="soc1"
                                                valueChangeListener="#{AddReviewBean.onSelectionChange}" autoSubmit="true">
                                <f:selectItems value="#{bindings.Empcode.items}" id="si1"/>
                                <f:validator binding="#{bindings.Empcode.validator}"/>
                            </af:selectOneChoice>

                            <p xmlns="http://www.w3.org/1999/xhtml">
                <af:inputText value="#{AddReviewBean.outDesignation}" readOnly="true" label="Designation" id="txtDesignation"
                              partialTriggers="soc1"/>
            </p>
             <p xmlns="http://www.w3.org/1999/xhtml">
                <af:inputDate label="From" id="dateTxtFrom" required="true" value="#{AddReviewBean.inFromDate}"/>
            </p>
            <p xmlns="http://www.w3.org/1999/xhtml">
                <af:inputDate label="To" id="dateTxtTo" required="true" value="#{AddReviewBean.inToDate}"/>
            </p>

            <p xmlns="http://www.w3.org/1999/xhtml">
            <af:inputFile label="Upload Review" maximumFiles="1" autoSubmit="true" id="inFileReview"
                          valueChangeListener="#{AddReviewBean.onFileUploadVCL}" value="#{AddReviewBean.file}"/>
            </p>
            <p xmlns="http://www.w3.org/1999/xhtml">

                <af:button partialSubmit="true" text="Submit" id="btnSubmit"
                           actionListener="#{AddReviewBean.onSubmit}"/>
            </p>

        </af:panelFormLayout>
</code>```

答: The variable will remain there if you declared your managed bean inside pageFlowScope or sessionScope (if you think it should survive the whole user session) and make the variable private (not static).</p>

Body:
I am creating a form in Oracle ADF in which i am using inputfile to upload a file to db. When i select a file through input file value is recieved in the ValueChangeListener but if i try to access that value outside the valuchangelistener function through public variables or getter , setter functions the value recieved is null.

// Value Change Listener for inputFileComponent
    public void onFileUploadVCL(ValueChangeEvent valueChangeEvent) {
        file=(UploadedFile)valueChangeEvent.getNewValue();
        // get the file name
        uploadedFileName=file.getFilename();
        // get the mime type
        contentType = file.getContentType();
        // get blob
        blob=getBlob(file);
    }

  //submit function where i need to use values

   public void onSubmit(ActionEvent actionEvent) {
        // Add event code here...
        System.out.println("String:"+inEmpCode+"#"+outDesignation+"#"+inFromDate+"#"+inToDate+"#"+uploadedFileName+"$$"+blob);
        insertRow(inEmpCode,inFromDate,inToDate,uploadedFileName,blob);
    }

// Code from its view

                            <af:selectOneChoice value="#{AddReviewBean.inEmpCode}"
                                                label="#{bindings.Empcode.label}"
                                                required="#{bindings.Empcode.hints.mandatory}"
                                                shortDesc="#{bindings.Empcode.hints.tooltip}" id="soc1"
                                                valueChangeListener="#{AddReviewBean.onSelectionChange}" autoSubmit="true">
                                <f:selectItems value="#{bindings.Empcode.items}" id="si1"/>
                                <f:validator binding="#{bindings.Empcode.validator}"/>
                            </af:selectOneChoice>

                <af:inputText value="#{AddReviewBean.outDesignation}" readOnly="true" label="Designation" id="txtDesignation"
                              partialTriggers="soc1"/>

                <af:inputDate label="From" id="dateTxtFrom" required="true" value="#{AddReviewBean.inFromDate}"/>

                <af:inputDate label="To" id="dateTxtTo" required="true" value="#{AddReviewBean.inToDate}"/>

            <af:inputFile label="Upload Review" maximumFiles="1" autoSubmit="true" id="inFileReview"
                          valueChangeListener="#{AddReviewBean.onFileUploadVCL}" value="#{AddReviewBean.file}"/>

                <af:button partialSubmit="true" text="Submit" id="btnSubmit"
                           actionListener="#{AddReviewBean.onSubmit}"/>

        </af:panelFormLayout>


问:
Simple google-map app not working in emulator
I'm a newbie to Android development. I was trying to create a very basic simple app to use google-map features but for some reason, the map is not loaded as expected. Attached is an image which shows how it is loaded.

Below is my google_maps_api.xml. I have created a new Google Maps API key and is active.

```<code><resources>
    <!--
    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=9F:9B:0A:4E:CA:F7:7C:D3:83:42:BE:E3:91:18:00:6C:16:D7:B2:96%3Bcom.mycompany.googlemapsdemo

    You can also add your credentials to an existing key, using these values:

    Package name:
    9F:9B:0A:4E:CA:F7:7C:D3:83:42:BE:E3:91:18:00:6C:16:D7:B2:96

    SHA-1 certificate fingerprint:
    9F:9B:0A:4E:CA:F7:7C:D3:83:42:BE:E3:91:18:00:6C:16:D7:B2:96

    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key

    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">**mykey**</string>
</resources>
</code>```

Below us activity_maps.xml

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mycompany.googlemapsdemo.MapsActivity" />
</code>```

and AndroidMainfest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mycompany.googlemapsdemo">
    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.
   READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
</code>```

MapsActivity.java

```<code>package com.mycompany.googlemapsdemo;

import android.os.Bundle;
import android.support.v4.app.BundleCompat;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}
</code>```

I don't see any errors in Logcat. One interesting thing is that, whenever I try to zoom in/out or scroll up/down, app crashes but again no errors. I'm using

Android Studio 3.0
Build #AI-171.4408382, built on October 20, 2017
JRE: 1.8.0_152-release-915-b01 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 7 6.1

Logcat messages

Update 3:
I'm not sure if it has anything to do with the below messages that I see in Logcat

11-14 11:57:18.471 2816-2974/com.example.mmuniyappa.googlemapdemonew W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.

11-14 11:57:18.491 2816-2974/com.example.mmuniyappa.googlemapdemonew W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/00000001/n/x86

Also, when I try to zoom in/out or scroll up/down, Emulator crashes with a popup message

Emulator: Process finished with exit code -1073741819 (0xC0000005)

答:
Are you sure that the API key is matching with the app ID, in the

Google API Console - Google Cloud Platform

Body:
I'm a newbie to Android development. I was trying to create a very basic simple app to use google-map features but for some reason, the map is not loaded as expected. Attached is an image which shows how it is loaded.

Below is my google_maps_api.xml. I have created a new Google Maps API key and is active.

<resources>

    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">**mykey**</string>
</resources>

Below us activity_maps.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mycompany.googlemapsdemo.MapsActivity" />

and AndroidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mycompany.googlemapsdemo">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.
   READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

MapsActivity.java

package com.mycompany.googlemapsdemo;

import android.os.Bundle;
import android.support.v4.app.BundleCompat;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

I don't see any errors in Logcat. One interesting thing is that, whenever I try to zoom in/out or scroll up/down, app crashes but again no errors. I'm using

Android Studio 3.0
Build #AI-171.4408382, built on October 20, 2017
JRE: 1.8.0_152-release-915-b01 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 7 6.1

Logcat messages

Update 3:
I'm not sure if it has anything to do with the below messages that I see in Logcat

11-14 11:57:18.471 2816-2974/com.example.mmuniyappa.googlemapdemonew W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.

11-14 11:57:18.491 2816-2974/com.example.mmuniyappa.googlemapdemonew W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/00000001/n/x86

Also, when I try to zoom in/out or scroll up/down, Emulator crashes with a popup message

Emulator: Process finished with exit code -1073741819 (0xC0000005)


问:
How to make right query to vTiger CRM API
I got an sql query:

```<code>$vtiger->query('*', 'Products', "(productname LIKE '%$name%' OR description LIKE '%$name%') AND cf_1007 = 'Ready'", null, 50, null);
</code>```

(using https://github.com/sumocoders/vtiger-api). It has an WHERE clause. How to make it right? (current query throws exception). I need to take all rows where productname or description contains %name% and where cell cf_1007 = "Ready".

UPD: answer from vTiger API (forgot to add it here)

```<code>{"success":false,"error":{"code":"QUERY_SYNTAX_ERROR","message":"Syntax Error on line 1: token '(' Unexpected PARENOPEN((), expected one of: COLUMNNAME"}}
</code>```

答:
There's a syntax error due to the first (.

Try removing it, changing

```<code>(A OR B) AND C
</code>```

for

```<code>A AND C OR B AND C
</code>```

Body:
I got an sql query:

$vtiger->query('*', 'Products', "(productname LIKE '%$name%' OR description LIKE '%$name%') AND cf_1007 = 'Ready'", null, 50, null);

(using https://github.com/sumocoders/vtiger-api). It has an WHERE clause. How to make it right? (current query throws exception). I need to take all rows where productname or description contains %name% and where cell cf_1007 = "Ready".

UPD: answer from vTiger API (forgot to add it here)

{"success":false,"error":{"code":"QUERY_SYNTAX_ERROR","message":"Syntax Error on line 1: token '(' Unexpected PARENOPEN((), expected one of: COLUMNNAME"}}

Body:
There's a syntax error due to the first (.

Try removing it, changing

(A OR B) AND C

for

A AND C OR B AND C