问:
sqlQuery of DocumentDB input bindings with modulation symbol makes function's failure
I using the DocumentDB input bindings on Azure Functions.

Today, I specified a following query as a sqlQuery.

SELECT c.id, c.created_at FROM c
WHERE {epoch} - c.created_at_epoch >= 86400*31
AND (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) % 31 = 0
```

<p>Afterwards, I saw a following error when function is triggered.</p>

```2017-07-04T10:31:44.873 Function started (Id=95a2ab7a-8eb8-4568-b314-2c3b04a0eadf)
2017-07-04T10:31:49.544 Function completed (Failure, Id=95a2ab7a-8eb8-4568-b314-2c3b04a0eadf, Duration=4681ms)
2017-07-04T10:31:50.106 Exception while executing function: Functions.Bonus. Microsoft.Azure.WebJobs.Host: The '%' at position 148 does not have a closing '%'.
```

<p>I want to use a modulation symbol within sqlQuery. What can I?</p>

<p>Best regards.</p>

<hr>

<p>2017-07-15(JST) Append.</p>

<p>And today, I tried following another query for avoid this issue.</p>

```SELECT c.id, c.created_at FROM c
WHERE {epoch} - c.created_at_epoch >= 86400*31 AND
(CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) -
(31 *
    CEILING(
        (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400))
        / 31
    )
) = 0
```

<p>Just in case, I tried this query that is specified a epoch = 1499218423 on the Cosmos DB.</p>

```SELECT c.id, c.created_at FROM c
WHERE 1499218423 - c.created_at_epoch >= 86400*31 AND
(CEILING(1499218423/86400) - CEILING(c.created_at_epoch / 86400)) -
(31 *
    CEILING(
        (CEILING(1499218423/86400) - CEILING(c.created_at_epoch / 86400))
        / 31
    )
) = 0
```

<p>That's result is followings.</p>

```[
  {
    "id": "70251cbf-44b3-4cd9-991f-81127ad78bca",
    "created_at": "2017-05-11 18:46:16"
  },
  {
    "id": "0fa31de2-4832-49ea-a0c6-b517d64ede85",
    "created_at": "2017-05-11 18:48:22"
  },
  {
    "id": "b9959d15-92e7-41c3-8eff-718c4ab2be6e",
    "created_at": "2017-05-11 19:01:43"
  }
]
```

<p>It looks fine. Then I specify it as sqlQuery and test with following queue data.</p>

```{"epoch":1499218423}
```

<p>And code of the function is followings.</p>

```module.exports = function (context, myQueueItem) {
    context.log(context.bindings.members, myQueueItem);
    context.done();
};
```

<p>Afetrwards, I saw following results.</p>

```2017-07-05T03:00:47.158 Function started (Id=e4d060b5-3ddc-4271-bf91-9f314e7e1148)
2017-07-05T03:00:47.408 [] { epoch: 1499871600 }
2017-07-05T03:00:47.408 Function completed (Success, Id=e4d060b5-3ddc-4271-bf91-9f314e7e1148, Duration=245ms)
```

It looks differences in results of bindings(as context.bindings.members).

Why appeared this differences?

Related question : Deferences among the Azure CosmosDB Query Explorer's results and the Azure Functions results

答:
I want to use a modulation symbol within sqlQuery. What can I?

The modulation symbol(%) in Azure function configuration is used to retrieve values from app settings. For your issue, I suggest you add a item in app setting as following.

After that, you could use %modulationsymbol% instead of % in your query as following.

```<code>SELECT c.id, c.created_at FROM c
WHERE {epoch} - c.created_at_epoch >= 86400*31
AND (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) %modulationsymbol% 31 = 0
</code>```

Body:
I using the DocumentDB input bindings on Azure Functions.

Today, I specified a following query as a sqlQuery.

SELECT c.id, c.created_at FROM c
WHERE {epoch} - c.created_at_epoch >= 86400*31
AND (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) % 31 = 0

Afterwards, I saw a following error when function is triggered.

2017-07-04T10:31:44.873 Function started (Id=95a2ab7a-8eb8-4568-b314-2c3b04a0eadf)
2017-07-04T10:31:49.544 Function completed (Failure, Id=95a2ab7a-8eb8-4568-b314-2c3b04a0eadf, Duration=4681ms)
2017-07-04T10:31:50.106 Exception while executing function: Functions.Bonus. Microsoft.Azure.WebJobs.Host: The '%' at position 148 does not have a closing '%'.

I want to use a modulation symbol within sqlQuery. What can I?

Best regards.

2017-07-15(JST) Append.

And today, I tried following another query for avoid this issue.

SELECT c.id, c.created_at FROM c
WHERE {epoch} - c.created_at_epoch >= 86400*31 AND
(CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) -
(31 *
    CEILING(
        (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400))
        / 31
    )
) = 0

Just in case, I tried this query that is specified a epoch = 1499218423 on the Cosmos DB.

SELECT c.id, c.created_at FROM c
WHERE 1499218423 - c.created_at_epoch >= 86400*31 AND
(CEILING(1499218423/86400) - CEILING(c.created_at_epoch / 86400)) -
(31 *
    CEILING(
        (CEILING(1499218423/86400) - CEILING(c.created_at_epoch / 86400))
        / 31
    )
) = 0

That's result is followings.

[
  {
    "id": "70251cbf-44b3-4cd9-991f-81127ad78bca",
    "created_at": "2017-05-11 18:46:16"
  },
  {
    "id": "0fa31de2-4832-49ea-a0c6-b517d64ede85",
    "created_at": "2017-05-11 18:48:22"
  },
  {
    "id": "b9959d15-92e7-41c3-8eff-718c4ab2be6e",
    "created_at": "2017-05-11 19:01:43"
  }
]

It looks fine. Then I specify it as sqlQuery and test with following queue data.

{"epoch":1499218423}

And code of the function is followings.

module.exports = function (context, myQueueItem) {
    context.log(context.bindings.members, myQueueItem);
    context.done();
};

Afetrwards, I saw following results.

2017-07-05T03:00:47.158 Function started (Id=e4d060b5-3ddc-4271-bf91-9f314e7e1148)
2017-07-05T03:00:47.408 [] { epoch: 1499871600 }
2017-07-05T03:00:47.408 Function completed (Success, Id=e4d060b5-3ddc-4271-bf91-9f314e7e1148, Duration=245ms)

It looks differences in results of bindings(as context.bindings.members).

Why appeared this differences?

Related question : Deferences among the Azure CosmosDB Query Explorer's results and the Azure Functions results

Body:
I want to use a modulation symbol within sqlQuery. What can I?

The modulation symbol(%) in Azure function configuration is used to retrieve values from app settings. For your issue, I suggest you add a item in app setting as following.

After that, you could use %modulationsymbol% instead of % in your query as following.

SELECT c.id, c.created_at FROM c
WHERE {epoch} - c.created_at_epoch >= 86400*31
AND (CEILING({epoch}/86400) - CEILING(c.created_at_epoch / 86400)) %modulationsymbol% 31 = 0


来源: stackexchange

问:
How to know if page visits occurred in expected order?
Let's suppose I have a table containing user sessions, the pages they visited in that session, and the datetime of those page visits. Users should visit pages in the correct order - that is, they should not be able to get to page 2 without first going through page 3.

Here (user 1, session 1) is a "good" session because she visited all of the pages in the correct order.

```<code>user_id  session_id  page_id  event_dt
1        1           1        2017-07-04 17:54:40
1        1           2        2017-07-04 17:54:43
1        1           3        2017-07-04 17:54:44
</code>```

But (user 2, session 2) is a "bad" session because somehow she managed to land on page 2 before page 1

```<code>user_id  session_id  page_id  event_dt
2        2           2        2017-07-04 17:54:47
2        2           1        2017-07-04 17:54:49
2        2           3        2017-07-04 17:54:50
</code>```

How can I determine that (user 1, session 1) is a "good" session, while (user 2, session 2) is a "bad" path using a SQL query.

Addendum

I have added a new event_dt column as suggested by Degan in the comments below.

Additionally, I am looking for queries using MySQL though I would also like to see queries using SQL Server (or any other implementation containing window functions).

答:
You can enumerate the pages twice, once in page order and once in date order.  Then compare them:</p>

```<code>select t.*
from (select t.*,
             (@rn := if(@us = concat_ws(user_id, session_id), @rn + 1,
                        if(@us := concat_ws(user_id, session_id), 1, 1)
                       )
             ) as rn_p
      from (select t.*,
                   (@rn := if(@us = concat_ws(user_id, session_id), @rn + 1,
                              if(@us := concat_ws(user_id, session_id), 1, 1)
                             )
                   ) as rn_e
            from t cross join
                 (select @us := '', @rn := 0) params
            order by user_id, session_id, event_dt
           ) t cross join
           (select @us := '', @rn := 0) params
      order by user_id, session_id, page_id
     ) t
where rn_e <> rn_p;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let's suppose I have a table containing user sessions, the pages they visited in that session, and the datetime of those page visits. Users should visit pages in the correct order - that is, they should not be able to get to page 2 without first going through page 3.

Here (user 1, session 1) is a "good" session because she visited all of the pages in the correct order.

user_id  session_id  page_id  event_dt
1        1           1        2017-07-04 17:54:40
1        1           2        2017-07-04 17:54:43
1        1           3        2017-07-04 17:54:44

But (user 2, session 2) is a "bad" session because somehow she managed to land on page 2 before page 1

user_id  session_id  page_id  event_dt
2        2           2        2017-07-04 17:54:47
2        2           1        2017-07-04 17:54:49
2        2           3        2017-07-04 17:54:50

How can I determine that (user 1, session 1) is a "good" session, while (user 2, session 2) is a "bad" path using a SQL query.

Addendum

I have added a new event_dt column as suggested by Degan in the comments below.

