问:
sqlsrv array doesn't return all rows
I can't seem to figure out why sqlsrv_fetch_assoc only returns 1 row when there are 2 rows in the result set according to sqlsrv_num_rows. I've tried to hard code the parameter, but I still get the same result.

SSMS Result Set

```id     description
------ -------------
2      Administrator
3      User```

PHP

```<code>$col = 'abcd';
$stmt = "SELECT id, [description] FROM dbo.tbl WHERE col = ?";
$params = array( $col );
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );

$query = sqlsrv_query( $conn, $stmt, $params, $options );
if( $query === false ) {
    print( print_r( sqlsrv_errors() ) );
}

while( $row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC )) {
    ...
}
</code>```

When I try to view the result set

```<code>$row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC );

print_r($row);
</code>```

I receive

```Array
(
    [id] => 2
    [description] => Administrator
)```

sqlsrv_num_rows

```<code>echo sqlsrv_num_rows( $query );
//Returns 2
</code>```

答:
A simple way is to use sqlsrv_fetch_array and use multi dimensional array to store each row data. But on doing so make sure to use $i++ instead of $i += 1
If we use $i +=1 then only single row is saved.</p>

```<code>   $i = 0;
   while( $row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC )) {
        $result[$i][0] = $row['id'];
        $result[$i][1] = $row['description'];

        $i++;    //works
       // $i += 1; //does not work with this !
    }
var_dump($result);
</code>```

Title: sqlsrv array doesn't return all rows

Body:
I can't seem to figure out why sqlsrv_fetch_assoc only returns 1 row when there are 2 rows in the result set according to sqlsrv_num_rows. I've tried to hard code the parameter, but I still get the same result.

SSMS Result Set

id     description
------ -------------
2      Administrator
3      User

PHP

$col = 'abcd';
$stmt = "SELECT id, [description] FROM dbo.tbl WHERE col = ?";
$params = array( $col );
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );

$query = sqlsrv_query( $conn, $stmt, $params, $options );
if( $query === false ) {
    print( print_r( sqlsrv_errors() ) );
}

while( $row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC )) {
    ...
}

When I try to view the result set

$row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC );

print_r($row);

I receive

Array
(
    [id] => 2
    [description] => Administrator
)

sqlsrv_num_rows

echo sqlsrv_num_rows( $query );
//Returns 2

Body:
A simple way is to use sqlsrv_fetch_array and use multi dimensional array to store each row data. But on doing so make sure to use $i++ instead of $i += 1
If we use $i +=1 then only single row is saved.

   $i = 0;
   while( $row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC )) {
        $result[$i][0] = $row['id'];
        $result[$i][1] = $row['description'];

        $i++;    //works
       // $i += 1; //does not work with this !
    }
var_dump($result);


来源: stackexchange

问:
tableView.selectRow has no effect when called within a UIContextualAction callback
When calling selectRow(at:animated:scrollPosition:) inside a UIContextualAction callback, nothing changes: the specified row doesn't turn gray.

Here's the simplest code I could write that exhibits the issue:

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, callback in
        tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
        callback(true)
    }

    return UISwipeActionsConfiguration(actions: [deleteAction])
}
```

I tried many variations:

properly performing the delete operation (updating the model then updating the table view with deleteRows())

not animating the selection operation

using a .normal action instead of a .destructive one

grouping various parts of the callback code in a tableView.performBatchUpdates() block

calling all of these methods in various orders, inside and outside the performBatchUpdates() call

somehow waiting for the end of the deletion animation with CATransaction.setCompletionBlock()

dispatching the selection operation on the main queue to have it execute a smidge later

All without success.

答:
One makeshift way to have the selection operation succeed is to use a timer, in order to call selectRow() after the deletion animation is finished:

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, callback in
        Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in
            tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
        }
        callback(true)
    }

    return UISwipeActionsConfiguration(actions: [deleteAction])
}
```

This is obviously far from a clean solution, since it depends on the timing of the animation not changing in future iOS releases, and requires writing extra code to make sure the selection operation is still relevant 0.5 seconds later, when the timer fires (which I didn't do in this sample).

ContentLicense: CC BY-SA 4.0

Body:
When calling selectRow(at:animated:scrollPosition:) inside a UIContextualAction callback, nothing changes: the specified row doesn't turn gray.

Here's the simplest code I could write that exhibits the issue:

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, callback in
        tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
        callback(true)
    }

    return UISwipeActionsConfiguration(actions: [deleteAction])
}

I tried many variations:

properly performing the delete operation (updating the model then updating the table view with deleteRows())

not animating the selection operation

using a .normal action instead of a .destructive one

grouping various parts of the callback code in a tableView.performBatchUpdates() block

calling all of these methods in various orders, inside and outside the performBatchUpdates() call

somehow waiting for the end of the deletion animation with CATransaction.setCompletionBlock()

dispatching the selection operation on the main queue to have it execute a smidge later

All without success.

Body:
One makeshift way to have the selection operation succeed is to use a timer, in order to call selectRow() after the deletion animation is finished:

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, callback in
        Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in
            tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
        }
        callback(true)
    }

    return UISwipeActionsConfiguration(actions: [deleteAction])
}

