问:
ES6 Named Object Parameter Destructuring
I am currently using the object destructuring pattern with default parameters described in that answer to ES6 Object Destructuring Default Parameters.

```<code>(function test({a = "foo", b = "bar"} = {}) {
  console.log(a + " " + b);
})();
</code>```

I would like to be able to access the object parameter without assigning it to a variable in the function body and explicitly listing each key.

(function test({a = "foo", b = "bar"} = {}) {
  const options = {a, b};
  console.log(options);
})();```
</div>
</div>
</p>

<p>I tried naming the object argument, but the function looses the ability to resolve missing keys to their default value.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function test(options = {a = "foo", b = "bar"} = {}) {
  console.log(options);
})();</code>```

It seems to be ignoring the default parameters when destructuring into a named argument.

Is this part of the ES6 spec? Is there a way to achieve the desired behavior without additional code in the function body?

Edit: I removed a superfluous example that did not add context to the question.

答:
Honestly, I think you're overcomplicating this. Default parameters are not compulsory -- in this case your code can be cleaner without it.

I would simply take the object options as the parameter and do the destructuring within the body of the function, after assigning default values.

function test(options) {
    options = Object.assign({a: 'foo', b: 'bar'}, options);
    let {a, b} = options;
    console.log(options, a, b);
}

test(); // foo bar
test({a: 'baz'}); // baz bar
test({b: 'fuz'}); // foo fuz
test({c: 'fiz'}); // foo bar```
</div>
</div>
</p>

<hr>

<p>With particular regard to your final snippet:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function test(options = {a: "foo", b: "bar"}) {
  console.log(options);
})({a: "baz"});</code>```

The problem is that a default parameter is used when the value passed is undefined. Here, the value passed is {a: "baz"}. That is not undefined, so the default parameter is ignored. Objects are not merged automatically.

More broadly in answer to your question: there is no way of getting both an object and destructuring some of its properties in the parameters of a method. Frankly, I'm grateful, because function signatures can be hard enough to read at first glance as it is.

Body:
I am currently using the object destructuring pattern with default parameters described in that answer to ES6 Object Destructuring Default Parameters.

(function test({a = "foo", b = "bar"} = {}) {
  console.log(a + " " + b);
})();

I would like to be able to access the object parameter without assigning it to a variable in the function body and explicitly listing each key.

(function test({a = "foo", b = "bar"} = {}) {
  const options = {a, b};
  console.log(options);
})();

I tried naming the object argument, but the function looses the ability to resolve missing keys to their default value.

(function test(options = {a = "foo", b = "bar"} = {}) {
  console.log(options);
})();

It seems to be ignoring the default parameters when destructuring into a named argument.

Is this part of the ES6 spec? Is there a way to achieve the desired behavior without additional code in the function body?

Edit: I removed a superfluous example that did not add context to the question.

Body:
Honestly, I think you're overcomplicating this. Default parameters are not compulsory -- in this case your code can be cleaner without it.

I would simply take the object options as the parameter and do the destructuring within the body of the function, after assigning default values.

function test(options) {
    options = Object.assign({a: 'foo', b: 'bar'}, options);
    let {a, b} = options;
    console.log(options, a, b);
}

test(); // foo bar
test({a: 'baz'}); // baz bar
test({b: 'fuz'}); // foo fuz
test({c: 'fiz'}); // foo bar

With particular regard to your final snippet:

(function test(options = {a: "foo", b: "bar"}) {
  console.log(options);
})({a: "baz"});

The problem is that a default parameter is used when the value passed is undefined. Here, the value passed is {a: "baz"}. That is not undefined, so the default parameter is ignored. Objects are not merged automatically.

More broadly in answer to your question: there is no way of getting both an object and destructuring some of its properties in the parameters of a method. Frankly, I'm grateful, because function signatures can be hard enough to read at first glance as it is.


来源: stackexchange

问:
Search for any number of unknown substrings in place of * in a list of string
First of all, sorry if the title isn't very explicit, it's hard for me to formulate it properly. That's also why I haven't found if the question has already been asked, if it has.

So, I have a list of string, and I want to perform a "procedural" search replacing every * in my target-substring by any possible substring.

Here is an example:

```<code>strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('mesh_*')
# should return: ['mesh_1_TMP', 'mesh_2_TMP']
</code>```

In this case where there is just one * I just split each string with * and use startswith() and/or endswith(), so that's ok.
But I don't know how to do the same thing if there are multiple * in the search string.

So my question is, how do I search for any number of unknown substrings in place of * in a list of string?

For example:

```<code>strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('*_1_*')
# should return: ['obj_1_mesh', 'mesh_1_TMP']
</code>```

Hope everything is clear enough. Thanks.

答:
Consider using 'fnmatch' which provides Unix-like file pattern matching. More info here http://docs.python.org/2/library/fnmatch.html

```<code>from fnmatch import fnmatch
strList = ['obj_1_mesh',
       'obj_2_mesh',
       'obj_TMP',
       'mesh_1_TMP',
       'mesh_2_TMP',
       'meshTMP']

searchFor = '*_1_*'

resultSubList = [ strList[i] for i,x in enumerate(strList) if fnmatch(x,searchFor) ]
</code>```

This should do the trick

ContentLicense: CC BY-SA 3.0

Body:
First of all, sorry if the title isn't very explicit, it's hard for me to formulate it properly. That's also why I haven't found if the question has already been asked, if it has.

So, I have a list of string, and I want to perform a "procedural" search replacing every * in my target-substring by any possible substring.

Here is an example:

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('mesh_*')
# should return: ['mesh_1_TMP', 'mesh_2_TMP']

In this case where there is just one * I just split each string with * and use startswith() and/or endswith(), so that's ok.
But I don't know how to do the same thing if there are multiple * in the search string.

So my question is, how do I search for any number of unknown substrings in place of * in a list of string?

For example:

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('*_1_*')
# should return: ['obj_1_mesh', 'mesh_1_TMP']

Hope everything is clear enough. Thanks.

Body:
Consider using 'fnmatch' which provides Unix-like file pattern matching. More info here http://docs.python.org/2/library/fnmatch.html

from fnmatch import fnmatch
strList = ['obj_1_mesh',
       'obj_2_mesh',
       'obj_TMP',
       'mesh_1_TMP',
       'mesh_2_TMP',
       'meshTMP']

searchFor = '*_1_*'

resultSubList = [ strList[i] for i,x in enumerate(strList) if fnmatch(x,searchFor) ]

This should do the trick


问:
How to combine three lists of different size in order Python
I have three lists: signal, returns, and pct_list:

```<code>     signal= ['signal0', 'signal1', 'signal2']

     returns = ['retSCIENCE_MSFT','retLOVE_MSFT','retMUSIC_MSFT',
                 'retSCIENCE_YHOO', 'retLOVE_YHOO', 'retMUSIC_YHOO']

     pct_list = ['Pct_MSFT', 'Pct_YHOO']
</code>```

I tried using the zip function and it gave me the following result:

```<code>    ret_sig_list = list(zip(returns, signal, pct_list))
    ret_sig_list
</code>```

Output:

```<code>     [('retSCIENCE_MSFT', 'signal0', 'Pct_MSFT'),
      ('retLOVE_MSFT', 'signal1', 'Pct_YHOO')]
</code>```

What I'm trying to get is both MSFT and YHOO lined up with the corresponding signal and percent change like so:

```<code>ret_sig_list = [('retSCIENCE_MSFT', 'signal0', 'Pct_MSFT'),
               ('retLOVE_MSFT', 'signal1', 'Pct_MSFT'),
               ('retMUSIC_MSFT', 'signal2', 'Pct_MSFT'),
               ('retSCIENCE_YHOO', 'signal0', 'Pct_YHOO'),
               ('retLOVE_YHOO', 'signal1', 'Pct_YHOO'),
               ('retMUSIC_YHOO','signal2', 'Pct_YHOO')]
</code>```

I tried with list(zip(returns, signal, pct_list)), but it seems to default down to the lowest number of elements in the three lists, which is pct_list.

If anyone knows how I can tackle this problem, I'd be very greatful!
I'd like to use the ret_sig_list with a for-loop to perform a calculation on multiple stocks percent change goes up or down to give returns based on the associated words; science, love, music, etc.
I got the words from a Python package for Google Trends called Pytrends which I'd recommend, it's very cool!

答:
Use itertools.cycle:

```<code>In [2]: from itertools import cycle

In [3]: list(zip(returns, cycle(signal), cycle(pct_list)))
Out[3]:
[('retSCIENCE_MSFT', 'signal0', 'Pct_MSFT'),
 ('retLOVE_MSFT', 'signal1', 'Pct_YHOO'),
 ('retMUSIC_MSFT', 'signal2', 'Pct_MSFT'),
 ('retSCIENCE_YHOO', 'signal0', 'Pct_YHOO'),
 ('retLOVE_YHOO', 'signal1', 'Pct_MSFT'),
 ('retMUSIC_YHOO', 'signal2', 'Pct_YHOO')]