Additionally, I am looking for queries using MySQL though I would also like to see queries using SQL Server (or any other implementation containing window functions).

Body:
You can enumerate the pages twice, once in page order and once in date order.  Then compare them:

select t.*
from (select t.*,
             (@rn := if(@us = concat_ws(user_id, session_id), @rn + 1,
                        if(@us := concat_ws(user_id, session_id), 1, 1)
                       )
             ) as rn_p
      from (select t.*,
                   (@rn := if(@us = concat_ws(user_id, session_id), @rn + 1,
                              if(@us := concat_ws(user_id, session_id), 1, 1)
                             )
                   ) as rn_e
            from t cross join
                 (select @us := '', @rn := 0) params
            order by user_id, session_id, event_dt
           ) t cross join
           (select @us := '', @rn := 0) params
      order by user_id, session_id, page_id
     ) t
where rn_e <> rn_p;


问:
Htaccess RewriteRule not passing parameters
I had a Plesk Onyx server, running on Centos 7.2, Apache 2.4 Nginx is OFF, I had the following htaccess

```<code>Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_URI} !(\.js|\.css|\.png|\.jpg|\.gif|\.jpeg|\.bmp|\.ttf|\.woff|\.woff2|\.otf|\.eot|\.ico|\.svg|\.txt|\.xml|\.json)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^folder1/folder2/([0-9]+)/(.*)[/]$ /folder1/folder2/index.php?get_var=$1 [NC,QSA,L]
</code>```

The rwwite works OK but its not passing the get_var
in index.php I had a var_dump ($_GET) and it is empty if I visit
https://sample_domain.com/folder1/folder2/123/

I want to get the 123 value into the get_var
tried disabling -MultiViews and no luck

答:
That rule can't be working at all for the URL you presented. It would only work for something like:

```<code>https://sample_domain.com/folder1/folder2/123//
</code>```

Or:

```<code>https://sample_domain.com/folder1/folder2/123/example/
</code>```

Try this:

```<code>Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_URI} !=/folder1/folder2/index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^folder1/folder2/([0-9]+)/$ /folder1/folder2/index.php?get_var=$1 [NC,QSA,L]
</code>```

I removed unnecessary tests since it could only be a directory. And I guess you don't even need that test? Do you have existing directories in /folder1/folder2/ named only with numbers? If not remove that test to improve performance.

Update

To operate this out of a .htaccess file in /folder1/folder2/, change it to be as follows:

```<code>Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9]+)/?$ index.php?get_var=$1 [NC,QSA,L]
</code>```

Body:
I had a Plesk Onyx server, running on Centos 7.2, Apache 2.4 Nginx is OFF, I had the following htaccess

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_URI} !(\.js|\.css|\.png|\.jpg|\.gif|\.jpeg|\.bmp|\.ttf|\.woff|\.woff2|\.otf|\.eot|\.ico|\.svg|\.txt|\.xml|\.json)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^folder1/folder2/([0-9]+)/(.*)[/]$ /folder1/folder2/index.php?get_var=$1 [NC,QSA,L]

The rwwite works OK but its not passing the get_var
in index.php I had a var_dump ($_GET) and it is empty if I visit
https://sample_domain.com/folder1/folder2/123/

I want to get the 123 value into the get_var
tried disabling -MultiViews and no luck

Body:
That rule can't be working at all for the URL you presented. It would only work for something like:

https://sample_domain.com/folder1/folder2/123//

Or:

https://sample_domain.com/folder1/folder2/123/example/

Try this:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_URI} !=/folder1/folder2/index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^folder1/folder2/([0-9]+)/$ /folder1/folder2/index.php?get_var=$1 [NC,QSA,L]

I removed unnecessary tests since it could only be a directory. And I guess you don't even need that test? Do you have existing directories in /folder1/folder2/ named only with numbers? If not remove that test to improve performance.

Update

To operate this out of a .htaccess file in /folder1/folder2/, change it to be as follows:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9]+)/?$ index.php?get_var=$1 [NC,QSA,L]


问:
JSONDecodeError: Expecting value: line 1 column 1
I am receiving this error in Python 3.5.1.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Here is my code:

```<code>import json
import urllib.request

connection = urllib.request.urlopen('http://python-data.dr-chuck.net/comments_220996.json')

js = connection.read()

print(js)

info = json.loads(str(js))
</code>```

答: in my case, some characters like "  , :"'{}[]  " maybe corrupt the JSON format, so use try json.loads(str) except to check your input

ContentLicense: CC BY-SA 4.0

Body:
I am receiving this error in Python 3.5.1.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Here is my code:

import json
import urllib.request

connection = urllib.request.urlopen('http://python-data.dr-chuck.net/comments_220996.json')

js = connection.read()

print(js)

info = json.loads(str(js))


问:
How compare the result from count(*) with INT in php
I want to compare the result for count(*) with INT. This is my code;

```<code> $sql_check = "SELECT COUNT(*) FROM hd";
 $result_check = mysqli_query($link, $sql_check) or die ("ERR");

 $row = mysql_fetch_assoc($result_check);
 if($row == 1)
 {...}
</code>```

It seem like there is no error. I tried to run it but it skip my if statement. If I tried to

```<code>echo $row
</code>```

It show error

NOTICE: Array to string conversion

If I used code

```<code> $sql_check = "SELECT COUNT(*) FROM hd";
 $result_check = mysqli_query($link, $sql_check) or die ("ERR");

 $row = int($result_check);
 if($row == 1)
 {...}
</code>```

It show  error

NOTICE: Object of class msqli_result could not converted to int

I have tried to used the answers from previous questions that have been asked before this (same question) but it doesn't work. Can you help me? Please I really need to know where my false.

Thankyou for helping.

Some other questions (that have been asked) and I have tried it but it seem does not work for me:
1. Object of class mysqli_result could not be converted to int and all entries return true
2. mysqli_result could not be converted to int in
3. Object of class mysqli_result could not be converted to int - Can't find my Error
4. Convert SQL query object into integer

答:
you can try this, not sure if it solves the problem!

```<code>   $sql_check = "SELECT COUNT(*) FROM hd as 'res'";
     $result_check = mysqli_query($link, $sql_check) or die ("ERR");

     $row = mysql_fetch_assoc($result_check);
     if($row['res'] == 1)
     {...}
</code>```

OR YOU CAN TRY THIS

```<code> $sql_check = "SELECT COUNT(*) FROM hd as 'res'";
 $result_check = mysqli_query($link, $sql_check) or die ("ERR");

 $row = mysql_fetch_assoc($result_check);
 if((int)$row['res'] == 1)
 {...}
</code>```

Body:
I want to compare the result for count(*) with INT. This is my code;

 $sql_check = "SELECT COUNT(*) FROM hd";
 $result_check = mysqli_query($link, $sql_check) or die ("ERR");

 $row = mysql_fetch_assoc($result_check);
 if($row == 1)
 {...}

It seem like there is no error. I tried to run it but it skip my if statement. If I tried to

echo $row

It show error

NOTICE: Array to string conversion

If I used code

 $sql_check = "SELECT COUNT(*) FROM hd";
 $result_check = mysqli_query($link, $sql_check) or die ("ERR");

 $row = int($result_check);
 if($row == 1)
 {...}

It show  error

NOTICE: Object of class msqli_result could not converted to int

I have tried to used the answers from previous questions that have been asked before this (same question) but it doesn't work. Can you help me? Please I really need to know where my false.

Thankyou for helping.

Some other questions (that have been asked) and I have tried it but it seem does not work for me:
1. Object of class mysqli_result could not be converted to int and all entries return true
2. mysqli_result could not be converted to int in
3. Object of class mysqli_result could not be converted to int - Can't find my Error
4. Convert SQL query object into integer

Body:
you can try this, not sure if it solves the problem!

   $sql_check = "SELECT COUNT(*) FROM hd as 'res'";
     $result_check = mysqli_query($link, $sql_check) or die ("ERR");

     $row = mysql_fetch_assoc($result_check);
     if($row['res'] == 1)
     {...}

OR YOU CAN TRY THIS

 $sql_check = "SELECT COUNT(*) FROM hd as 'res'";
 $result_check = mysqli_query($link, $sql_check) or die ("ERR");

 $row = mysql_fetch_assoc($result_check);
 if((int)$row['res'] == 1)
 {...}


问:
Custom bullets in Flash
Is there a way to make a bulleted list in flash with custom bullets? If so, can this be used from within a TextArea in Flex (mx.controls.TextArea) when setting htmlText?

For example:

```<code><li>Item</li>
<li>Item</li>
</code>```

The list above will render fine when set into a TextArea using htmlText (versus just setting the text property). The rendered text will have standard vanilla bullets. Is there a way to style these bullets with custom images, like you can in standard HTML/CSS?

Thanks!

答:
You can enter the bullet points manually and style them how you like but then you lose the indentation.

```<code><font color='#FFE400'>  •   </font> My bulleted item<br>
<font color='#FFE400'>  •   </font> My bulleted item<br>
<font color='#FFE400'>  •   </font> My bulleted item<br>
</code>```

There is also another approach on this site

http://blog.formatlos.de/2009/06/18/styling-html-textfield-bullet-points/

ContentLicense: CC BY-SA 2.5

Title: Custom bullets in Flash

Body:
Is there a way to make a bulleted list in flash with custom bullets? If so, can this be used from within a TextArea in Flex (mx.controls.TextArea) when setting htmlText?

For example:

Item

Item

The list above will render fine when set into a TextArea using htmlText (versus just setting the text property). The rendered text will have standard vanilla bullets. Is there a way to style these bullets with custom images, like you can in standard HTML/CSS?

Thanks!

Body:
You can enter the bullet points manually and style them how you like but then you lose the indentation.

<font color='#FFE400'>  •   </font> My bulleted item<br>
<font color='#FFE400'>  •   </font> My bulleted item<br>
<font color='#FFE400'>  •   </font> My bulleted item<br>