This is obviously far from a clean solution, since it depends on the timing of the animation not changing in future iOS releases, and requires writing extra code to make sure the selection operation is still relevant 0.5 seconds later, when the timer fires (which I didn't do in this sample).


问:
How to run or execute Talend jobs through python script?
I need to run a talend job outside of the talend studio. Is there any way to execute a talend job through python script ?</p>

答:
normally you can use any processmanagement tool to do that. For example
supervisor http://supervisord.org/. That's a processmanagement based
on python.</p>


问:
How can I set a breakpoint in referenced code in Visual Studio?
My main solution is using code from a utility class library, that I wrote myself, but is a part from another solution. How can I set a breakpoint in the referenced DLL file?</p>

答:
follow these steps:

Go to Debug

Go to New Breakpoint

Click on Function Breakpoint or simple press the Ctrl+K, B

a window shows up, type the function name in the following format:

namespace.ClassName.FunctionName

For example, assume that you have a code like this and I want to put a breakpoint at the beginning of function D:

```<code>namespace A.B{
    public class C{
          public void D(){
               int x= 10;
          }
    }
}
</code>```

So in Function Breakpoint window you need to type: A::B::C::D

ContentLicense: CC BY-SA 3.0

Body:
follow these steps:

Go to Debug

Go to New Breakpoint

Click on Function Breakpoint or simple press the Ctrl+K, B

a window shows up, type the function name in the following format:

namespace.ClassName.FunctionName

For example, assume that you have a code like this and I want to put a breakpoint at the beginning of function D:

namespace A.B{
    public class C{
          public void D(){
               int x= 10;
          }
    }
}

So in Function Breakpoint window you need to type: A::B::C::D


问:
403 when calling API from Azure App Service
I have a strange problem. I have a .NET Core App which works fine on local machine and passes unit tests.

Inside the app it basically calls our platform web service:

```<code>using( WebClient client = new WebClient() )
{
    NetworkCredential creds = new NetworkCredential(_userName, _password);
    CredentialCache credCache = new CredentialCache();
    credCache.Add(new System.Uri(_baseUrl), "Basic", creds);
    client.Credentials = credCache;

    var url = _baseUrl + "/api/v1/Pricing/Rates";
    client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    var request = JsonConvert.SerializeObject(data);
    System.Console.Out.WriteLine(request);
    var response = client.UploadString(url, request);
    var responseObject = JObject.Parse(response);
    var products = responseObject["PricingProducts"].Children();

    var result = new Dictionary<string, double>();
    foreach( var product in products )
    {
        result.Add(product.Value<string>("LoanProgramName"),
                   product.Value<double>("Rate"));
    }
    return result;
}
</code>```

When I execute this on local machine using dotnet run, everything works fine.  Unit tests work great too.  The logs on the App Service don't tell me much except that I am getting a 403 from the platform web service.

```<code>ers.RatesController.Get (AlexaRates) with arguments ((null)) - ModelState is Valid
2018-02-24 06:37:44.418 +00:00 [Information] Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Executed action AlexaRates.Controllers.RatesController.Get (AlexaRates) in 201.3483ms
2018-02-24 06:37:44.447 +00:00 [Error] Microsoft.AspNetCore.Server.Kestrel: Connection id "0HLBRA4B41EO8", Request id "0HLBRA4B41EO8:00000002": An unhandled exception was thrown by the application.
System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.HttpWebRequest.GetResponse()
   at System.Net.WebClient.GetWebResponse(WebRequest request)
   at System.Net.WebClient.DownloadBits(WebRequest request, Stream writeStream)
   at System.Net.WebClient.UploadBits(WebRequest request, Stream readStream, Byte[] buffer, Int32 chunkSize, Byte[] header, Byte[] footer)
   at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
   at System.Net.WebClient.UploadString(Uri address, String method, String data)
   at Rates.RetrieveLatest() in D:\home\site\repository\AlexaRates\Rates.cs:line 50
   at AlexaRates.Controllers.RatesController.Get() in D:\home\site\repository\AlexaRates\Controllers\RatesController.cs:line 22
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Exten
</code>```

Has anyone experienced anything similar?  I see a bunch 403 posts, but they are mostly about people calling a REST API hosted on the service not calling out.

答:
My fix was that I realized that our infrastructure guys added a IP restriction on the azure app. That is why the app was bouncing back with a 403.

I removed the IP restrictions on the "Networking" -> "Access Restrictions" page.

Body:
I have a strange problem. I have a .NET Core App which works fine on local machine and passes unit tests.

Inside the app it basically calls our platform web service:

using( WebClient client = new WebClient() )
{
    NetworkCredential creds = new NetworkCredential(_userName, _password);
    CredentialCache credCache = new CredentialCache();
    credCache.Add(new System.Uri(_baseUrl), "Basic", creds);
    client.Credentials = credCache;

    var url = _baseUrl + "/api/v1/Pricing/Rates";
    client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    var request = JsonConvert.SerializeObject(data);
    System.Console.Out.WriteLine(request);
    var response = client.UploadString(url, request);
    var responseObject = JObject.Parse(response);
    var products = responseObject["PricingProducts"].Children();

    var result = new Dictionary<string, double>();
    foreach( var product in products )
    {
        result.Add(product.Value<string>("LoanProgramName"),
                   product.Value<double>("Rate"));
    }
    return result;
}

When I execute this on local machine using dotnet run, everything works fine.  Unit tests work great too.  The logs on the App Service don't tell me much except that I am getting a 403 from the platform web service.

ers.RatesController.Get (AlexaRates) with arguments ((null)) - ModelState is Valid
2018-02-24 06:37:44.418 +00:00 [Information] Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Executed action AlexaRates.Controllers.RatesController.Get (AlexaRates) in 201.3483ms
2018-02-24 06:37:44.447 +00:00 [Error] Microsoft.AspNetCore.Server.Kestrel: Connection id "0HLBRA4B41EO8", Request id "0HLBRA4B41EO8:00000002": An unhandled exception was thrown by the application.
System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.HttpWebRequest.GetResponse()
   at System.Net.WebClient.GetWebResponse(WebRequest request)
   at System.Net.WebClient.DownloadBits(WebRequest request, Stream writeStream)
   at System.Net.WebClient.UploadBits(WebRequest request, Stream readStream, Byte[] buffer, Int32 chunkSize, Byte[] header, Byte[] footer)
   at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
   at System.Net.WebClient.UploadString(Uri address, String method, String data)
   at Rates.RetrieveLatest() in D:\home\site\repository\AlexaRates\Rates.cs:line 50
   at AlexaRates.Controllers.RatesController.Get() in D:\home\site\repository\AlexaRates\Controllers\RatesController.cs:line 22
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Exten

Has anyone experienced anything similar?  I see a bunch 403 posts, but they are mostly about people calling a REST API hosted on the service not calling out.


问:
C++ socket option reuse port
I have a problem with a c++ socket.

I'm using CAsyncSocket from MFC that i want to join a multicast group.

Also I need to have multiple listener on this group and here is where i get in trouble.

I found some examples on the web but it doesn't seems to work.

Here is my code:

```<code>//create socket on port 17233
BOOL bRet = Create(17233,SOCK_DGRAM, FD_READ);

//set reuse socket option
BOOL bMultipleApps = TRUE;
bRet = SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

//join multicast group
ip_mreq m_mrMReq;           // Contains IP and interface of the host group
m_mrMReq.imr_multiaddr.s_addr = inet_addr((LPCSTR)"224.30.0.1");    /* group addr */
m_mrMReq.imr_interface.s_addr = htons(INADDR_ANY);      /* use default */

int uRes =setsockopt(m_hSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char FAR *)&m_mrMReq, sizeof(m_mrMReq));
</code>```

There are no errors when i run this.

But when i try to run another instance of the app it fails to create a new socket on that port because the port is in use.

I have done this in C# and it worked fine like this:

```<code>IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
s.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.MulticastTimeToLive, int.Parse("1"));
</code>```

So if any body sees a problem with my code or have some tips i will gladly appreciated.

EDIT 1:

Is CAsyncSocket a TCP socket?

EDIT 2:
After reading Can two applications listen to the same port?

I think i made a confusion. I need a Multicast UDP port that can be access by multiple application using SO_REUSEADDR

Edit for Clarification:

```<code>BOOL bRet = Create(17233,SOCK_DGRAM, FD_READ)
</code>```

Creates an UDP socket and bind's to to port 17223.

For SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET); to work you need to set it before binding  as @Hasturkun said.

The final working code looks like this:

```<code>    BOOL bRet = Socket(SOCK_DGRAM, FD_READ);
    if(bRet != TRUE)
    {
        UINT uErr = GetLastError();
        std::cout<<"Error:"<<uErr<<std::endl;
        return FALSE;
    }else{
        std::cout<<"Create sock: OK"<<std::endl;
    }

    //add reuse
    BOOL bMultipleApps = TRUE;      /* allow reuse of local port if needed */
    SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

    //bind
    bRet = Bind(17233, NULL);
    if(bRet != TRUE)
    {
        UINT uErr = GetLastError();
        std::cout<<"Error(BIND):"<<uErr<<std::endl;
    }else{
        std::cout<<"BIND sock: OK"<<std::endl;
    }
</code>```

Thanks,

Gabriel

;

答:
You should be able to separate the creation of the socket from the binding, create the socket using Socket, eg.

```<code>BOOL bRet = Socket(SOCK_DGRAM, FD_READ);
</code>```

Then bind it with Bind after setting the sockopt

```<code>BOOL bMultipleApps = TRUE;
bRet = SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

bRet = Bind(17233, NULL);
</code>```

Title: C++ socket option reuse port

Body:
I have a problem with a c++ socket.

I'm using CAsyncSocket from MFC that i want to join a multicast group.

Also I need to have multiple listener on this group and here is where i get in trouble.

I found some examples on the web but it doesn't seems to work.

Here is my code:

//create socket on port 17233
BOOL bRet = Create(17233,SOCK_DGRAM, FD_READ);

//set reuse socket option
BOOL bMultipleApps = TRUE;
bRet = SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

//join multicast group
ip_mreq m_mrMReq;           // Contains IP and interface of the host group
m_mrMReq.imr_multiaddr.s_addr = inet_addr((LPCSTR)"224.30.0.1");    /* group addr */
m_mrMReq.imr_interface.s_addr = htons(INADDR_ANY);      /* use default */

int uRes =setsockopt(m_hSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char FAR *)&m_mrMReq, sizeof(m_mrMReq));

There are no errors when i run this.

But when i try to run another instance of the app it fails to create a new socket on that port because the port is in use.

I have done this in C# and it worked fine like this:

IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
s.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.MulticastTimeToLive, int.Parse("1"));

So if any body sees a problem with my code or have some tips i will gladly appreciated.

EDIT 1:

Is CAsyncSocket a TCP socket?

EDIT 2:
After reading Can two applications listen to the same port?

I think i made a confusion. I need a Multicast UDP port that can be access by multiple application using SO_REUSEADDR