</code>```

Body:
I have three lists: signal, returns, and pct_list:

     signal= ['signal0', 'signal1', 'signal2']

     returns = ['retSCIENCE_MSFT','retLOVE_MSFT','retMUSIC_MSFT',
                 'retSCIENCE_YHOO', 'retLOVE_YHOO', 'retMUSIC_YHOO']

     pct_list = ['Pct_MSFT', 'Pct_YHOO']

I tried using the zip function and it gave me the following result:

    ret_sig_list = list(zip(returns, signal, pct_list))
    ret_sig_list

Output:

     [('retSCIENCE_MSFT', 'signal0', 'Pct_MSFT'),
      ('retLOVE_MSFT', 'signal1', 'Pct_YHOO')]

What I'm trying to get is both MSFT and YHOO lined up with the corresponding signal and percent change like so:

ret_sig_list = [('retSCIENCE_MSFT', 'signal0', 'Pct_MSFT'),
               ('retLOVE_MSFT', 'signal1', 'Pct_MSFT'),
               ('retMUSIC_MSFT', 'signal2', 'Pct_MSFT'),
               ('retSCIENCE_YHOO', 'signal0', 'Pct_YHOO'),
               ('retLOVE_YHOO', 'signal1', 'Pct_YHOO'),
               ('retMUSIC_YHOO','signal2', 'Pct_YHOO')]

I tried with list(zip(returns, signal, pct_list)), but it seems to default down to the lowest number of elements in the three lists, which is pct_list.

If anyone knows how I can tackle this problem, I'd be very greatful!
I'd like to use the ret_sig_list with a for-loop to perform a calculation on multiple stocks percent change goes up or down to give returns based on the associated words; science, love, music, etc.
I got the words from a Python package for Google Trends called Pytrends which I'd recommend, it's very cool!

Body:
Use itertools.cycle:

In [2]: from itertools import cycle

In [3]: list(zip(returns, cycle(signal), cycle(pct_list)))
Out[3]:
[('retSCIENCE_MSFT', 'signal0', 'Pct_MSFT'),
 ('retLOVE_MSFT', 'signal1', 'Pct_YHOO'),
 ('retMUSIC_MSFT', 'signal2', 'Pct_MSFT'),
 ('retSCIENCE_YHOO', 'signal0', 'Pct_YHOO'),
 ('retLOVE_YHOO', 'signal1', 'Pct_MSFT'),
 ('retMUSIC_YHOO', 'signal2', 'Pct_YHOO')]


问:
Uploading Image from Android to Node
I am trying to upload multiple images to my node server via Android Studio. However the image file always seems to be corrupt on the server. I am able to take and preview the picture in Android but not able to store it on my server.

Here is my server code

```<code>app.post('/upload', function(req, res) {
    var base64Data = req.rawBody;
    fs.writeFile("test.jpg",base64Data,'base64',function(err,written){
        if(err) console.log(err);
        else {
            console.log("file Succesfully written ");
            cloudinary.uploader.upload("test.jpg", function (image) {
                if(image !== undefined) {

                     res.json({link: image.secure_url}).end();
                     console.log("url = " , image.secure_url);
                 //   fs.unlink(ImageFile);
                } else console.log.error("Error uploading to Cloudinary, ", image);
            });
        }
    });
});
</code>```

Here is my front end code I use to convert my bitmap to an encoded Base64 String.

```<code>final String encodedString = ImageBase64.encode(fileArray.get(i));
</code>```

Here is a log of what encodedString holds after being set. Obviously the full value is not displayed.

```<code>/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
                                                                          AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
                                                                          AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAMgA+gDASIA
                                                                          AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
</code>```

However on my backend it is displayed as this

```<code>2F9j%2F4AAQSkZJRgABAQAAAQABAAD%2F2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2F2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2FwAARCAMgA%2BgDASIA%0AAhEBAxEB%2F8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQ
</code>```

答: If you get it url encoded then you should url decode it. </p>

Title: Uploading Image from Android to Node

Body:
I am trying to upload multiple images to my node server via Android Studio. However the image file always seems to be corrupt on the server. I am able to take and preview the picture in Android but not able to store it on my server.

Here is my server code

app.post('/upload', function(req, res) {
    var base64Data = req.rawBody;
    fs.writeFile("test.jpg",base64Data,'base64',function(err,written){
        if(err) console.log(err);
        else {
            console.log("file Succesfully written ");
            cloudinary.uploader.upload("test.jpg", function (image) {
                if(image !== undefined) {

                     res.json({link: image.secure_url}).end();
                     console.log("url = " , image.secure_url);
                 //   fs.unlink(ImageFile);
                } else console.log.error("Error uploading to Cloudinary, ", image);
            });
        }
    });
});

Here is my front end code I use to convert my bitmap to an encoded Base64 String.

final String encodedString = ImageBase64.encode(fileArray.get(i));

Here is a log of what encodedString holds after being set. Obviously the full value is not displayed.

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
                                                                          AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
                                                                          AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAMgA+gDASIA
                                                                          AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA

However on my backend it is displayed as this

2F9j%2F4AAQSkZJRgABAQAAAQABAAD%2F2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2F2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2FwAARCAMgA%2BgDASIA%0AAhEBAxEB%2F8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQ


问:
Server sent event messaging issue
I was looking for a way to get feedback on the progress of a long running script and came across server-sent events.  I followed the guidelines set down here http://www.htmlgoodies.com/beyond/reference/receive-updates-from-the-server-using-the-eventsource.html , copied the examples given, created a couple of php files and put them on my localhost server on my laptop (running Apache web server).

They worked just fine, the server returned a message each second of the message loop which I received in the browser. I tested it in Firefox, Chrome and IE and of course IE just reported the "not supported" message as expected.

Before diving in to create my real application I then copied the two files up to my production company server (running IIS) and called them from the same browser on my laptop.

The result was that I got all the messages, but only AFTER the loop had completed, not at the time each iteration message was sent, which of course rather defeats the object.

Am I missing something - might there be some setting on the IIS server restricting use of sse? If so what?

Any help appreciated.

Here are the two files (apart from a name change they follow pretty exactly the examples on more than one introductory web page on the subject):

First file ssetest.php:

```<code><?php

    echo "<!DOCTYPE html><html><head><meta charset=\"utf-8\" /></head><body>";

    echo "<script language='javascript' type='text/javascript'>

    var esSupport = false, es, result;

    function init() {
      noEsSupport = (window.EventSource === undefined);
      if(noEsSupport) addLog('This browser does not support server-sent events.<br>You will not get any progress messages.<br>Try Firefox or Chrome');
    }

    window.onload = init;

    function startTask() {
        es = new EventSource('ssetest_task.php');

        //a message is received
        es.addEventListener('message', function(e) {
            var result = JSON.parse( e.data );

            addLog(result.message);

            if(e.lastEventId == 'CLOSE') {
                addLog('Received CLOSE closing');
                es.close();
                var pBar = document.getElementById('progressor');
                pBar.value = pBar.max; //max out the progress bar
            }
            else {
                var pBar = document.getElementById('progressor');
                pBar.value = result.progress;
                var perc = document.getElementById('percentage');
                perc.innerHTML   = result.progress  + \"%\";
                perc.style.width = (Math.floor(pBar.clientWidth * (result.progress/100)) + 15) + 'px';
            }
        });

        es.addEventListener('error', function(e){addLog('Error occurred'); es.close();});
    }

    function stopTask() {
        es.close();
        addLog('Interrupted');
    }

    function addLog(message) {
        var r = document.getElementById('results');
        r.innerHTML += message + '<br>';
        r.scrollTop = r.scrollHeight;
    }
    </script>";

    echo "<br />";
    echo "<input type=\"button\" onclick=\"startTask();\"  value=\"Start Long Task\" />";
    echo "<input type=\"button\" onclick=\"stopTask();\"  value=\"Stop Task\" />";
    echo "<br /><br />";
    echo "<p>Results</p>";
    echo "<br /><div id=\"results\" style=\"border:1px solid #000; padding:10px; width:300px; height:250px; overflow:auto; background:#eee;\"></div><br />";
    echo "<progress id='progressor' value='0' max='100'></progress> ";
    echo "<span id=\"percentage\" style=\"text-align:right; display:block; margin-top:5px;\">0</span>";
    echo "</body></html>";

?>
</code>```

and the task file ssetest_task.php:

```<code><?php

    header('Content-Type: text/event-stream');
    // recommended to prevent caching of event data.
    header('Cache-Control: no-cache');

    function send_message($id, $message, $progress) {
        $d = array('message' => $message , 'progress' => $progress);
        echo "id: $id" . PHP_EOL;
        echo "data: " . json_encode($d) . PHP_EOL;
        echo PHP_EOL;
        ob_flush();
        flush();
    }

    //LONG RUNNING TASK
    for($i = 1; $i <= 10; $i++) {
        send_message($i, 'on iteration ' . $i . ' of 10' , $i*10);
        sleep(1);
    }

    send_message('CLOSE', 'Process complete');

?>
</code>```

答:
I've overcome these issues on IIS with the web.config settings that follow. The important bit is setting PHP's responseBufferLimit=0. You'll have to adjust for the version of PHP on your server

```<code><configuration>
    <system.webServer>
        <handlers>
            <remove name="PHP55_via_FastCGI" />
            <add name="PHP55_via_FastCGI" path="*.php" verb="GET,HEAD,POST" type="" modules="FastCgiModule" scriptProcessor="C:\Program Files (x86)\PHP\v5.5\php-cgi.exe" resourceType="Either" requireAccess="Script" allowPathInfo="true" preCondition="" responseBufferLimit="0" />
        </handlers>
        <urlCompression doDynamicCompression="false"/>
    </system.webServer>
</configuration>
</code>```

Title: Server sent event messaging issue

Body:
I was looking for a way to get feedback on the progress of a long running script and came across server-sent events.  I followed the guidelines set down here http://www.htmlgoodies.com/beyond/reference/receive-updates-from-the-server-using-the-eventsource.html , copied the examples given, created a couple of php files and put them on my localhost server on my laptop (running Apache web server).

They worked just fine, the server returned a message each second of the message loop which I received in the browser. I tested it in Firefox, Chrome and IE and of course IE just reported the "not supported" message as expected.

Before diving in to create my real application I then copied the two files up to my production company server (running IIS) and called them from the same browser on my laptop.

The result was that I got all the messages, but only AFTER the loop had completed, not at the time each iteration message was sent, which of course rather defeats the object.

Am I missing something - might there be some setting on the IIS server restricting use of sse? If so what?

Any help appreciated.

Here are the two files (apart from a name change they follow pretty exactly the examples on more than one introductory web page on the subject):

First file ssetest.php:

<?php

    echo "<!DOCTYPE html><meta charset=\"utf-8\" />";

    echo "";

    echo "
";
    echo "<input type=\"button\" onclick=\"startTask();\"  value=\"Start Long Task\" />";
    echo "<input type=\"button\" onclick=\"stopTask();\"  value=\"Stop Task\" />";
    echo "

";
    echo "
Results
";
    echo "

";
    echo "<progress id='progressor' value='0' max='100'></progress> ";
    echo "0";
    echo "";

?>

and the task file ssetest_task.php:

<?php

    header('Content-Type: text/event-stream');
    // recommended to prevent caching of event data.
    header('Cache-Control: no-cache');

    function send_message($id, $message, $progress) {
        $d = array('message' => $message , 'progress' => $progress);
        echo "id: $id" . PHP_EOL;
        echo "data: " . json_encode($d) . PHP_EOL;
        echo PHP_EOL;
        ob_flush();
        flush();
    }

    //LONG RUNNING TASK
    for($i = 1; $i <= 10; $i++) {
        send_message($i, 'on iteration ' . $i . ' of 10' , $i*10);
        sleep(1);
    }

    send_message('CLOSE', 'Process complete');

?>

Body:
I've overcome these issues on IIS with the web.config settings that follow. The important bit is setting PHP's responseBufferLimit=0. You'll have to adjust for the version of PHP on your server

<configuration>
    <system.webServer>
        <handlers>
            <remove name="PHP55_via_FastCGI" />
            <add name="PHP55_via_FastCGI" path="*.php" verb="GET,HEAD,POST" type="" modules="FastCgiModule" scriptProcessor="C:\Program Files (x86)\PHP\v5.5\php-cgi.exe" resourceType="Either" requireAccess="Script" allowPathInfo="true" preCondition="" responseBufferLimit="0" />
        </handlers>
        <urlCompression doDynamicCompression="false"/>
    </system.webServer>
</configuration>


问:
How do you fetch a remote branch without "checking it out"
I am working on a branch "branch-A" and using the command git branch I can see that its the only branch locally.

If I use git branch -a I can see the remote copy of "remotes/origin/branch-B"

What I want to do is bring branch-B locally, but I don't want to actually check it out... I mean I could do that and then checkout my other branch to go back, but its slightly more painful since I am doing this to lots of repos.

I was thinking some sort of fetch? but I can't figure out how to phrase the command. Is it possible?

So I have:

```<code>user@pc> git branch
* branch-A
  master