There is also another approach on this site

http://blog.formatlos.de/2009/06/18/styling-html-textfield-bullet-points/


问:
"node --debug" and "node --debug-brk" are invalid
I have updated the node (v8.1.2). When I want to debug my previous test project in nodejs using NTVS (in visual studio 2017) I've gotten the following error:

StandardError: (node:5292) [DEP0062] DeprecationWarning: node --debug and node --debug-brk are invalid. Please use node --inspect or node --inspect-brk instead.

The problem is clear. The tool try to run the node --debug to start the project.

The question is, how can I change node --debug to node --inspect in Visual Studio 2017 to running the test?

Also, I should have mentioned that I can't solve the problem by adding --inspect into the Script Arguments.

答:
You should downgrade your nodejs to 7.0.0 or less.
Use NVM on windows, see this post.

you can have several node´s version, on your computer.

luck!


问:
Select email that triggers script
I am working on a Outlook script that will automatically select an email, and download the attachments, from a specific sender.

Reports are generated on a database and emailed to a specified address.

The next step is to automatically download those reports to a specified folder. Currently if an email comes in from the specified sender the script downloads attachments from the currently selected email.

I need the script to run on the email that triggers the script.

Public Sub SaveAttachments(Item As Outlook.MailItem)
    Dim objOL As Outlook.Application
    Dim objMsg As Outlook.MailItem 'Object
    Dim objAttachments As Outlook.Attachments
    Dim objSelection As Outlook.Selection
    Dim i As Long
    Dim lngCount As Long
    Dim strFile As String
    Dim strFolderpath As String
    Dim strDeletedFiles As String

    'Get the path to the target folder
    strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    On Error Resume Next

    'Instantiate an Outlook Application Object
    Set objOL = CreateObject("Outlook.Application")

    'Get the collection of selected objects
    Set objSelection = objOL.ActiveExplorer.Selection

    'Set the Attachment folder
    strFolderpath = strFolderpath & "\Attachments\"

    'Check each selected item for attachements. If attachments exist, save them
    'to the strFOlderPath folder and strip them from the item.
    For Each objMsg In objSelection

    'This code only strips attachments from mail items.
    'If objMsg.class=olMail Then
    'Get the Attachments collection of the item
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
    strDeletedFile = ""

    If lngCount > 0 Then

        'A count down loop needs to be used for removing items
        'from a collection. Otherwise the loop counter gets
        'confused and only every other item is removed

        For i = lngCount To 1 Step -1

            'Save attachment before deleting from item.
            'Get the file name
            strFile = objAttachments.Item(i).FileName

            'Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            'Save the attachment as a file
            objAttachments.Item(i).SaveAsFile strFile

            'Delete the attachment
            objAttachments.Item(i).Delete

            'write the save as path to a string to add to the
            'message check from html and use html tags in link
            If objMsg.BodyFormat <> olFormatHTML Then
                strDeletedFile = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "
" & "" & strFile & ""
            End If

            'use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        'Adds the filename string to the message body and save it
        'Checks for HTML body
        If objMsg.BodyFormat <> olFormatHTML Then
            objMsg.Body = vbCrLf & "The File(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
        Else
            objMsg.HTMLBody = "
" & "The file(s) were saved to " & strDeletedFiles & "
" & objMsg.HTMLBody
        End If
        objMsg.Save
    End If
    Next

Exit Sub:

    Set objAttachments = Nothing
    Set objMsg = Nothing
    Set objSelection = Nothing
    Set objOL = Nothing
End Sub
```

答:
You pass the mailitem that triggers the script as a parameter.

If, for example, you pass Item then process Item.

```<code>Sub CustomMailMessageRule(Item As MailItem)
    MsgBox "Mail message arrived: " & Item.Subject
End Sub
</code>```

Title: Select email that triggers script

Body:
You pass the mailitem that triggers the script as a parameter.

If, for example, you pass Item then process Item.

Sub CustomMailMessageRule(Item As MailItem)
    MsgBox "Mail message arrived: " & Item.Subject
End Sub


问:
Nothing showing on screen with custom listview adapter
As the title states, I'm having some troubles getting my custom listview adapter to work properly. The app displays nothing on the list, and gives just a blank white screen. I tested my data with a simple list I already have setup, and that worked just fine.

History.java

```<code>public class History {
    public String score;
    public String gametype;
    public int icon;

    public History() {
        super();
    }

    public History(String score, String gametype, int icon) {
        super();
        this.score = score;
        this.gametype = gametype;
        this.icon = icon;
    }
}
</code>```

HistoryAdapter.java

```<code>public class HistoryAdapter extends ArrayAdapter<History> {

    Context context;
    int layoutResId;
    History data[] = null;

    public HistoryAdapter(Context context, int layoutResId, History[] data) {
        super(context, layoutResId, data);
        this.layoutResId = layoutResId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        HistoryHolder holder = null;

        if(convertView == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            convertView = inflater.inflate(layoutResId, parent, false);

            holder = new HistoryHolder();
            holder.imageIcon = (ImageView)convertView.findViewById(R.id.icon);
            holder.textTitle = (TextView)convertView.findViewById(R.id.gameType);
            holder.textScore = (TextView)convertView.findViewById(R.id.score);

            convertView.setTag(holder);
        }
        else
        {
            holder = (HistoryHolder)convertView.getTag();
        }

        History history = data[position];
        holder.textScore.setText(history.score);
        holder.textTitle.setText(history.gametype);
        holder.imageIcon.setImageResource(history.icon);

        return convertView;
    }

    static class HistoryHolder
    {
        ImageView imageIcon;
        TextView textTitle;
        TextView textScore;
    }
}
</code>```

Implementation

```<code>for(int i = 0; i < games.length(); i++) {
                    JSONObject c = games.getJSONObject(i);
                    JSONObject gameStats = games.getJSONObject(i).getJSONObject(TAG_STATS);
                    type[i] = c.getString(TAG_TYPE);
                    champId[i] = c.getString("championId");
                    cs[i] = gameStats.getString("minionsKilled");
                    kills[i] = gameStats.getString("championsKilled");
                    deaths[i] = gameStats.getString("numDeaths");
                    assists[i] = gameStats.getString("assists");
                    win[i] = gameStats.getString("win");

                    if(win[i].equals("true"))
                        win[i] = "Victory";
                    else
                        win[i] = "Defeat";

                    if(type[i].equals("RANKED_SOLO_5x5"))
                        type[i] = "Ranked (Solo)";

                    if(type[i].equals("CAP_5x5"))
                        type[i] = "TeamBuilder";

                    if(type[i].equals("NORMAL"))
                        type[i] = "Unranked";

                    score[i] = kills[i] +"/" + deaths[i] + "/" + assists[i];

                    historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image

                }

                adapter = new HistoryAdapter(MatchHistoryActivity.this,
                        R.layout.list_adapter,
                        historyData);

                list.setAdapter(adapter);
</code>```

listview.xml

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

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list"
    android:background="#111111">
    </ListView>
</code>```

list_item.xml

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:background="#111111"
    android:padding="6dip" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="6dip"
        android:contentDescription="TODO"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/score"
        android:textColor="#C49246"
        android:layout_width="fill_parent"
        android:layout_height="26dip"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/icon"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:text="0/0/0 KDA"
        android:textSize="12sp" />

    <TextView
        android:id="@+id/gameType"
        android:textColor="#C49246"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/score"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="true"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/icon"
        android:gravity="center_vertical"
        android:textSize="16sp" />

</RelativeLayout>
</code>```

答:
I think you should replace ArrayAdapter by BaseAdapter and implement all required method e.g. getItemId(), getItem(), getCount(), getView().

It should work fine!.
Below is example code of mine, dont care about what is MusicModel.

```<code>protected class MusicCustomAdapter extends BaseAdapter {

        private Activity context;
        private List<MusicModel> musicModelList;
        private SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");

        public MusicCustomAdapter(Activity context, List<MusicModel> musicModelList) {
            this.context = context;
            this.musicModelList = musicModelList;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return this.musicModelList.get(position);
        }

        @Override
        public int getCount() {
            return this.musicModelList.size();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = context.getLayoutInflater().inflate(R.layout.song_item, null);
            }

            MusicModel musicModel = (MusicModel) getItem(position);

            TextView tvMusicName = (TextView) view.findViewById(R.id.tv_song_name);
            tvMusicName.setText(musicModel.getName());

            TextView tvArtist = (TextView) view.findViewById(R.id.tv_artist);
            tvArtist.setText(musicModel.getArtist());

            TextView tvDuration = (TextView) view.findViewById(R.id.tv_duration);
            tvDuration.setText(sdf.format(musicModel.getDuration()));

            ImageView imgThumbnail = (ImageView) view.findViewById(R.id.img_thumbnail);
            imgThumbnail.setImageDrawable(musicModel.getThumbnail());

            return view;
        }
    }