Edit for Clarification:

BOOL bRet = Create(17233,SOCK_DGRAM, FD_READ)

Creates an UDP socket and bind's to to port 17223.

For SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET); to work you need to set it before binding  as @Hasturkun said.

The final working code looks like this:

    BOOL bRet = Socket(SOCK_DGRAM, FD_READ);
    if(bRet != TRUE)
    {
        UINT uErr = GetLastError();
        std::cout<<"Error:"<<uErr<<std::endl;
        return FALSE;
    }else{
        std::cout<<"Create sock: OK"<<std::endl;
    }

    //add reuse
    BOOL bMultipleApps = TRUE;      /* allow reuse of local port if needed */
    SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

    //bind
    bRet = Bind(17233, NULL);
    if(bRet != TRUE)
    {
        UINT uErr = GetLastError();
        std::cout<<"Error(BIND):"<<uErr<<std::endl;
    }else{
        std::cout<<"BIND sock: OK"<<std::endl;
    }

Thanks,

Gabriel

;

Body:
You should be able to separate the creation of the socket from the binding, create the socket using Socket, eg.

BOOL bRet = Socket(SOCK_DGRAM, FD_READ);

Then bind it with Bind after setting the sockopt

BOOL bMultipleApps = TRUE;
bRet = SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

bRet = Bind(17233, NULL);


问:
SELECT only row where all other activity are completed
I have a table with column called , ID,Activity,Activity_type,Activity Status.

Here activity status 11 = Completed, 12 = Incomplete.

Each ID is associated with activity type call1,call2,email1,email2 and text1. I only want to query all the ID with activity Text1 with "Activity Status"=12  when all other "Activity Status" related to that ID = 11.

In the example I would like to get output of Text1 with ID 10 as ID 11 still has email 2 with activity status 12. Any help on this is much appreciated.

答:
Using GROUP BY and HAVING should be a working solution, but your question probably has two possible answers:

case, when "Activity Status" = 12 and all other (all the rest) "Activity Status" = 11

case, when "Activity Status" = 12 and all other (all possible four) "Activity Status" = 11

Input:

```<code>CREATE TABLE #Data
(
    ID int,
    Activity varchar(10),
    Activity_type int,
    Activity_status int
)
INSERT INTO #Data
    (ID, Activity, Activity_type, Activity_status)
VALUES
    (10, 'call1',  10893, 11),
    (10, 'call2',  10894, 11),
    (10, 'email1', 10895, 11),
    (10, 'email2', 10896, 11),
    (10, 'text1',  10897, 12),
    (11, 'call1',  10893, 11),
    (11, 'call2',  10894, 11),
    (11, 'email1', 10895, 11),
    (11, 'email2', 10896, 12),
    (11, 'text1',  10897, 12)
</code>```

T-SQL (for all the rest):

```<code>SELECT ID
FROM #Data
GROUP BY ID
HAVING
    SUM(CASE WHEN Activity = 'text1' AND Activity_status = 12 THEN 1 END) = 1 AND
    SUM(1) - SUM(CASE WHEN Activity <> 'text1' AND Activity_status = 11 THEN 1 END) = 1
</code>```

T-SQL (for all possible four):

```<code>SELECT ID
FROM #Data
GROUP BY ID
HAVING
    SUM(CASE WHEN Activity = 'text1' AND Activity_status = 12 THEN 1 END) = 1 AND
    SUM(CASE WHEN Activity IN ('call1', 'call2', 'email1', 'email2') AND Activity_status = 11 THEN 1 END) = 4
</code>```

Output:

```<code>---
ID
---
10
</code>```

Body:
Using GROUP BY and HAVING should be a working solution, but your question probably has two possible answers:

case, when "Activity Status" = 12 and all other (all the rest) "Activity Status" = 11

case, when "Activity Status" = 12 and all other (all possible four) "Activity Status" = 11

Input:

CREATE TABLE #Data
(
    ID int,
    Activity varchar(10),
    Activity_type int,
    Activity_status int
)
INSERT INTO #Data
    (ID, Activity, Activity_type, Activity_status)
VALUES
    (10, 'call1',  10893, 11),
    (10, 'call2',  10894, 11),
    (10, 'email1', 10895, 11),
    (10, 'email2', 10896, 11),
    (10, 'text1',  10897, 12),
    (11, 'call1',  10893, 11),
    (11, 'call2',  10894, 11),
    (11, 'email1', 10895, 11),
    (11, 'email2', 10896, 12),
    (11, 'text1',  10897, 12)

T-SQL (for all the rest):

SELECT ID
FROM #Data
GROUP BY ID
HAVING
    SUM(CASE WHEN Activity = 'text1' AND Activity_status = 12 THEN 1 END) = 1 AND
    SUM(1) - SUM(CASE WHEN Activity <> 'text1' AND Activity_status = 11 THEN 1 END) = 1

T-SQL (for all possible four):

SELECT ID
FROM #Data
GROUP BY ID
HAVING
    SUM(CASE WHEN Activity = 'text1' AND Activity_status = 12 THEN 1 END) = 1 AND
    SUM(CASE WHEN Activity IN ('call1', 'call2', 'email1', 'email2') AND Activity_status = 11 THEN 1 END) = 4

Output:

---
ID
---
10


问:
Design for JavaFX application
I'm currently developing an application with JavaFX using FXML Windows. the scope of the application is the following:

Get User Inputs (e.g. credentials) -> use these credentials to retrieve information using Web Services API calls -> use the collected information to either create a file or visualize in a table.

Currently, I am using the Main class to launch each FXML Window, return the info to the Main class and pass it to the next FXML Window and so on (e.g. Main -> FXMLWindow_1 -> Main -> FXML_Window_2 -> Main -> ...).

My question: Is this correct from a design / workflow stanpoint? Or would it be better / same to launch each FXML Window sequentially from the previous one (e.g. Main -> FXMLWindow_1 -> FMXLWindow_2...)?

答:
I do not think there is a "right way".

It all depends on what functionality the application provides. If the individual windows in it are logically connected and solve a common task, it is more appropriate to use the Main -> FXMLWindow_1 -> FMXLWindow_2 approach. Actually, these are the "wizard" tools. In them the navigation is prev, next and finish. Another example of such an architecture is the installers next -> next -> .... -> finish.

If the tasks are not connected and the user can choose whether and when to perform a task (to open a dialog, for example), it is best to use Main -> FXMLWindow_1 -> Main -> FXML_Window_2 -> Main... In this case, you may want to consider using a separate application storage object (MVC pattern at application level).

With both approaches, you can get an additional dialog that can be used to authorize the user before it is admitted to the actual portion of the application.

You alone need to decide which solution best suits your application.

Title: Design for JavaFX application


问:
Make a loading screen appear at the same time as a select index change
i wanted to make a loading screen , but when i trigger the selectedindexchanged the code is executing all at the same timem so it just loads for a long time, what i wanted to do is select the option of the dropdown then show the loading screen by making the "coverscreen" visible as the page is loading, I have tried a few diferent things including javascript and the System.Threading.Thread.Sleep(22); but with no luck, thank you in advance for your time.