</code>```

and

```<code>user@pc> git branch -a
* branch-A
  remotes/origin/branch-B
  remotes/origin/branch-A
  remotes/origin/master
</code>```

I want to be able to get:

```<code>user@pc> git branch
* branch-A
  branch-B
  master
</code>```

答:
You can do this, one liner very simple.

```<code>git fetch <remote> <srcBranch>:<destBranch>
</code>```

this will avoid to checkout the remote branch.

See this question for more information:

Merge, update, and pull Git branches without using checkouts

Body:
I am working on a branch "branch-A" and using the command git branch I can see that its the only branch locally.

If I use git branch -a I can see the remote copy of "remotes/origin/branch-B"

What I want to do is bring branch-B locally, but I don't want to actually check it out... I mean I could do that and then checkout my other branch to go back, but its slightly more painful since I am doing this to lots of repos.

I was thinking some sort of fetch? but I can't figure out how to phrase the command. Is it possible?

So I have:

user@pc> git branch
* branch-A
  master

and

user@pc> git branch -a
* branch-A
  remotes/origin/branch-B
  remotes/origin/branch-A
  remotes/origin/master

I want to be able to get:

user@pc> git branch
* branch-A
  branch-B
  master

Body:
You can do this, one liner very simple.

git fetch <remote> <srcBranch>:<destBranch>

this will avoid to checkout the remote branch.

See this question for more information:

Merge, update, and pull Git branches without using checkouts


问:
Could not bind TCP port 443 LetsEncrypt
Could not bind TCP port 443 because it is already in use by another process on this system (such as a web server). Please stop the program in question and then try again

My operating system is (include version): mac OS Sierra version 10.12

My web server is (include version): apache2-mod-php7.0_7.0.15

My hosting provider, if applicable, is: Linode (Ubuntu 16.04.1 LTS)

I can login to a root shell on my machine (yes or no, or I don't know): not sure

I'm using a control panel to manage my site (no, or provide the name and version of the control panel): I use terminal and filezilla

Question is how do stop the program??? If any more details are required, let me know!

答:
Try the following command in terminal to list and search for process using a regex:-

```<code>ps gx | grep 'java'
</code>```

The above example is to list all the 'Symantec' related processes. Replace 'Symantec' with your own phrase. Next use variations of 'kill' command. You can either use:-

```<code>kill pid
</code>```

Replace 'pid' with actual process id. Or use,

```<code>killall
</code>```

as suggested before. To reiterate another useful suggestion, use

```<code>man kill
</code>```

to see the manual for 'kill' command and also scroll down and see related commands which is mentioned under, "SEE ALSO" section.

Title: Could not bind TCP port 443 LetsEncrypt

Body:
Try the following command in terminal to list and search for process using a regex:-

ps gx | grep 'java'

The above example is to list all the 'Symantec' related processes. Replace 'Symantec' with your own phrase. Next use variations of 'kill' command. You can either use:-

kill pid

Replace 'pid' with actual process id. Or use,

killall

as suggested before. To reiterate another useful suggestion, use

man kill

to see the manual for 'kill' command and also scroll down and see related commands which is mentioned under, "SEE ALSO" section.


问:
php | ERR_TOO_MANY_REDIRECTS
I am experiencing some issues with php, on my localhost. I receive a err_too_many_redirects error from my browser.

I am recieving this error when I am trying to direct a user from accessing information from a different place on the web server.

Here is the code:

```<code><?php
session_start();
if(isset($_SESSION['valid'])) {
    $loggedIn = $_SESSION['name'];
    if($loggedIn != basename(getcwd())) {
        echo "You are in the wrong place.";
        $url = '../../users/' . $loggedIn . '/index.php';
        header('Location: ' . $url);
    } else {
        echo "Hello";
    }
} else {
    $url = 'index.php';
    header('Location: ' . $url);
}
?>
</code>```

Can someone please explain to me why it is doing this? I have tried multiple things such as re-arranging the order of the process.

Can someone please help me?

答:
My bad, silly mistake.

I was re-directing them straight back to the INDEX page of the user

Code:

```<code><?php
session_start();
if(isset($_SESSION['valid'])) {
    $loggedIn = $_SESSION['name'];
    if($loggedIn != basename(getcwd())) {
        echo "You are in the wrong place.";
        $url = '../../users/' . $loggedIn . '/index.php';
        header('Location: ' . $url);
    } else {
        echo "Hello";
    }
} else {
    $url = 'index.php';
    header('Location: ' . $url);
}
?>
</code>```

I had to update the URL here in the else statement for the if(isset($_SESSION['valid]')) Here it is:

```<code>$url = '../../index.php';
header('Location: ' . $url);
</code>```

Title: php | ERR_TOO_MANY_REDIRECTS

Body:
I am experiencing some issues with php, on my localhost. I receive a err_too_many_redirects error from my browser.

I am recieving this error when I am trying to direct a user from accessing information from a different place on the web server.

Here is the code:

<?php
session_start();
if(isset($_SESSION['valid'])) {
    $loggedIn = $_SESSION['name'];
    if($loggedIn != basename(getcwd())) {
        echo "You are in the wrong place.";
        $url = '../../users/' . $loggedIn . '/index.php';
        header('Location: ' . $url);
    } else {
        echo "Hello";
    }
} else {
    $url = 'index.php';
    header('Location: ' . $url);
}
?>

Can someone please explain to me why it is doing this? I have tried multiple things such as re-arranging the order of the process.

Can someone please help me?

Body:
My bad, silly mistake.

I was re-directing them straight back to the INDEX page of the user

Code:

<?php
session_start();
if(isset($_SESSION['valid'])) {
    $loggedIn = $_SESSION['name'];
    if($loggedIn != basename(getcwd())) {
        echo "You are in the wrong place.";
        $url = '../../users/' . $loggedIn . '/index.php';
        header('Location: ' . $url);
    } else {
        echo "Hello";
    }
} else {
    $url = 'index.php';
    header('Location: ' . $url);
}
?>

I had to update the URL here in the else statement for the if(isset($_SESSION['valid]')) Here it is:

$url = '../../index.php';
header('Location: ' . $url);


问:
Thread-safe implementation of the Copy-on-write (COW) idiom?
Can anyone point me to a thread-safe implementation of the Copy-on-write (COW) idiom? The sample code on this site looks good -- is it thread-safe?

In case anyone is wondering what I will be using it for: I have a Foo class that has a std::map<int,double> member. Foo objects are copied very frequently in my code, but the copies rarely modify the contained map. I found that COW gives me a 22% performance boost, compared to copying the whole map contents in the Foo copy constructor, but my COW implementation crashes when multiple threads are used.

UPDATE:

Okay, here is the code, reduced to a minimal example, since you asked for it:

First, a reference-counting map:

```<code>class RcMap {
 public:
  typedef std::map<int,double> Container;
  typedef Container::const_iterator const_iterator;
  typedef Container::iterator iterator;

  RcMap() : count_(1) {}

  RcMap(const RcMap& other) : count_(1) {
    m_ = other.Get();
  }

  unsigned Count() const { return count_; }
  unsigned IncCount() { return ++count_; }
  unsigned DecCount() {
    if(count_ > 0) --count_;
    return count_;
  }
  void insert(int i, double d) {
    m_.insert(std::make_pair(i,d));
  }
  iterator begin() { return m_.begin(); }
  iterator end() { return m_.end(); }
  const_iterator begin() const { return m_.begin(); }
  const_iterator end() const { return m_.end(); }

 protected:
  const Container& Get() const { return m_; }

 private:
  void operator=(const RcMap&); // disallow

  Container m_;
  unsigned count_;
};
</code>```

And here is the class Foo that contains such a map RcMap, using a Copy-on-write mechanism:

```<code>class Foo {
 public:
  Foo() : m_(NULL) {}

  Foo(const Foo& other) : m_(other.m_) {
    if (m_) m_->IncCount();
  }

  Foo& operator= (const Foo& other) {
    RcMap* const old = m_;
    m_ = other.m_;
    if(m_ != 0)
      m_->IncCount();
    if (old != 0 && old->DecCount() == 0) {
      delete old;
    }
    return *this;
  }

  virtual ~Foo() {
    if(m_ != 0 && m_->DecCount() == 0){
      delete m_;
      m_ = 0;
    }
  }

  const RcMap& GetMap() const {
    if(m_ == 0)
      return EmptyStaticRcMap();
    return *m_;
  }

  RcMap& GetMap() {
    if(m_ == 0)
      m_ = new RcMap();
    if (m_->Count() > 1) {
      RcMap* d = new RcMap(*m_);
      m_->DecCount();
      m_ = d;
    }
    assert(m_->Count() == 1);
    return *m_;
  }

  static const RcMap& EmptyStaticRcMap(){
    static const RcMap empty;
    return empty;
  }

 private:
  RcMap* m_;
};
</code>```

I haven't yet been able to reproduce the crash using this minimal example, but in my original code it happens when I use the copy constructor or assignment operator of Foo objects in parallel. But maybe someone can spot the thread-safety bug?

答:
COW is inherently thread-safe, since the original is essentially immutable, and only the thread that induces the copy sees the copied version in the process of being created. You only need to watch for two things:

Make sure the original doesn't get deleted by another thread while the copy is occurring. This an orthogonal problem, though (e.g., you could use thread-safe ref-counting).

Make sure all the read operations you perform while copying are thread-safe. This is rarely a problem, but sometimes a read might populate a cache, for instance.

In fact, if this assumption is violated, that's a problem with the read operation not being thread-safe, and will probably affect more code than just the COW.

ContentLicense: CC BY-SA 2.5

Body:
Can anyone point me to a thread-safe implementation of the Copy-on-write (COW) idiom? The sample code on this site looks good -- is it thread-safe?

In case anyone is wondering what I will be using it for: I have a Foo class that has a std::map<int,double> member. Foo objects are copied very frequently in my code, but the copies rarely modify the contained map. I found that COW gives me a 22% performance boost, compared to copying the whole map contents in the Foo copy constructor, but my COW implementation crashes when multiple threads are used.

UPDATE:

Okay, here is the code, reduced to a minimal example, since you asked for it:

First, a reference-counting map:

class RcMap {
 public:
  typedef std::map<int,double> Container;
  typedef Container::const_iterator const_iterator;
  typedef Container::iterator iterator;

  RcMap() : count_(1) {}

  RcMap(const RcMap& other) : count_(1) {
    m_ = other.Get();
  }

  unsigned Count() const { return count_; }
  unsigned IncCount() { return ++count_; }
  unsigned DecCount() {
    if(count_ > 0) --count_;
    return count_;
  }
  void insert(int i, double d) {
    m_.insert(std::make_pair(i,d));
  }
  iterator begin() { return m_.begin(); }
  iterator end() { return m_.end(); }
  const_iterator begin() const { return m_.begin(); }
  const_iterator end() const { return m_.end(); }

 protected:
  const Container& Get() const { return m_; }

 private:
  void operator=(const RcMap&); // disallow

  Container m_;
  unsigned count_;
};

And here is the class Foo that contains such a map RcMap, using a Copy-on-write mechanism:

class Foo {
 public:
  Foo() : m_(NULL) {}

  Foo(const Foo& other) : m_(other.m_) {
    if (m_) m_->IncCount();
  }

  Foo& operator= (const Foo& other) {
    RcMap* const old = m_;
    m_ = other.m_;
    if(m_ != 0)
      m_->IncCount();
    if (old != 0 && old->DecCount() == 0) {
      delete old;
    }
    return *this;
  }

  virtual ~Foo() {
    if(m_ != 0 && m_->DecCount() == 0){
      delete m_;
      m_ = 0;
    }
  }

  const RcMap& GetMap() const {
    if(m_ == 0)
      return EmptyStaticRcMap();
    return *m_;
  }

  RcMap& GetMap() {
    if(m_ == 0)
      m_ = new RcMap();
    if (m_->Count() > 1) {
      RcMap* d = new RcMap(*m_);
      m_->DecCount();
      m_ = d;
    }
    assert(m_->Count() == 1);
    return *m_;
  }

  static const RcMap& EmptyStaticRcMap(){
    static const RcMap empty;
    return empty;
  }

 private:
  RcMap* m_;
};

I haven't yet been able to reproduce the crash using this minimal example, but in my original code it happens when I use the copy constructor or assignment operator of Foo objects in parallel. But maybe someone can spot the thread-safety bug?


问:
should my clients to have installed Excel if my app use Excel.DLL
Should my client to install MS Excell on their PC, if my application use Microsoft.Office.Interop.Excel.dll to import data from EXCEL file?
Or is enough only my app. to have this reference.

Thank you.

答:
If your client does not have excel installed and your app reads sheets you must install the assembly.
Excel DLL</p>


问:
Sometimes i receive the following error : Procedure or function expects parameter which was not supplied
first I want to emphasize that this code is working in 99% of the times, but every once in a while clients complain for receiving this error. I have the bellow code for passing 2 parameters to a stored procedure. frmSetLoggerTime is a form with a datetimepicker (dtpToDate).
Did anyone came across this issue? I'm using Borland Delphi 7 with SQL Server 2008.

```<code>procedure TFormDBManager.ActionSetLoggerTimeExecute(Sender: TObject);
var
  frmSetLoggerTime: TfrmSetLoggerTime;
  var
  RecAffected, tmpOleVar:OleVariant;
  cmdObj: _Command;
  ParDataLoggerID, ParUdapteTime :_Parameter;