</code>```

Hope this help.

Body:
As the title states, I'm having some troubles getting my custom listview adapter to work properly. The app displays nothing on the list, and gives just a blank white screen. I tested my data with a simple list I already have setup, and that worked just fine.

History.java

public class History {
    public String score;
    public String gametype;
    public int icon;

    public History() {
        super();
    }

    public History(String score, String gametype, int icon) {
        super();
        this.score = score;
        this.gametype = gametype;
        this.icon = icon;
    }
}

HistoryAdapter.java

public class HistoryAdapter extends ArrayAdapter<History> {

    Context context;
    int layoutResId;
    History data[] = null;

    public HistoryAdapter(Context context, int layoutResId, History[] data) {
        super(context, layoutResId, data);
        this.layoutResId = layoutResId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        HistoryHolder holder = null;

        if(convertView == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            convertView = inflater.inflate(layoutResId, parent, false);

            holder = new HistoryHolder();
            holder.imageIcon = (ImageView)convertView.findViewById(R.id.icon);
            holder.textTitle = (TextView)convertView.findViewById(R.id.gameType);
            holder.textScore = (TextView)convertView.findViewById(R.id.score);

            convertView.setTag(holder);
        }
        else
        {
            holder = (HistoryHolder)convertView.getTag();
        }

        History history = data[position];
        holder.textScore.setText(history.score);
        holder.textTitle.setText(history.gametype);
        holder.imageIcon.setImageResource(history.icon);

        return convertView;
    }

    static class HistoryHolder
    {
        ImageView imageIcon;
        TextView textTitle;
        TextView textScore;
    }
}

Implementation

for(int i = 0; i < games.length(); i++) {
                    JSONObject c = games.getJSONObject(i);
                    JSONObject gameStats = games.getJSONObject(i).getJSONObject(TAG_STATS);
                    type[i] = c.getString(TAG_TYPE);
                    champId[i] = c.getString("championId");
                    cs[i] = gameStats.getString("minionsKilled");
                    kills[i] = gameStats.getString("championsKilled");
                    deaths[i] = gameStats.getString("numDeaths");
                    assists[i] = gameStats.getString("assists");
                    win[i] = gameStats.getString("win");

                    if(win[i].equals("true"))
                        win[i] = "Victory";
                    else
                        win[i] = "Defeat";

                    if(type[i].equals("RANKED_SOLO_5x5"))
                        type[i] = "Ranked (Solo)";

                    if(type[i].equals("CAP_5x5"))
                        type[i] = "TeamBuilder";

                    if(type[i].equals("NORMAL"))
                        type[i] = "Unranked";

                    score[i] = kills[i] +"/" + deaths[i] + "/" + assists[i];

                    historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image

                }

                adapter = new HistoryAdapter(MatchHistoryActivity.this,
                        R.layout.list_adapter,
                        historyData);

                list.setAdapter(adapter);

listview.xml

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

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list"
    android:background="#111111">
    </ListView>

list_item.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:background="#111111"
    android:padding="6dip" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="6dip"
        android:contentDescription="TODO"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/score"
        android:textColor="#C49246"
        android:layout_width="fill_parent"
        android:layout_height="26dip"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/icon"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:text="0/0/0 KDA"
        android:textSize="12sp" />

    <TextView
        android:id="@+id/gameType"
        android:textColor="#C49246"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/score"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="true"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/icon"
        android:gravity="center_vertical"
        android:textSize="16sp" />

</RelativeLayout>

Body:
I think you should replace ArrayAdapter by BaseAdapter and implement all required method e.g. getItemId(), getItem(), getCount(), getView().

It should work fine!.
Below is example code of mine, dont care about what is MusicModel.

protected class MusicCustomAdapter extends BaseAdapter {

        private Activity context;
        private List<MusicModel> musicModelList;
        private SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");

        public MusicCustomAdapter(Activity context, List<MusicModel> musicModelList) {
            this.context = context;
            this.musicModelList = musicModelList;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return this.musicModelList.get(position);
        }

        @Override
        public int getCount() {
            return this.musicModelList.size();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = context.getLayoutInflater().inflate(R.layout.song_item, null);
            }

            MusicModel musicModel = (MusicModel) getItem(position);

            TextView tvMusicName = (TextView) view.findViewById(R.id.tv_song_name);
            tvMusicName.setText(musicModel.getName());

            TextView tvArtist = (TextView) view.findViewById(R.id.tv_artist);
            tvArtist.setText(musicModel.getArtist());

            TextView tvDuration = (TextView) view.findViewById(R.id.tv_duration);
            tvDuration.setText(sdf.format(musicModel.getDuration()));

            ImageView imgThumbnail = (ImageView) view.findViewById(R.id.img_thumbnail);
            imgThumbnail.setImageDrawable(musicModel.getThumbnail());

            return view;
        }
    }

Hope this help.


问:
Bind mutex to object
Given the following example code:

```<code>int var;
int mvar;
std::mutex mvar_mutex;

void f(){
    mvar_mutex.lock();
    mvar = var * var;
    mvar_mutex.unlock();
}
</code>```

I want to express that mvar_mutex is bound to the variable mvar and protects only that variable. mvar_mutex should not protect var because it is not bound to it. Hence the compiler would be allowed to transform the above code into the below code:

```<code>int var;
int mvar;
std::mutex mvar_mutex;

void f(){
    int r = var * var; //possible data race created if binding is not known
    mvar_mutex.lock();
    mvar = r;
    mvar_mutex.unlock();
}
</code>```

This might reduce contention on the lock as less work is being done while holding it.

For int this can be done using std::atomic<int> mvar; and removing mvar_mutex, but for other types such as std::vector<int> this is not possible.

How do I express the mutex-variable binding in a way that C++ compilers understand it and do the optimization? It should be allowed to reorder any variable up or down across mutex boundaries for any variable that is not bound to that mutex

Since the code is being generated using clang::ASTConsumer and clang::RecursiveASTVisitor I am willing to use non-standard extensions and AST manipulations as long as clang (ideally clang 4.0) supports them and the resulting code does not need to be elegant or human-readable.

Edit since this seems to be causing confusion: The above transformation is not legal in C++. The described binding of mutex to variable doesn't exist. The question is about how to implement that or achieve the same effect.

答:
How about a locked var template ?

```<code>template<typename Type, typename Mutex = std::mutex>
class Lockable
{
public:
   Lockable(_Type t) : var_(std::move(t));
   Lockable(_Type&&) = default;
   // ...  could need a bit more

   T operator = (const T& x)
   {
      std::lock_guard<Lockable> lock(*this);
      var_ = x;
      return x;
   }

   T operator *() const
   {
      std::lock_guard<Lockable> lock(*this);
      return var_;
   }