```<code><div id="loading">
        <div id="coverScreen" class="LockOn">
        </div>
    </div>
<asp:DropDownList ID="DropDown" DataValueField="IDCoContratante" DataTextField="Designation" runat="server" Enabled="true" CssClass="dropdownCocont" Style="border-radius: 7px; border-style: none;" AutoPostBack="true" OnSelectedIndexChanged="DropDown_ListarPropostas_SelectedIndexChanged"></asp:DropDownList>

protected void DropDown_ListarPropostas_SelectedIndexChanged(object sender, EventArgs e)
        {

            //Response.Write("<script>document.getElementById('coverScreen').style.visibility = 'visible';</script>");
            coverScreen.Visible = true;

            System.Threading.Thread.Sleep(22);

            ClassConn c = new ClassConn();
            c.OpenConection();

            DataTable dt = new DataTable();

            //SqlDataAdapter AtualizaDropLotes = new SqlDataAdapter(" SELECT dbo.TblLoteCoContratanteAdjudicado.IDLote, CAST(dbo.TblLote.NrLote AS varchar) + '  ' + dbo.TblLote.DescricaoLote AS DescricaoLote, dbo.TblLote.IDAcordoQuadro " +
            //                                                      " FROM dbo.TblLoteCoContratanteAdjudicado INNER JOIN dbo.TblLote ON dbo.TblLoteCoContratanteAdjudicado.IDLote = dbo.TblLote.IDLote AND dbo.TblLoteCoContratanteAdjudicado.IDLote = dbo.TblLote.IDLote " +
            //                                                      " WHERE (dbo.TblLote.IDAcordoQuadro = '" + DropDownAcordosQuadros_ListarPropostas.SelectedValue + "') " +
            //                                                      " GROUP BY dbo.TblLoteCoContratanteAdjudicado.IDLote, CAST(dbo.TblLote.NrLote AS varchar) + '  ' + dbo.TblLote.DescricaoLote, dbo.TblLote.IDAcordoQuadro", c.con);
            string _query = "SELECT '%' as IDLote, 'Todos' as DescricaoLote UNION ALL SELECT CAST(dbo.TblLoteCoContratanteAdjudicado.IDLote AS VARCHAR), 'Nº' + CAST(dbo.TblLote.NrLote AS varchar) + ' - ' + dbo.TblLote.DescricaoLote AS DescricaoLote FROM dbo.TblLoteCoContratanteAdjudicado INNER JOIN dbo.TblLote ON dbo.TblLoteCoContratanteAdjudicado.IDLote = dbo.TblLote.IDLote AND dbo.TblLoteCoContratanteAdjudicado.IDLote = dbo.TblLote.IDLote WHERE(dbo.TblLoteCoContratanteAdjudicado.NIFCoContratante = '" + id_Vat + "') AND(dbo.TblLote.IDAcordoQuadro = '" + DropDownAcordosQuadros_ListarPropostas.SelectedValue + "')";

            SqlDataAdapter AtualizaDropLotes = new SqlDataAdapter(_query, c.con);

            AtualizaDropLotes.Fill(dt);

            if (dt != null)
            {
                DropDownLotes_ListaPropostas.DataSource = dt;
                DropDownLotes_ListaPropostas.DataBind();

            }

            c.CloseConnection();
            coverScreen.Visible = false;
        }
</code>```

答:
Following the information that  Alex Kudryashev and Gus gave me i was able to search for a solution what I did to solve the problem was:

I inserted my loading screen in between the asp:UpdatePanel with the asp:ScriptManager on top.

```<code><asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        <asp:UpdateProgress ID="UpdateProgress1" runat="server">
            <ProgressTemplate>
                <div id="coverScreen" class="LockOn" runat="server">
                </div>
            </ProgressTemplate>
        </asp:UpdateProgress>
</code>```

And I inserted the following code in the main div

```<code><div id="Main">
 <asp:UpdatePanel ID="UpdatePanel2" runat="server">
            <ContentTemplate>

//your code

    </ContentTemplate>
  </asp:UpdatePanel>
</div>
</code>```

Body:
i wanted to make a loading screen , but when i trigger the selectedindexchanged the code is executing all at the same timem so it just loads for a long time, what i wanted to do is select the option of the dropdown then show the loading screen by making the "coverscreen" visible as the page is loading, I have tried a few diferent things including javascript and the System.Threading.Thread.Sleep(22); but with no luck, thank you in advance for your time.

<asp:DropDownList ID="DropDown" DataValueField="IDCoContratante" DataTextField="Designation" runat="server" Enabled="true" CssClass="dropdownCocont" Style="border-radius: 7px; border-style: none;" AutoPostBack="true" OnSelectedIndexChanged="DropDown_ListarPropostas_SelectedIndexChanged"></asp:DropDownList>

protected void DropDown_ListarPropostas_SelectedIndexChanged(object sender, EventArgs e)
        {

            //Response.Write("");
            coverScreen.Visible = true;

            System.Threading.Thread.Sleep(22);

            ClassConn c = new ClassConn();
            c.OpenConection();

            DataTable dt = new DataTable();

            //SqlDataAdapter AtualizaDropLotes = new SqlDataAdapter(" SELECT dbo.TblLoteCoContratanteAdjudicado.IDLote, CAST(dbo.TblLote.NrLote AS varchar) + '  ' + dbo.TblLote.DescricaoLote AS DescricaoLote, dbo.TblLote.IDAcordoQuadro " +
            //                                                      " FROM dbo.TblLoteCoContratanteAdjudicado INNER JOIN dbo.TblLote ON dbo.TblLoteCoContratanteAdjudicado.IDLote = dbo.TblLote.IDLote AND dbo.TblLoteCoContratanteAdjudicado.IDLote = dbo.TblLote.IDLote " +
            //                                                      " WHERE (dbo.TblLote.IDAcordoQuadro = '" + DropDownAcordosQuadros_ListarPropostas.SelectedValue + "') " +
            //                                                      " GROUP BY dbo.TblLoteCoContratanteAdjudicado.IDLote, CAST(dbo.TblLote.NrLote AS varchar) + '  ' + dbo.TblLote.DescricaoLote, dbo.TblLote.IDAcordoQuadro", c.con);
            string _query = "SELECT '%' as IDLote, 'Todos' as DescricaoLote UNION ALL SELECT CAST(dbo.TblLoteCoContratanteAdjudicado.IDLote AS VARCHAR), 'Nº' + CAST(dbo.TblLote.NrLote AS varchar) + ' - ' + dbo.TblLote.DescricaoLote AS DescricaoLote FROM dbo.TblLoteCoContratanteAdjudicado INNER JOIN dbo.TblLote ON dbo.TblLoteCoContratanteAdjudicado.IDLote = dbo.TblLote.IDLote AND dbo.TblLoteCoContratanteAdjudicado.IDLote = dbo.TblLote.IDLote WHERE(dbo.TblLoteCoContratanteAdjudicado.NIFCoContratante = '" + id_Vat + "') AND(dbo.TblLote.IDAcordoQuadro = '" + DropDownAcordosQuadros_ListarPropostas.SelectedValue + "')";

            SqlDataAdapter AtualizaDropLotes = new SqlDataAdapter(_query, c.con);

            AtualizaDropLotes.Fill(dt);

            if (dt != null)
            {
                DropDownLotes_ListaPropostas.DataSource = dt;
                DropDownLotes_ListaPropostas.DataBind();

            }

            c.CloseConnection();
            coverScreen.Visible = false;
        }

Body:
Following the information that  Alex Kudryashev and Gus gave me i was able to search for a solution what I did to solve the problem was:

I inserted my loading screen in between the asp:UpdatePanel with the asp:ScriptManager on top.

<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        <asp:UpdateProgress ID="UpdateProgress1" runat="server">
            <ProgressTemplate>
                <div id="coverScreen" class="LockOn" runat="server">
                </div>
            </ProgressTemplate>
        </asp:UpdateProgress>

And I inserted the following code in the main div

<div id="Main">
 <asp:UpdatePanel ID="UpdatePanel2" runat="server">
            <ContentTemplate>

//your code

    </ContentTemplate>
  </asp:UpdatePanel>
</div>


问:
FCM - Send to topics and "Not Registered" error
I developed an Android app that subscribes to a topic (subscribeToTopic() in OnCreate of main activity) and then receives notifications sent by my server to that topic.