begin
  tmpOleVar:=OleCtrls.EmptyParam;
  frmSetLoggerTime := TfrmSetLoggerTime.Create(self);
  try
    frmSetLoggerTime.dtpToDate.DateTime := now;
    if frmSetLoggerTime.ShowModal = mrOK then
    begin
      cmdObj := CoCommand.Create;
      cmdObj.Set_ActiveConnection(DBRemoteModule.SLogConnection.ConnectionObject);
      cmdObj.CommandType := adCmdStoredProc;
      cmdObj.CommandText := 'UpdateRebelDateTime';
      ParUdapteTime := cmdObj.CreateParameter('@UdapteTime', adDate,     adParamInput, 3, frmSetLoggerTime.dtpToDate.DateTime);
      cmdObj.Parameters.Append(ParUdapteTime);
      ParDataLoggerID := cmdObj.CreateParameter('@DataLoggerID', adInteger,     adParamInput, 4, QueryLogger.FieldByName('DataLoggerID').AsInteger);
      cmdObj.Parameters.Append(ParDataLoggerID);
      cmdObj.Execute(RecAffected, tmpOleVar, 0);

    end;
  finally
    frmSetLoggerTime.free;
  end;

end;
</code>```

Here is the stored procedure:

```<code>ALTER PROCEDURE [dbo].[UpdateRebelDateTime]  @UpdateDateTime datetime,      @DataLoggerID int
AS
SET NOCOUNT ON
  UPDATE tblDataLoggers SET UpdateDateTime = @UpdateDateTime,     UpdateDateTimeDelay = GETUTCDATE()
  WHERE  DataLoggerID = @DataLoggerID
</code>```

答:
You are using another parameter name: @UdapteTime

Your code:

```<code> ParUdapteTime := cmdObj.CreateParameter('@UdapteTime', adDate, adParamInput, 3, frmSetLoggerTime.dtpToDate.DateTime);
</code>```

And it expects:

```<code>@UpdateDateTime
</code>```

Body:
first I want to emphasize that this code is working in 99% of the times, but every once in a while clients complain for receiving this error. I have the bellow code for passing 2 parameters to a stored procedure. frmSetLoggerTime is a form with a datetimepicker (dtpToDate).
Did anyone came across this issue? I'm using Borland Delphi 7 with SQL Server 2008.

procedure TFormDBManager.ActionSetLoggerTimeExecute(Sender: TObject);
var
  frmSetLoggerTime: TfrmSetLoggerTime;
  var
  RecAffected, tmpOleVar:OleVariant;
  cmdObj: _Command;
  ParDataLoggerID, ParUdapteTime :_Parameter;
begin
  tmpOleVar:=OleCtrls.EmptyParam;
  frmSetLoggerTime := TfrmSetLoggerTime.Create(self);
  try
    frmSetLoggerTime.dtpToDate.DateTime := now;
    if frmSetLoggerTime.ShowModal = mrOK then
    begin
      cmdObj := CoCommand.Create;
      cmdObj.Set_ActiveConnection(DBRemoteModule.SLogConnection.ConnectionObject);
      cmdObj.CommandType := adCmdStoredProc;
      cmdObj.CommandText := 'UpdateRebelDateTime';
      ParUdapteTime := cmdObj.CreateParameter('@UdapteTime', adDate,     adParamInput, 3, frmSetLoggerTime.dtpToDate.DateTime);
      cmdObj.Parameters.Append(ParUdapteTime);
      ParDataLoggerID := cmdObj.CreateParameter('@DataLoggerID', adInteger,     adParamInput, 4, QueryLogger.FieldByName('DataLoggerID').AsInteger);
      cmdObj.Parameters.Append(ParDataLoggerID);
      cmdObj.Execute(RecAffected, tmpOleVar, 0);

    end;
  finally
    frmSetLoggerTime.free;
  end;

end;

Here is the stored procedure:

ALTER PROCEDURE [dbo].[UpdateRebelDateTime]  @UpdateDateTime datetime,      @DataLoggerID int
AS
SET NOCOUNT ON
  UPDATE tblDataLoggers SET UpdateDateTime = @UpdateDateTime,     UpdateDateTimeDelay = GETUTCDATE()
  WHERE  DataLoggerID = @DataLoggerID

Body:
You are using another parameter name: @UdapteTime

Your code:

 ParUdapteTime := cmdObj.CreateParameter('@UdapteTime', adDate, adParamInput, 3, frmSetLoggerTime.dtpToDate.DateTime);

And it expects:

@UpdateDateTime


问:
Combining one or more characters (`+?`) and positive lookahead (?=)
I have a string like this:

```<code>"resourceType": "com.bmc.arsys.rx.services.view.domain.ContainerViewComponentDefinition",
</code>```

I want to match the first double quote in this part:

```<code>"resourceType":
</code>```

So I construct a regexp to find ", then one or more characters (greedy) followed by ": literals, so I have the first part:

```<code>".+?
</code>```

and then I want to add positive lookahead part ?=":

```<code>".+??=":
</code>```

but I get syntax error. What's the syntax for combining them?

答:
To match anything in between quotes you can do this. You don't need a positive look ahead.

".+":

Body:
I have a string like this:

"resourceType": "com.bmc.arsys.rx.services.view.domain.ContainerViewComponentDefinition",

I want to match the first double quote in this part:

"resourceType":

So I construct a regexp to find ", then one or more characters (greedy) followed by ": literals, so I have the first part:

".+?

and then I want to add positive lookahead part ?=":

".+??=":

but I get syntax error. What's the syntax for combining them?


问:
Bootstrap input control width is too short
I am having an issue with my controls showing far less than 100% using Bootstrap 3.  This is an example:

As you can see, all but the Tags control are far shorter than their container.  Tags started showing with full length after making it a Tokenfield.  The code that generates this is:

```<code><div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <b class="panel-title">Information</b>
                <a href="#" data-toggle="collapse" data-target="#Information" style="color: black;"><span id="InfoCollapseIcon"></span></a>
            </div>
            <div class="panel-body panel-collapse collapse in" id="Information">
                <div class="form-group">
                    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label text-left col-md-4" })
                    <div class="col-md-8">
                        @Html.TextBoxFor(model => model.Name, htmlAttributes: new { @class = "form-control", @title = "The unique name of the generator." })
                        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                    </div>
                </div>

                <!-- Rinse and Repeat the above -->
            </div>
        </div>
    </div>
</div>
</code>```

How can I make my controls fill their container's width?

答:
If you generated a project from a template check for this rule in Content/Site.css

```<code>/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}
</code>```

Body:
I am having an issue with my controls showing far less than 100% using Bootstrap 3.  This is an example:

As you can see, all but the Tags control are far shorter than their container.  Tags started showing with full length after making it a Tokenfield.  The code that generates this is:

                Information

                    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label text-left col-md-4" })

                        @Html.TextBoxFor(model => model.Name, htmlAttributes: new { @class = "form-control", @title = "The unique name of the generator." })
                        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

How can I make my controls fill their container's width?

Body:
If you generated a project from a template check for this rule in Content/Site.css

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}


答:
If the string you are looking for looks always like string you can just use the find function, you'll get something like:

```<code>for s in strList:
    if s.find(searchFor) != -1:
        do_something()