   void lock() const   { const_cast<Lockable*>(this)->mutex_.lock(); }
   void unlock() const { const_cast<Lockable*>(this)->mutex_.unlock().; }
private:
  Mutex mutex_;
  Type var_;
};
</code>```

locked by assignment operator

```<code>Lockable<int>var;
var = mylongComputation();
</code>```

Works great with lock_guard

```<code>Lockable<int>var;
std::lock_guard<Lockable<int>> lock(var);
var = 3;
</code>```

Practical on containers

```<code>Lockable<std::vector<int>> vec;
</code>```

etc...

Title: Bind mutex to object

Body:
Given the following example code:

int var;
int mvar;
std::mutex mvar_mutex;

void f(){
    mvar_mutex.lock();
    mvar = var * var;
    mvar_mutex.unlock();
}

I want to express that mvar_mutex is bound to the variable mvar and protects only that variable. mvar_mutex should not protect var because it is not bound to it. Hence the compiler would be allowed to transform the above code into the below code:

int var;
int mvar;
std::mutex mvar_mutex;

void f(){
    int r = var * var; //possible data race created if binding is not known
    mvar_mutex.lock();
    mvar = r;
    mvar_mutex.unlock();
}

This might reduce contention on the lock as less work is being done while holding it.

For int this can be done using std::atomic<int> mvar; and removing mvar_mutex, but for other types such as std::vector<int> this is not possible.

How do I express the mutex-variable binding in a way that C++ compilers understand it and do the optimization? It should be allowed to reorder any variable up or down across mutex boundaries for any variable that is not bound to that mutex

Since the code is being generated using clang::ASTConsumer and clang::RecursiveASTVisitor I am willing to use non-standard extensions and AST manipulations as long as clang (ideally clang 4.0) supports them and the resulting code does not need to be elegant or human-readable.

Edit since this seems to be causing confusion: The above transformation is not legal in C++. The described binding of mutex to variable doesn't exist. The question is about how to implement that or achieve the same effect.

Body:
How about a locked var template ?

template<typename Type, typename Mutex = std::mutex>
class Lockable
{
public:
   Lockable(_Type t) : var_(std::move(t));
   Lockable(_Type&&) = default;
   // ...  could need a bit more

   T operator = (const T& x)
   {
      std::lock_guard<Lockable> lock(*this);
      var_ = x;
      return x;
   }

   T operator *() const
   {
      std::lock_guard<Lockable> lock(*this);
      return var_;
   }

   void lock() const   { const_cast<Lockable*>(this)->mutex_.lock(); }
   void unlock() const { const_cast<Lockable*>(this)->mutex_.unlock().; }
private:
  Mutex mutex_;
  Type var_;
};

locked by assignment operator

Lockable<int>var;
var = mylongComputation();

Works great with lock_guard

Lockable<int>var;
std::lock_guard<Lockable<int>> lock(var);
var = 3;

Practical on containers

Lockable<std::vector<int>> vec;

etc...


问:
c++ stl vector causing memory overflow?
I am making extensive use of stl vectors to manage memory (de-) allocation of large arrays of data. In particular I am generating perspective projections of anatomical structures from a large number of angles (180 in 2 degree steps), processing and analysing the results. The results are used to define radiation fields for radiotherapy.

It seems that if the arrays exceed a certain size (>3 anatomical structures) that the memory overflows. In particular the error is as follows

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check

This is the a result of using at, which does bounds checking, rather than the faster [] operator. If I have <=3 structures the error does not occur.

I have tracked the error down to the following block of code

```<code>bool dicomCP::assignBeamlet(int beamletNumber, Beamlet &b1)
{
 //std::cout << "\nInside dicomCP::assignBeamlet (int, Beamlet &)\n";

  if (!this->isSet)
  {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);

   this->isSet=true;

   return true;

  }

  else if (!this->beamlets.at(beamletNumber-1).isOpen())
  {

   return false;

  }

  // left (outside) min(left) and right (outside) max(right) leaves
  else if ((this->beamlets.at(beamletNumber-1).right-b1.left >EPSILON2)&&(b1.right-this->beamlets.at(beamletNumber-1).left>EPSILON2))
  {

   if (this->beamlets.at(beamletNumber).open) return false;

   else if (!this->beamlets.at(beamletNumber).open)
   {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);
   this->beamlets.at(beamletNumber).isAssigned=true;

   this->isSet=true;
   return true;
   }
  }

  else return false;

}
</code>```

Note that if the "this->isSet=true;" lines are commented out the error does not manifest itself regardless of the number of structures :yes it works with 6! The "isSet" boolean value is used to determine which objects have been set, and hence which objects need to be written out to a data file for further processing.

System and sodtware:

gcc (SUSE Linux) 4.4.1 [gcc-4_4-branch revision 150839]
SuSE 11.2 64bit
Intel Celsius with 4 Xeon 2.66GHz CPUs and 4GB RAM
Eclipse CDT (IDE) 64 bit Build 20100218-1602

答:
My guess is that you are passing beamletNumber==0, which is then made (unsigned)-1, or in other words a very large number.

at(largenumber) then throws

Title: c++ stl vector causing memory overflow?

Body:
I am making extensive use of stl vectors to manage memory (de-) allocation of large arrays of data. In particular I am generating perspective projections of anatomical structures from a large number of angles (180 in 2 degree steps), processing and analysing the results. The results are used to define radiation fields for radiotherapy.

It seems that if the arrays exceed a certain size (>3 anatomical structures) that the memory overflows. In particular the error is as follows

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check

This is the a result of using at, which does bounds checking, rather than the faster [] operator. If I have <=3 structures the error does not occur.

I have tracked the error down to the following block of code

bool dicomCP::assignBeamlet(int beamletNumber, Beamlet &b1)
{
 //std::cout << "\nInside dicomCP::assignBeamlet (int, Beamlet &)\n";

  if (!this->isSet)
  {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);

   this->isSet=true;

   return true;

  }

  else if (!this->beamlets.at(beamletNumber-1).isOpen())
  {

   return false;

  }

  // left (outside) min(left) and right (outside) max(right) leaves
  else if ((this->beamlets.at(beamletNumber-1).right-b1.left >EPSILON2)&&(b1.right-this->beamlets.at(beamletNumber-1).left>EPSILON2))
  {

   if (this->beamlets.at(beamletNumber).open) return false;

   else if (!this->beamlets.at(beamletNumber).open)
   {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);
   this->beamlets.at(beamletNumber).isAssigned=true;

   this->isSet=true;
   return true;
   }
  }

  else return false;

}

Note that if the "this->isSet=true;" lines are commented out the error does not manifest itself regardless of the number of structures :yes it works with 6! The "isSet" boolean value is used to determine which objects have been set, and hence which objects need to be written out to a data file for further processing.

System and sodtware:

gcc (SUSE Linux) 4.4.1 [gcc-4_4-branch revision 150839]
SuSE 11.2 64bit
Intel Celsius with 4 Xeon 2.66GHz CPUs and 4GB RAM
Eclipse CDT (IDE) 64 bit Build 20100218-1602


问:
Why is vscode removing my spaces?
I have an angular project generated using the angular-cli with the following extensions in my vscode:

Angular Language Service
Auto Import
Debugger for Chrome
EditorConfig for VS Code
TSLint

I have a problem where vscode is removing my spaces.  For example say I add the following spaces underneath the switch statement.  If I don't type a non space character, then within less than a second it will delete my spaces underneath the switch statement.  It's very annoying.

答:
I have an .editorconfig file which has the following setting:

```<code>trim_trailing_whitespace = true
</code>```

I also installed the EditorConfig for VS Code extension.  This will cause the annoying behavior of trimming trailing whitespace.  To fix this I just have to set this setting to:

```<code>trim_trailing_whitespace = false
</code>```

Finally it's annoying to manually delete extra trailing whitespace so I can have a linter automatically fix this for me.  In my case I'm doing an angular2 development using the angular cli and I just need to run this for it automatically fix my trailing whitespace problems:

```<code>ng lint --fix
</code>```

I'm assuming that there are going to be similar commands for plain javascript linting and typescript linting.

Title: Why is vscode removing my spaces?

Body:
I have an .editorconfig file which has the following setting:

trim_trailing_whitespace = true

I also installed the EditorConfig for VS Code extension.  This will cause the annoying behavior of trimming trailing whitespace.  To fix this I just have to set this setting to:

trim_trailing_whitespace = false

Finally it's annoying to manually delete extra trailing whitespace so I can have a linter automatically fix this for me.  In my case I'm doing an angular2 development using the angular cli and I just need to run this for it automatically fix my trailing whitespace problems:

ng lint --fix

I'm assuming that there are going to be similar commands for plain javascript linting and typescript linting.


问:
How to keep service alive when remove app from stack
I want to show notification every minute using Alarm Manager, I have implemented below code, it's working fine but the problem is when I remove app from stack the service is not running.

I want keep alive, I have tried START_STICKY in onStartCommand and also used onTaskRemoved but it's same.

I also tried to implement using WakefulIntentService but the problem is same. My code is below.

In MainActivity

```<code>    Intent myIntent = new Intent(NotificationDemo.this, MyReceiver.class);

                myIntent.putExtra("title", "2 minutes");

                Random random = new Random();
                int m = random.nextInt(9999 - 1000) + 1000;

                Log.d("m::: In Notification", m + "");
                myIntent.putExtra("id", m);

                pendingIntent = PendingIntent.getBroadcast(NotificationDemo.this, m, myIntent, 0);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
//                alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),alarmManager.Inte pendingIntent);
                alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime(),
                        1 * 60 * 1000,
                        pendingIntent);
</code>```

MyService

```<code>       public class MyAlarmService extends Service {

            private NotificationManager mManager;

            @Override
            public IBinder onBind(Intent arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void onCreate() {
                // TODO Auto-generated method stub
                super.onCreate();
            }

            @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
        String title = intent.getStringExtra("title");
        int id = intent.getIntExtra("id", 0);
        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);

        Notification notification = new Notification(R.mipmap.ic_launcher, title, System.currentTimeMillis());
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Log.d("id::", id + "");

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
//        notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(MyAlarmService.this);

        notification = builder.setContentTitle(title)
                .setContentText("Hellooo...")
                .setTicker("Good Evening...")
                .setSmallIcon(android.R.drawable.ic_btn_speak_now)
                .setVibrate(new long[]{1000, 1000, 1000, 100})
                .setLights(5, 5, 5)
                .setContentIntent(pendingNotificationIntent).build();

        mManager.notify(id, notification);
        startForeground(1337, notification);
        return START_STICKY;
    }

            @Override
            public void onDestroy() {
                // TODO Auto-generated method stub
                super.onDestroy();
               // sendBroadcast(new Intent("IWillStartAuto"));
            }

            @Override
            public void onTaskRemoved(Intent rootIntent) {
                super.onTaskRemoved(rootIntent);
        //        sendBroadcast(new Intent("IWillStartAuto"));
        //        Intent intent = new Intent(getApplicationContext(),MyReceiver.class);
        //        sendBroadcast(intent);
            }
        }
</code>```

and this is my receiver

```<code>public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         String title = intent.getStringExtra("title");
    int id = intent.getIntExtra("id", 0);
    Intent service1 = new Intent(context, MyAlarmService.class);
    service1.putExtra("title", title);
    service1.putExtra("id", id);
    context.startService(service1);

    }
}
</code>```

In Manifest

```<code><receiver android:name=".MyReceiver">
        <!--<intent-filter>
            <action android:name="IWillStartAuto"/>
        </intent-filter>-->
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service
        android:name=".MyAlarmService"
        android:enabled="true"
        android:stopWithTask="false" />
