问:
AttributeError: 'NoneType' object has no attribute 'replace' (python)

http://cs1.ucc.ie/~adc2/cgi-bin/lab7/index.html
You can check out the error for yourself by just inputting anything into anyone of the boxes , doesnt have to be all, any help would be great
, I will send on the code after this

```<code>from cgitb import enable
enable()

from cgi import FieldStorage,escape

print('Content-Type: text/html')
print()

actor=''

genre=''

theyear=''

director=''

mood=''

result=''

form_data= FieldStorage()
if len(form_data) != 0:

    try:
        actor=escape(form_data.getfirst('actor'))
        genre=escape(form_data.getfirst('genre'))
        theyear=escape(form_data.getfirst('theyear'))
        director=escape(form_data.getfirst('director'))
        mood= escape(form_data.getfirst('mood'))
        connection = db.connect('####', '###', '####', '###')
        cursor = connection.cursor(db.cursors.DictCursor)
        cursor.execute("""SELECT title
                          FROM films
                          WHERE (actor = '%s')
                          OR (actor='%s' AND genre='%s')
                          OR (actor='%s' AND genre='%s' AND theyear='%i')
                          OR (actor='%s' AND genre='%s' AND theyear='%i' AND director='%s')
                          OR (actor='%s' AND genre='%s' AND theyear='%i' AND director='%s' AND mood='%s') % (actor, actor,genre, actor,genre,theyear, actor,genre,theyear,director,actor,genre,theyear,director,mood))
                          """)
        result = """<table>
                    <tr><th>Your movie!</th></tr>
                    <tr><th></th></tr>"""
        for row in cursor.fetchall():
            result+= '<tr><td>%s</td></tr>' ,(row['title'])
        result+= '</table>'
        cursor.close()
        connection.close()

    except db.Error:
        result = '<p>Sorry! We are currently experiencing technical difficulties.</p>'
</code>```

答: Your <input> is named year but you try to run escape(form_data.getfirst('theyear')). getfirst returns None when there is no corresponding form value and escape fails one None. For similar reasons you need to better handle optional fields like what Willem said in the comments.

Body:
http://cs1.ucc.ie/~adc2/cgi-bin/lab7/index.html
You can check out the error for yourself by just inputting anything into anyone of the boxes , doesnt have to be all, any help would be great
, I will send on the code after this

from cgitb import enable
enable()

from cgi import FieldStorage,escape

print('Content-Type: text/html')
print()

actor=''

genre=''

theyear=''

director=''

mood=''

result=''

form_data= FieldStorage()
if len(form_data) != 0:

    try:
        actor=escape(form_data.getfirst('actor'))
        genre=escape(form_data.getfirst('genre'))
        theyear=escape(form_data.getfirst('theyear'))
        director=escape(form_data.getfirst('director'))
        mood= escape(form_data.getfirst('mood'))
        connection = db.connect('####', '###', '####', '###')
        cursor = connection.cursor(db.cursors.DictCursor)
        cursor.execute("""SELECT title
                          FROM films
                          WHERE (actor = '%s')
                          OR (actor='%s' AND genre='%s')
                          OR (actor='%s' AND genre='%s' AND theyear='%i')
                          OR (actor='%s' AND genre='%s' AND theyear='%i' AND director='%s')
                          OR (actor='%s' AND genre='%s' AND theyear='%i' AND director='%s' AND mood='%s') % (actor, actor,genre, actor,genre,theyear, actor,genre,theyear,director,actor,genre,theyear,director,mood))
                          """)
        result = """

Your movie!

"""
        for row in cursor.fetchall():
            result+= '
%s
' ,(row['title'])
        result+= '
'
        cursor.close()
        connection.close()

    except db.Error:
        result = '
Sorry! We are currently experiencing technical difficulties.
'


来源: stackexchange

问:
How to properly use AJAX in Symfony2
I'm trying to use AJAX to run my controller code after a button is clicked. From what I gathered, this is what you should use AJAX for...it sends a response from the front end to the back end and then generates a json response.

However I cannot figure out how to properly do this. I'm unsure on how to get AJAX to run the controller code on success.

All I have been able to do is show the table upon success but I don't want the controller code to run until button is clicked, as that is the point of the AJAX .

Symfony does not appear to have a documentation on this: http://symfony.com/legacy/doc/book/1_0/en/11-Ajax-Integration

And these stack overflow question/answers are too old for my use or do not help me:

How to integrate Ajax with Symfony2

How to make a POST Ajax request with Symfony and Jquery

twig:

```<code><button id="begin-check" type="button">Run Test</button>

<table class="stab">
  <thead>
    <tr>
      <th style="text-align: center">Ang</th>
      <th style="text-align: center">Lat</th>
    </tr>
    <tr>
        <th>Name & Age</th>
        <th>Name & Age</th>
    </tr>
  </thead>
  <tbody>
  {% for person in persons %}
        <tr>
            <td>
                <a href="{{ path('users_edit', { 'id': person[0] }) }}">
                    {{ person[1] }}, {{ person[2] }}
                </a>
            </td>
            <td>
            {% if person[7] == 'Moe' %}
                <a href="{{ path('edit', { 'id': person[6] }) }}">
            {% else %}
                <a href="{{ path('low_edit', { 'id': person[8] }) }}">
            {% endif %}
                    {{ person[4] }}, {{ person[5] }}
                </a>
            </td>
        </tr>
    {% endfor %}
  </tbody>
</table>
</code>```

AJAX:

```<code><script type="text/javascript">
    $(document).ready(function(){
        $(document).on('click', "#begin-check", function(e){
            console.log('You have clicked');
            e.preventDefault();
            $.ajax({
                method: 'POST',
                url: "{{ path('control_check') }}",
                data: { //research what to put here
                 },
                success: function(responseData){
                    //run the controller code
                    //Show HTML table
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log(xhr.status);
                    console.log(xhr.responseText);
                    console.log(thrownError);
                },
            })
        });
    });

</script>
</code>```

In controller:

```<code>/**
 *
 * @Route("/control", name="control_check")
 * @Template()
 */
public function controlCheckAction()
{
    $request = $this->get('request');
    $em = $this->getDoctrine()->getManager();

    $persons = array();

    //more code

    return new JsonResponse(array('persons' => $persons));

}
</code>```

答:
Probably, I encountered the same situation.

In my case, I forgot to add "use" statement.
Don't you forget to add this line?

```<code>use Symfony\Component\HttpFoundation\JsonResponse;
</code>```

I attache my check point.

【1】checking server side application logs

```<code>error_log("create json response OK" . "\n", 3, "/usr/local/var/log/php/error.log");
return new JsonResponse(array('persons' => $persons));
</code>```

【2】checking console debugger

open chrome debugger(F12) -> Network tab -> "/control" (left navigation)

So, you can confirm "Response header".

```<code>[OK] Content-Type:application/json
[NG] Content-Type:text/html
</code>```

if you find "text/html", I think server side problem.

【3】checking symfony2 debugger

You can find symfony2 debugger url in the same tab 【2】

```<code>X-Debug-Token-Link:http://xxxxxxxxx/_profiler/xxxxx
</code>```

you should open this profiler link.
you can find any problems if this problem come from server side.

ContentLicense: CC BY-SA 3.0

Title: How to properly use AJAX in Symfony2

Body:
I'm trying to use AJAX to run my controller code after a button is clicked. From what I gathered, this is what you should use AJAX for...it sends a response from the front end to the back end and then generates a json response.

However I cannot figure out how to properly do this. I'm unsure on how to get AJAX to run the controller code on success.

All I have been able to do is show the table upon success but I don't want the controller code to run until button is clicked, as that is the point of the AJAX .

Symfony does not appear to have a documentation on this: http://symfony.com/legacy/doc/book/1_0/en/11-Ajax-Integration

And these stack overflow question/answers are too old for my use or do not help me:

How to integrate Ajax with Symfony2

How to make a POST Ajax request with Symfony and Jquery

twig:

<button id="begin-check" type="button">Run Test</button>

      Ang
      Lat

        Name & Age
        Name & Age

  {% for person in persons %}

                    {{ person[1] }}, {{ person[2] }}

            {% if person[7] == 'Moe' %}

            {% else %}

            {% endif %}
                    {{ person[4] }}, {{ person[5] }}

    {% endfor %}

AJAX:

In controller:

/**
 *
 * @Route("/control", name="control_check")
 * @Template()
 */
public function controlCheckAction()
{
    $request = $this->get('request');
    $em = $this->getDoctrine()->getManager();

    $persons = array();

    //more code

    return new JsonResponse(array('persons' => $persons));

}

Body:
Probably, I encountered the same situation.

In my case, I forgot to add "use" statement.
Don't you forget to add this line?

use Symfony\Component\HttpFoundation\JsonResponse;

I attache my check point.

【1】checking server side application logs

error_log("create json response OK" . "\n", 3, "/usr/local/var/log/php/error.log");
return new JsonResponse(array('persons' => $persons));

【2】checking console debugger

open chrome debugger(F12) -> Network tab -> "/control" (left navigation)

So, you can confirm "Response header".

[OK] Content-Type:application/json
[NG] Content-Type:text/html

if you find "text/html", I think server side problem.

【3】checking symfony2 debugger

You can find symfony2 debugger url in the same tab 【2】

X-Debug-Token-Link:http://xxxxxxxxx/_profiler/xxxxx

you should open this profiler link.
you can find any problems if this problem come from server side.


问:
How to find number of image results for a given search term using VBA
I have been messing around with HTML from within Excel, trying to approximate how common images are at different resolutions. I'm hoping to get something dynamic - a user enters a search term and the code loops through a set of pre-defined image resolutions, ranking how common images are for that search term between the specified resolutions.

Step one though is to get a reliable (and speedy) way of returning the number of images at a specific resolution. I wrote this code:

```<code>Sub GoogleWithURL() 'requires Microsoft HTML Object Library

    Dim url As String, searchTerm As String
    Dim objIE As InternetExplorer 'special object variable representing the IE browser
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("sheet1")
    Dim currPage As HTMLDocument
    Dim xRes As Integer, yRes As Integer
    With ws
        xRes = .Range("XRes")
        yRes = .Range("YRes")
        searchTerm = .Range("search")
    End With

    'create URL to page with these image criteria
    url = WorksheetFunction.Concat("https://www.google.com/search?q=", searchTerm, _
                        "&tbm=isch&source=lnt&tbs=isz:ex,iszw:", xRes, "iszh:", yRes)

    'initiating a new instance of Internet Explorer and asigning it to objIE
    Set objIE = New InternetExplorer
    'objIE.Visible = True 'for debugging purposes

    'Google images search
    objIE.navigate url
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
    Set currPage = objIE.document

    'Count image results
    Set valueResult = currPage.getElementById("rg_s").getElementsByTagName("IMG")
    MsgBox WorksheetFunction.Concat("'", searchTerm, "' returns ", valueResult.Length _
    , " images @ ", xRes, "x", yRes, "px.") 'returns number of loaded images on page

    'close the browser
    On Error Resume Next 'required when the browser is visible and I close it manually half way
    objIE.Quit

End Sub
</code>```

It navigates an internet explorer object to a specific resolution google image search, counts the number of images in the rg_s ID (these are the image results as opposed to the banner images etc.). Then it returns that count as a message box. (When I eventually implement this, I will return the values in a column on the sheet, looping through 30ish different resolutions)

Problems

The main problems with this code are:

It doesn't give a very useful count. The resolution is low because it only counts the images that have loaded - meaning most search terms at common resolutions like 1920x1080 or 1366x768 return the max 100 images.

It is slow. To me, navigating to pages, counting image tags, it all seems a lot like using .Select in VBA. It's like a manual approach, what a human would do, and therefore inefficient.

Solutions

I can think of some approaches to solve these problems

Resolution of data/ getting a more useful count

Scroll down. If I can load more images, it's likely I'll be able to differentiate a little better. I found that scrolling as far down as I can (up to the 'Load more results' button) gives a cap of 400 not 100 - if there are at least that many images for a given resolution then I'm happy and I'll give it the top rank. Doesn't help with problem 2 though. Still, how would I do that?

Narrow results. If 100 is returned, I could change the filetype: in the URL I send, like appending filetype:png to maybe halve the number of images returned, giving me a better spread in the 0-100 range. Not ideal though as I would have to iterate through multiple filetypes for some resolutions, slowing down the code and even then, not necessarily giving me what I want.

Use Google's (or another search engine's) own values for this. I've asked this on various sites and in various forms, is there any data on image count available direct from Google - i.e. without returning (and slowly loading) the images themselves. Like the about 1,300,500 results in 0.03 seconds for a regular search, only for images? If I could use a pre-calculated value each time that samples a bigger array than the 100 results, I might get a much more detailed picture.

Slowness

Try a different kind of HTTP request. Right now I open an instance of internet explorer and navigate to a page. That sounds very human style, I would prefer a computer style request. What I mean is, instead of using my laptop to trawl through images one by one, I get Google's supercomputers to do the leg work by only asking for the count, as oppose to the images themselves. Not a clue how to do this. I'm aware of another 2 ways to search the web from within Excel; web query and CreateObject("MSXML2.serverXMLHTTP"). Don't know either of those much but if you think they would be a better way to go then I'll look into them more closely.

Summary

Hopefully that's plenty to go on, I think my train of thought should be fairly clear. Actual answers on how to scroll down/ load more images/ get Google to return a count rather than images themselves would be best, advice on what to pursue would be useful too.

答:
After a few more questions, and now feeling somewhat wiser, I've made a UDF for this:

```<code>Public Function GOOGLE_COUNT(searchTerm As String, xRes As Long, yRes As Long, Optional timeout As Long = 10) As Long

    Dim url As String
    Dim objIE As InternetExplorer
    Dim currPage As HTMLDocument
    Dim stTimer As Double, tElapsed As Single
    Dim valueResult As IHTMLElementCollection

    'create URL to page with these image criteria
    url = "https://www.google.com/search?q=" & searchTerm & _
                        "&tbm=isch&source=lnt&tbs=isz:ex,iszw:" & xRes & ",iszh:" & yRes

    'initiating a new instance of Internet Explorer and asigning it to objIE
    Set objIE = New InternetExplorer

    'Google images search
    objIE.navigate url
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
    Set currPage = objIE.document
    Dim myDiv As HTMLDivElement: Set myDiv = currPage.getElementById("fbar")
    Dim elemRect As IHTMLRect: Set elemRect = myDiv.getBoundingClientRect
    stTimer = Timer
    'Scroll until bottom of page is in view
    Do Until elemRect.bottom > 0 Or tElapsed > timeout 'timeout after n seconds
        currPage.parentWindow.scrollBy 0, 10000
        Set elemRect = myDiv.getBoundingClientRect
        tElapsed = Timer - stTimer
    Loop
    myDiv.ScrollIntoView
    'Count the images
    Set valueResult = currPage.getElementById("rg_s").getElementsByTagName("IMG")
    GOOGLE_COUNT = valueResult.Length
    objIE.Quit

End Function
</code>```

Employed like this: to search "St. Mary" at 1366:768 image size then

```<code>=GOOGLE_COUNT("St. Mary", 1366, 768)
</code>```

Or with a 10 second timeout (the search stops scrolling if 10 seconds have passed, and just counts the images loaded)

```<code>=GOOGLE_COUNT("St. Mary", 1366, 768, 10)
</code>```

I explain in another question how the scrolling works, it's now messy but functional.

Important:

As @John Muggins points out, the significant time taken is in loading, not counting. In particular, opening and closing InternetExplorer. So to avoid huge re-calculation times; if (like me) you want to check for more than one term/resolution, put this code in a macro, not a function (comment if you think I should post this). This UDF is only for a one off search

Hope it's useful, I thought I should re-visit the question to post the answer I got to.

Final Note:

Your computer (probably) isn't crashing, the function is just calculating.

For search term, type anything you'd enter in a google search bar - e.g. "Jaguar -car" returns images of the animal, not the car company

The result is a number 0-400; 0-399 is the actual number of images counted (as long as you set timeout to be big enough - auto is 10s). 400 is the max, so there may be more than 400 images availible for that term, at that resolution.

Body:
I have been messing around with HTML from within Excel, trying to approximate how common images are at different resolutions. I'm hoping to get something dynamic - a user enters a search term and the code loops through a set of pre-defined image resolutions, ranking how common images are for that search term between the specified resolutions.

Step one though is to get a reliable (and speedy) way of returning the number of images at a specific resolution. I wrote this code:

Sub GoogleWithURL() 'requires Microsoft HTML Object Library

    Dim url As String, searchTerm As String
    Dim objIE As InternetExplorer 'special object variable representing the IE browser
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("sheet1")
    Dim currPage As HTMLDocument
    Dim xRes As Integer, yRes As Integer
    With ws
        xRes = .Range("XRes")
        yRes = .Range("YRes")
        searchTerm = .Range("search")
    End With

    'create URL to page with these image criteria
    url = WorksheetFunction.Concat("https://www.google.com/search?q=", searchTerm, _
                        "&tbm=isch&source=lnt&tbs=isz:ex,iszw:", xRes, "iszh:", yRes)

    'initiating a new instance of Internet Explorer and asigning it to objIE
    Set objIE = New InternetExplorer
    'objIE.Visible = True 'for debugging purposes

    'Google images search
    objIE.navigate url
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
    Set currPage = objIE.document

    'Count image results
    Set valueResult = currPage.getElementById("rg_s").getElementsByTagName("IMG")
    MsgBox WorksheetFunction.Concat("'", searchTerm, "' returns ", valueResult.Length _
    , " images @ ", xRes, "x", yRes, "px.") 'returns number of loaded images on page

    'close the browser
    On Error Resume Next 'required when the browser is visible and I close it manually half way
    objIE.Quit

End Sub

It navigates an internet explorer object to a specific resolution google image search, counts the number of images in the rg_s ID (these are the image results as opposed to the banner images etc.). Then it returns that count as a message box. (When I eventually implement this, I will return the values in a column on the sheet, looping through 30ish different resolutions)

Problems

The main problems with this code are:

It doesn't give a very useful count. The resolution is low because it only counts the images that have loaded - meaning most search terms at common resolutions like 1920x1080 or 1366x768 return the max 100 images.

It is slow. To me, navigating to pages, counting image tags, it all seems a lot like using .Select in VBA. It's like a manual approach, what a human would do, and therefore inefficient.

Solutions

I can think of some approaches to solve these problems

Resolution of data/ getting a more useful count

Scroll down. If I can load more images, it's likely I'll be able to differentiate a little better. I found that scrolling as far down as I can (up to the 'Load more results' button) gives a cap of 400 not 100 - if there are at least that many images for a given resolution then I'm happy and I'll give it the top rank. Doesn't help with problem 2 though. Still, how would I do that?

Narrow results. If 100 is returned, I could change the filetype: in the URL I send, like appending filetype:png to maybe halve the number of images returned, giving me a better spread in the 0-100 range. Not ideal though as I would have to iterate through multiple filetypes for some resolutions, slowing down the code and even then, not necessarily giving me what I want.

Use Google's (or another search engine's) own values for this. I've asked this on various sites and in various forms, is there any data on image count available direct from Google - i.e. without returning (and slowly loading) the images themselves. Like the about 1,300,500 results in 0.03 seconds for a regular search, only for images? If I could use a pre-calculated value each time that samples a bigger array than the 100 results, I might get a much more detailed picture.

Slowness

Try a different kind of HTTP request. Right now I open an instance of internet explorer and navigate to a page. That sounds very human style, I would prefer a computer style request. What I mean is, instead of using my laptop to trawl through images one by one, I get Google's supercomputers to do the leg work by only asking for the count, as oppose to the images themselves. Not a clue how to do this. I'm aware of another 2 ways to search the web from within Excel; web query and CreateObject("MSXML2.serverXMLHTTP"). Don't know either of those much but if you think they would be a better way to go then I'll look into them more closely.

Summary

Hopefully that's plenty to go on, I think my train of thought should be fairly clear. Actual answers on how to scroll down/ load more images/ get Google to return a count rather than images themselves would be best, advice on what to pursue would be useful too.

Body:
After a few more questions, and now feeling somewhat wiser, I've made a UDF for this:

Public Function GOOGLE_COUNT(searchTerm As String, xRes As Long, yRes As Long, Optional timeout As Long = 10) As Long

    Dim url As String
    Dim objIE As InternetExplorer
    Dim currPage As HTMLDocument
    Dim stTimer As Double, tElapsed As Single
    Dim valueResult As IHTMLElementCollection

    'create URL to page with these image criteria
    url = "https://www.google.com/search?q=" & searchTerm & _
                        "&tbm=isch&source=lnt&tbs=isz:ex,iszw:" & xRes & ",iszh:" & yRes

    'initiating a new instance of Internet Explorer and asigning it to objIE
    Set objIE = New InternetExplorer

    'Google images search
    objIE.navigate url
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
    Set currPage = objIE.document
    Dim myDiv As HTMLDivElement: Set myDiv = currPage.getElementById("fbar")
    Dim elemRect As IHTMLRect: Set elemRect = myDiv.getBoundingClientRect
    stTimer = Timer
    'Scroll until bottom of page is in view
    Do Until elemRect.bottom > 0 Or tElapsed > timeout 'timeout after n seconds
        currPage.parentWindow.scrollBy 0, 10000
        Set elemRect = myDiv.getBoundingClientRect
        tElapsed = Timer - stTimer
    Loop
    myDiv.ScrollIntoView
    'Count the images
    Set valueResult = currPage.getElementById("rg_s").getElementsByTagName("IMG")
    GOOGLE_COUNT = valueResult.Length
    objIE.Quit

End Function

Employed like this: to search "St. Mary" at 1366:768 image size then

=GOOGLE_COUNT("St. Mary", 1366, 768)

Or with a 10 second timeout (the search stops scrolling if 10 seconds have passed, and just counts the images loaded)

=GOOGLE_COUNT("St. Mary", 1366, 768, 10)

I explain in another question how the scrolling works, it's now messy but functional.

Important:

As @John Muggins points out, the significant time taken is in loading, not counting. In particular, opening and closing InternetExplorer. So to avoid huge re-calculation times; if (like me) you want to check for more than one term/resolution, put this code in a macro, not a function (comment if you think I should post this). This UDF is only for a one off search

Hope it's useful, I thought I should re-visit the question to post the answer I got to.

Final Note:

Your computer (probably) isn't crashing, the function is just calculating.

For search term, type anything you'd enter in a google search bar - e.g. "Jaguar -car" returns images of the animal, not the car company

The result is a number 0-400; 0-399 is the actual number of images counted (as long as you set timeout to be big enough - auto is 10s). 400 is the max, so there may be more than 400 images availible for that term, at that resolution.


问:
Find shortest path in maze with landmines and limited lives
I've encountered a problem I'm having a bit of trouble solving. I am trying to write a program that solves an m by n grid maze that has landmines in it. The tricky part is that the player/maze runner has a L >= 1 number of lives, meaning they can step on a maximum of L - 1 landmines before they will die on the next landmine.

Further details:

-Each cell can be connected to any of the adjacent cells. All connections are two-way.

-We can assume that the maze has a correct path from start to end given the number of lives.

-The maze can contain loops or 'islands' where two paths from a given cell lead to the same cell.

My current thoughts:

I have tried a variety of approaches to this problem. There is the obvious brute force solution which involves traversing every possible path and taking the one with the lowest distance. But that is exponential time. I feel that there may be a Dijkstra-like or A*-like solution that leads to O(n + vlogv) time. Vanilla Dijkstra or A* do not lead to solutions for this problem since the state of the graph effectively changes depending on how it is traversed. I have also tried a variety of breadth first search + tracing back to start using priority queue. These schemes, after further investigation, can lead to exponential time.

The most promising idea I've come up with so far involves parsing each maze into a graph and performing a modified Dijkstra. Each cell with three or more connections will be a node. Each cell with two connections is part of a path. Each cell with one connection can be discarded. The end result is a graph. You then perform something similar to Dijkstra, but I have not yet clarified a solution.

I can only guess that this solution requires an algorithm that is efficient in the best case but can become exponential in the worst case.

答:
The state during a maze traverse consists of the cell and the number of lives left, so you can represent the set of possible traverses as a graph with N*L vertices (where N is the number of cells.)

To simplify slightly, you can fold all L final vertices in into a single final vertex, since the number of remaining lives at the end of the traverse is irrelevant.

You can then use any shortest-paths algorithm to find a solution.

The transformed graph has approximately L times as many vertices and L times as many edges, so it will multiply the complexity by L².


问:
ksoap2 request wrong formed-
This is my request:

```<code><v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
<v:Body>
<insertBeacons xmlns="http://tempuri.org/insertBeacons/">
<MAC_ADDRESS>gmg</MAC_ADDRESS>
<UUID>gmg</UUID>
<MAJOR>gmg</MAJOR>
<MINOR>gmg</MINOR>
<MEASURED_POWER>gmg</MEASURED_POWER>
<RSSI>rssi ejemplo</RSSI>
</insertBeacons>
</v:Body>
</v:Envelope>
</code>```

And i need send to service like that

```<code><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <insertBeacons xmlns="http://tempuri.org/">
      <MAC_ADDRESS>string</MAC_ADDRESS>
      <UUID>string</UUID>
      <MAJOR>string</MAJOR>
      <MINOR>string</MINOR>
      <MEASURED_POWER>string</MEASURED_POWER>
      <RSSI>string</RSSI>
    </insertBeacons>
  </soap:Body>
</soap:Envelope>
</code>```

can you see, in my request is with "v" and my service need "soap" word.

Anybody can helpme.

答:
Glad you asked this question, i faced the same problem when i started out with soap webservice. The key here is to avoid using soap libraries and go for the classes that java has provided to make the request and parse it i.e http,DOM parser or SAX parser. This is how you make your request without using ksoap or any other libraries.

Now on to the androiod code :

We will create a class named runTask which extends async task and use http to send the request body and get request response :

```<code>private class runTask extends AsyncTask<String, String, String> {

            private String response;
            String string = "your string parameter"
            String SOAP_ACTION = "your soap action here";

            String stringUrl = "http://your_url_here";
            //if you experience a problem with url remove the '?wsdl' ending

            @Override
            protected String doInBackground(String... params) {

                try {

                            //paste your request structure here as the String body.

                    String body = "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">"+
                                    "<soap:Body>"+
                                    "<insertBeacons xmlns="http://tempuri.org/">"+
                                    "<MAC_ADDRESS>"+string+"</MAC_ADDRESS>"+
                                    "<UUID>"+string+"</UUID>"+
                                    "<MAJOR>"+string+"</MAJOR>"+
                                    "<MINOR>"+string+"</MINOR>"+
                                    "<MEASURED_POWER>"+string+"</MEASURED_POWER>"+
                                    "<RSSI>"+string+"</RSSI>"+
                                    "</insertBeacons>"+
                                    "</soap:Body>"+
                                    "</soap:Envelope>";

                    try {
                        URL url = new URL(stringUrl);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("POST");
                        conn.setDoOutput(true);
                        conn.setDefaultUseCaches(false);
                        conn.setRequestProperty("Accept", "text/xml");
                        conn.setRequestProperty("SOAPAction", SOAP_ACTION);
                        //you can pass all your request parameters here usong .setRequestProperty() method

                        //push the request to the server address

                        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                        wr.write(body);
                        wr.flush();

                        //get the server response

                        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder builder = new StringBuilder();
                        String line = null;

                        while ((line = reader.readLine()) != null) {

                            builder.append(line);
                            response = builder.toString();//this is the response, parse it in onPostExecute

                        }

                    } catch (Exception e) {

                        e.printStackTrace();
                    } finally {

                        try {

                            reader.close();
                        } catch (Exception e) {

                            e.printStackTrace();
                        }
                    }

                } catch (Exception e) {

                    e.printStackTrace();
                }

                return response;
            }

            /**
             * @see AsyncTask#onPostExecute(Object)
             */
            @Override
            protected void onPostExecute(String result) {

               try {

                  Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();

                  //Go ahead and parse the response now

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
</code>```

Now in your onCreate just go ahead and execute this class using the following code

```<code>runTask task = new runTask();
task.execute();
</code>```

You will get your response in your onPostExecute, format and parse it from here.
The main advantages of using this libraryless way is that it is flexible, you can format the request in any way the webservice requires as compared to the libraries which you only use the provided request formats. This solution works seamlessly in my code, feel free to ask for any further clarification.

Title: ksoap2 request wrong formed-

Body:
This is my request:

<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
<v:Body>
<insertBeacons xmlns="http://tempuri.org/insertBeacons/">
<MAC_ADDRESS>gmg</MAC_ADDRESS>
<UUID>gmg</UUID>
<MAJOR>gmg</MAJOR>
<MINOR>gmg</MINOR>
<MEASURED_POWER>gmg</MEASURED_POWER>
<RSSI>rssi ejemplo</RSSI>
</insertBeacons>
</v:Body>
</v:Envelope>

And i need send to service like that

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <insertBeacons xmlns="http://tempuri.org/">
      <MAC_ADDRESS>string</MAC_ADDRESS>
      <UUID>string</UUID>
      <MAJOR>string</MAJOR>
      <MINOR>string</MINOR>
      <MEASURED_POWER>string</MEASURED_POWER>
      <RSSI>string</RSSI>
    </insertBeacons>
  </soap:Body>
</soap:Envelope>

can you see, in my request is with "v" and my service need "soap" word.

Anybody can helpme.

Body:
Glad you asked this question, i faced the same problem when i started out with soap webservice. The key here is to avoid using soap libraries and go for the classes that java has provided to make the request and parse it i.e http,DOM parser or SAX parser. This is how you make your request without using ksoap or any other libraries.

Now on to the androiod code :

We will create a class named runTask which extends async task and use http to send the request body and get request response :

private class runTask extends AsyncTask<String, String, String> {

            private String response;
            String string = "your string parameter"
            String SOAP_ACTION = "your soap action here";

            String stringUrl = "http://your_url_here";
            //if you experience a problem with url remove the '?wsdl' ending