</code>```

If you have more than one string to look for (like abc*123*test) you gonna need to look for the each string, find the second one in the same string starting at the index you found the first + it's len and so on.

Title: Search for any number of unknown substrings in place of * in a list of string

Body:
First of all, sorry if the title isn't very explicit, it's hard for me to formulate it properly. That's also why I haven't found if the question has already been asked, if it has.

So, I have a list of string, and I want to perform a "procedural" search replacing every * in my target-substring by any possible substring.

Here is an example:

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('mesh_*')
# should return: ['mesh_1_TMP', 'mesh_2_TMP']

In this case where there is just one * I just split each string with * and use startswith() and/or endswith(), so that's ok.
But I don't know how to do the same thing if there are multiple * in the search string.

So my question is, how do I search for any number of unknown substrings in place of * in a list of string?

For example:

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('*_1_*')
# should return: ['obj_1_mesh', 'mesh_1_TMP']

Hope everything is clear enough. Thanks.

Body:
If the string you are looking for looks always like string you can just use the find function, you'll get something like:

for s in strList:
    if s.find(searchFor) != -1:
        do_something()

If you have more than one string to look for (like abc*123*test) you gonna need to look for the each string, find the second one in the same string starting at the index you found the first + it's len and so on.


问:
I don't have the whole project from git
I am new to git. I made a repo and added a friend of mine to also contribute. He pushes the changes. Then i pull them and when i open solution explorer in vs 2015 it shows up only the files he was working on, but not mine. I searched in the file explorer and my files ARE there. How to view them from vs?</p>

答:
It's likely that you simply don't have your files included in the appropriate *.csproj file for your project. This actually sometimes happens to me as well. If you just right-click on the appropriate parent folder(s) in VS and select "add existing", that usually is all you need to do.

Post back if that doesn't fix the issue.

Title: I don't have the whole project from git


问:
How to dynamically create the same input fields upon user request (clicking Add More button)?
On the Job Positions  page, I would like to have 3 groups of input fields which are static so user can enter Job Name, Job Description, etc. respectively.

I'm not sure what the best approach is but I imagine there would be a button at the bottom which says "Add More". When user clicks on this, it would reveal (say 3) more groups of the input fields. And after entering up to 6 groups, the user can still click "Add More" (perhaps as many times as permissible) to bring up 3 more each time it is clicked.

Hope this is clear enough. I'm slowly getting into the AJAX world.

Thank you.

答: I would recommend using a framework such as jQuery and use a particular function called append, very easy to do and you'll find the framework simplifying alot of thing for you in the future as well</p>


问:
How do I automatically save my preferences on as3?
How do I automatically save my game and load the game with a button in actionScrpt3?

I am developing a game and I want to leave the game when I can save it automatically and that when I start it again, a button appears in the main menu and it loads the game where it was saved

Thank You

答:
Simplest way would be to save a file onto the application storage directory on a specific action (like on a save button click, or after a certain time period etc).

Depending on your needs you could choose to save a simple text file, an XML file or even a JSON file, whichever suits your need. Simply insert your data into the file and save it then to the application storage directory.

Following is the code to save a simple text file onto the application storage directory:

```<code>var dataToSave:String = "Some data to be saved.....";
var file:File = File.applicationStorageDirectory.resolvePath("savedUserInfo.txt");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes(dataToSave);
stream.close();
</code>```

You can put the above code inside a method and call in when you want to save data.

And on application startup each time you could check if the file exists and load in the data and perform your actions accordingly to resume/restore game state.

Here's the code to load the file:

```<code>var file:File = File.applicationStorageDirectory.resolvePath("savedUserInfo.txt");
if(file.exists){
    var stream:FileStream = new FileStream();
    stream.open(file, FileMode.READ);
    var data:String = stream.readUTF();
    stream.close();
    //perform your operations to restore/resume game state
}else{
    //there was no saved game file. Resume normal game bootup.
}
</code>```

As I said, this maybe the simplest way to save a file onto the application storage directory. Depending on your needs, you may want to choose a more code friendly format like JSON or XML to save and load your data. Of course there will be some code changes based on what format you decide.

Also, make sure you have permissions set to write the file. To do this you need to add the following, in particular the "WRITE_EXTERNAL_STORAGE" line, to your application descriptor.

```<code><android>
    <manifestAdditions><![CDATA[
        <manifest android:installLocation="auto">
            <uses-permission android:name="android.permission.INTERNET"/>
            <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        </manifest>
    ]]></manifestAdditions>
</android>
</code>```

Hope this helps. Cheers.

Body:
Simplest way would be to save a file onto the application storage directory on a specific action (like on a save button click, or after a certain time period etc).

Depending on your needs you could choose to save a simple text file, an XML file or even a JSON file, whichever suits your need. Simply insert your data into the file and save it then to the application storage directory.

Following is the code to save a simple text file onto the application storage directory:

var dataToSave:String = "Some data to be saved.....";
var file:File = File.applicationStorageDirectory.resolvePath("savedUserInfo.txt");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes(dataToSave);
stream.close();

You can put the above code inside a method and call in when you want to save data.

And on application startup each time you could check if the file exists and load in the data and perform your actions accordingly to resume/restore game state.

Here's the code to load the file:

var file:File = File.applicationStorageDirectory.resolvePath("savedUserInfo.txt");
if(file.exists){
    var stream:FileStream = new FileStream();
    stream.open(file, FileMode.READ);
    var data:String = stream.readUTF();
    stream.close();
    //perform your operations to restore/resume game state
}else{
    //there was no saved game file. Resume normal game bootup.
}

As I said, this maybe the simplest way to save a file onto the application storage directory. Depending on your needs, you may want to choose a more code friendly format like JSON or XML to save and load your data. Of course there will be some code changes based on what format you decide.

Also, make sure you have permissions set to write the file. To do this you need to add the following, in particular the "WRITE_EXTERNAL_STORAGE" line, to your application descriptor.

<android>
    <manifestAdditions><![CDATA[
        <manifest android:installLocation="auto">
            <uses-permission android:name="android.permission.INTERNET"/>
            <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        </manifest>
    ]]></manifestAdditions>
</android>

Hope this helps. Cheers.


问:
Table rows toggle() with jQuery and DataTable
I have a small table with some rows and some of them with extra information which will be show or hide with jQuery toggle(). Everything works fine but I can't use DataTable in this context. My jQuery looks like this:

```<code>

    $(document).ready(function() {
        $('#serien tbody').on('click', 'td.details-control', function () {

            if ( $(this).hasClass('showDetails') ) {
                $(this).closest('tr').removeClass('shown');
            }
            else {
                $(this).closest('tr').addClass('shown');
            }

            $(this).toggleClass('showDetails');
            $(this).parent().next().toggle();
        });
    });

</code>```

But when I want to use DataTable - in the easiest way like https://datatables.net/examples/advanced_init/events_live.html

```<code>

    $(document).ready(function() {
        var table = $('#serien').DataTable();

        $('#serien tbody').on('click', 'td.details-control', function () {
            var data = table.row( this ).data();
            alert( 'You clicked on '+data[0]+'\'s row' );
        } );
    } );

</code>```

It won't work, can somebody give me a hint?

答:
You are using this to pass into the row() function. this in this context points to the td. You should be passing in that td's parent tr element instead.

```<code>$(document).ready(function() {
    var table = $('#serien').DataTable();

    $('#serien tbody').on('click', 'td.details-control', function () {
        var data = table.row( $(this).closest("tr")[0] ).data();
        alert( 'You clicked on '+data[0]+'\'s row' );
    } );
} );
</code>```

Body:
I have a small table with some rows and some of them with extra information which will be show or hide with jQuery toggle(). Everything works fine but I can't use DataTable in this context. My jQuery looks like this:

    $(document).ready(function() {
        $('#serien tbody').on('click', 'td.details-control', function () {

            if ( $(this).hasClass('showDetails') ) {
                $(this).closest('tr').removeClass('shown');
            }
            else {
                $(this).closest('tr').addClass('shown');
            }

            $(this).toggleClass('showDetails');
            $(this).parent().next().toggle();
        });
    });

But when I want to use DataTable - in the easiest way like https://datatables.net/examples/advanced_init/events_live.html

    $(document).ready(function() {
        var table = $('#serien').DataTable();

        $('#serien tbody').on('click', 'td.details-control', function () {
            var data = table.row( this ).data();
            alert( 'You clicked on '+data[0]+'\'s row' );
        } );
    } );

It won't work, can somebody give me a hint?

Body:
You are using this to pass into the row() function. this in this context points to the td. You should be passing in that td's parent tr element instead.

$(document).ready(function() {
    var table = $('#serien').DataTable();

    $('#serien tbody').on('click', 'td.details-control', function () {
        var data = table.row( $(this).closest("tr")[0] ).data();
        alert( 'You clicked on '+data[0]+'\'s row' );
    } );
} );


问:
Why does my "marshaller" have to be "static"?
I'm trying to "marshall" and "unmarshall" objects, in their own class, and using a "Marshaller".

The Main method :

```<code>public class Main {

    public static void main(String[] args) {
        new Something();
    }
}
</code>```

The "Something" class that will produce the instances to marshall or unmarshall :

```<code>import java.io.File;
import java.io.Serializable;