</code>```

答:
You need to start your service in foreground.

You are missing something this in your service OnCreate() method.

```<code>startForeground(1337, notification);
return START_STICKY;
</code>```

And don't stop your service in your activities or fragments onDestroy() methods.

Body:
I want to show notification every minute using Alarm Manager, I have implemented below code, it's working fine but the problem is when I remove app from stack the service is not running.

I want keep alive, I have tried START_STICKY in onStartCommand and also used onTaskRemoved but it's same.

I also tried to implement using WakefulIntentService but the problem is same. My code is below.

In MainActivity

    Intent myIntent = new Intent(NotificationDemo.this, MyReceiver.class);

                myIntent.putExtra("title", "2 minutes");

                Random random = new Random();
                int m = random.nextInt(9999 - 1000) + 1000;

                Log.d("m::: In Notification", m + "");
                myIntent.putExtra("id", m);

                pendingIntent = PendingIntent.getBroadcast(NotificationDemo.this, m, myIntent, 0);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
//                alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),alarmManager.Inte pendingIntent);
                alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime(),
                        1 * 60 * 1000,
                        pendingIntent);

MyService

       public class MyAlarmService extends Service {

            private NotificationManager mManager;

            @Override
            public IBinder onBind(Intent arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void onCreate() {
                // TODO Auto-generated method stub
                super.onCreate();
            }

            @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
        String title = intent.getStringExtra("title");
        int id = intent.getIntExtra("id", 0);
        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);

        Notification notification = new Notification(R.mipmap.ic_launcher, title, System.currentTimeMillis());
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Log.d("id::", id + "");

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
//        notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(MyAlarmService.this);

        notification = builder.setContentTitle(title)
                .setContentText("Hellooo...")
                .setTicker("Good Evening...")
                .setSmallIcon(android.R.drawable.ic_btn_speak_now)
                .setVibrate(new long[]{1000, 1000, 1000, 100})
                .setLights(5, 5, 5)
                .setContentIntent(pendingNotificationIntent).build();

        mManager.notify(id, notification);
        startForeground(1337, notification);
        return START_STICKY;
    }

            @Override
            public void onDestroy() {
                // TODO Auto-generated method stub
                super.onDestroy();
               // sendBroadcast(new Intent("IWillStartAuto"));
            }

            @Override
            public void onTaskRemoved(Intent rootIntent) {
                super.onTaskRemoved(rootIntent);
        //        sendBroadcast(new Intent("IWillStartAuto"));
        //        Intent intent = new Intent(getApplicationContext(),MyReceiver.class);
        //        sendBroadcast(intent);
            }
        }

and this is my receiver

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         String title = intent.getStringExtra("title");
    int id = intent.getIntExtra("id", 0);
    Intent service1 = new Intent(context, MyAlarmService.class);
    service1.putExtra("title", title);
    service1.putExtra("id", id);
    context.startService(service1);

    }
}

In Manifest

<receiver android:name=".MyReceiver">

        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service
        android:name=".MyAlarmService"
        android:enabled="true"
        android:stopWithTask="false" />

Body:
You need to start your service in foreground.

You are missing something this in your service OnCreate() method.

startForeground(1337, notification);
return START_STICKY;

And don't stop your service in your activities or fragments onDestroy() methods.


问:
NodeJs AJAX undefined values for submit buttons
I'm using Node.js as server-side with express and ejs with Twitter Bootstrap as front-end. The page has a modal with a form and 2 submit buttons. I want to display different messages depending on what button was used to submit with ajax (later I will add other handlings but for now I just want to display messages). My problem is that I can't get the value of the submitted button.

index.ejs

```<code><!DOCTYPE html>
<html lang="fr">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>test</title>

    <link href="/css/style.css" rel="stylesheet">

    <link href="/css/bootstrap.min.css" rel="stylesheet">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    </head>

    <body>
        <button type="button" class="btn btn-lg btn-primary"
        data-toggle="modal" data-target="#modalCreateMdl">Click here</button>

        <div id="modalCreateMdl" class="modal fade" role="dialog">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">×</button>
                        <h4 class="modal-title">Form</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal" id="formTest" action="test" method="post">
                                <div class="form-group">
                                    <div class="col-sm-offset-2 col-sm-10">
                                        <button type="submit" name="sub" class="btn btn-primary" value="submit1">SUBMIT 1</button>
                                    </div>
                                    <div class="col-sm-offset-2 col-sm-10">
                                        <button type="submit" name="sub" class="btn btn-primary" value="submit2">SUBMIT 2</button>
                                    </div>
                                </div>
                                <div id="msgTest" style="display:none"></div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

        <script src="/js/ajax.js"></script>
    </body>
</html>
</code>```

test.js

```<code>var express = require('express');
var bodyParser = require('body-parser')

var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("/home/mainuser/test_node/"));

app.post('/test', function(req, res) {
    console.log(req.body.sub);
    if(req.body.sub == "submit1") {
        obj = {test : "json1"};
        console.log("submit number 1");
    } else if(req.body.sub == "submit2") {
        obj = {test : "json2"};
        console.log("submit number 2");
    } else {
        obj = {test : "json_default"};
        console.log("default");
    }
    res.json(obj);
});

app.get('/', function(req, res) {
    res.render('index.ejs');
});

app.listen(8080);
</code>```

ajax.js

```<code>$(document).ready(function() {
    $('#formTest').submit(function() {
        $.ajax({
            method : $(this).attr('method'),
            url : $(this).attr('action'),
            data : $(this).serialize(),
            success : onSuccessLoad,
            error : onError
        });
        return false;
    });
});
// ready

function onSuccessLoad(json) {
    $('#msgTest').fadeOut('slow');
    $('#msgTest').html(json.test);
    $('#msgTest').fadeIn('slow');
}

function onError(returnation) {
    alert("problem");
}
</code>```

When I click on SUBMIT 1 button, I get the following output in the terminal :

```<code>undefined
default
</code>```

and json_default is displayed on the page.

when it should be this in the terminal :

```<code>submit1
submit number 1
</code>```

and json1 on the page.

When I remove ajax.js the console output is fine but obviously the json is displayed in a new page which is not what I want.

答:
```<code><button type="button" class="btn btn-lg btn-primary"
                    data-toggle="modal" data-target="#modalCreateMdl">Click here</button>

    <div id="modalCreateMdl" class="modal fade" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">Form</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" id="formTest" action="test" method="post">
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <input type="text" name="sub" class="btn btn-primary" value="submit1">
                            </div>
                            <div class="col-sm-offset-2 col-sm-10">
                                <input type="text" name="sub" class="btn btn-primary" value="submit2">
                            </div>
                        </div>
                        <div id="msgTest" style="display:none"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
 <script>
     $('input[name="sub"]').on('click',function() {
         var serializeStr = $('#formTest').serialize();
         var serializeArray = serializeStr.split('&');
         var params = {};
         for(var i=0;i<serializeArray.length;i++){
            var value = serializeArray[i].split('=');
             params[value[0]] = value[1];
         }
         $.ajax({
             method : $('#formTest').attr('method'),
             url : $('#formTest').attr('action'),
             data : params,
             success : onSuccessLoad,
             error : onError
         });
         return false;
     });
     function onSuccessLoad(json) {
         $('#msgTest').fadeOut('slow');
         $('#msgTest').html(json.test);
         $('#msgTest').fadeIn('slow');
     }

     function onError(returnation) {
         alert("problem");
     }
</code>```

Body:
I'm using Node.js as server-side with express and ejs with Twitter Bootstrap as front-end. The page has a modal with a form and 2 submit buttons. I want to display different messages depending on what button was used to submit with ajax (later I will add other handlings but for now I just want to display messages). My problem is that I can't get the value of the submitted button.

index.ejs

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>test</title>

    <link href="/css/style.css" rel="stylesheet">

    <link href="/css/bootstrap.min.css" rel="stylesheet">

        <button type="button" class="btn btn-lg btn-primary"
        data-toggle="modal" data-target="#modalCreateMdl">Click here</button>

                        <button type="button" class="close" data-dismiss="modal">×</button>

Form

                        <form class="form-horizontal" id="formTest" action="test" method="post">

                                        <button type="submit" name="sub" class="btn btn-primary" value="submit1">SUBMIT 1</button>

                                        <button type="submit" name="sub" class="btn btn-primary" value="submit2">SUBMIT 2</button>

                        </form>

                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

test.js

var express = require('express');
var bodyParser = require('body-parser')

var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("/home/mainuser/test_node/"));

app.post('/test', function(req, res) {
    console.log(req.body.sub);
    if(req.body.sub == "submit1") {
        obj = {test : "json1"};
        console.log("submit number 1");
    } else if(req.body.sub == "submit2") {
        obj = {test : "json2"};
        console.log("submit number 2");
    } else {
        obj = {test : "json_default"};
        console.log("default");
    }
    res.json(obj);
});

app.get('/', function(req, res) {
    res.render('index.ejs');
});

app.listen(8080);

ajax.js

$(document).ready(function() {
    $('#formTest').submit(function() {
        $.ajax({
            method : $(this).attr('method'),
            url : $(this).attr('action'),
            data : $(this).serialize(),
            success : onSuccessLoad,
            error : onError
        });
        return false;
    });
});
// ready

function onSuccessLoad(json) {
    $('#msgTest').fadeOut('slow');
    $('#msgTest').html(json.test);
    $('#msgTest').fadeIn('slow');
}

function onError(returnation) {
    alert("problem");
}

When I click on SUBMIT 1 button, I get the following output in the terminal :

undefined
default

and json_default is displayed on the page.

when it should be this in the terminal :

submit1
submit number 1

and json1 on the page.

When I remove ajax.js the console output is fine but obviously the json is displayed in a new page which is not what I want.

Body:
<button type="button" class="btn btn-lg btn-primary"
                    data-toggle="modal" data-target="#modalCreateMdl">Click here</button>

    <div id="modalCreateMdl" class="modal fade" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Form</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" id="formTest" action="test" method="post">
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <input type="text" name="sub" class="btn btn-primary" value="submit1">
                            </div>
                            <div class="col-sm-offset-2 col-sm-10">
                                <input type="text" name="sub" class="btn btn-primary" value="submit2">
                            </div>
                        </div>
                        <div id="msgTest" style="display:none"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
 <script>
     $('input[name="sub"]').on('click',function() {
         var serializeStr = $('#formTest').serialize();
         var serializeArray = serializeStr.split('&');
         var params = {};
         for(var i=0;i<serializeArray.length;i++){
            var value = serializeArray[i].split('=');
             params[value[0]] = value[1];
         }
         $.ajax({
             method : $('#formTest').attr('method'),
             url : $('#formTest').attr('action'),
             data : params,
             success : onSuccessLoad,
             error : onError
         });
         return false;
     });
     function onSuccessLoad(json) {
         $('#msgTest').fadeOut('slow');
         $('#msgTest').html(json.test);
         $('#msgTest').fadeIn('slow');
     }

     function onError(returnation) {
         alert("problem");
     }


问:
Replace in ColdFusion spoiling SQL query
I've got the below MySQL query, it's causing an error, the error is below too.

```<code>    SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
    FROM    sales s LEFT JOIN saleloc sl ON sl.saleId = s.id LEFT JOIN saledates sd ON sd.saleLoc = sl.id,
            auctioneers an,
            lookupcopy st,
            lookupcopy at
    #replace(findWhere,"''","'","all")# AND
    s.id = sd.saleId AND sl.saleId = s.id
    AND an.id = s.auctioneer
    AND st.id = s.saleType
    AND at.id = s.advertType
    GROUP BY id
    ORDER BY startDate, auctioneerName, city