The problem is that, from time to time, someone complains that notifications cease to arrive. In this case, I usually ask the user to use a function, included in my app, that reads the Firebase Registration Token and sends it to me via email (I don't usually use or store it).

Then, I try to send a notification to that Token and FCM Server answers with the Not Registered error! How can it be Not Registered? When using the Topic Subscription, shouldn't Firebase manage the whole "token process" and take care of its renewal?

Is there some way to inform the app that it is not registered anymore and take appropriate actions? Thanks.

答:
This is not exactly for your case, but see if it helps!
I was facing the same issue. Here is how I fixed it (iOS specific, android was working out of the box)-

Uninstall the app from your phone

Clear ALL the tokens stored in your database for this particular account(or however you have set it up in your backend. In my case, tokens are tied to the account)

In componentDidmount-

async componentDidMount() {
    this.checkPermission();
    this.createNotificationListeners();
  }

4.

```<code>  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
      this.getToken();
    } else {
      this.requestPermission();
    }
  }

  async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
    } catch (error) {
      // User has rejected permissions
      console.log('permission rejected');
    }
  }

  async getToken() {
    try {
      const enabled = await firebase.messaging().hasPermission();
      if (!enabled) {
        await firebase.messaging().requestPermission();
      }

      const fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
        console.log("got token");
        console.log('fcm token:', fcmToken); //-->use this token from the console to send a post request via postman
        this.setState({ fcmToken });
        return fcmToken;
      }
    } catch (error) {
      console.warn('notification token error', error);
    }
  }
</code>```

5.

```<code> async createNotificationListeners() {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase.notifications().onNotification((notification) => {
        const { title, body } = notification;
        this.showAlert(title, body);
    });

    /*
    * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
    * */
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
        const { title, body } = notificationOpen.notification;
        this.showAlert(title, body);
    });

    /*
    * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
    * */
    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
        const { title, body } = notificationOpen.notification;
        this.showAlert(title, body);
    }
    /*
    * Triggered for data only payload in foreground
    * */
    this.messageListener = firebase.messaging().onMessage((message) => {
      //process data message
      console.log(JSON.stringify(message));
    });
  }
</code>```

Finally, use the token that you see in the console as a value for the "to" key in your post request. You should no longer see the "notRegistered" error and should be getting push notifications.
Done!!

Citations-https://medium.com/@anum.amin/react-native-integrating-push-notifications-using-fcm-349fff071591

Body:
This is not exactly for your case, but see if it helps!
I was facing the same issue. Here is how I fixed it (iOS specific, android was working out of the box)-

Uninstall the app from your phone

Clear ALL the tokens stored in your database for this particular account(or however you have set it up in your backend. In my case, tokens are tied to the account)

In componentDidmount-

async componentDidMount() {
    this.checkPermission();
    this.createNotificationListeners();
  }

4.

  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
      this.getToken();
    } else {
      this.requestPermission();
    }
  }

  async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
    } catch (error) {
      // User has rejected permissions
      console.log('permission rejected');
    }
  }

  async getToken() {
    try {
      const enabled = await firebase.messaging().hasPermission();
      if (!enabled) {
        await firebase.messaging().requestPermission();
      }

      const fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
        console.log("got token");
        console.log('fcm token:', fcmToken); //-->use this token from the console to send a post request via postman
        this.setState({ fcmToken });
        return fcmToken;
      }
    } catch (error) {
      console.warn('notification token error', error);
    }
  }

5.

 async createNotificationListeners() {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase.notifications().onNotification((notification) => {
        const { title, body } = notification;
        this.showAlert(title, body);
    });

    /*
    * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
    * */
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
        const { title, body } = notificationOpen.notification;
        this.showAlert(title, body);
    });

    /*
    * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
    * */
    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
        const { title, body } = notificationOpen.notification;
        this.showAlert(title, body);
    }
    /*
    * Triggered for data only payload in foreground
    * */
    this.messageListener = firebase.messaging().onMessage((message) => {
      //process data message
      console.log(JSON.stringify(message));
    });
  }

Finally, use the token that you see in the console as a value for the "to" key in your post request. You should no longer see the "notRegistered" error and should be getting push notifications.
Done!!

Citations-https://medium.com/@anum.amin/react-native-integrating-push-notifications-using-fcm-349fff071591


问:
size() option is missing using Selenium webdriver through Java
have been following some classes to improve my automation skills with Selenium Webdrive. I don't have size() method as an option when trying to count the numbers of links inside a page.

Am I missing some jars? Import libraries?

```<code>java public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "/Users/Follo/Dropbox/Chrome Drivers/chromedriver");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        // options.addArguments("--headless");
        WebDriver driver = new ChromeDriver(options);
        driver.get("URL");
        WebElement link = driver.findElement(By.tagName("a"));
        link.size()
        // .size do not appear as an option in the dropdown menu
        System.out.println(link.size());
        driver.quit();
    }
}
</code>```

答:
size()

The size() method of List interface in Java is used to get the number of elements in this list. That is, this method returns the count of elements present in this list container.

So essentially, the variable link which is of type WebElement won't support the size() method. So you have to change the type of the variable link as List and populate the List using findElements() method and you can use the following solution:

```<code>List<WebElement> link = driver.findElements(By.tagName("a"));
System.out.println(link.size());
</code>```

Body:
have been following some classes to improve my automation skills with Selenium Webdrive. I don't have size() method as an option when trying to count the numbers of links inside a page.

Am I missing some jars? Import libraries?

java public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "/Users/Follo/Dropbox/Chrome Drivers/chromedriver");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        // options.addArguments("--headless");
        WebDriver driver = new ChromeDriver(options);
        driver.get("URL");
        WebElement link = driver.findElement(By.tagName("a"));
        link.size()
        // .size do not appear as an option in the dropdown menu
        System.out.println(link.size());
        driver.quit();
    }
}

Body:
size()

The size() method of List interface in Java is used to get the number of elements in this list. That is, this method returns the count of elements present in this list container.

So essentially, the variable link which is of type WebElement won't support the size() method. So you have to change the type of the variable link as List and populate the List using findElements() method and you can use the following solution:

List<WebElement> link = driver.findElements(By.tagName("a"));
System.out.println(link.size());


问:
How to set min value for field in form?
I have form with integer field - price.

```<code>$builder->add('list',
            CollectionType::class,
            [
                'required' => false,
                'allow_add' => true,
                'error_bubbling' => true,
            ])
            ->add('price',
            IntegerType::class,
            [
                'required' => false,
                'error_bubbling' => true,
            ]);
</code>```

How to set, for example, for validation i need min value for price 0 or greater?

I tried this one, but it's not work:

```<code>'constraints' => [
new GreaterThanOrEqual(50)
 ],
</code>```

Thanks for all help.

controller Action

```<code> public function getProductAction(Request $request)
    {
        $variables = $request->get('list');

        $price = $request->get('price');

        $form = $this->createForm(ProductForm::class, null, ['csrf_protection' => false, 'allow_extra_fields' => true]);

        $form->submit(['variables' => $variables, 'prices' => $price]);

        if(!$form->isValid()) {

            $errors = '';

            foreach ($form->getErrors() as $error) {
                $errors = $error->getMessage();
            }

            return new JsonResponse([
                'errors' => $errors
            ],Response::HTTP_BAD_REQUEST);
        } else {

            $product = $this->getDoctrine()
                ->getRepository(Product::class)
                ->findByListAndPrice($list, $price);

            if (!$product) {
                return new JsonResponse([
                    'errors' => 'Product not found.'
                ],Response::HTTP_BAD_REQUEST);
            }

            return new JsonResponse($product);
        }
    }
</code>```

Form not validate, and don't show errors, $form->isValid() === true

答:
According to https://github.com/symfony/symfony/issues/3533 you can use min and max for the IntegerType even though the documentation might not mention this.

```<code>$builder->add('list',
    CollectionType::class,
    [
        'required' => false,
        'allow_add' => true,
        'error_bubbling' => true,
    ])
    ->add('price',
    IntegerType::class,
    [
        'required' => false,
        'error_bubbling' => true,
        /*'min' => 50*/
        'attr' => [
          'min' => 50
        ]
    ]);
</code>```

EDIT: According to the documentation the 'min' property has to be inside 'attr' tag. This will add the min inside the input in the HTML.

Title: How to set min value for field in form?

Body:
I have form with integer field - price.

$builder->add('list',
            CollectionType::class,
            [
                'required' => false,
                'allow_add' => true,
                'error_bubbling' => true,
            ])
            ->add('price',
            IntegerType::class,
            [
                'required' => false,
                'error_bubbling' => true,
            ]);

How to set, for example, for validation i need min value for price 0 or greater?

I tried this one, but it's not work:

'constraints' => [
new GreaterThanOrEqual(50)
 ],

Thanks for all help.