            @Override
            protected String doInBackground(String... params) {

                try {

                            //paste your request structure here as the String body.

                    String body = "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">"+
                                    "<soap:Body>"+
                                    "<insertBeacons xmlns="http://tempuri.org/">"+
                                    "<MAC_ADDRESS>"+string+"</MAC_ADDRESS>"+
                                    "<UUID>"+string+"</UUID>"+
                                    "<MAJOR>"+string+"</MAJOR>"+
                                    "<MINOR>"+string+"</MINOR>"+
                                    "<MEASURED_POWER>"+string+"</MEASURED_POWER>"+
                                    "<RSSI>"+string+"</RSSI>"+
                                    "</insertBeacons>"+
                                    "</soap:Body>"+
                                    "</soap:Envelope>";

                    try {
                        URL url = new URL(stringUrl);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("POST");
                        conn.setDoOutput(true);
                        conn.setDefaultUseCaches(false);
                        conn.setRequestProperty("Accept", "text/xml");
                        conn.setRequestProperty("SOAPAction", SOAP_ACTION);
                        //you can pass all your request parameters here usong .setRequestProperty() method

                        //push the request to the server address

                        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                        wr.write(body);
                        wr.flush();

                        //get the server response

                        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder builder = new StringBuilder();
                        String line = null;

                        while ((line = reader.readLine()) != null) {

                            builder.append(line);
                            response = builder.toString();//this is the response, parse it in onPostExecute

                        }

                    } catch (Exception e) {

                        e.printStackTrace();
                    } finally {

                        try {

                            reader.close();
                        } catch (Exception e) {

                            e.printStackTrace();
                        }
                    }

                } catch (Exception e) {

                    e.printStackTrace();
                }

                return response;
            }