</code>```

Error from database

```<code>SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
FROM sales s
LEFT JOIN saleloc sl ON sl.saleId = s.id
LEFT JOIN saledates sd ON sd.saleLoc = sl.id, auctioneers an, lookupcopy st, lookupcopy at
'WHERE s.advertType > 0
AND s.saleType > 0
AND sl.region = "2" '
AND s.id = sd.saleId
AND sl.saleId = s.id
AND an.id = s.auctioneer
AND st.id = s.saleType
AND at.id = s.advertType
GROUP BY id
ORDER BY startDate, auctioneerName, city
</code>```

I didn't write this code and I'm not sure why the #Replace()# is being used, can anyone see how to fix the syntax error it's causing?

答:
On another note: Unless you created findWhere without any direct user input value, then you need to secure it.

Better to do:

```<code>...
WHERE 1= 1
<cfif listFind( 'foo' , findWhere )>
foo= 2

<cfelseif listFind( 'bar' , findWhere )>
bar= 209

</cfif>
...
</code>```

Body:
I've got the below MySQL query, it's causing an error, the error is below too.

    SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
    FROM    sales s LEFT JOIN saleloc sl ON sl.saleId = s.id LEFT JOIN saledates sd ON sd.saleLoc = sl.id,
            auctioneers an,
            lookupcopy st,
            lookupcopy at
    #replace(findWhere,"''","'","all")# AND
    s.id = sd.saleId AND sl.saleId = s.id
    AND an.id = s.auctioneer
    AND st.id = s.saleType
    AND at.id = s.advertType
    GROUP BY id
    ORDER BY startDate, auctioneerName, city

Error from database

SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
FROM sales s
LEFT JOIN saleloc sl ON sl.saleId = s.id
LEFT JOIN saledates sd ON sd.saleLoc = sl.id, auctioneers an, lookupcopy st, lookupcopy at
'WHERE s.advertType > 0
AND s.saleType > 0
AND sl.region = "2" '
AND s.id = sd.saleId
AND sl.saleId = s.id
AND an.id = s.auctioneer
AND st.id = s.saleType
AND at.id = s.advertType
GROUP BY id
ORDER BY startDate, auctioneerName, city

I didn't write this code and I'm not sure why the #Replace()# is being used, can anyone see how to fix the syntax error it's causing?

Body:
On another note: Unless you created findWhere without any direct user input value, then you need to secure it.

Better to do:

...
WHERE 1= 1
<cfif listFind( 'foo' , findWhere )>
foo= 2

<cfelseif listFind( 'bar' , findWhere )>
bar= 209

</cfif>
...


问:
FavIcon issue in springMVC
Our Fav icon is placed in different url and we added below link in the header jsp.
<link rel="shortcut icon" type="image/x-icon" media="all" href="/siteid/_ui/responsive/theme/images/favicon.ico" />

but still browser is searching as www.sitename.com/favicon.ico randomly mainly in google chrome. This is causing the user session out issue in springs.

Any suggestions.

Thanks,
Sreenivas A.

答:
I think to problem is you are missing the parent directory.

Try this

```<code>href="~/siteid/_ui/responsive/theme/images/favicon.ico" />
</code>```

or

```<code>href="../siteid/_ui/responsive/theme/images/favicon.ico" />
</code>```

Title: FavIcon issue in springMVC

Body:
I think to problem is you are missing the parent directory.

Try this

href="~/siteid/_ui/responsive/theme/images/favicon.ico" />

or

href="../siteid/_ui/responsive/theme/images/favicon.ico" />


问:
How do I add a score text list that adds 1 each time I click my cookie sprite? (python)
Game code deals with classes Cookie and Shop. How do I make it so that I have a text box which says {Cookie Number} Cookies? Is there a command that says if event.click then cookie +1?

Inside of the game_loop is a simple text box that just says "some cookie number, with the word cookies at the end. I think I would have to create a list but I am not sure how to do that. Would I use {}? Also, thank you to everyone for your help.

```<code>import pygame as pg
import os

WIDTH = 1024
HEIGHT = 768

CLOCK = pg.time.Clock()
FPS = 60

WHITE = (255, 255, 255)
BROWN = (153, 51, 51)
DARKGRAY = (40, 40, 40)
BGCOLOR = DARKGRAY

game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")

screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption("Cookie Clicker")

class Cookie(pg.sprite.Sprite):

    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.image.load(os.path.join(img_folder, "2.png")).convert()
        self.rect = self.image.get_rect()
        self.rect.center = ((WIDTH - 670, HEIGHT / 2))

cookie = Cookie()

class Shop(pg.sprite.Sprite):

    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((300, 768))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.rect.center = ((WIDTH - 150, HEIGHT / 2))

def game_loop():
    pg.init()
    pg.font.init()

    my_font = pg.font.SysFont("Comic Sans MS", 30)

    text_surface = my_font.render('SOME NUMBER - Cookies', False, (0, 255, 0))

    running = True
    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False

        all_sprites = pg.sprite.Group()
        all_sprites.add(cookie, shop)
        all_sprites.update()

        screen.fill(BGCOLOR)
        all_sprites.draw(screen)
        screen.blit(text_surface, (175, 100))
        pg.display.flip()

        CLOCK.tick(FPS)

    pg.quit()

game_loop()
</code>```

答:
In the event loop, check if the user presses a mousebutton, then see if the cookie.rect collides with the event.pos (or use pg.mouse.get_pos()), and if they collide, increment a score variable:

```<code>elif event.type == pg.MOUSEBUTTONDOWN:
    # Use the collidepoint method of this `pygame.Rect`.
    if cookie.rect.collidepoint(event.pos):
        score += 1
        print(score)
</code>```

To blit the text onto the screen, you need to put the score into a string with the help of the .format method: '{} Cookies'.format(score). Then pass it to my_font.render and blit the returned surface.

```<code>text_surface = my_font.render('{} Cookies'.format(score), True, BROWN)
screen.blit(text_surface, (30, 30))
</code>```

Also, you shouldn't create and fill the all_sprites group inside of the while loop. Here's the updated game_loop function:

```<code>def game_loop():
    pg.init()

    my_font = pg.font.SysFont("Comic Sans MS", 30)
    cookie = Cookie()
    shop = Shop()
    all_sprites = pg.sprite.Group()
    all_sprites.add(cookie, shop)
    score = 0

    running = True
    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
            elif event.type == pg.MOUSEBUTTONDOWN:
                if cookie.rect.collidepoint(event.pos):
                    score += 1
                    print(score)

        all_sprites.update()

        screen.fill(BGCOLOR)
        all_sprites.draw(screen)
        screen.blit(text_surface, (175, 100))
        text_surface = my_font.render('{} Cookies'.format(score), True, BROWN)
        screen.blit(text_surface, (30, 30))
        pg.display.flip()

        CLOCK.tick(FPS)

    pg.quit()
    sys.exit()  # import sys at the top of the file.
</code>```

Body:
Game code deals with classes Cookie and Shop. How do I make it so that I have a text box which says {Cookie Number} Cookies? Is there a command that says if event.click then cookie +1?

Inside of the game_loop is a simple text box that just says "some cookie number, with the word cookies at the end. I think I would have to create a list but I am not sure how to do that. Would I use {}? Also, thank you to everyone for your help.

import pygame as pg
import os

WIDTH = 1024
HEIGHT = 768

CLOCK = pg.time.Clock()
FPS = 60

WHITE = (255, 255, 255)
BROWN = (153, 51, 51)
DARKGRAY = (40, 40, 40)
BGCOLOR = DARKGRAY

game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")

screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption("Cookie Clicker")

class Cookie(pg.sprite.Sprite):

    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.image.load(os.path.join(img_folder, "2.png")).convert()
        self.rect = self.image.get_rect()
        self.rect.center = ((WIDTH - 670, HEIGHT / 2))

cookie = Cookie()

class Shop(pg.sprite.Sprite):

    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((300, 768))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.rect.center = ((WIDTH - 150, HEIGHT / 2))

def game_loop():
    pg.init()
    pg.font.init()

    my_font = pg.font.SysFont("Comic Sans MS", 30)

    text_surface = my_font.render('SOME NUMBER - Cookies', False, (0, 255, 0))

    running = True
    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False

        all_sprites = pg.sprite.Group()
        all_sprites.add(cookie, shop)
        all_sprites.update()

        screen.fill(BGCOLOR)
        all_sprites.draw(screen)
        screen.blit(text_surface, (175, 100))
        pg.display.flip()

        CLOCK.tick(FPS)

    pg.quit()

game_loop()

Body:
In the event loop, check if the user presses a mousebutton, then see if the cookie.rect collides with the event.pos (or use pg.mouse.get_pos()), and if they collide, increment a score variable:

elif event.type == pg.MOUSEBUTTONDOWN:
    # Use the collidepoint method of this `pygame.Rect`.
    if cookie.rect.collidepoint(event.pos):
        score += 1
        print(score)

To blit the text onto the screen, you need to put the score into a string with the help of the .format method: '{} Cookies'.format(score). Then pass it to my_font.render and blit the returned surface.

text_surface = my_font.render('{} Cookies'.format(score), True, BROWN)
screen.blit(text_surface, (30, 30))

Also, you shouldn't create and fill the all_sprites group inside of the while loop. Here's the updated game_loop function:

def game_loop():
    pg.init()

    my_font = pg.font.SysFont("Comic Sans MS", 30)
    cookie = Cookie()
    shop = Shop()
    all_sprites = pg.sprite.Group()
    all_sprites.add(cookie, shop)
    score = 0

    running = True
    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
            elif event.type == pg.MOUSEBUTTONDOWN:
                if cookie.rect.collidepoint(event.pos):
                    score += 1
                    print(score)

        all_sprites.update()

        screen.fill(BGCOLOR)
        all_sprites.draw(screen)
        screen.blit(text_surface, (175, 100))
        text_surface = my_font.render('{} Cookies'.format(score), True, BROWN)
        screen.blit(text_surface, (30, 30))
        pg.display.flip()

        CLOCK.tick(FPS)

    pg.quit()
    sys.exit()  # import sys at the top of the file.


问:
NullPointerException when using multiple stepdefinitions in Cucumber-jvm
I am currently building a framework to test a Rest-API endpoint. As I am planning to write a lot of test cases, I decided to organize the project to allow me to reuse common Step Definition methods.

The structure is as follows;

```<code>FunctionalTest
    com.example.steps
        -- AbstractEndpointSteps.java
        -- SimpleSearchSteps.java
    com.example.stepdefinitions
        -- CommonStepDefinition.java
        -- SimpleSearchStepDefinition.java`
</code>```