controller Action

 public function getProductAction(Request $request)
    {
        $variables = $request->get('list');

        $price = $request->get('price');

        $form = $this->createForm(ProductForm::class, null, ['csrf_protection' => false, 'allow_extra_fields' => true]);

        $form->submit(['variables' => $variables, 'prices' => $price]);

        if(!$form->isValid()) {

            $errors = '';

            foreach ($form->getErrors() as $error) {
                $errors = $error->getMessage();
            }

            return new JsonResponse([
                'errors' => $errors
            ],Response::HTTP_BAD_REQUEST);
        } else {

            $product = $this->getDoctrine()
                ->getRepository(Product::class)
                ->findByListAndPrice($list, $price);

            if (!$product) {
                return new JsonResponse([
                    'errors' => 'Product not found.'
                ],Response::HTTP_BAD_REQUEST);
            }

            return new JsonResponse($product);
        }
    }

Form not validate, and don't show errors, $form->isValid() === true

Body:
According to https://github.com/symfony/symfony/issues/3533 you can use min and max for the IntegerType even though the documentation might not mention this.

$builder->add('list',
    CollectionType::class,
    [
        'required' => false,
        'allow_add' => true,
        'error_bubbling' => true,
    ])
    ->add('price',
    IntegerType::class,
    [
        'required' => false,
        'error_bubbling' => true,
        /*'min' => 50*/
        'attr' => [
          'min' => 50
        ]
    ]);

EDIT: According to the documentation the 'min' property has to be inside 'attr' tag. This will add the min inside the input in the HTML.


问:
Filter top n largest groups in data.frame
For the example data:

```<code>set.seed(2222)
example_data <- data.frame(col1 = 1:15,
                           col2 = 16:30,
                           group = sample(1:3, 15, replace = TRUE))

   col1 col2 group
1     1   16     2
2     2   17     1
3     3   18     3
4     4   19     2
5     5   20     3
6     6   21     1
7     7   22     3
8     8   23     1
9     9   24     3
10   10   25     1
11   11   26     2
12   12   27     2
13   13   28     2
14   14   29     3
15   15   30     3
</code>```

I want to find the top n groups with the most number of records.

Let's say I want to get the top 2 groups with the most number of records. In the data, this would be group 3 and 2:

```<code>example_data %>%
  group_by(group) %>%
  summarise(n = n())

# A tibble: 3 x 2
  group     n
  <int> <int>
1     1     4
2     2     5
3     3     6
</code>```

The expected output is:

```<code>   col1 col2 group
1     1   16     2
2     3   18     3
3     4   19     2
4     5   20     3
5     7   22     3
6     9   24     3
7    11   26     2
8    12   27     2
9    13   28     2
10   14   29     3
11   15   30     3
</code>```

答:
With dplyr, you can also do:

```<code>example_data %>%
 add_count(group) %>%
 filter(dense_rank(desc(n)) <= 2) %>%
 select(-n)

   col1  col2 group
   <int> <int> <int>
 1     1    16     2
 2     3    18     3
 3     4    19     2
 4     5    20     3
 5     7    22     3
 6     9    24     3
 7    11    26     2
 8    12    27     2
 9    13    28     2
10    14    29     3
11    15    30     3
</code>```

Or:

```<code>example_data %>%
 add_count(group) %>%
 slice(which(dense_rank(desc(n)) <= 2)) %>%
 select(-n)
</code>```

Body:
For the example data:

set.seed(2222)
example_data <- data.frame(col1 = 1:15,
                           col2 = 16:30,
                           group = sample(1:3, 15, replace = TRUE))

   col1 col2 group
1     1   16     2
2     2   17     1
3     3   18     3
4     4   19     2
5     5   20     3
6     6   21     1
7     7   22     3
8     8   23     1
9     9   24     3
10   10   25     1
11   11   26     2
12   12   27     2
13   13   28     2
14   14   29     3
15   15   30     3

I want to find the top n groups with the most number of records.

Let's say I want to get the top 2 groups with the most number of records. In the data, this would be group 3 and 2:

example_data %>%
  group_by(group) %>%
  summarise(n = n())

# A tibble: 3 x 2
  group     n
  <int> <int>
1     1     4
2     2     5
3     3     6

The expected output is:

   col1 col2 group
1     1   16     2
2     3   18     3
3     4   19     2
4     5   20     3
5     7   22     3
6     9   24     3
7    11   26     2
8    12   27     2
9    13   28     2
10   14   29     3
11   15   30     3

Body:
With dplyr, you can also do:

example_data %>%
 add_count(group) %>%
 filter(dense_rank(desc(n)) <= 2) %>%
 select(-n)

   col1  col2 group
   <int> <int> <int>
 1     1    16     2
 2     3    18     3
 3     4    19     2
 4     5    20     3
 5     7    22     3
 6     9    24     3
 7    11    26     2
 8    12    27     2
 9    13    28     2
10    14    29     3
11    15    30     3

Or:

example_data %>%
 add_count(group) %>%
 slice(which(dense_rank(desc(n)) <= 2)) %>%
 select(-n)


问:
Getting NullPointerException at onFilterTouchEventForSecurity
I have built app in which I integrate YouTube API and it is working fine without any crash but on Fabric I checked some crash whis is ipf.onFilterTouchEventForSecurity. Here is the full logs of the crash:

```<code>java.lang.NullPointerException:
  at ipf.onFilterTouchEventForSecurity(ipf.java:115)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2351)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2876)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
  at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2840)
  at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1853)
  at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
  at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2801)
  at android.view.View.dispatchPointerEvent(View.java:10246)
  at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5447)
  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5283)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4721)
  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4774)
  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4740)
  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4882)
  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4748)
  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4939)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4721)
  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4774)
  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4740)
  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4748)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4721)
  at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7429)
  at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7298)
  at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7259)
  at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7539)
  at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
  at android.os.MessageQueue.nativePollOnce(MessageQueue.java:0)
  at android.os.MessageQueue.next(MessageQueue.java:323)
  at android.os.Looper.loop(Looper.java:135)
  at android.app.ActivityThread.main(ActivityThread.java:7325)
  at java.lang.reflect.Method.invoke(Method.java:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

I know that this issue is not because of code but I need to prevent crashing.

Here is list of devices on which I am facing issue:

Samsung Galaxy J7 (j7elte), 1536MB RAM, Android 6.0

Xiaomi Redmi Note 3 (kenzo), 2048MB RAM, Android 6.0

Lenovo TB3-710F (TB3-710F), 1024MB RAM, Android 5.0

Xiaomi Redmi 3S (land), 2048MB RAM, Android 6.0

LeTV Le 2 (le_s2_ww), 3072MB RAM, Android 6.0

LGE LG Stylus2 4G (ph2), 2048MB RAM, Android 6.0

Infocus M2_3G (G10), 10124MB RAM, Android 4.4

答:
I am not able to reproduce it but there are several things you can try:

If possible try adding android:filterTouchesWhenObscured=false as pellucide suggested from the docs:

Specifies whether to filter touches when the view's window is obscured
  by another visible window. When set to true, the view will not receive
  touches whenever a toast, dialog or other window appears above the
  view's window. Refer to the View security documentation for more
  details.

May be a boolean value, such as "true" or "false".

Otherwise, you can try overriding the dispatch method of your root view and place a try catch there, you can use it as a custom Component if needed.

```<code>@Override
void dispatchTouchEvent(MotionEvent event){
    try{
        super.dispatchTouchEvent(event);
    }
    catch (Exception e){
        e.printStackTrace();
    }
}
</code>```

Body:
I have built app in which I integrate YouTube API and it is working fine without any crash but on Fabric I checked some crash whis is ipf.onFilterTouchEventForSecurity. Here is the full logs of the crash:

java.lang.NullPointerException:
  at ipf.onFilterTouchEventForSecurity(ipf.java:115)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2351)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2876)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2519)
  at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2840)
  at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1853)
  at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
  at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2801)
  at android.view.View.dispatchPointerEvent(View.java:10246)
  at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5447)
  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5283)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4721)
  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4774)
  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4740)
  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4882)
  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4748)
  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4939)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4721)
  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4774)
  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4740)
  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4748)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4721)
  at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7429)
  at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7298)
  at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7259)
  at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7539)
  at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
  at android.os.MessageQueue.nativePollOnce(MessageQueue.java:0)
  at android.os.MessageQueue.next(MessageQueue.java:323)
  at android.os.Looper.loop(Looper.java:135)
  at android.app.ActivityThread.main(ActivityThread.java:7325)
  at java.lang.reflect.Method.invoke(Method.java:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

I know that this issue is not because of code but I need to prevent crashing.

Here is list of devices on which I am facing issue:

Samsung Galaxy J7 (j7elte), 1536MB RAM, Android 6.0

Xiaomi Redmi Note 3 (kenzo), 2048MB RAM, Android 6.0

Lenovo TB3-710F (TB3-710F), 1024MB RAM, Android 5.0

Xiaomi Redmi 3S (land), 2048MB RAM, Android 6.0

LeTV Le 2 (le_s2_ww), 3072MB RAM, Android 6.0

LGE LG Stylus2 4G (ph2), 2048MB RAM, Android 6.0

Infocus M2_3G (G10), 10124MB RAM, Android 4.4

Body:
I am not able to reproduce it but there are several things you can try:

If possible try adding android:filterTouchesWhenObscured=false as pellucide suggested from the docs:

Specifies whether to filter touches when the view's window is obscured
  by another visible window. When set to true, the view will not receive
  touches whenever a toast, dialog or other window appears above the
  view's window. Refer to the View security documentation for more
  details.

May be a boolean value, such as "true" or "false".

Otherwise, you can try overriding the dispatch method of your root view and place a try catch there, you can use it as a custom Component if needed.

@Override
void dispatchTouchEvent(MotionEvent event){
    try{
        super.dispatchTouchEvent(event);
    }
    catch (Exception e){
        e.printStackTrace();
    }
}


问:
Tuple swap with indexOf
I'm trying to swap positions of elements in this array with a tuple swap and indexOf()

```<code>array1 = [1, 2, 3, 4, 5, 6, 7, 8]
</code>```

should equal:  [1, 2, 4, 3, 5, 6, 7, 8]

```<code>[ array1[array1.indexOf(3)], array1[array1.indexOf(4)] ] =