public class Something implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public int value = 2;
    private File file = new File("something.serial");
    private static Marshaller marshaller = new Marshaller();

    Something() {

        value = 3;
        marshaller.marshalling(file, this);
        Something anotherThing = (Something) marshaller.unmarshalling(file);
        System.out.println(anotherThing.value);
    }
}
</code>```

Here is the Marshaller :

```<code>import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Marshaller {

    public Marshaller() {

}

    /**
     * Charge l'objet sérializé d'un fichier si il existe
     * @param file : le fichier à désérialiser
     * @return obj : l'instance d'objet désérialisé
     */
    public Object unmarshalling(File file) {
        Object obj = null;
        ObjectInputStream ois;
        try {
            BufferedInputStream bis = new BufferedInputStream(
            new FileInputStream(file));
            ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * Permet d'enregistrer un objet (settings, client...) dans un fichier
     * @param file : le fichier support de la sérialisation
     * @param obj : l'instance d'objet à sérialiser
     *
     */
    public void marshalling(File file, Object obj) {
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(
            new BufferedOutputStream(
            new FileOutputStream(file)));
            oos.writeObject(obj);
            oos.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

In the class Something, if my Marshaller isn't declared "static", I get a java.io.NotSerializableException. Why ?

Thank you for your answers to help me to understand.

Have a good day.

PS : Shall I use the word marshall or serialize ?

答:
When you serialize an object, all of the objects that are reachable from that object are stored as well, so all of them must be serializable. If you declare your class like:

```<code>public class Something implements Serializable {
    private static final long serialVersionUID = 1L;
    public int value = 2;
    private File file = new File("something.serial");
    private Marshaller marshaller = new Marshaller();
}
</code>```

Then reachable fields from any instance of class Something are value, file and marshaller, so jvm will try to serialize them as well, which requires each of them must be serializable, but class Marshaller is not, then exception happens.

When you declare a field as static, you make it a member of the class, not individual instance, since serialization only cares about the current state of instances, only data associated with a specific instance will be serilized, therefore all static fields are ignored and your program works OK.

If you do need a field be instance member but don't want it to be serialized, you need to declare it with keyword transient, then it'll be ignored during the serialization.

And for the word marshall and serialize, I'm not a native English speaker so I cann't tell too much about the difference between them, but personally I prefer serialize in this case, and use marshall when dealing JSON/XML from/to java objects.

Hope this could be helpful to you :-)

Body:
I'm trying to "marshall" and "unmarshall" objects, in their own class, and using a "Marshaller".

The Main method :

public class Main {

    public static void main(String[] args) {
        new Something();
    }
}

The "Something" class that will produce the instances to marshall or unmarshall :

import java.io.File;
import java.io.Serializable;

public class Something implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public int value = 2;
    private File file = new File("something.serial");
    private static Marshaller marshaller = new Marshaller();

    Something() {

        value = 3;
        marshaller.marshalling(file, this);
        Something anotherThing = (Something) marshaller.unmarshalling(file);
        System.out.println(anotherThing.value);
    }
}

Here is the Marshaller :

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Marshaller {

    public Marshaller() {

}

    /**
     * Charge l'objet sérializé d'un fichier si il existe
     * @param file : le fichier à désérialiser
     * @return obj : l'instance d'objet désérialisé
     */
    public Object unmarshalling(File file) {
        Object obj = null;
        ObjectInputStream ois;
        try {
            BufferedInputStream bis = new BufferedInputStream(
            new FileInputStream(file));
            ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * Permet d'enregistrer un objet (settings, client...) dans un fichier
     * @param file : le fichier support de la sérialisation
     * @param obj : l'instance d'objet à sérialiser
     *
     */
    public void marshalling(File file, Object obj) {
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(
            new BufferedOutputStream(
            new FileOutputStream(file)));
            oos.writeObject(obj);
            oos.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

In the class Something, if my Marshaller isn't declared "static", I get a java.io.NotSerializableException. Why ?

Thank you for your answers to help me to understand.

Have a good day.

PS : Shall I use the word marshall or serialize ?

Body:
When you serialize an object, all of the objects that are reachable from that object are stored as well, so all of them must be serializable. If you declare your class like:

public class Something implements Serializable {
    private static final long serialVersionUID = 1L;
    public int value = 2;
    private File file = new File("something.serial");
    private Marshaller marshaller = new Marshaller();
}

Then reachable fields from any instance of class Something are value, file and marshaller, so jvm will try to serialize them as well, which requires each of them must be serializable, but class Marshaller is not, then exception happens.

When you declare a field as static, you make it a member of the class, not individual instance, since serialization only cares about the current state of instances, only data associated with a specific instance will be serilized, therefore all static fields are ignored and your program works OK.

If you do need a field be instance member but don't want it to be serialized, you need to declare it with keyword transient, then it'll be ignored during the serialization.

And for the word marshall and serialize, I'm not a native English speaker so I cann't tell too much about the difference between them, but personally I prefer serialize in this case, and use marshall when dealing JSON/XML from/to java objects.

Hope this could be helpful to you :-)


问:
Does SWRL support enumeration statement for individuals?
I'm doing some SWRL rules in OWL ontology like this:

```<code>..., hasHazardCode(?a, H350) -> DangerousProduct(?a)
..., hasHazardCode(?a, H350i) -> DangerousProduct(?a)
..., hasHazardCode(?a, H400) -> DangerousProduct(?a)
..., hasHazardCode(?a, H401) -> DangerousProduct(?a)
......
</code>```

H350, H350i, H400 and H401 are some named individuals. As we can see that the pattern of these SWRL rules are similar. So I think maybe we can replace these rules with only one rule that goes like:

```<code>..., hasHazardCode(?a, {H350, H350i, H400, H401}) -> DangerousProduct(?a)
</code>```

I tried this syntax in the Rules tab in Protege, but it didn't work. Does SWRL have support for individual enumeration statement like that?

答:
This is possible with an OWL Class Expression of type "Range".

let myClass = the class of thing that have some hasHazardCode in range [H350, H350i, ... ] in hasHazardCode(?a, ?HValue) /\ Class(myClass, ?HValue) -> Class(DangerousProduct,?a)

Using the pellet java syntax, here how your example could be re-write:

```<code>    OWLObjectProperty myProperty = OWL.ObjectProperty("hasHazardCode");
    OWLObjectOneOf myRange = OWL.oneOf(OWL.Individual("H350"), OWL.Individual("H350i"), OWL.Individual("H400"), OWL.Individual("H401"));
    OWLClassExpression myClass = OWL.some(OWL.ObjectProperty("hasHazardCode"), myRange);

    SWRL.rule(
        SWRL.antecedent(
           SWRL.propertyAtom(myProperty, SWRL.variable("?a"), SWRL.variable("?HValue")),
           SWRL.classAtom(myClass, SWRL.variable("?HValue"))
        ),
        SWRL.consequent(SWRL.classAtom(OWL.Class("DangerousProduct"), SWRL.variable("?a")))
    );
</code>```

Body:
I'm doing some SWRL rules in OWL ontology like this:

..., hasHazardCode(?a, H350) -> DangerousProduct(?a)
..., hasHazardCode(?a, H350i) -> DangerousProduct(?a)
..., hasHazardCode(?a, H400) -> DangerousProduct(?a)
..., hasHazardCode(?a, H401) -> DangerousProduct(?a)
......

H350, H350i, H400 and H401 are some named individuals. As we can see that the pattern of these SWRL rules are similar. So I think maybe we can replace these rules with only one rule that goes like:

..., hasHazardCode(?a, {H350, H350i, H400, H401}) -> DangerousProduct(?a)

I tried this syntax in the Rules tab in Protege, but it didn't work. Does SWRL have support for individual enumeration statement like that?

Body:
This is possible with an OWL Class Expression of type "Range".

let myClass = the class of thing that have some hasHazardCode in range [H350, H350i, ... ] in hasHazardCode(?a, ?HValue) /\ Class(myClass, ?HValue) -> Class(DangerousProduct,?a)

Using the pellet java syntax, here how your example could be re-write:

    OWLObjectProperty myProperty = OWL.ObjectProperty("hasHazardCode");
    OWLObjectOneOf myRange = OWL.oneOf(OWL.Individual("H350"), OWL.Individual("H350i"), OWL.Individual("H400"), OWL.Individual("H401"));
    OWLClassExpression myClass = OWL.some(OWL.ObjectProperty("hasHazardCode"), myRange);

    SWRL.rule(
        SWRL.antecedent(
           SWRL.propertyAtom(myProperty, SWRL.variable("?a"), SWRL.variable("?HValue")),
           SWRL.classAtom(myClass, SWRL.variable("?HValue"))
        ),
        SWRL.consequent(SWRL.classAtom(OWL.Class("DangerousProduct"), SWRL.variable("?a")))
    );


问:
EmberJS router and external library
I have currently difficulties in using the EmberJS router and an external library.
Using the EmberJS router, the routing functionality works perfectly.
Also the inclusion of the external library within a component works as expected.

BUT the combination of both is not working.

In detail: the library (pdf.js) is manipulating the DOM and inserting anchor tags while scrolling through the document. These anchor tags work fine. But if I try to "catch" the event and use the EmberJS routing functionality, it is not working!
I cannot create an eventlistener in the DidRender() function and use preventDefault, because the elements are not present during the time of execution of DidRender.

Did anyone face the same issue or maybe has a solution for this problem?

Cheers,
Franz

答:
I am assuming you are using a component,

Init 3-rd party lib inside didInsertElement hook instead of DidRender.

The DOM is ready inside that hook and you can assess the component HTML element using this.$().

What does this mean?

But if I try to "catch" the event and use the EmberJS routing functionality, it is not working!

DOM manipulation operations are all sync operations. Bind the your own even handler inside the didInsertElement hook too, but pay close attention to your this context.

Title: EmberJS router and external library


问:
Angularjs way, conditionally to generate new form and append it to the page or state change
i am  new to angularjs,
and wonder What is the angularjs way to complete such a task as conditionally generating or showing the form ?
Lets say

```<code>$scope.counter = function(){
   if ($scope.years < 5){

    // what is here? append or should  return true and use ng-if directive in html?

    }}
</code>```

Thank you

答:
Ideally you should do it from HTML file via by ng-if\ng-show\ng-hide directives.

Like below (years should be part of controller\component):

```<code><div ng-if="years<5"> html code </div>
</code>```

Body:
i am  new to angularjs,
and wonder What is the angularjs way to complete such a task as conditionally generating or showing the form ?
Lets say

$scope.counter = function(){
   if ($scope.years < 5){

    // what is here? append or should  return true and use ng-if directive in html?

    }}

Thank you

Body:
Ideally you should do it from HTML file via by ng-if\ng-show\ng-hide directives.

Like below (years should be part of controller\component):

<div ng-if="years<5"> html code </div>


答:
You could use both negative and positive lookahead.

var str = '"resourceType": "com.bmc.arsys.rx.services.view.domain.ContainerViewComponentDefinition"';
    console.log(str.match(/(?!")\w+(?=")/)[0]);```

Title: Combining one or more characters (`+?`) and positive lookahead (?=)


问:
Clojure : Idiomatic (when (predicate x) x)
In the same way you can convert

```<code>(if (something)
    something
    fallback)
</code>```

into the shorter version :

```<code>(or something fallback)
</code>```

I was wondering if there is a composition function/elegant builtin for threading a value into the validation of a predicate like :

```<code>(when (pred x)
  x)
</code>```

Into something like

```<code>(thread-pred pred x)
</code>```

I could easily build some function or macro to do it, but I'd rather not go NIH here.

答:
It took me way longer than I care to admit - but here you go:

Beware this might explode.

```<code>(defmacro -pred->
  [pred body]
  `(when (~pred ~body) ~body))

(macroexpand-1 '(-pred-> odd? 3))
=> (clojure.core/when (odd? 3) 3)

(-pred-> odd? 3)
=> 3

(-pred-> odd? 2)
=> nil
</code>```

EDIT: as the comments correctly pointed out it would be wiser to let-bind the body to an autogensym like so:

```<code>(defmacro -pred->
  [pred body]
  `(let [b# ~body]
     (when (~pred b#) b#)))
</code>```

Body:
In the same way you can convert

(if (something)
    something
    fallback)

into the shorter version :

(or something fallback)

I was wondering if there is a composition function/elegant builtin for threading a value into the validation of a predicate like :

(when (pred x)
  x)

Into something like

(thread-pred pred x)

I could easily build some function or macro to do it, but I'd rather not go NIH here.

Body:
It took me way longer than I care to admit - but here you go:

Beware this might explode.

(defmacro -pred->
  [pred body]
  `(when (~pred ~body) ~body))

(macroexpand-1 '(-pred-> odd? 3))
=> (clojure.core/when (odd? 3) 3)

(-pred-> odd? 3)
=> 3

(-pred-> odd? 2)
=> nil

EDIT: as the comments correctly pointed out it would be wiser to let-bind the body to an autogensym like so:

(defmacro -pred->
  [pred body]
  `(let [b# ~body]
     (when (~pred b#) b#)))


问:
How to convert this query to doctrine DQL
```<code>SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
    select 1
    from `distribution_mobiletokens`
    where userid = '20'
    and deviceid = dm.deviceid
    and created > dm.created
    )
</code>```

What this query does is selects all mobiletokens where the user id is equal to 20 and the deviceid is the same but chooses the newest apntoken for the device.

My database looks like below.

For more information on this query, I got this answer from another question I asked here(How to group by in SQL by largest date (Order By a Group By))

Things I've Tried

```<code>$mobiletokens = $em->createQueryBuilder()
          ->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
          ->from('AppBundle:MobileTokens', 'u')
          ->leftJoin('u.companyId', 'company')
          ->leftJoin('u.userId', 'user')
          ->where('u.status = 1 and user.id = :userid')
          ->setParameter('userid',(int)$jsondata['userid'])
          ->groupby('u.apntoken')
          ->getQuery()
          ->getResult();

       //@JA - Get the list of all the apn tokens we need to send the message to.
       foreach($mobiletokens as $tokenobject){
           $deviceTokens[] = $tokenobject["apntoken"];
           echo $tokenobject["apntoken"]."\n";
       }

        die();
</code>```

This gives me the incorrect response of

```<code>63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone
</code>```

Any help here is appreciated!

Other Information

Data with SELECT * FROM

Data after using the SQL I provided up top.

答:
You could use a subselect created with the querybuilder as example:</p>

```<code>public function selectNewAppToken($userId)
{
    // get an ExpressionBuilder instance, so that you
    $expr = $this->_em->getExpressionBuilder();

    // create a subquery in order to take all address records for a specified user id
    $sub = $this->_em->createQueryBuilder()
        ->select('a')
        ->from('AppBundle:MobileTokens', 'a')
        ->where('a.user = dm.id')
        ->andWhere('a.deviceid = dm.deviceid')
        ->andWhere($expr->gte('a.created','dm.created'));

    $qb = $this->_em->createQueryBuilder()
        ->select('dm')
        ->from('AppBundle:MobileTokens', 'dm')
        ->where($expr->not($expr->exists($sub->getDQL())))
        ->andWhere('dm.user = :user_id')
        ->setParameter('user_id', $userId);

    return $qb->getQuery()->getResult();
}
</code>```

Body:
SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
    select 1
    from `distribution_mobiletokens`
    where userid = '20'
    and deviceid = dm.deviceid
    and created > dm.created
    )

What this query does is selects all mobiletokens where the user id is equal to 20 and the deviceid is the same but chooses the newest apntoken for the device.

My database looks like below.

For more information on this query, I got this answer from another question I asked here(How to group by in SQL by largest date (Order By a Group By))

Things I've Tried

$mobiletokens = $em->createQueryBuilder()
          ->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
          ->from('AppBundle:MobileTokens', 'u')
          ->leftJoin('u.companyId', 'company')
          ->leftJoin('u.userId', 'user')
          ->where('u.status = 1 and user.id = :userid')
          ->setParameter('userid',(int)$jsondata['userid'])
          ->groupby('u.apntoken')
          ->getQuery()
          ->getResult();

       //@JA - Get the list of all the apn tokens we need to send the message to.
       foreach($mobiletokens as $tokenobject){
           $deviceTokens[] = $tokenobject["apntoken"];
           echo $tokenobject["apntoken"]."\n";
       }

        die();

This gives me the incorrect response of

63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone

Any help here is appreciated!

Other Information

Data with SELECT * FROM

Data after using the SQL I provided up top.

Body:
You could use a subselect created with the querybuilder as example:

public function selectNewAppToken($userId)
{
    // get an ExpressionBuilder instance, so that you
    $expr = $this->_em->getExpressionBuilder();

    // create a subquery in order to take all address records for a specified user id
    $sub = $this->_em->createQueryBuilder()
        ->select('a')
        ->from('AppBundle:MobileTokens', 'a')
        ->where('a.user = dm.id')
        ->andWhere('a.deviceid = dm.deviceid')
        ->andWhere($expr->gte('a.created','dm.created'));

    $qb = $this->_em->createQueryBuilder()
        ->select('dm')
        ->from('AppBundle:MobileTokens', 'dm')
        ->where($expr->not($expr->exists($sub->getDQL())))
        ->andWhere('dm.user = :user_id')
        ->setParameter('user_id', $userId);

    return $qb->getQuery()->getResult();
}


问:
Struct isn't readable in AnotherSource but in Source
I have a structure declared in header and implemented in source. Source file can perform on my struct variable, but my main can't see it. Why ?

A.hpp

```<code>#include "stdafx.h"
#include <iostream>
#include <stdlib.h>

class A {
public:
    struct myStruct {
        int someInt;
    } myStructVar;

    void loadA();
};
</code>```

A.cpp

```<code>#include "stdafx.h"
#include "A.h"

void A::loadA() {
    myStructVar.someInt = 10;
    std::cout << myStructVar.someInt << std::endl; // 10 OK
}
</code>```

Main.cpp

```<code>#include "stdafx.h"
#include "A.h"

int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    a.loadA();
    std::cout << myStructVar.someInt() << std::endl; // Error: identifier "myStructVar" is undefined
    system("PAUSE");
    return 0;
}
</code>```

Error is is Main.cpp

Error: identifier "myStructVar" is undefined.

Thanks.

答:
Change

```<code>std::cout << myStructVar.someInt() << std::endl;
</code>```

To

```<code>std::cout << a.myStructVar.someInt << std::endl;
</code>```

Body:
I have a structure declared in header and implemented in source. Source file can perform on my struct variable, but my main can't see it. Why ?

A.hpp

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>

class A {
public:
    struct myStruct {
        int someInt;
    } myStructVar;

    void loadA();
};

A.cpp

#include "stdafx.h"
#include "A.h"

void A::loadA() {
    myStructVar.someInt = 10;
    std::cout << myStructVar.someInt << std::endl; // 10 OK
}

Main.cpp

#include "stdafx.h"
#include "A.h"

int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    a.loadA();
    std::cout << myStructVar.someInt() << std::endl; // Error: identifier "myStructVar" is undefined
    system("PAUSE");
    return 0;
}

Error is is Main.cpp

Error: identifier "myStructVar" is undefined.

Thanks.

Body:
Change

std::cout << myStructVar.someInt() << std::endl;

To

std::cout << a.myStructVar.someInt << std::endl;


问:
Reference all indexes in list and check for existence of value in python
I'm trying to create if block in my python3 script that checks if a value exists within a list I pull from JSON. The JSON data is below:

```<code>[
  {
    "id": 59616405645,
    "name": "Foo"
  },
  {
    "id": 990164054345,
    "name": "FindMe"
  },
  {
    "id": 2009167874,
    "name": "Bar"
  }
]
</code>```

I'm trying to determine whether or not the value of Bar exists within the list. To do so I'm doing the following which directly references the index:

```<code>if "FindMe" in m_orgs[1].values():
    print("Yo it's here")
else:
    print("Yo it's not here.")
</code>```

But the JSON data I'm pulling will always have different results and we will never know the index numbers, so direct reference will not work. How do I reference all indexes in a list at once?

答:
You can't reference all indexes at once, but you can loop through them, and stop as soon as you find the first existence. Something like:

```<code>found = any("findMe" in item.values() for item in m_orgs)
</code>```

This line will stop the execution when it finds the first True value. So worst case, it will look through every position and not find anything.

Body:
I'm trying to create if block in my python3 script that checks if a value exists within a list I pull from JSON. The JSON data is below:

[
  {
    "id": 59616405645,
    "name": "Foo"
  },
  {
    "id": 990164054345,
    "name": "FindMe"
  },
  {
    "id": 2009167874,
    "name": "Bar"
  }
]

I'm trying to determine whether or not the value of Bar exists within the list. To do so I'm doing the following which directly references the index:

if "FindMe" in m_orgs[1].values():
    print("Yo it's here")
else:
    print("Yo it's not here.")

But the JSON data I'm pulling will always have different results and we will never know the index numbers, so direct reference will not work. How do I reference all indexes in a list at once?

Body:
You can't reference all indexes at once, but you can loop through them, and stop as soon as you find the first existence. Something like:

found = any("findMe" in item.values() for item in m_orgs)

This line will stop the execution when it finds the first True value. So worst case, it will look through every position and not find anything.


问:
tikxml and Gradle
I'm trying to use tikxml library.
I put this in build.gradle (app) :

```<code>apply plugin: 'com.neenbedankt.android-apt'
...
dependencies {
    ...
    // tikxml
    compile "com.tickaroo.tikxml:annotation:${libs.tikxml}"
    compile "com.tickaroo.tikxml:core:${libs.tikxml}"
    apt "com.tickaroo.tikxml:processor:${libs.tikxml}"
}
</code>```

And this in my build.gradle (project) :

```<code>buildscript {
    ...
    dependencies {
        ...
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

ext {
    libs = [tikxml           : '0.8.9-SNAPSHOT']
}
</code>```

But I'm getting this error when I build the project :

Error:Could not find com.tickaroo.tikxml:processor:0.8.9-SNAPSHOT.
  Searched in the following locations:
      file:/opt/android-sdk/extras/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/maven-metadata.xml
      file:/opt/android-sdk/extras/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.pom
      file:/opt/android-sdk/extras/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.jar
      file:/opt/android-sdk/extras/google/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/maven-metadata.xml
      file:/opt/android-sdk/extras/google/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.pom
      file:/opt/android-sdk/extras/google/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.jar
      file:/opt/android-sdk/extras/android/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/maven-metadata.xml
      file:/opt/android-sdk/extras/android/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.pom
      file:/opt/android-sdk/extras/android/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.jar
      file:/opt/android-studio/gradle/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/maven-metadata.xml
      file:/opt/android-studio/gradle/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.pom
      file:/opt/android-studio/gradle/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.jar
      https://jcenter.bintray.com/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/maven-metadata.xml
      https://jcenter.bintray.com/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.pom
      https://jcenter.bintray.com/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.jar
  Required by:
      LVS.Training.Android.Lab.SimpleEpubReader:app:unspecified

I have no folder named m2repository in /opt/android-sdk/extras/. I checked the URL where Gradle tried to download the library (https://jcenter.bintray.com/com/tickaroo/tikxml/ and there no tickaroo subdir in com : https://jcenter.bintray.com/com/

Anybody knows if there is a problem with this library ?

答:
Since this is a SNAPSHOT release (which means it is not a stable 1.0 release),
you have to include the snapshot repository url in your build.gradle file (from where com.tickaroo.tikxml:processor:0.8.9-SNAPSHOT etc. will be downloaded):

You have to add the url "http://oss.sonatype.org/content/repositories/snapshots" to your repositories section of your root build.gradle file:

```<code>repositories {
  mavenCentral()
  maven {
    url 'http://oss.sonatype.org/content/repositories/snapshots'
  }
}
</code>```

Title: tikxml and Gradle

Body:
I'm trying to use tikxml library.
I put this in build.gradle (app) :

apply plugin: 'com.neenbedankt.android-apt'
...
dependencies {
    ...
    // tikxml
    compile "com.tickaroo.tikxml:annotation:${libs.tikxml}"
    compile "com.tickaroo.tikxml:core:${libs.tikxml}"
    apt "com.tickaroo.tikxml:processor:${libs.tikxml}"
}

And this in my build.gradle (project) :

buildscript {
    ...
    dependencies {
        ...
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

ext {
    libs = [tikxml           : '0.8.9-SNAPSHOT']
}

But I'm getting this error when I build the project :

Error:Could not find com.tickaroo.tikxml:processor:0.8.9-SNAPSHOT.
  Searched in the following locations:
      file:/opt/android-sdk/extras/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/maven-metadata.xml
      file:/opt/android-sdk/extras/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.pom
      file:/opt/android-sdk/extras/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.jar
      file:/opt/android-sdk/extras/google/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/maven-metadata.xml
      file:/opt/android-sdk/extras/google/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.pom
      file:/opt/android-sdk/extras/google/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.jar
      file:/opt/android-sdk/extras/android/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/maven-metadata.xml
      file:/opt/android-sdk/extras/android/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.pom
      file:/opt/android-sdk/extras/android/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.jar
      file:/opt/android-studio/gradle/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/maven-metadata.xml
      file:/opt/android-studio/gradle/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.pom
      file:/opt/android-studio/gradle/m2repository/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.jar
      https://jcenter.bintray.com/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/maven-metadata.xml
      https://jcenter.bintray.com/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.pom
      https://jcenter.bintray.com/com/tickaroo/tikxml/processor/0.8.9-SNAPSHOT/processor-0.8.9-SNAPSHOT.jar
  Required by:
      LVS.Training.Android.Lab.SimpleEpubReader:app:unspecified

I have no folder named m2repository in /opt/android-sdk/extras/. I checked the URL where Gradle tried to download the library (https://jcenter.bintray.com/com/tickaroo/tikxml/ and there no tickaroo subdir in com : https://jcenter.bintray.com/com/

Anybody knows if there is a problem with this library ?

Body:
Since this is a SNAPSHOT release (which means it is not a stable 1.0 release),
you have to include the snapshot repository url in your build.gradle file (from where com.tickaroo.tikxml:processor:0.8.9-SNAPSHOT etc. will be downloaded):

You have to add the url "http://oss.sonatype.org/content/repositories/snapshots" to your repositories section of your root build.gradle file:

repositories {
  mavenCentral()
  maven {
    url 'http://oss.sonatype.org/content/repositories/snapshots'
  }
}


问:
How to change the body of text for C# .NET RequestBin HTTP API?
hey guys I'm new to C# and I wanted to try out Request Bin after seeing it in another youtube video, however it was a PHP video, can any of you please tell me how I can implement a body of text into the request so I can see it on the site? thank you :D here's my current code.</p>

```<code>using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace RequestBinExample
{
   class Program
   {
     static void Main(string[] args)
     {
      var task = MakeRequest();
      task.Wait();

      var response = task.Result;
      var body = response.Content.ReadAsStringAsync().Result;
      Console.WriteLine(body);
    }

    private static async Task<HttpResponseMessage> MakeRequest()
    {
      var httpClient = new HttpClient();
      return await httpClient.GetAsync(new    Uri("http://requestb.in/1hui2vv1"));
    }
  }
}
</code>```

答:
```<code>class Program
{
    static void Main(string[] args)
    {
        var task = MakeRequest();
        task.Wait();

        var response = task.Result;
        var body = response.Content.ReadAsStringAsync().Result;
        Console.WriteLine(body);
        Console.Read();
    }

    private static async Task<HttpResponseMessage> MakeRequest()
    {
        var httpClient = new HttpClient();
        HttpContent requestContent = new StringContent("I am the message body");

        return await httpClient.PostAsync("https://requestb.in/188bhf01", requestContent);
    }
}
</code>```

I think this should do the trick.

Body:
hey guys I'm new to C# and I wanted to try out Request Bin after seeing it in another youtube video, however it was a PHP video, can any of you please tell me how I can implement a body of text into the request so I can see it on the site? thank you :D here's my current code.

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace RequestBinExample
{
   class Program
   {
     static void Main(string[] args)
     {
      var task = MakeRequest();
      task.Wait();

      var response = task.Result;
      var body = response.Content.ReadAsStringAsync().Result;
      Console.WriteLine(body);
    }

    private static async Task<HttpResponseMessage> MakeRequest()
    {
      var httpClient = new HttpClient();
      return await httpClient.GetAsync(new    Uri("http://requestb.in/1hui2vv1"));
    }
  }
}

Body:
class Program
{
    static void Main(string[] args)
    {
        var task = MakeRequest();
        task.Wait();

        var response = task.Result;
        var body = response.Content.ReadAsStringAsync().Result;
        Console.WriteLine(body);
        Console.Read();
    }

    private static async Task<HttpResponseMessage> MakeRequest()
    {
        var httpClient = new HttpClient();
        HttpContent requestContent = new StringContent("I am the message body");

        return await httpClient.PostAsync("https://requestb.in/188bhf01", requestContent);
    }
}

I think this should do the trick.


问:
android FragmentActivity is invisible but onStop() is not called
Does anyone have the problem of a FragmentActivity, when call finish() on itself, it only calls onPause() and doesn't call onStop() and onDestroy(). But the activity is invisible on the device?

I don't see any other error log.

According to the android activity life cycle, If the activity is invisible, then it should call onstop(). But it is not. It is happened on Android 5.0.

I found the cause, but i don't understand why it happened.

A extends FragmentActivity, it is defined launchmode: singleTask.

B extends Activity, it is defined  android:launchMode="singleInstance", android:theme="@android:style/Theme.NoDisplay" in Manifest.

C extends FragmentActivity, it is defined launchmode: singleTask,  android:excludeFromRecents="true", android:taskAffinity="com.xxx.xxxx.xxx" in Manifest.

D is a serviceConnector singleton instance. What handles the event from the binding service callback.

The scenario is:

```<code>Step1 : A calls B with startActivity(intent).
Step2 : B calls serviceConnector to send event to the service process and finish itself. It has no UI. It is set as Theme.NoDisplay.
Step3 : Service callbacks init C if not exist yet and C handle service responses event.
Step4 : In one case, C calls B with startActivity(intent)
Step5 : B calls serviceConnection to send event. No UI. C will onPause and when B finsih itself, C onResume()
Step6: Service callbacks and found C already exist, no create new one. C handle service respsonses.
Step7: user click button on C Fragement activity, C calls finish itself, But only C got onPause(). C couldn't be finish, no onStop(), no onDestroy() is called.
</code>```

I don't understand C calls B, B finsih itself, C resume and C finish itself later has the issue.

答:
It only calls onPause() and doesn't call onStop() and onDestroy()

If from Activity1 you launch Activity2 with a background that has transparency, then onPause() of Activity1 will be called, but onStop() will not.

Body:
Does anyone have the problem of a FragmentActivity, when call finish() on itself, it only calls onPause() and doesn't call onStop() and onDestroy(). But the activity is invisible on the device?

I don't see any other error log.

According to the android activity life cycle, If the activity is invisible, then it should call onstop(). But it is not. It is happened on Android 5.0.

I found the cause, but i don't understand why it happened.

A extends FragmentActivity, it is defined launchmode: singleTask.

B extends Activity, it is defined  android:launchMode="singleInstance", android:theme="@android:style/Theme.NoDisplay" in Manifest.

C extends FragmentActivity, it is defined launchmode: singleTask,  android:excludeFromRecents="true", android:taskAffinity="com.xxx.xxxx.xxx" in Manifest.

D is a serviceConnector singleton instance. What handles the event from the binding service callback.

The scenario is:

Step1 : A calls B with startActivity(intent).
Step2 : B calls serviceConnector to send event to the service process and finish itself. It has no UI. It is set as Theme.NoDisplay.
Step3 : Service callbacks init C if not exist yet and C handle service responses event.
Step4 : In one case, C calls B with startActivity(intent)
Step5 : B calls serviceConnection to send event. No UI. C will onPause and when B finsih itself, C onResume()
Step6: Service callbacks and found C already exist, no create new one. C handle service respsonses.
Step7: user click button on C Fragement activity, C calls finish itself, But only C got onPause(). C couldn't be finish, no onStop(), no onDestroy() is called.

I don't understand C calls B, B finsih itself, C resume and C finish itself later has the issue.


问:
Combining one or more characters (`+?`) and positive lookahead (?=)
I have a string like this:

```<code>"resourceType": "com.bmc.arsys.rx.services.view.domain.ContainerViewComponentDefinition",
</code>```

I want to match the first double quote in this part:

```<code>"resourceType":
</code>```

So I construct a regexp to find ", then one or more characters (greedy) followed by ": literals, so I have the first part:

```<code>".+?
</code>```

and then I want to add positive lookahead part ?=":

```<code>".+??=":
</code>```

but I get syntax error. What's the syntax for combining them?

答: This simple one should suit your needs: "[^"]+"

Body:
I have a string like this:

"resourceType": "com.bmc.arsys.rx.services.view.domain.ContainerViewComponentDefinition",

I want to match the first double quote in this part:

"resourceType":

So I construct a regexp to find ", then one or more characters (greedy) followed by ": literals, so I have the first part:

".+?

and then I want to add positive lookahead part ?=":

".+??=":

but I get syntax error. What's the syntax for combining them?