            /**
             * @see AsyncTask#onPostExecute(Object)
             */
            @Override
            protected void onPostExecute(String result) {

               try {

                  Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();

                  //Go ahead and parse the response now

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

Now in your onCreate just go ahead and execute this class using the following code

runTask task = new runTask();
task.execute();

You will get your response in your onPostExecute, format and parse it from here.
The main advantages of using this libraryless way is that it is flexible, you can format the request in any way the webservice requires as compared to the libraries which you only use the provided request formats. This solution works seamlessly in my code, feel free to ask for any further clarification.


问:
Ignore SIGINT in Python multiprocessing Subprocess
When I run the following code on OSX or Linux and then press ctrl+c a "graceful shutdown" is initiated. Which looks something like this:

```<code>$ python subprocess_test.py
Subprocess:  <MyProcess(MyProcess-1, started)>
^CMain: Graceful shutdown
Subprocess: shutdown
</code>```

However, when I run the some code on a Windows10 machine a KeyboardInterrupt is raised in line self.event.wait() preventing a graceful shutdown. I have tried different approaches as described here to prevent that the subprocess is receiving the signal.

What is the correct way to to get the same behavior on the different OS using Python 2.7?

```<code>import multiprocessing
import signal

class MyProcess(multiprocessing.Process):

    def __init__(self):
        super(MyProcess, self).__init__()
        self.event = multiprocessing.Event()

    def run(self):
        print "Subprocess: ", multiprocessing.current_process()
        self.event.wait()
        print "Subprocess: shutdown"

def sighandler(a,b,):
    print "Main: Graceful shutdown"
    p1.event.set()

def run():
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    global p1
    p1 = MyProcess()

    p1.start()

    signal.signal(signal.SIGINT, sighandler)
    p1.join()

if __name__ == '__main__':
    run()
</code>```

答:
On Windows SIGINT is implemented using a console control event handler for CTRL_C_EVENT. It's the console state that gets inherited by a child process, not the CRT's signal handling state. Thus you need to first call SetConsoleCtrlHandler to ignore Ctrl+C in the parent process before creating a child process if you want the child to ignore Ctrl+C.

There's a catch. Python doesn't use alertable waits on Windows, such as the wait in the process join method. Since it dispatches signal handlers on the main thread, the fact that the main thread is blocked in join() means your signal handler will never be called. You have to replace the join with a loop on time.sleep(), which is interruptible by Ctrl+C because internally it waits on a Windows Event and sets its own control handler that sets this Event. Or you can instead use your own asynchronous control handler set via ctypes. The following example implements both approaches and works in both Python 2 and 3.

```<code>import sys
import signal
import multiprocessing

if sys.platform == "win32":
    # Handle Ctrl+C in the Windows Console
    import time
    import errno
    import ctypes
    import threading

    from ctypes import wintypes

    kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)

    PHANDLER_ROUTINE = ctypes.WINFUNCTYPE(
        wintypes.BOOL,
        wintypes.DWORD) # _In_ dwCtrlType

    win_ignore_ctrl_c = PHANDLER_ROUTINE() # alias for NULL handler

    def _errcheck_bool(result, func, args):
        if not result:
            raise ctypes.WinError(ctypes.get_last_error())
        return args

    kernel32.SetConsoleCtrlHandler.errcheck = _errcheck_bool
    kernel32.SetConsoleCtrlHandler.argtypes = (
        PHANDLER_ROUTINE, # _In_opt_ HandlerRoutine
        wintypes.BOOL)    # _In_     Add

class MyProcess(multiprocessing.Process):

    def __init__(self):
        super(MyProcess, self).__init__()
        self.event = multiprocessing.Event()

    def run(self):
        print("Subprocess: %r" % multiprocessing.current_process())
        self.event.wait()
        print("Subprocess: shutdown")

    if sys.platform == "win32":
        def join(self, timeout=None):
            if threading.current_thread().name != "MainThread":
                super(MyProcess, self).join(timeout)
            else:
                # use time.sleep to allow the main thread to
                # interruptible by Ctrl+C
                interval = 1
                remaining = timeout
                while self.is_alive():
                    if timeout is not None:
                        if remaining <= 0:
                            break
                        if remaining < interval:
                            interval = remaining
                            remaining = 0
                        else:
                            remaining -= interval
                    try:
                        time.sleep(interval)
                    except IOError as e:
                        if e.errno != errno.EINTR:
                            raise
                        break

def run():
    p1 = MyProcess()

    # Ignore Ctrl+C, which is inherited by the child process.
    if sys.platform == "win32":
         kernel32.SetConsoleCtrlHandler(win_ignore_ctrl_c, True)
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    p1.start()

    # Set a Ctrl+C handler to signal graceful shutdown.
    if sys.platform == "win32":
        kernel32.SetConsoleCtrlHandler(win_ignore_ctrl_c, False)
        # comment out the following to rely on sig_handler
        # instead. Note that using the normal sig_handler requires
        # joining using a loop on time.sleep() instead of the
        # normal process join method. See the join() method
        # defined above.
        @PHANDLER_ROUTINE
        def win_ctrl_handler(dwCtrlType):
            if (dwCtrlType == signal.CTRL_C_EVENT and
                not p1.event.is_set()):
                print("Main <win_ctrl_handler>: Graceful shutdown")
                p1.event.set()
            return False

        kernel32.SetConsoleCtrlHandler(win_ctrl_handler, True)

    def sig_handler(signum, frame):
        if not p1.event.is_set():
            print("Main <sig_handler>: Graceful shutdown")
            p1.event.set()

    signal.signal(signal.SIGINT, sig_handler)
    p1.join()

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

Body:
When I run the following code on OSX or Linux and then press ctrl+c a "graceful shutdown" is initiated. Which looks something like this:

$ python subprocess_test.py
Subprocess:  <MyProcess(MyProcess-1, started)>
^CMain: Graceful shutdown
Subprocess: shutdown

However, when I run the some code on a Windows10 machine a KeyboardInterrupt is raised in line self.event.wait() preventing a graceful shutdown. I have tried different approaches as described here to prevent that the subprocess is receiving the signal.

What is the correct way to to get the same behavior on the different OS using Python 2.7?

import multiprocessing
import signal

class MyProcess(multiprocessing.Process):

    def __init__(self):
        super(MyProcess, self).__init__()
        self.event = multiprocessing.Event()

    def run(self):
        print "Subprocess: ", multiprocessing.current_process()
        self.event.wait()
        print "Subprocess: shutdown"

def sighandler(a,b,):
    print "Main: Graceful shutdown"
    p1.event.set()

def run():
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    global p1
    p1 = MyProcess()

    p1.start()

    signal.signal(signal.SIGINT, sighandler)
    p1.join()

if __name__ == '__main__':
    run()

Body:
On Windows SIGINT is implemented using a console control event handler for CTRL_C_EVENT. It's the console state that gets inherited by a child process, not the CRT's signal handling state. Thus you need to first call SetConsoleCtrlHandler to ignore Ctrl+C in the parent process before creating a child process if you want the child to ignore Ctrl+C.

There's a catch. Python doesn't use alertable waits on Windows, such as the wait in the process join method. Since it dispatches signal handlers on the main thread, the fact that the main thread is blocked in join() means your signal handler will never be called. You have to replace the join with a loop on time.sleep(), which is interruptible by Ctrl+C because internally it waits on a Windows Event and sets its own control handler that sets this Event. Or you can instead use your own asynchronous control handler set via ctypes. The following example implements both approaches and works in both Python 2 and 3.

import sys
import signal
import multiprocessing

if sys.platform == "win32":
    # Handle Ctrl+C in the Windows Console
    import time
    import errno
    import ctypes
    import threading

    from ctypes import wintypes

    kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)

    PHANDLER_ROUTINE = ctypes.WINFUNCTYPE(
        wintypes.BOOL,
        wintypes.DWORD) # _In_ dwCtrlType

    win_ignore_ctrl_c = PHANDLER_ROUTINE() # alias for NULL handler

    def _errcheck_bool(result, func, args):
        if not result:
            raise ctypes.WinError(ctypes.get_last_error())
        return args

    kernel32.SetConsoleCtrlHandler.errcheck = _errcheck_bool
    kernel32.SetConsoleCtrlHandler.argtypes = (
        PHANDLER_ROUTINE, # _In_opt_ HandlerRoutine
        wintypes.BOOL)    # _In_     Add

class MyProcess(multiprocessing.Process):

    def __init__(self):
        super(MyProcess, self).__init__()
        self.event = multiprocessing.Event()

    def run(self):
        print("Subprocess: %r" % multiprocessing.current_process())
        self.event.wait()
        print("Subprocess: shutdown")

    if sys.platform == "win32":
        def join(self, timeout=None):
            if threading.current_thread().name != "MainThread":
                super(MyProcess, self).join(timeout)
            else:
                # use time.sleep to allow the main thread to
                # interruptible by Ctrl+C
                interval = 1
                remaining = timeout
                while self.is_alive():
                    if timeout is not None:
                        if remaining <= 0:
                            break
                        if remaining < interval:
                            interval = remaining
                            remaining = 0
                        else:
                            remaining -= interval
                    try:
                        time.sleep(interval)
                    except IOError as e:
                        if e.errno != errno.EINTR:
                            raise
                        break

def run():
    p1 = MyProcess()

    # Ignore Ctrl+C, which is inherited by the child process.
    if sys.platform == "win32":
         kernel32.SetConsoleCtrlHandler(win_ignore_ctrl_c, True)
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    p1.start()

    # Set a Ctrl+C handler to signal graceful shutdown.
    if sys.platform == "win32":
        kernel32.SetConsoleCtrlHandler(win_ignore_ctrl_c, False)
        # comment out the following to rely on sig_handler
        # instead. Note that using the normal sig_handler requires
        # joining using a loop on time.sleep() instead of the
        # normal process join method. See the join() method
        # defined above.
        @PHANDLER_ROUTINE
        def win_ctrl_handler(dwCtrlType):
            if (dwCtrlType == signal.CTRL_C_EVENT and
                not p1.event.is_set()):
                print("Main <win_ctrl_handler>: Graceful shutdown")
                p1.event.set()
            return False

        kernel32.SetConsoleCtrlHandler(win_ctrl_handler, True)

    def sig_handler(signum, frame):
        if not p1.event.is_set():
            print("Main <sig_handler>: Graceful shutdown")
            p1.event.set()

    signal.signal(signal.SIGINT, sig_handler)
    p1.join()

if __name__ == "__main__":
    run()


问:
I don't fully understand app indexing
Okay, so I get that if I have a website and an app that roughly displays the same content, app indexing can be used to open links to the website in the app instead (if the user has it installed).

To do this, one specifies deep links in the web pages that specify a URI to the app and the content. This also lets Googlebot know about the webpage-to-app-intent connection so it can display stuff in search results, etc (i.e. indexing). One can also specify intent-filters that handle website URL's, so links to your website can automatically open the app and display the content there, without even opening the webpage in a browser.

The part that I'm having problem understanding is that in an android app you add code (which can be automatically generated by Android Studio) that "goes the other way".

For example

```<code>@Override
public void onStart() {
    super.onStart();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client.connect();
    Action viewAction = Action.newAction(
            Action.TYPE_VIEW, // TODO: choose an action type.
            "Main Page", // TODO: Define a title for the content shown.
            // TODO: If you have web page content that matches this app activity's content,
            // make sure this auto-generated web page URL is correct.
            // Otherwise, set the URL to null.
            Uri.parse("http://host/path"),
            // TODO: Make sure this auto-generated app URL is correct.
            Uri.parse("android-app://com.magnuswikhog.adrlibrary/http/host/path")
    );
    AppIndex.AppIndexApi.start(client, viewAction);
}
</code>```

So what is the purpose of this code? This seems to go the other way compared to the website-to-app-intent, and I don't really understand why you'd need to do that? If I only implement deep-linking and handling URL-intents, users will be able to open the app instead of the webpage, no need for AppIndex.

Is it mostly a way for Google to gather statistics for how users of the app are using screens that have a corresponding webpage? If so, what impact does this have? Does it affect app ranking (and/or website ranking?) Is it essential to implement this if I'm implementing all the other parts of app indexing?

答:
Okay, so it seems I'm confusing App Indexing and App Links. I'm sure I'm not alone in this, since even Google seem to use the terms interchangeably and non-strictly - for example if you choose Tools -> Firebase App Indexing Test and the test fails, when you click on Learn more you are taken to a page that is 90% about App Links, and down at the bottom is one small paragraph about App Indexing.

Here's what that paragraph says:

Add Firebase App Indexing

After adding Android App Links to your app, you can add Firebase App Indexing code to an activity to get re-engagement to your app from additional Google Search features, including autocomplete suggestions and In Apps search. Learn more about Firebase App Indexing in the Firebase App Indexing documentation.

So it seems that App Indexing is not directly connected to App Links, and is in a sense a totally different feature.

Furthermore, looking at the Firebase documentation, here is finally some real information about the purpose of the indexing code:

Log User Actions

Google Search takes into account the actions users take on public and personal app content and uses that to provide improved ranking for Search results and suggestions. Log user actions in your app to improve your users' experience when they search for content in your app.

Title: I don't fully understand app indexing

Body:
Okay, so I get that if I have a website and an app that roughly displays the same content, app indexing can be used to open links to the website in the app instead (if the user has it installed).

To do this, one specifies deep links in the web pages that specify a URI to the app and the content. This also lets Googlebot know about the webpage-to-app-intent connection so it can display stuff in search results, etc (i.e. indexing). One can also specify intent-filters that handle website URL's, so links to your website can automatically open the app and display the content there, without even opening the webpage in a browser.

The part that I'm having problem understanding is that in an android app you add code (which can be automatically generated by Android Studio) that "goes the other way".

For example

@Override
public void onStart() {
    super.onStart();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client.connect();
    Action viewAction = Action.newAction(
            Action.TYPE_VIEW, // TODO: choose an action type.
            "Main Page", // TODO: Define a title for the content shown.
            // TODO: If you have web page content that matches this app activity's content,
            // make sure this auto-generated web page URL is correct.
            // Otherwise, set the URL to null.
            Uri.parse("http://host/path"),
            // TODO: Make sure this auto-generated app URL is correct.
            Uri.parse("android-app://com.magnuswikhog.adrlibrary/http/host/path")
    );
    AppIndex.AppIndexApi.start(client, viewAction);
}

So what is the purpose of this code? This seems to go the other way compared to the website-to-app-intent, and I don't really understand why you'd need to do that? If I only implement deep-linking and handling URL-intents, users will be able to open the app instead of the webpage, no need for AppIndex.

Is it mostly a way for Google to gather statistics for how users of the app are using screens that have a corresponding webpage? If so, what impact does this have? Does it affect app ranking (and/or website ranking?) Is it essential to implement this if I'm implementing all the other parts of app indexing?


问:
Java : Convert string to use in url as part of a get
Hello I shall get straight to the point, I am trying to use a EditText input to use in a php url i want the url to to be like thi when it runs.

```<code>http://www.free-map.org.uk/course/mad/ws/hits.php?artist=Oasis
</code>```

SO I tried

```<code> URL url = new URL("http://www.free-map.org.uk/course/mad/ws/hits.php?artist=",et1);
</code>```

but i get the error

Here is the main part of my code.

```<code> class MyTask extends AsyncTask<Void,Void,String>
{
    EditText et1 = (EditText)findViewById(R.id.et1);

    public String doInBackground(Void... unused)
    {
        HttpURLConnection conn = null;
        try
        {
            URL url = new URL("http://www.free-map.org.uk/course/mad/ws/hits.php?artist=",et1);
            conn = (HttpURLConnection) url.openConnection();
            InputStream in = conn.getInputStream();
            if(conn.getResponseCode() == 200)
            {
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String result = "", line;
                while((line = br.readLine()) !=null)
                    result += line;
                return result;
            }
            else
                return "HTTP ERROR: " + conn.getResponseCode();
        }
        catch(IOException e)
        {
            return e.toString();
        }
        finally
        {
            if(conn!=null)
                conn.disconnect();
        }
    }
</code>```

答:
You can't append EditText with String. You have to append input from EditText.

To get input from EditText use -

```<code>EditText et1 = (EditText)findViewById(R.id.et1);
final String input = et1.getText().toString();
// then append it
URL url = new URL("http://www.free-map.org.uk/course/mad/ws/hits.php?artist="+input);
</code>```

Body:
Hello I shall get straight to the point, I am trying to use a EditText input to use in a php url i want the url to to be like thi when it runs.

http://www.free-map.org.uk/course/mad/ws/hits.php?artist=Oasis

SO I tried

 URL url = new URL("http://www.free-map.org.uk/course/mad/ws/hits.php?artist=",et1);

but i get the error

Here is the main part of my code.

 class MyTask extends AsyncTask<Void,Void,String>
{
    EditText et1 = (EditText)findViewById(R.id.et1);

    public String doInBackground(Void... unused)
    {
        HttpURLConnection conn = null;
        try
        {
            URL url = new URL("http://www.free-map.org.uk/course/mad/ws/hits.php?artist=",et1);
            conn = (HttpURLConnection) url.openConnection();
            InputStream in = conn.getInputStream();
            if(conn.getResponseCode() == 200)
            {
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String result = "", line;
                while((line = br.readLine()) !=null)
                    result += line;
                return result;
            }
            else
                return "HTTP ERROR: " + conn.getResponseCode();
        }
        catch(IOException e)
        {
            return e.toString();
        }
        finally
        {
            if(conn!=null)
                conn.disconnect();
        }
    }

Body:
You can't append EditText with String. You have to append input from EditText.

To get input from EditText use -

EditText et1 = (EditText)findViewById(R.id.et1);
final String input = et1.getText().toString();
// then append it
URL url = new URL("http://www.free-map.org.uk/course/mad/ws/hits.php?artist="+input);


问:
Set rating right in the App (Swift 3, iOS 10.3)
I have a menu-button in my app. If user clicks this button he sees UIAlertView which include app-link to the App Store.

Here is the code:

```<code>@IBAction func navButton(_ sender: AnyObject) {

let alertController = UIAlertController(title: "Menu", message: "Thanks for using our app!", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Rate Us on the App Store", style: .default, handler: { (action: UIAlertAction) in
print("Send user to the App Store App Page")

let url  = URL(string: "itms-apps://itunes.apple.com/app/id")
     if UIApplication.shared.canOpenURL(url!) == true  {
     UIApplication.shared.openURL(url!)
}
}))
</code>```

I know that in iOS 10.3 there was an opportunity to set a rating right in the application. What should I change, so that when a user clicks on a link in UIAlertView, he could set a rating right in the application?

I found some information on Apple Developer website (https://developer.apple.com/reference/storekit/skstorereviewcontroller) but I don't know how to do this in my app.

答:
It's one class function based on looking at the docs.

```<code>SKStoreReviewController.requestReview()
</code>```

It also states you shouldn't call this function dependent on a user pressing a button or any other type of action because it is not guaranteed to be called. It would be a bad user experience if you indicate they are about to be shown a review modal and then nothing appears.

If you use this new option in your app it seems the best option is to just place it somewhere that won't interrupt any important actions being conducted by the user and let the framework do the work.

You can use criteria the user isn't aware of to choose when to call the function, i.e. launched the app x amount of times, used x number of days in a row, etc.

Edit: alternative

If you want to keep more control over the ability to request reviews you can continue the old way and append the following to your store URL to bring them directly to the review page.

action=write-review

```<code>guard let url = URL(string: "appstoreURLString&action=write-review") else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
</code>```

Body:
I have a menu-button in my app. If user clicks this button he sees UIAlertView which include app-link to the App Store.

Here is the code:

@IBAction func navButton(_ sender: AnyObject) {

let alertController = UIAlertController(title: "Menu", message: "Thanks for using our app!", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Rate Us on the App Store", style: .default, handler: { (action: UIAlertAction) in
print("Send user to the App Store App Page")

let url  = URL(string: "itms-apps://itunes.apple.com/app/id")
     if UIApplication.shared.canOpenURL(url!) == true  {
     UIApplication.shared.openURL(url!)
}
}))

I know that in iOS 10.3 there was an opportunity to set a rating right in the application. What should I change, so that when a user clicks on a link in UIAlertView, he could set a rating right in the application?

I found some information on Apple Developer website (https://developer.apple.com/reference/storekit/skstorereviewcontroller) but I don't know how to do this in my app.

Body:
It's one class function based on looking at the docs.

SKStoreReviewController.requestReview()

It also states you shouldn't call this function dependent on a user pressing a button or any other type of action because it is not guaranteed to be called. It would be a bad user experience if you indicate they are about to be shown a review modal and then nothing appears.

If you use this new option in your app it seems the best option is to just place it somewhere that won't interrupt any important actions being conducted by the user and let the framework do the work.

You can use criteria the user isn't aware of to choose when to call the function, i.e. launched the app x amount of times, used x number of days in a row, etc.

Edit: alternative

If you want to keep more control over the ability to request reviews you can continue the old way and append the following to your store URL to bring them directly to the review page.

action=write-review

guard let url = URL(string: "appstoreURLString&action=write-review") else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)


问:
replace specific link to *******
using php or javascript or ajax
how to replace specific link to *

http://www.google.com/.
to
http://www.****

答:
str_replace()

```<code>$text = str_replace('google.com', '***', $text);
</code>```

Even if the question is very different: A short JS solution

```<code>text = text.split("google.com").join("***");
</code>```

ContentLicense: CC BY-SA 2.5

Title: replace specific link to *******

Body:
str_replace()

$text = str_replace('google.com', '***', $text);

Even if the question is very different: A short JS solution

text = text.split("google.com").join("***");


问:
Change message body before sending in outlook 365
It possible to change message body (e.g. add some text at the end) on send button clicking.</p>

答:
Outlook 365? There is no such thing. Do you mean Outlook 2016 (desktop app)? Or Outlook Web App?

In the former case, trap the Application.ItemSend event and modify the message passed as the parameter.

In the latter case, there is nothing you can do.


问:
Install opencv-python under python3 ubuntu 14.04
I want to use opencv under python 3 in Ubunto 14.04. I plan to use the PyCharm IDE to develop my program.

Inside PyCharm I choose, I set:

File/Settings/Project:HelloWorld/Project Interpreter/3.4.3(/usr/bin/python3.4)

Python 3.4.3 is the default version of python in Ubunto 14.04.

Then I try to add opencv-python package:

File/Settings/Project:HelloWorld/Project Interpreter/+ (where you add the package)

and the system gives me this error:

```<code> Executed command:

 pip install opencv-python

 Try to run this command from the system terminal. Make sure that you
 use the correct version of 'pip' installed for your Python interpreter located at '/usr/bin/python3.4'.

 DEPRECATION: --no-install, --no-download, --build, and --no-clean are   deprecated.  See https://github.com/pypa/pip/issues/906.
 Downloading/unpacking opencv-python
 Could not find any downloads that satisfy the requirement opencv-python
 Cleaning up...
 No distributions at all found for opencv-python
 Storing debug log for failure in /root/.pip/pip.log
</code>```

the error is the same when I run the command from terminal. I believe the problem is related to installing opencv under python3 but I am not sure I know if I can fix it. Please let me know your opinion.

Thanks

答:
First, you should not use install opencv-python, this is not the official opencv package.
Please, see:
**SOLVED** How to include libgtk2.0-dev and pkg-config in cmake when installing openCV on Ubuntu 16

If you want to install opencv, you can follow this website, that worked for me. You might need to apapt some parts (mainly version numbers, and paths during the cmake process).

ContentLicense: CC BY-SA 4.0

Body:
I want to use opencv under python 3 in Ubunto 14.04. I plan to use the PyCharm IDE to develop my program.

Inside PyCharm I choose, I set:

File/Settings/Project:HelloWorld/Project Interpreter/3.4.3(/usr/bin/python3.4)

Python 3.4.3 is the default version of python in Ubunto 14.04.

Then I try to add opencv-python package:

File/Settings/Project:HelloWorld/Project Interpreter/+ (where you add the package)

and the system gives me this error:

 Executed command:

 pip install opencv-python

 Try to run this command from the system terminal. Make sure that you
 use the correct version of 'pip' installed for your Python interpreter located at '/usr/bin/python3.4'.

 DEPRECATION: --no-install, --no-download, --build, and --no-clean are   deprecated.  See https://github.com/pypa/pip/issues/906.
 Downloading/unpacking opencv-python
 Could not find any downloads that satisfy the requirement opencv-python
 Cleaning up...
 No distributions at all found for opencv-python
 Storing debug log for failure in /root/.pip/pip.log

the error is the same when I run the command from terminal. I believe the problem is related to installing opencv under python3 but I am not sure I know if I can fix it. Please let me know your opinion.

Thanks


问:
Serializing an object in Symfony
Within my Review entity:

```<code>/**
 * @Groups({"books"})
 * @ORM\ManyToOne(targetEntity="Book\MainBundle\Entity\Book", inversedBy="reviews")
 * @ORM\JoinColumn(name="bookID", referencedColumnName="id")
 */
private $bookID;
</code>```

And within my Controller, I have:

```<code>public function getReviewsAction()
{
    $serializer = $this->get('jms_serializer');
    $em = $this->getDoctrine()->getManager();
    $reviews = $em->getRepository('BookMainBundle:Review')->findAll();
    $serializer->serialize($reviews, 'json', SerializationContext::create()->setGroups(array('Default', 'books')));
    return $this->handleView($this->view($reviews));
}
</code>```

However serialization isn't working at all, does anyone know what I am doing wrong?

答:
You do the following:

```<code>$serializer->serialize($reviews, 'json', SerializationContext::create()->setGroups(array('Default', 'books')));
</code>```

This will serialize the reviews but not assign it to anything.

You probably want to do something like:

```<code>$serializedReviews = $serializer->serialize($reviews, 'json', SerializationContext::create()->setGroups(array('Default', 'books')));
return $this->handleView($this->view($serializedReviews));
</code>```

Title: Serializing an object in Symfony

Body:
Within my Review entity:

/**
 * @Groups({"books"})
 * @ORM\ManyToOne(targetEntity="Book\MainBundle\Entity\Book", inversedBy="reviews")
 * @ORM\JoinColumn(name="bookID", referencedColumnName="id")
 */
private $bookID;

And within my Controller, I have:

public function getReviewsAction()
{
    $serializer = $this->get('jms_serializer');
    $em = $this->getDoctrine()->getManager();
    $reviews = $em->getRepository('BookMainBundle:Review')->findAll();
    $serializer->serialize($reviews, 'json', SerializationContext::create()->setGroups(array('Default', 'books')));
    return $this->handleView($this->view($reviews));
}

However serialization isn't working at all, does anyone know what I am doing wrong?

Body:
You do the following:

$serializer->serialize($reviews, 'json', SerializationContext::create()->setGroups(array('Default', 'books')));

This will serialize the reviews but not assign it to anything.

You probably want to do something like:

$serializedReviews = $serializer->serialize($reviews, 'json', SerializationContext::create()->setGroups(array('Default', 'books')));
return $this->handleView($this->view($serializedReviews));


问:
Save regular expression result in variable
I would like to split a string into separated, single strings and save each in a new variable. That's the use case:

Direct user input with BC1 = input("BC1: ") in the following format: '17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'

Now I want each number - and just the number in a single variable:

```<code>a = 17899792270101010000000000
b = 17899792270102010000000000
c = 17899792270103010000000000
</code>```

How to realise that in python 3?

Sadly I'm not able to create a suitable regular expression for it and neither a way to save string parts in separate variables. I hope someone of you could help me.
Thanks already in advance!

Body:
I would like to split a string into separated, single strings and save each in a new variable. That's the use case:

Direct user input with BC1 = input("BC1: ") in the following format: '17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'

Now I want each number - and just the number in a single variable:

a = 17899792270101010000000000
b = 17899792270102010000000000
c = 17899792270103010000000000

How to realise that in python 3?

Sadly I'm not able to create a suitable regular expression for it and neither a way to save string parts in separate variables. I hope someone of you could help me.
Thanks already in advance!

Body:
Look into re

import re

input = "'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'"

 matches = re.findall('(\d+)', input)
 # matches = ['17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000']

 a, b, c = re.findall('(\d+)', input)
 # a = '17899792270101010000000000'
 # b = '17899792270102010000000000'
 # c = '17899792270103010000000000'

edit:
If you want int not str, you can map(int, matches)


问:
Floating point comparison in shell
Can you please suggest to me the syntax for doing floating point comparison in a Bash script? I would ideally like to use it as part of an if statement. Here is a small code snippet :

```<code>key1="12.3"
result="12.2"

if (( $result <= $key1 ))
then
    # some code here
fi
</code>```

答:
```<code>### The funny thing about bash is this:
> AA=10.3
> BB=10.4
### It needs `$` for compare
> [[ $AA > $BB ]] && echo Hello
> [[ $AA < $BB ]] && echo Hello
Hello
</code>```

Yeah, I know it's cheating but it works. And scientific notation does not work here.

Title: Floating point comparison in shell

Body:
Can you please suggest to me the syntax for doing floating point comparison in a Bash script? I would ideally like to use it as part of an if statement. Here is a small code snippet :

key1="12.3"
result="12.2"

if (( $result <= $key1 ))
then
    # some code here
fi

Body:
### The funny thing about bash is this:
> AA=10.3
> BB=10.4
### It needs `$` for compare
> [[ $AA > $BB ]] && echo Hello
> [[ $AA < $BB ]] && echo Hello
Hello

Yeah, I know it's cheating but it works. And scientific notation does not work here.


问:
C Array change causing variable modification
I am trying to modify a value in an array using the C programming language and I seem to be hitting a blank wall with this seemingly easy operation. Please see code snippet below:

```<code>while(1) {
        printf("Current prime candidate is %i\n",nextPrimeCandidate);
        int innerSieve;//=2;
        int currentPrimeCandidate=0;

        for (innerSieve=2;innerSieve<SIEVELIMIT;innerSieve++) {
            currentPrimeCandidate = nextPrimeCandidate * innerSieve;
            //printf("Inner Sieve  is b4 funny place %i,%i\n",innerSieve,currentPrimeCandidate);

            //initArray[currentPrimeCandidate]=5;
            //VERY UNIQUE LINE
            myArray[currentPrimeCandidate] = 0;

            //printf("Inner Sieve after funny place is %i,%i \n",innerSieve,currentPrimeCandidate);

        }
        nextPrimeCandidate=getNextPrimeCandidate(myArray,++nextPrimeCandidate);
        if ((nextPrimeCandidate^2) > SIEVELIMIT ) break;

    }
</code>```

The problem is with the line highlighted with the VERY UNIQUE LINE comment. For some reason, when the innerSieve variable reaches 33 and gets to that line, it sets the contents of the innerSieve variable to the value of that line ( which currently is 0) and basically forces the loop into an infinite loop( the SIEVELIMIT variable is set at 50). It seems that there is some funny stuff going on in the registers when I checked using the Eclipse Debug facility but I am not too sure what I should be looking for.

If you need the whole code listing, this can be provided.( with a particular variable which is not yet initialised in the code being initialised at the precise point that the innerSieve variable hits 32)

Any help will be greatly appreciated.

答: Guessing that currentPrimeCandidate is greater than the maximum index of myArray, and you're overwriting innerSieve (which likely follows myArray on the stack).

Body:
I am trying to modify a value in an array using the C programming language and I seem to be hitting a blank wall with this seemingly easy operation. Please see code snippet below:

while(1) {
        printf("Current prime candidate is %i\n",nextPrimeCandidate);
        int innerSieve;//=2;
        int currentPrimeCandidate=0;

        for (innerSieve=2;innerSieve<SIEVELIMIT;innerSieve++) {
            currentPrimeCandidate = nextPrimeCandidate * innerSieve;
            //printf("Inner Sieve  is b4 funny place %i,%i\n",innerSieve,currentPrimeCandidate);

            //initArray[currentPrimeCandidate]=5;
            //VERY UNIQUE LINE
            myArray[currentPrimeCandidate] = 0;

            //printf("Inner Sieve after funny place is %i,%i \n",innerSieve,currentPrimeCandidate);

        }
        nextPrimeCandidate=getNextPrimeCandidate(myArray,++nextPrimeCandidate);
        if ((nextPrimeCandidate^2) > SIEVELIMIT ) break;

    }

The problem is with the line highlighted with the VERY UNIQUE LINE comment. For some reason, when the innerSieve variable reaches 33 and gets to that line, it sets the contents of the innerSieve variable to the value of that line ( which currently is 0) and basically forces the loop into an infinite loop( the SIEVELIMIT variable is set at 50). It seems that there is some funny stuff going on in the registers when I checked using the Eclipse Debug facility but I am not too sure what I should be looking for.

If you need the whole code listing, this can be provided.( with a particular variable which is not yet initialised in the code being initialised at the precise point that the innerSieve variable hits 32)

Any help will be greatly appreciated.


问:
how to edit a text file without editing other lines (cmd)
First, I'm in Korea. So my English will very bad.

I want to edit third line with out touching first line and the second line.

Before:

```<code>echo sample
echo sample
echo sample
echo sample
</code>```

After:

```<code>echo sample
echo sample
echo hello
echo sample
</code>```

Just like this.
without using this command:

```<code>echo echo sample> test.txt
echo echo sample> test.txt
echo echo hello> test.txt
echo echo sample> test.txt
</code>```

So, I mean is not write 1,2,4's 'echo' and 'sample' things.
Only the third line's 'echo'.
What can I do?

答:
This will edit the 2nd line in C:\test.txt, just change the 3rd line down to the line number you want to edit.</p>

```<code>@echo off
setlocal enabledelayedexpansion
set i=1
for /f %%a in (C:\test.txt) do (
if !i!==2 (
echo your new line >>C:\test2.txt
) else (
echo %%a >>C:\test2.txt
)
set /a i+=1
)
del C:\test.txt
ren C:\test2.txt test.txt
</code>```

Body:
First, I'm in Korea. So my English will very bad.

I want to edit third line with out touching first line and the second line.

Before:

echo sample
echo sample
echo sample
echo sample

After:

echo sample
echo sample
echo hello
echo sample

Just like this.
without using this command:

echo echo sample> test.txt
echo echo sample> test.txt
echo echo hello> test.txt
echo echo sample> test.txt

So, I mean is not write 1,2,4's 'echo' and 'sample' things.
Only the third line's 'echo'.
What can I do?

Body:
This will edit the 2nd line in C:\test.txt, just change the 3rd line down to the line number you want to edit.

@echo off
setlocal enabledelayedexpansion
set i=1
for /f %%a in (C:\test.txt) do (
if !i!==2 (
echo your new line >>C:\test2.txt
) else (
echo %%a >>C:\test2.txt
)
set /a i+=1
)
del C:\test.txt
ren C:\test2.txt test.txt


问:
real time javascript calculations
visit the link to see where the code is. The problem that I'm having is the bottom three groups of checkboxes don't do the right calculations and don't change when not clicked.

https://jsfiddle.net/hunterlop122/nLz0t11u/3/

```<code>$('input[name=food]').change(function(){
    if($(this).is(':checked')){
      gettotal();
    }
    else{
    }
});
</code>```

//checks to see if the checkbox's with the name food have been check and which one was checked and then calls the function get total.

答:
Use

```<code>$(".your-input").on("input", function(){ // });
</code>```

That will change in live, not only on the unfocus event.

Title: real time javascript calculations

Body:
visit the link to see where the code is. The problem that I'm having is the bottom three groups of checkboxes don't do the right calculations and don't change when not clicked.

https://jsfiddle.net/hunterlop122/nLz0t11u/3/

$('input[name=food]').change(function(){
    if($(this).is(':checked')){
      gettotal();
    }
    else{
    }
});

//checks to see if the checkbox's with the name food have been check and which one was checked and then calls the function get total.

Body:
Use

$(".your-input").on("input", function(){ // });

That will change in live, not only on the unfocus event.


问:
Vue.js Input field loses its focus after entry of one character
I have a view with an input field, which can be multiplicated by a given button. The problem is that after any entry of a char, the focus of the input field is lost. You have to click again to enter another char.

Do someone have a clue what could be the problem?

My model:

```<code>'model': [
    ...,
    'filter': [
        ...,
        'something': [
            'string'
        ]
    ]
]
</code>```

My code:

```<code><div v-for="(something, index) in model.filter.something" v-bind:key="something">
    <input type="text" v-model.trim="model.filter.something[index]"/>
</div>
</code>```

答:
The problem is that you are using a changing value as key. Vue expects key to indicate a unique identifier for the item. When you change it, it becomes a new item and must be re-rendered.

In the snippet below, I have two loops, both using the same data source. The first is keyed the way you have it set up. The second uses index instead (that may not be what you need, but the point is to use something other than what you're editing; in this example, key isn't needed anyway). The first exhibits the loss-of-focus you describe, the second works as expected.

new Vue({
  el: '#app',
  data: {
    'model': {
      'filter': {
        'something': [
          'string'
        ]
      }
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="app">
  <div v-for="(something, index) in model.filter.something" v-bind:key="something">
    <input type="text" v-model.trim="model.filter.something[index]" />
    {{something}}
  </div>
  <div v-for="(something, index) in model.filter.something">
    <input type="text" v-model.trim="model.filter.something[index]" :key="index" />
    {{something}}
  </div>
</div></code>```

Body:
I have a view with an input field, which can be multiplicated by a given button. The problem is that after any entry of a char, the focus of the input field is lost. You have to click again to enter another char.

Do someone have a clue what could be the problem?

My model:

'model': [
    ...,
    'filter': [
        ...,
        'something': [
            'string'
        ]
    ]
]

My code:

    <input type="text" v-model.trim="model.filter.something[index]"/>

Body:
The problem is that you are using a changing value as key. Vue expects key to indicate a unique identifier for the item. When you change it, it becomes a new item and must be re-rendered.

In the snippet below, I have two loops, both using the same data source. The first is keyed the way you have it set up. The second uses index instead (that may not be what you need, but the point is to use something other than what you're editing; in this example, key isn't needed anyway). The first exhibits the loss-of-focus you describe, the second works as expected.

new Vue({
  el: '#app',
  data: {
    'model': {
      'filter': {
        'something': [
          'string'
        ]
      }
    }
  }
});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="app">
  <div v-for="(something, index) in model.filter.something" v-bind:key="something">
    <input type="text" v-model.trim="model.filter.something[index]" />
    {{something}}
  </div>
  <div v-for="(something, index) in model.filter.something">
    <input type="text" v-model.trim="model.filter.something[index]" :key="index" />
    {{something}}
  </div>
</div>


问:
How to get epoch time in Redshift?
In my schema I have a created_on field. I want to assign EPOCH time value to it automatically on insert. How to achieve that?</p>

答:
```<code>select date_part(epoch,sysdate)::int
</code>```

If I’ve made a bad assumption please comment and I’ll refocus my answer.

Title: How to get epoch time in Redshift?

Body:
select date_part(epoch,sysdate)::int

If I’ve made a bad assumption please comment and I’ll refocus my answer.


问:
Javascript Nested Function - Need help returning result
I am trying to create a function to return a lat/long array from the Google Maps JS API (v3). I am able to write the data out that I retrieve from the API, but I am not able to pass the data along to a variable. I am wanting to do something like this:

```<code>var latLong = getLatLong(Address);
</code>```

The function that I have created is here:

```<code>function getLatLong(loc, callback) {
  var geocoder = new google.maps.Geocoder();
  var array = new Array();

  if (geocoder) {
    geocoder.geocode({ 'address': loc }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latLng = results[0].geometry.location;;
        $.each(latLng, function(k, v) {
          if (k == 'va' || k == 'wa') {
            array.push(v);
          }
        });
        var ret = array;
        callback(ret);
      } else {
        console.log("Geocoding failed: " + status);
      }
    });
  }
}
</code>```

I then am assigning the function to a variable and calling it to give me the lat/long.

```<code>var geo = getLatLong('Dallas, TX', function(result) {
  return result;
});
</code>```

Unfortunately this produces an 'undefined' result. I can access the result in the function, I just can't pass it along. How can I pass the result of the function to a variable to be accessed?

答:
The key point here is that getLatLong doesn't return a value. That is why geo is always undefined.

To make this work, you'll need to modify your callback function. Something like this:

```<code>getLatLong('Dallas, TX', function(result)
{
    var geo = result;
    //continue to use geo here as you normally would
});
</code>```

Body:
I am trying to create a function to return a lat/long array from the Google Maps JS API (v3). I am able to write the data out that I retrieve from the API, but I am not able to pass the data along to a variable. I am wanting to do something like this:

var latLong = getLatLong(Address);

The function that I have created is here:

function getLatLong(loc, callback) {
  var geocoder = new google.maps.Geocoder();
  var array = new Array();

  if (geocoder) {
    geocoder.geocode({ 'address': loc }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latLng = results[0].geometry.location;;
        $.each(latLng, function(k, v) {
          if (k == 'va' || k == 'wa') {
            array.push(v);
          }
        });
        var ret = array;
        callback(ret);
      } else {
        console.log("Geocoding failed: " + status);
      }
    });
  }
}

I then am assigning the function to a variable and calling it to give me the lat/long.

var geo = getLatLong('Dallas, TX', function(result) {
  return result;
});

Unfortunately this produces an 'undefined' result. I can access the result in the function, I just can't pass it along. How can I pass the result of the function to a variable to be accessed?

Body:
The key point here is that getLatLong doesn't return a value. That is why geo is always undefined.

To make this work, you'll need to modify your callback function. Something like this:

getLatLong('Dallas, TX', function(result)
{
    var geo = result;
    //continue to use geo here as you normally would
});


问:
Can I store image in array?
I want to save photos from photo gallery in my app and after show them in collection View. Is there some way to store this image in array in UserDefaults? </p>

答:
In NSUserDefaults you just must save Dictionary Objects, you must not save big amount of data.

To save big amount of data like images you should take a look to the Sandbox.

Take a look to the tutorial How to save in Sandbox

Title: Can I store image in array?


问:
Swift border color
I want to have color border on button:

```<code>buyButton.layer.borderColor = UIColor(red: 83.0, green: 186.0, blue: 183.0, alpha: 1.0).cgColor
</code>```

doesn't work for me, but

```<code> buyButton.layer.borderColor = UIColor.blue.cgColor
</code>```

works. What is wrong with my color?

Thank you

答:
You are using 'raw' RGB values, divide them by 255.0.

```<code>buyButton.layer.borderColor = UIColor(red: 83.0/255.0, green: 186.0/255.0, blue: 183.0/255.0, alpha: 1.0).cgColor
</code>```

So in UIColor terms, 1.0 is 255 red. 0.5 is 127.5 red etc.

Title: Swift border color

Body:
I want to have color border on button:

buyButton.layer.borderColor = UIColor(red: 83.0, green: 186.0, blue: 183.0, alpha: 1.0).cgColor

doesn't work for me, but

 buyButton.layer.borderColor = UIColor.blue.cgColor

works. What is wrong with my color?

Thank you

Body:
You are using 'raw' RGB values, divide them by 255.0.

buyButton.layer.borderColor = UIColor(red: 83.0/255.0, green: 186.0/255.0, blue: 183.0/255.0, alpha: 1.0).cgColor

So in UIColor terms, 1.0 is 255 red. 0.5 is 127.5 red etc.


问:
Unit Testing Visual Studio Online Selenium ChromeDriver Exception
I use Selenium ChromeDriver in a Unit Test project to test some action on a web page ...

var chromeDriver = new ChromeDriver();
 chromeDriver.Navigate().GoToUrl("https://www.google.com");

Chrome driver has been installed from nuget

Install-Package Selenium.WebDriver.ChromeDriver -Version 2.28.0.

When build my project in Visual Studio Online I receive some error:

System.InvalidOperationException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.28.455520

Any solution to solve this?

答:
You haven't set the path of chromedriver binary in System PATH variable, this how you can do it in code. Do it before you initialize the driver object.</p>

```<code>System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
</code>```

Body:
You haven't set the path of chromedriver binary in System PATH variable, this how you can do it in code. Do it before you initialize the driver object.

System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");


问:
Get absolute co-ordinates in MPandroid chart
I am using the MPAndroid charting library.

Suppose I use the following code to get the point (x,y)

```<code>RectF rectF = mChart.getBarBounds(entry);
float x = rectF.centerX();
float y = rectF.centerY();
</code>```

As fas as I understand, here the points are relative to the canvas on which the chart is being drawn.

How do I get the absolute co-ordinates of the same point on my screen ?

I did try the Tranformer class the library provides but was not able to achieve this.

答:
I used getLocationInWindow to get the top-left position of the chart and converted the canvas position to screen position as follows :</p>

```<code>int[] loc = new int[2];
yourChartView.getLocationInWindow(loc);
screenX = (int) (canvasPositionX + loc[0]);
screenY = (int) (canvasPositionY + loc[1]);
</code>```

Body:
I am using the MPAndroid charting library.

Suppose I use the following code to get the point (x,y)

RectF rectF = mChart.getBarBounds(entry);
float x = rectF.centerX();
float y = rectF.centerY();

As fas as I understand, here the points are relative to the canvas on which the chart is being drawn.

How do I get the absolute co-ordinates of the same point on my screen ?

I did try the Tranformer class the library provides but was not able to achieve this.

Body:
I used getLocationInWindow to get the top-left position of the chart and converted the canvas position to screen position as follows :

int[] loc = new int[2];
yourChartView.getLocationInWindow(loc);
screenX = (int) (canvasPositionX + loc[0]);
screenY = (int) (canvasPositionY + loc[1]);


问:
How can i do this query by linq ,extensions methods or pure sql?
I have a table below

```<code> first      second
-------     ----------
100        0
200        0
0           400
</code>```

I want to get below result

```<code> first      second      result
-------     ---------- ----------
100        0            100
200        0            300
0           400         -100
</code>```

As you can see that result parameter is sum of previous (first-sum)
How can i write such a query ?

答:
Here's how to do it with LINQ (including setup):

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    public class Pair
    {
        public Pair(int first, int second)
        {
            this.First = first;
            this.Second = second;
        }

        public int First { get; set; }
        public int Second { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var pairs = new List<Pair>();
            pairs.Add(new Pair(100, 0));
            pairs.Add(new Pair(200, 0));
            pairs.Add(new Pair(0, 400));

            int currentTotal = 0;
            var runningTotals = pairs.Select(m =>
            {
                currentTotal = currentTotal + (m.First - m.Second);

                return new
                {
                    First = m.First,
                    Second = m.Second,
                    Total = currentTotal
                };
            });

            foreach (var total in runningTotals)
            {
                Console.Write(total.First);
                Console.Write("\t\t");
                Console.Write(total.Second);
                Console.Write("\t\t");
                Console.Write(total.Total);
                Console.Write(Environment.NewLine);
            }

            Console.ReadLine();
        }
    }
}
</code>```

Here's how to do it with SQL:
http://www.databasejournal.com/features/mssql/article.php/3112381/SQL-Server-Calculating-Running-Totals-Subtotals-and-Grand-Total-Without-a-Cursor.htm

Hope that helps!

==UPDATE==

If you're using LINQ 2 SQL, you could pull in the records with something like this:

```<code>int currentTotal = 0;
var runningTotals = DataContextName.TableName.Select(m =>
{
    currentTotal = currentTotal + (m.First - m.Second);

    return new
    {
        First = m.First,
        Second = m.Second,
        Total = currentTotal
    };
});
</code>```

Body:
I have a table below

 first      second
-------     ----------
100        0
200        0
0           400

I want to get below result

 first      second      result
-------     ---------- ----------
100        0            100
200        0            300
0           400         -100

As you can see that result parameter is sum of previous (first-sum)
How can i write such a query ?

Body:
Here's how to do it with LINQ (including setup):

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    public class Pair
    {
        public Pair(int first, int second)
        {
            this.First = first;
            this.Second = second;
        }

        public int First { get; set; }
        public int Second { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var pairs = new List<Pair>();
            pairs.Add(new Pair(100, 0));
            pairs.Add(new Pair(200, 0));
            pairs.Add(new Pair(0, 400));

            int currentTotal = 0;
            var runningTotals = pairs.Select(m =>
            {
                currentTotal = currentTotal + (m.First - m.Second);

                return new
                {
                    First = m.First,
                    Second = m.Second,
                    Total = currentTotal
                };
            });

            foreach (var total in runningTotals)
            {
                Console.Write(total.First);
                Console.Write("\t\t");
                Console.Write(total.Second);
                Console.Write("\t\t");
                Console.Write(total.Total);
                Console.Write(Environment.NewLine);
            }

            Console.ReadLine();
        }
    }
}

Here's how to do it with SQL:
http://www.databasejournal.com/features/mssql/article.php/3112381/SQL-Server-Calculating-Running-Totals-Subtotals-and-Grand-Total-Without-a-Cursor.htm

Hope that helps!

==UPDATE==

If you're using LINQ 2 SQL, you could pull in the records with something like this:

int currentTotal = 0;
var runningTotals = DataContextName.TableName.Select(m =>
{
    currentTotal = currentTotal + (m.First - m.Second);

    return new
    {
        First = m.First,
        Second = m.Second,
        Total = currentTotal
    };
});