[ array1[array1.indexOf(4)], array1[array1.indexOf(3)] ]

</code>```

the evaluated result is simply the swapped elements and not the array itself..

```<code>[4, 3]
</code>```

How can I get the whole array back?

答:
You are using destructuring assignment to swap elements but it will work in this case because the array.indexOf(4) is changed to 2. So after the first assignment array looks like.

```<code>[1,2,4,4,5,6,7,8]
</code>```

In the second assignment the the indexOf(4) returns 2. So you change the second element again to 3. So the array looks same.

The line is same as

```<code>array1[array1.indexOf(3)] = array1[array1.indexOf(4)] // array become [1,2,4,4,5,6,7,9]
array1[array1.indexOf(4)] = array1[array1.indexOf(3)] //here  indexOf(4) is `2`
</code>```

See the below snippet

let arr = [1,2,3];

[arr[1],arr[console.log(arr[1]) || 5]] = ['changed',3]```
</div>
</div>
</p>

<p>So you for the second element the first element is already changed.</p>

<p>You should store the index in variable and then use it.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let array1 = [1, 2, 3, 4, 5, 6, 7, 8]
let ind = array1.indexOf(3);
array1[array1.indexOf(4)] = 3;
array1[ind] = 4
console.log(array1)</code>```

Title: Tuple swap with indexOf

Body:
I'm trying to swap positions of elements in this array with a tuple swap and indexOf()

array1 = [1, 2, 3, 4, 5, 6, 7, 8]

should equal:  [1, 2, 4, 3, 5, 6, 7, 8]

[ array1[array1.indexOf(3)], array1[array1.indexOf(4)] ] =

[ array1[array1.indexOf(4)], array1[array1.indexOf(3)] ]

the evaluated result is simply the swapped elements and not the array itself..

[4, 3]

How can I get the whole array back?

Body:
You are using destructuring assignment to swap elements but it will work in this case because the array.indexOf(4) is changed to 2. So after the first assignment array looks like.

[1,2,4,4,5,6,7,8]

In the second assignment the the indexOf(4) returns 2. So you change the second element again to 3. So the array looks same.

The line is same as

array1[array1.indexOf(3)] = array1[array1.indexOf(4)] // array become [1,2,4,4,5,6,7,9]
array1[array1.indexOf(4)] = array1[array1.indexOf(3)] //here  indexOf(4) is `2`

See the below snippet

let arr = [1,2,3];

[arr[1],arr[console.log(arr[1]) || 5]] = ['changed',3]

So you for the second element the first element is already changed.

You should store the index in variable and then use it.

let array1 = [1, 2, 3, 4, 5, 6, 7, 8]
let ind = array1.indexOf(3);
array1[array1.indexOf(4)] = 3;
array1[ind] = 4
console.log(array1)


问:
Why the MonkeyRunner.waitForConnection() doesn't work in my environment？
Script:

```<code>from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
device = MonkeyRunner.waitForConnection(5,'192.168.6.60:5555')
device.installPackage('Douban_Radio.apk')
</code>```

Before it runs:

```<code>~/android-sdk-linux_86/tools$adb connect 192.168.6.60:5555
connected to 192.168.6.60:5555
~/android-sdk-linux_86/tools$adb devices
List of devices attached
192.168.6.60:5555   device
</code>```

The output of monkeyrunner:

```<code>~/android-sdk-linux_86/tools$./monkeyrunner monkeyrunnerTest.py
110412 18:12:35.017:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] Script terminated due to an exception
110412 18:12:35.017:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions]Traceback (most recent call last):
  File "/home/jobsyang/android-sdk-linux_86/tools/monkeyrunnerTest.py", line 6, in <module>
    device.installPackage('Douban_Radio.apk')
AttributeError: 'NoneType' object has no attribute 'installPackage'
</code>```

......

After it runs:

```<code>~/android-sdk-linux_86/tools$adb devices
adb server is out of date.  killing...
* daemon started successfully *
List of devices attached
</code>```

I just don't know why the MonkeyRunner.waitForConnection doesn't work and kills the adb connection to the device?  Please help me， thanks very much!

I start up an AVD in local env, and the connected devices are:

```<code>~/android-sdk-linux_86/tools$adb devices
List of devices attached
emulator-5554   device
192.168.6.60:5555   device
</code>```

Using the adb command is correct:

```<code>~/android-sdk-linux_86/tools$adb -s emulator-5554 install Douban_Radio.apk
859 KB/s (287518 bytes in 0.326s)
    pkg: /data/local/tmp/Douban_Radio.apk
Success

~/android-sdk-linux_86/tools$adb -s 192.168.6.60:5555  install Douban_Radio.apk
2108 KB/s (287518 bytes in 0.133s)
    pkg: /data/local/tmp/Douban_Radio.apk