However when I try to call SimpleSearchSteps.java methods I get a NullPointerException

CommonStepDefinition Code

```<code>package com.example.functionaltest.features.stepdefinitions;

import net.thucydides.core.annotations.Steps;

import com.example.functionaltest.steps.AbstractEndpointSteps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CommonStepDefinition {

    @Steps
    private AbstractEndpointSteps endpointSteps;

    @Given("^a base uri \"([^\"]*)\" and base path \"([^\"]*)\"$")
    public void aBaseUriAndBasePath(String baseURI, String basePath) {
        endpointSteps.givenBasepath(baseURI, basePath);
    }

    @When("^country is \"([^\"]*)\"$")
    public void countryIs(String country)
    {
        endpointSteps.whenCountry(country);
    }

    @Then("^the status code is (\\d+)$")
    public void theStatusCodeIs(int statusCode) {
        endpointSteps.executeRequest();
        endpointSteps.thenTheStatusCodeIs200(statusCode);
    }

}
</code>```

SimpleSearchStepDefinition.java

```<code>package com.example.functionaltest.features.stepdefinitions;

import net.thucydides.core.annotations.Steps;
import com.example.functionaltest.steps.EndpointSteps;
import cucumber.api.java.en.When;

public class SimpleSearchStepDefinition {

    @Steps
    private SimpleSearchSteps searchSteps;

    @When("^what is \"([^\"]*)\"$")
    public void whatIs(String what) {
        searchSteps.whenWhatIsGiven(what);
    }

}
</code>```

答:
Can you take a look at Karate it is exactly what you are trying to build !  Since you are used to Cucumber, here are a few things that Karate provides as enhancements  (being based on Cucumber-JVM)

built-in step-definitions, no need to write Java code

re-use *.feature files and call them from other scripts

dynamic data-driven testing

parallel-execution of tests

ability to run some routines only once per feature

Disclaimer: I am the dev.

Body:
I am currently building a framework to test a Rest-API endpoint. As I am planning to write a lot of test cases, I decided to organize the project to allow me to reuse common Step Definition methods.

The structure is as follows;

FunctionalTest
    com.example.steps
        -- AbstractEndpointSteps.java
        -- SimpleSearchSteps.java
    com.example.stepdefinitions
        -- CommonStepDefinition.java
        -- SimpleSearchStepDefinition.java`

However when I try to call SimpleSearchSteps.java methods I get a NullPointerException

CommonStepDefinition Code

package com.example.functionaltest.features.stepdefinitions;

import net.thucydides.core.annotations.Steps;

import com.example.functionaltest.steps.AbstractEndpointSteps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CommonStepDefinition {

    @Steps
    private AbstractEndpointSteps endpointSteps;

    @Given("^a base uri \"([^\"]*)\" and base path \"([^\"]*)\"$")
    public void aBaseUriAndBasePath(String baseURI, String basePath) {
        endpointSteps.givenBasepath(baseURI, basePath);
    }

    @When("^country is \"([^\"]*)\"$")
    public void countryIs(String country)
    {
        endpointSteps.whenCountry(country);
    }

    @Then("^the status code is (\\d+)$")
    public void theStatusCodeIs(int statusCode) {
        endpointSteps.executeRequest();
        endpointSteps.thenTheStatusCodeIs200(statusCode);
    }

}

SimpleSearchStepDefinition.java

package com.example.functionaltest.features.stepdefinitions;

import net.thucydides.core.annotations.Steps;
import com.example.functionaltest.steps.EndpointSteps;
import cucumber.api.java.en.When;

public class SimpleSearchStepDefinition {

    @Steps
    private SimpleSearchSteps searchSteps;

    @When("^what is \"([^\"]*)\"$")
    public void whatIs(String what) {
        searchSteps.whenWhatIsGiven(what);
    }

}


问:
JQuery - Check if each dynamically added button clicked
I have buttons being added to an element via JQuery Ajax and a PHP script.  The number of buttons being added is variable.  I want to be able to check if each button has been clicked before enabling another action.

The relevant code in the PHP script is as follows with each button having an incremented ID:

```<code>$i = 1;
while ($row = mysql_fetch_array($result)) {
echo "<div class='dr_feedback_btn' id='dr_" . $i++ . "'>Feedback</div>";
}
</code>```

I have the following code in JQuery for the button click based on the button class:

```<code>    $('#dr_container').on('click', '.dr_feedback_btn', function() {
         ...
    });
</code>```

The image below shows the feedback buttons.

Any help appreciated.

答:
You can add a "clicked" class to each button when clicked, and then test if there are any buttons that don't have that class:

```<code>$('#dr_container').on('click', '.dr_feedback_btn', function() {
   $(this).addClass('clicked');
   if ($('.dr_feedback_btn').not('.clicked').length === 0) {
     // all are clicked, so enable your other action here
   }

   // other click processing here
});
</code>```

The "clicked" class can of course be named whatever you want, and need not exist in your CSS, though you might consider giving the user some visual indication of which buttons have been clicked already (and you could use the new class for that).

Body:
I have buttons being added to an element via JQuery Ajax and a PHP script.  The number of buttons being added is variable.  I want to be able to check if each button has been clicked before enabling another action.

The relevant code in the PHP script is as follows with each button having an incremented ID:

$i = 1;
while ($row = mysql_fetch_array($result)) {
echo "
Feedback
";
}

I have the following code in JQuery for the button click based on the button class:

    $('#dr_container').on('click', '.dr_feedback_btn', function() {
         ...
    });

The image below shows the feedback buttons.

Any help appreciated.

Body:
You can add a "clicked" class to each button when clicked, and then test if there are any buttons that don't have that class:

$('#dr_container').on('click', '.dr_feedback_btn', function() {
   $(this).addClass('clicked');
   if ($('.dr_feedback_btn').not('.clicked').length === 0) {
     // all are clicked, so enable your other action here
   }

   // other click processing here
});

The "clicked" class can of course be named whatever you want, and need not exist in your CSS, though you might consider giving the user some visual indication of which buttons have been clicked already (and you could use the new class for that).


问:
More information on Columnar or 'Column-family' data model in Cosmos DB
The documenation states that the Cosmos DB engine "natively supports multiple data models: key-value, documents, graphs, and columnar ".

However, I can't seem to find any other information relating specifically to the columnar model.

There is also information available on the following APIs:

DocumentDB APIs

Table APIs

Graph APIs

But nothing on Columnar or Column-family, as described in various summaries.

Reference: https://learn.microsoft.com/en-us/azure/cosmos-db/introduction

答:
can't seem to find any other information relating specifically to the columnar model

This article will help you understand the concept of column-family:

You can think of a column-family database as holding tabular data with rows and columns, but the columns are divided into groups known as column families. Each column family holds a set of columns that are logically related together and are typically retrieved or manipulated as a unit. Other data that is accessed separately can be stored in separate column families. Within a column family, new columns can be added dynamically, and rows can be sparse (that is, a row doesn't need to have a value for every column).

Besides, as David Makogon said, you can give your feedback (or comment) on that page or contact Cosmos DB team on this email (askdocdb@microsoft.com) for more details about column-family data model.


问:
Why won't form.submit() trigger the "submit" event?
I am submitting my form by using JavaScript .submit() function.

```<code>form.submit();
</code>```

But when I using addEventListener to capture my submit event, it wouldn't work.

```<code>form.addEventListener("submit", function(event){
    //codes
});
</code>```

I found out addEvenetListener function will only listen for onsubmit event instead of submit. Is there have any alternative solution to call my function when form.submit() is executed?

ps: For some reasons I need to stay with form.submit() to submit my form instead of using submit button.

答: Make the event handler listen for the button click and then call form.submit() inside the callback.

Body:
I am submitting my form by using JavaScript .submit() function.

form.submit();

But when I using addEventListener to capture my submit event, it wouldn't work.

form.addEventListener("submit", function(event){
    //codes
});

I found out addEvenetListener function will only listen for onsubmit event instead of submit. Is there have any alternative solution to call my function when form.submit() is executed?

ps: For some reasons I need to stay with form.submit() to submit my form instead of using submit button.


问:
Eval within if statement
How can I dynamically pass eq or ne inside perl if statement? I tried below but is not working:</p>

```<code>my $this="this";
my $that="that";
my $cond='ne';
if($this eval($cond) $that)
{
  print "$cond\n";
}
</code>```

答:
You don't need eval for this. Just use a dispatch table:

```<code>sub test {
    my %op = (
        eq => sub { $_[0] eq $_[1] },
        ne => sub { $_[0] ne $_[1] },
    );
    return $op{ $_[2] }->($_[0], $_[1]);
}

if (test($this, $that, $cond)){
    print "$cond\n";
}
</code>```

Title: Eval within if statement

Body:
How can I dynamically pass eq or ne inside perl if statement? I tried below but is not working:

my $this="this";
my $that="that";
my $cond='ne';
if($this eval($cond) $that)
{
  print "$cond\n";
}

Body:
You don't need eval for this. Just use a dispatch table:

sub test {
    my %op = (
        eq => sub { $_[0] eq $_[1] },
        ne => sub { $_[0] ne $_[1] },
    );
    return $op{ $_[2] }->($_[0], $_[1]);
}

if (test($this, $that, $cond)){
    print "$cond\n";
}