Success
</code>```

With the MonkeyRunner.waitForConnection in script

MonkeyRunner.waitForConnection(5,'emulator-5554') works,

but MonkeyRunner.waitForConnection(5,'192.168.6.60:5555') still not work.

PS: 192.168.6.60 is the ip of a real device connected with adb.

Is the serialNumber of the real device wrong, but why the command "adb -s 192.168.6.60:5555  install Douban_Radio.apk" works?

答:
The second parameter of waitForConnection is the device's serial number, in the case of the emulator is 'emulator-<port>':

```<code>device = MonkeyRunner.waitForConnection(5,'emulator-5554')
</code>```

Body:
Script:

from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
device = MonkeyRunner.waitForConnection(5,'192.168.6.60:5555')
device.installPackage('Douban_Radio.apk')

Before it runs:

~/android-sdk-linux_86/tools$adb connect 192.168.6.60:5555
connected to 192.168.6.60:5555
~/android-sdk-linux_86/tools$adb devices
List of devices attached
192.168.6.60:5555   device

The output of monkeyrunner:

~/android-sdk-linux_86/tools$./monkeyrunner monkeyrunnerTest.py
110412 18:12:35.017:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] Script terminated due to an exception
110412 18:12:35.017:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions]Traceback (most recent call last):
  File "/home/jobsyang/android-sdk-linux_86/tools/monkeyrunnerTest.py", line 6, in <module>
    device.installPackage('Douban_Radio.apk')
AttributeError: 'NoneType' object has no attribute 'installPackage'

......

After it runs:

~/android-sdk-linux_86/tools$adb devices
adb server is out of date.  killing...
* daemon started successfully *
List of devices attached

I just don't know why the MonkeyRunner.waitForConnection doesn't work and kills the adb connection to the device?  Please help me， thanks very much!

I start up an AVD in local env, and the connected devices are:

~/android-sdk-linux_86/tools$adb devices
List of devices attached
emulator-5554   device
192.168.6.60:5555   device

Using the adb command is correct:

~/android-sdk-linux_86/tools$adb -s emulator-5554 install Douban_Radio.apk
859 KB/s (287518 bytes in 0.326s)
    pkg: /data/local/tmp/Douban_Radio.apk
Success

~/android-sdk-linux_86/tools$adb -s 192.168.6.60:5555  install Douban_Radio.apk
2108 KB/s (287518 bytes in 0.133s)
    pkg: /data/local/tmp/Douban_Radio.apk
Success

With the MonkeyRunner.waitForConnection in script

MonkeyRunner.waitForConnection(5,'emulator-5554') works,

but MonkeyRunner.waitForConnection(5,'192.168.6.60:5555') still not work.

PS: 192.168.6.60 is the ip of a real device connected with adb.

Is the serialNumber of the real device wrong, but why the command "adb -s 192.168.6.60:5555  install Douban_Radio.apk" works?

Body:
The second parameter of waitForConnection is the device's serial number, in the case of the emulator is 'emulator-<port>':

device = MonkeyRunner.waitForConnection(5,'emulator-5554')


问:
Is there a way to force `<body>` Element to respect offset? (I.e. Users current scroll position) when 'custombox' modal is fired?
I'm working with custombox.js along with BS4 and I'm having a little bit of difficulty with the scroll bars within the browser.

Ok so let me explain;

I have effectively a BS4 Modal (Except it's a Custombox one. They are quite similar.) With BS4 there is a class that is applied to the body tag when a modal is opened this class is as follows;

```<code>/* BS4 Class */
.modal-open {
  overflow: hidden;
}
</code>```

Effectively this class hides the browsers scroll feature while the
  modal is open.

Sadly, this isn't what I want as it causes some unsightly jittering, when opening or closing the modal.

As such, I wrote this to combat the issue;

```<code>/* Custom Box Lock */
.custombox-lock {
  position: fixed;
  left: inherit;
  overflow-y:scroll !important;
}
</code>```

Effectively this class keeps the scroll bar visible, while locking the user in place. (I.e Disables Scrolling.)

The Problem

Unfortunately, when this class is applied by the modal firing, it jumps the user to the very top of the page. Very undesirable indeed...

As such I attempted to use, inherit: left; in the hopes I could force the body element to respect the scroll position but alas, I had no such luck.

Question: Does anyone know of a way I could achieve my desired result, without
  over complicating the issue?

答:
If you think .modal-open { overflow: hidden; } is causing the problem, then why don't you just override it to .modal-open { overflow: scroll !important; }? Bootstrap classes can be overritten like that.

BUT... I don't think your problem comes from that line. This just hides the overflow inside the modal itself. What you wanna do is displaying the page's scrollbar at all times. You can do that by adding

body{overflow: scroll !important}

to your code. This makes it so the scrollbar is always present and there is no screen adjustment happening if you open a modal.

Body:
I'm working with custombox.js along with BS4 and I'm having a little bit of difficulty with the scroll bars within the browser.

Ok so let me explain;

I have effectively a BS4 Modal (Except it's a Custombox one. They are quite similar.) With BS4 there is a class that is applied to the body tag when a modal is opened this class is as follows;

/* BS4 Class */
.modal-open {
  overflow: hidden;
}

Effectively this class hides the browsers scroll feature while the
  modal is open.

Sadly, this isn't what I want as it causes some unsightly jittering, when opening or closing the modal.

As such, I wrote this to combat the issue;

/* Custom Box Lock */
.custombox-lock {
  position: fixed;
  left: inherit;
  overflow-y:scroll !important;
}

Effectively this class keeps the scroll bar visible, while locking the user in place. (I.e Disables Scrolling.)

The Problem

Unfortunately, when this class is applied by the modal firing, it jumps the user to the very top of the page. Very undesirable indeed...

As such I attempted to use, inherit: left; in the hopes I could force the body element to respect the scroll position but alas, I had no such luck.

Question: Does anyone know of a way I could achieve my desired result, without
  over complicating the issue?


问:
(Deprecated) Fragment onOptionsItemSelected not being called
EDIT:
This question was for the deprecated sherlock action bar. Android support library should be used instead now

I have added an action bar menu option called share for my fragment which appears but the selection event is not being caught

I am adding it like this

```<code>@Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
    MenuItem item = menu.add(0, 7,0, R.string.share);
    item.setIcon(R.drawable.social_share).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
</code>```

Trying to capture it in both the fragment and the fragment activity like

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case 7:
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("text/plain");
            share.putExtra(Intent.EXTRA_TEXT, "I'm being sent!!");
            startActivity(Intent.createChooser(share, "Share Text"));
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
</code>```

and I have setHasOptionsMenu(true); in the onCreate().

答:
you must add this code toolbar.bringToFront(); next set toolbar in your activity

```<code> public class MainActivity extends AppCompatActivity {
     protected void onCreate(Bundle savedInstanceState) {
        ...

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("Yazd");
        setSupportActionBar(toolbar);
        toolbar.bringToFront(); // <<= add here
         ...
</code>```

Body:
EDIT:
This question was for the deprecated sherlock action bar. Android support library should be used instead now

I have added an action bar menu option called share for my fragment which appears but the selection event is not being caught

I am adding it like this

@Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
    MenuItem item = menu.add(0, 7,0, R.string.share);
    item.setIcon(R.drawable.social_share).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}

Trying to capture it in both the fragment and the fragment activity like

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case 7:
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("text/plain");
            share.putExtra(Intent.EXTRA_TEXT, "I'm being sent!!");
            startActivity(Intent.createChooser(share, "Share Text"));
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

and I have setHasOptionsMenu(true); in the onCreate().

Body:
you must add this code toolbar.bringToFront(); next set toolbar in your activity

 public class MainActivity extends AppCompatActivity {
     protected void onCreate(Bundle savedInstanceState) {
        ...

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("Yazd");
        setSupportActionBar(toolbar);
        toolbar.bringToFront(); // <<= add here
         ...


问:
SSIS: string(varchar) to date conversion
I need to achieve the date format yyyy-mm-dd conversion on SSIS

I tried the below code but I keep getting error:

```<code>year and posting_period is a varchar(50) on my source data.
</code>```

Sample data on my source:

year = 2014

posting_period = always 2 digit

What did I miss in my codes below?

```<code>(DT_DBDATE)((DT_WSTR,4)year + "-" + (DT_WSTR,2)posting_period + "-" + "01")
</code>```

答:
You need to set the variable's data type to datetime; encapsulate the string in parenthesis; and cast it as DT_DATE:

(DT_DATE)(@[User::Year] + "-" +  @[User::posting_period] + "-01")

To my knowledge, you cannot specify how the datetime is displayed. So, this will evaluate to MM/DD/YYYY, which is fine. You should not worry how the date is formatted in the database. You should only care about how it is displayed in the reporting tool, which typically allows you to convert or cast the date in many different ways.

Body:
I need to achieve the date format yyyy-mm-dd conversion on SSIS

I tried the below code but I keep getting error:

year and posting_period is a varchar(50) on my source data.

Sample data on my source:

year = 2014

posting_period = always 2 digit

What did I miss in my codes below?

(DT_DBDATE)((DT_WSTR,4)year + "-" + (DT_WSTR,2)posting_period + "-" + "01")