问:
Angular 7 cancelled HTTP request not reflecting in Core API
I've got a DotNet Core 2.2 api endpoint that accepts a CancellationToken and periodically checks it while processing.  When I call that endpoint from my Angular 7 front end, then cancel the request (by unsubscribing), the cancellation token doesn't reflect the cancelled status.  Is there a step I'm missing in order for the token to be cancelled correctly?  Or is this totally not now the request cancelling process works?

Note that I can see the initial request fire, the api doing work, and the request cancelling (via the Chrome devtools Network tab).

Angular 7

private sub: Subscription;
doWork(): void {
  // calls to http client, sending a POST
  this.sub = this.service.doWork([1,2,3,4]).subscribe();
}
cancelWork(): void {
  if(this.sub && !this.sub.closed) {
    this.sub.unsubscribe();
  }
}
```

<p><strong>API</strong></p>

<pre class="lang-cs prettyprint-override"><code>[HttpPost("DoWork")]
public async Task<ActionResult<HttpResponseMessage>> DoWork([FromBody] List<int> ids, CancellationToken cancellationToken)
{
    foreach(var id in ids)
    {
        // ---> cancellationToken.IsCancellationRequested is always false   <-------
        cancellationToken.ThrowIfCancellationRequested();

        await doLongRunningTask(id);
    }
}
</code>```

答: cancellationToken.ThrowIfCancellationRequested(); throws if the request was canceled by the moment of evaluating this line so it just won't work in your case. usually some async utils provide APIs for passing that token that they will use internally

Body:
I've got a DotNet Core 2.2 api endpoint that accepts a CancellationToken and periodically checks it while processing.  When I call that endpoint from my Angular 7 front end, then cancel the request (by unsubscribing), the cancellation token doesn't reflect the cancelled status.  Is there a step I'm missing in order for the token to be cancelled correctly?  Or is this totally not now the request cancelling process works?

Note that I can see the initial request fire, the api doing work, and the request cancelling (via the Chrome devtools Network tab).

Angular 7

private sub: Subscription;
doWork(): void {
  // calls to http client, sending a POST
  this.sub = this.service.doWork([1,2,3,4]).subscribe();
}
cancelWork(): void {
  if(this.sub && !this.sub.closed) {
    this.sub.unsubscribe();
  }
}

API

[HttpPost("DoWork")]
public async Task<ActionResult<HttpResponseMessage>> DoWork([FromBody] List<int> ids, CancellationToken cancellationToken)
{
    foreach(var id in ids)
    {
        // ---> cancellationToken.IsCancellationRequested is always false   <-------
        cancellationToken.ThrowIfCancellationRequested();

        await doLongRunningTask(id);
    }
}


来源: stackexchange

问:
Schedule Jenkins job using Jenkins Rest API
I have a Jenkins job which is scheduled for a specific time. I want to modify that timing programmatically.

I tried to modify the build by installing Schedule Build plugin and modify it using http://jenkins_url/job/jobname/build?delay=3344sec. But this will put the job in quiet period which holds the java thread. I'm looking to modify the Schedule entry without putting it to quiet period.

答:
I can't get it to work, but the source code for the plugin references a "schedule" url action and a "date" param.

I tried something like:

```<code>http://localhost:8080/job/jobname/job/develop/schedule?date=2020-02-20
</code>```

Which it didn't reject but I can't see a build.

below is the source code of the action performed when the button is pressed to schedule:

```<code>var newRequest = function() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

var sumbitScheduleRequest = function(absoluteUrl, quietPeriodInSeconds, isJobParameterized){

    if(isJobParameterized){
        // if job has parameters, redirect to build page, so user can set parameters
        window.location = absoluteUrl + "build?delay=" + quietPeriodInSeconds + "sec";
    }else{
        // if job has NO parameters, submit build directly
        var csrfCrumb;
        var csrfRequest = newRequest();
        csrfRequest.onreadystatechange = function() {
            if (csrfRequest.readyState === 4) {
                if (csrfRequest.status === 200 || csrfRequest.status === 201) {
                    csrfCrumb = JSON.parse(csrfRequest.responseText);
                } else {
                    // csrf might be deactivated
                }

                // do the actual submit
                var xmlhttp = newRequest();
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState === 4) {
                        if (xmlhttp.status === 200 || xmlhttp.status === 201) {
                            window.location = absoluteUrl;
                            return false;
                        } else {
                            window.location = absoluteUrl;
                            return false;
                        }
                    }
                };
                xmlhttp.open("POST", absoluteUrl + "build?delay=" + quietPeriodInSeconds + "sec", true);
                if (csrfCrumb) {
                    xmlhttp.setRequestHeader(csrfCrumb.crumbRequestField, csrfCrumb.crumb)
                }
                xmlhttp.send();
            }
        };

        csrfRequest.open('GET', rootURL + '/crumbIssuer/api/json', false);
        csrfRequest.send();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can't get it to work, but the source code for the plugin references a "schedule" url action and a "date" param.

I tried something like:

http://localhost:8080/job/jobname/job/develop/schedule?date=2020-02-20

Which it didn't reject but I can't see a build.

below is the source code of the action performed when the button is pressed to schedule:

var newRequest = function() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

var sumbitScheduleRequest = function(absoluteUrl, quietPeriodInSeconds, isJobParameterized){

    if(isJobParameterized){
        // if job has parameters, redirect to build page, so user can set parameters
        window.location = absoluteUrl + "build?delay=" + quietPeriodInSeconds + "sec";
    }else{
        // if job has NO parameters, submit build directly
        var csrfCrumb;
        var csrfRequest = newRequest();
        csrfRequest.onreadystatechange = function() {
            if (csrfRequest.readyState === 4) {
                if (csrfRequest.status === 200 || csrfRequest.status === 201) {
                    csrfCrumb = JSON.parse(csrfRequest.responseText);
                } else {
                    // csrf might be deactivated
                }

                // do the actual submit
                var xmlhttp = newRequest();
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState === 4) {
                        if (xmlhttp.status === 200 || xmlhttp.status === 201) {
                            window.location = absoluteUrl;
                            return false;
                        } else {
                            window.location = absoluteUrl;
                            return false;
                        }
                    }
                };
                xmlhttp.open("POST", absoluteUrl + "build?delay=" + quietPeriodInSeconds + "sec", true);
                if (csrfCrumb) {
                    xmlhttp.setRequestHeader(csrfCrumb.crumbRequestField, csrfCrumb.crumb)
                }
                xmlhttp.send();
            }
        };

        csrfRequest.open('GET', rootURL + '/crumbIssuer/api/json', false);
        csrfRequest.send();
    }
}


问:
Using React hooks, how to update the state of part of an object in an array of objects
If I have the following state using React hooks:

```<code>const [users, setUsers] = useState([
        {
            user: "Bob",
            cost: 25,
        },
{
            user: "Paul",
            cost: 30,
        },
    ])
</code>```

I can map over the state like so:

```<code>{users.map((user, index) => (
                                <div key={index}>
                                        <input
                                            type="text"
                                            value={user.user}
                                            name="user"
                                            onChange={handleFoo(index)}
                                        />
                                        <input
                                            type="number"
                                            value={user.cost}
                                            name="cost"
                                            onChange={handleFoo(index)}
                                        />

                                </div>
                            ))}
</code>```

Yet I am struggling to update the state when only one input is edited.

```<code>const handleFoo = index => e => {
        const { name, value } = e.target
        let newArr = [...users]
        newArr[index] = {[name]: value }
        setUsers(newArr)
    }
</code>```

The above semi works, but it only updates one parameter. Using the above the state would be updated as per below (for example)

```<code>[
        {
            user: "Bob",
            cost: 25,
        },
{
            cost: 30,
        },
    ]
</code>```

How can i spread the [index] and only update the section I need?

A.

答:
Just need to make use of the spread syntax to copy the old user before adding the updated property:</p>

```<code>newArr[index] = {
 ...users[index],
 [name]: value
}
</code>```

Body:
If I have the following state using React hooks:

const [users, setUsers] = useState([
        {
            user: "Bob",
            cost: 25,
        },
{
            user: "Paul",
            cost: 30,
        },
    ])

I can map over the state like so:

{users.map((user, index) => (

                                        <input
                                            type="text"
                                            value={user.user}
                                            name="user"
                                            onChange={handleFoo(index)}
                                        />
                                        <input
                                            type="number"
                                            value={user.cost}
                                            name="cost"
                                            onChange={handleFoo(index)}
                                        />

                            ))}

Yet I am struggling to update the state when only one input is edited.

const handleFoo = index => e => {
        const { name, value } = e.target
        let newArr = [...users]
        newArr[index] = {[name]: value }
        setUsers(newArr)
    }

The above semi works, but it only updates one parameter. Using the above the state would be updated as per below (for example)

[
        {
            user: "Bob",
            cost: 25,
        },
{
            cost: 30,
        },
    ]

How can i spread the [index] and only update the section I need?

A.

Body:
Just need to make use of the spread syntax to copy the old user before adding the updated property:

newArr[index] = {
 ...users[index],
 [name]: value
}


问:
Stop people uploading malicious PHP files via forms
I have an upload form created in php on my website where people are able to upload a zip file. The zip file is then extracted and all file locations are added to a database. The upload form is for people to upload pictures only, obviously, with the files being inside the zip folder I cant check what files are being uploaded until the file has been extracted. I need a piece of code which will delete all the files which aren't image formats (.png, .jpeg, etc). I'm really worried about people being able to upload malicious php files, big security risk! I also need to be aware of people changing the extensions of php files trying to get around this security feature.

This is the original script I used http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/

This is the code which actually extracts the .zip file:

```<code>function openZip($file_to_open) {
    global $target;

    $zip = new ZipArchive();
    $x = $zip->open($file_to_open);
    if($x === true) {
        $zip->extractTo($target);
        $zip->close();

        unlink($file_to_open);
    } else {
        die("There was a problem. Please try again!");
    }
}
</code>```

Thanks, Ben.

OwnerDisplayName: Ben McRae

ContentLicense: CC BY-SA 3.0

Body:
I have an upload form created in php on my website where people are able to upload a zip file. The zip file is then extracted and all file locations are added to a database. The upload form is for people to upload pictures only, obviously, with the files being inside the zip folder I cant check what files are being uploaded until the file has been extracted. I need a piece of code which will delete all the files which aren't image formats (.png, .jpeg, etc). I'm really worried about people being able to upload malicious php files, big security risk! I also need to be aware of people changing the extensions of php files trying to get around this security feature.

This is the original script I used http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/

This is the code which actually extracts the .zip file:

function openZip($file_to_open) {
    global $target;

    $zip = new ZipArchive();
    $x = $zip->open($file_to_open);
    if($x === true) {
        $zip->extractTo($target);
        $zip->close();

        unlink($file_to_open);
    } else {
        die("There was a problem. Please try again!");
    }
}

Thanks, Ben.

LastEditorDisplayName: gs

Body:
Im really worried about people being able to upload malicious php files, big security risk!

Tip of the iceberg!

i also need to be aware of people changing the extensions of php files trying to get around this security feature.

Generally changing the extensions will stop PHP from interpreting those files as scripts. But that's not the only problem. There are more things than ‘...php’ that can damage the server-side; ‘.htaccess’ and files with the X bit set are the obvious ones, but by no means all you have to worry about. Even ignoring the server-side stuff, there's a huge client-side problem.

For example if someone can upload an ‘.html’ file, they can include a <script> tag in it that hijacks a third-party user's session, and deletes all their uploaded files or changes their password or something. This is a classic cross-site-scripting (XSS) attack.

Plus, thanks to the ‘content-sniffing’ behaviours of some browsers (primarily IE), a file that is uploaded as ‘.gif’ can actually contain malicious HTML such as this. If IE sees telltales like (but not limited to) ‘<html>’ near the start of the file it can ignore the served ‘Content-Type’ and display as HTML, resulting in XSS.

Plus, it's possible to craft a file that is both a valid image your image parser will accept, and contains embedded HTML. There are various possible outcomes depending on the exact version of the user's browser and the exact format of the image file (JPEGs in particular have a very variable set of possible header formats). There are mitigations coming in IE8, but that's no use for now, and you have to wonder why they can't simply stop doing content-sniffing, you idiots MS instead of burdening us with shonky non-standard extensions to HTTP headers that should have Just Worked in the first place.

I'm falling into a rant again. I'll stop. Tactics for serving user-supplied images securely:

1: Never store a file on your server's filesystem using a filename taken from user input. This prevents bugs as well as attacks: different filesystems have different rules about what characters are allowable where in a filename, and it's much more difficult than you might think to ‘sanitise’ filenames.

Even if you took something very restrictive like “only ASCII letters”, you still have to worry about too-long, too-short, and reserved names: try to save a file with as innocuous a name as “com.txt” on a Windows server and watch your app go down. Think you know all the weird foibles of path names of every filesystem on which your app might run? Confident?

Instead, store file details (such as name and media-type) in the database, and use the primary key as a name in your filestore (eg. “74293.dat”). You then need a way to serve them with different apparent filenames, such as a downloader script spitting the file out, a downloader script doing a web server internal redirect, or URL rewriting.

2: Be very, very careful using ZipArchive. There have been traversal vulnerabilities in extractTo of the same sort that have affected most naive path-based ZIP extractors. In addition, you lay yourself open to attack from ZIP bombs. Best to avoid any danger of bad filenames, by stepping through each file entry in the archive (eg. using zip_read/zip_entry_*) and checking its details before manually unpacking its stream to a file with known-good name and mode flags, that you generated without the archive's help. Ignore the folder paths inside the ZIP.

3: If you can load an image file and save it back out again, especially if you process it in some way in between (such as to resize/thumbnail it, or add a watermark) you can be reasonably certain that the results will be clean. Theoretically it might be possible to make an image that targeted a particular image compressor, so that when it was compressed the results would also look like HTML, but that seems like a very difficult attack to me.

4: If you can get away with serving all your images as downloads (ie. using ‘Content-Disposition: attachment’ in a downloader script), you're probably safe. But that might be too much of an inconvenience for users. This can work in tandem with (3), though, serving smaller, processed images inline and having the original higher-quality images available as a download only.

5: If you must serve unaltered images inline, you can remove the cross-site-scripting risk by serving them from a different domain. For example use ‘images.example.com’ for untrusted images and ‘www.example.com’ for the main site that holds all the logic. Make sure that cookies are limited to only the correct virtual host, and that the virtual hosts are set up so they cannot respond on anything but their proper names (see also: DNS rebinding attacks). This is what many webmail services do.

In summary, user-submitted media content is a problem.

In summary of the summary, AAAARRRRRRRGGGGHHH.

ETA re comment:

at the top you mentioned about 'files with the X bit set', what do you mean by that?

I can't speak for ZipArchive.extractTo() as I haven't tested it, but many extractors, when asked to dump files out of an archive, will recreate [some of] the Unix file mode flags associated with each file (if the archive was created on a Unix and so actually has mode flags). This can cause you permissions problems if, say, owner read permission is missing. But it can also be a security problem if your server is CGI-enabled: an X bit can allow the file to be interpreted as a script and passed to any script interpreter listed in the hashbang on the first line.

i thought .htaccess had to be in the main root directory, is this not the case?

Depends how Apache is set up, in particular the AllowOverride directive. It is common for general-purpose hosts to AllowOverride on any directory.

what would happen if someone still uploaded a file like ../var/www/wr_dir/evil.php?

I would expect the leading ‘..’ would be discarded, that's what other tools that have suffered the same vulnerability have done.

But I still wouldn't trust extractTo() against hostile input, there are too many weird little filename/directory-tree things that can go wrong — especially if you're expecting ever to run on Windows servers. zip_read() gives you much greater control over the dearchiving process, and hence the attacker much less.

OwnerDisplayName: bobince

LastEditorDisplayName: bobince


问:
JavaScript: location.replace doesn't work in the function
I'm making a web app and I'm struggling with replacing the page.
In the function myPage(), when I put the location.replace("file.html"); in the start, it works if I don't insert inputs on the web app, but when I put the location.replace("file.html"); in the if statement then doesn't work at all, and is there where I need to put the location.replace.

Please help me.

js code:

```<code>    var submit = document.getElementById("submit");
    submit.addEventListener("click",myPage);

    function myPage(){
        //location.replace("file.html"); // here this is working
        var name=document.formId.nameRadio.value;//name="abc"
        if (name=="abc"){
            location.replace("file.html");//but here not
        }
    }

</code>```

html code:

```<code><form  id="formId" name="formId" >
        <label>sth </label><br><br>
        <label for="name"> name  </label>
        <input type="text" id="name" name="name" required>
        <fieldset>
        <legend>sth</legend>
        <ul class="class-radio" >
            <li> <input  type="radio" name="nameRadio" id="abc" value="abc" required><label for="abc">abc</label></li>
            <li> <input  type="radio" name="nameRadio" id="cdf" value="cdf"><label for="cdf">cdf</label></li>

        </ul>
        </fieldset>
        <input id="submit" type="submit" value="next" >
        </form>
</code>```

答:
You can stop the usual form submission by adding preventDefault() to your onClick function.

var submit = document.getElementById("submit");
submit.addEventListener("click", myPage);

function myPage(e) {
  //prevent form submission
  e.preventDefault();

  var name = document.getElementById('formId').nameRadio.value;
  if (name == "abc") {
    location.replace("file.html");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="formId" name="formId">
  <label>sth </label><br><br>
  <label for="name"> name  </label>
  <input type="text" id="name" name="name" required>
  <fieldset>
    <legend>sth</legend>
    <ul class="class-radio">
      <li> <input type="radio" name="nameRadio" id="abc" value="abc" required><label for="abc">abc</label></li>
      <li> <input type="radio" name="nameRadio" id="cdf" value="cdf"><label for="cdf">cdf</label></li>

    </ul>
  </fieldset>
  <input id="submit" type="submit" value="next">
</form></code>```

Body:
I'm making a web app and I'm struggling with replacing the page.
In the function myPage(), when I put the location.replace("file.html"); in the start, it works if I don't insert inputs on the web app, but when I put the location.replace("file.html"); in the if statement then doesn't work at all, and is there where I need to put the location.replace.

Please help me.

js code:

    var submit = document.getElementById("submit");
    submit.addEventListener("click",myPage);

    function myPage(){
        //location.replace("file.html"); // here this is working
        var name=document.formId.nameRadio.value;//name="abc"
        if (name=="abc"){
            location.replace("file.html");//but here not
        }
    }

html code:

<form  id="formId" name="formId" >
        sth

         name
        <input type="text" id="name" name="name" required>
        <fieldset>
        <legend>sth</legend>

 <input  type="radio" name="nameRadio" id="abc" value="abc" required>abc

 <input  type="radio" name="nameRadio" id="cdf" value="cdf">cdf

        </fieldset>
        <input id="submit" type="submit" value="next" >
        </form>

Body:
You can stop the usual form submission by adding preventDefault() to your onClick function.

var submit = document.getElementById("submit");
submit.addEventListener("click", myPage);

function myPage(e) {
  //prevent form submission
  e.preventDefault();

  var name = document.getElementById('formId').nameRadio.value;
  if (name == "abc") {
    location.replace("file.html");
  }
}

<form id="formId" name="formId">
  <label>sth </label><br><br>
  <label for="name"> name  </label>
  <input type="text" id="name" name="name" required>
  <fieldset>
    <legend>sth</legend>
    <ul class="class-radio">
      <li> <input type="radio" name="nameRadio" id="abc" value="abc" required><label for="abc">abc</label></li>
      <li> <input type="radio" name="nameRadio" id="cdf" value="cdf"><label for="cdf">cdf</label></li>

    </ul>
  </fieldset>
  <input id="submit" type="submit" value="next">
</form>


问:
Get actual count of matches in Azure Search
Azure Search returns a maximum of 1,000 results at a time. For paging on the client, I want the total count of matches in order to be able to display the correct number of paging buttons at the bottom and in order to be able to tell the user how many results there are. However, if there are over a thousand, how do I get the actual count? All I know is that there were at least 1,000 matches.

I need to be able to do this from within the SDK.

答:
For REST clients using the POST API, just include "count": "true" to the payload. You get the count in @odata.count.

Ref: https://learn.microsoft.com/en-us/rest/api/searchservice/search-documents


问:
Create a collection in mongodb stitch app
Is there a way to create a collection in MongoDB stitch app in react-native. I tried the normal MongoDB way

```<code>const stitchClient = Stitch.getAppClient(myAppID);
const mongodb = stitchClient.getServiceClient(RemoteMongoClient.factory, "mongodb-atlas")
    .db("ToDo");
        // console.log("mongodb is ", mongodb);
mongodb.createCollection("test", (err, res) => {
   if (err) {
       throw ("Error creating a collection : ", err);
   }
   console.log("Collection creted");
});

</code>```

But then react-native keeps giving this error :

TypeError: undefined is not a function(near 'MongoDB.createCollection...')

答:
But then react-native keeps giving this error

RemoteMongoDatabase does not have createCollection method. It's not a function that you could call/invoke.

Conceptually, worth mentioning that MongoDB Stitch prevents access to your data by default. First you need to create a collection first, and define it's Rules. You can create a collection either manually from mongo shell or from Stitch Rules UI. Please note that you must define at least one role before you can successfully query a collection.

See also Stitch: Define Roles And Permissions for step by step procedure on how to create Rules.

Body:
Is there a way to create a collection in MongoDB stitch app in react-native. I tried the normal MongoDB way

const stitchClient = Stitch.getAppClient(myAppID);
const mongodb = stitchClient.getServiceClient(RemoteMongoClient.factory, "mongodb-atlas")
    .db("ToDo");
        // console.log("mongodb is ", mongodb);
mongodb.createCollection("test", (err, res) => {
   if (err) {
       throw ("Error creating a collection : ", err);
   }
   console.log("Collection creted");
});

But then react-native keeps giving this error :

TypeError: undefined is not a function(near 'MongoDB.createCollection...')


问:
How can I search for a code snippet in all folders/files of a site?
How can I search for a code snippet in all folders/files of a site?

I can't find the line of code I'm looking for. It's a large site and looking through file by file is not reasonable. How can I go about finding this snippet?

Other details:

It's a Drupal site

I use a Mac

Code editing software I currently have avail: Coda, Text Wrangler, Dreamweaver

Any help would be incredibly appreciated.

答:
While grep via a terminal will work wonderfully for OSX and *nix users, those on Windows may find that grep isn't available.

For Windows users who want a solution to this, you can try the following:

1) Using cygwin (http://www.cygwin.com), which can be installed with grep

or

2) Grabbing a copy of grepWin (http://tools.tortoisesvn.net/grepWin.html); a grep tool with a frontend UI.


答:
It seems that you want more control over the form submit.

You can change the input type from submit to button; Also rename that button to avoid confusion with submit method of the form.

You can also simplify the code, by using the click event directly on the input.

Here is something you can try:

```<code><html>
   <body>
      <form id="formId" name="formId">
         <label>sth</label><br><br>
         <label for="name">name</label>
         <input type="text" id="name" name="name" required>
         <fieldset>
            <legend>sth</legend>
            <ul class="class-radio">
               <li><input type="radio" name="nameRadio" id="abc" value="abc" required><label for="abc">abc</label></li>
               <li><input type="radio" name="nameRadio" id="cdf" value="cdf"><label for="cdf">cdf</label></li>
            </ul>
         </fieldset>
         <input id="btnSubmit" type="button" value="next" onclick="mySubmit()">
      </form>
      <script>
           function mySubmit()
           {
               var name = document.formId.nameRadio.value;
               if (name == "abc"){
                   location.replace("file.html");
               } else {
                   // Submit a form
                   document.formId.submit();
               }
           }
      </script>
   </body>
</html>
</code>```

Title: JavaScript: location.replace doesn't work in the function

Body:
It seems that you want more control over the form submit.

You can change the input type from submit to button; Also rename that button to avoid confusion with submit method of the form.

You can also simplify the code, by using the click event directly on the input.

Here is something you can try:

<html>
   <body>
      <form id="formId" name="formId">
         <label>sth</label><br><br>
         <label for="name">name</label>
         <input type="text" id="name" name="name" required>
         <fieldset>
            <legend>sth</legend>
            <ul class="class-radio">
               <li><input type="radio" name="nameRadio" id="abc" value="abc" required><label for="abc">abc</label></li>
               <li><input type="radio" name="nameRadio" id="cdf" value="cdf"><label for="cdf">cdf</label></li>
            </ul>
         </fieldset>
         <input id="btnSubmit" type="button" value="next" onclick="mySubmit()">
      </form>
      <script>
           function mySubmit()
           {
               var name = document.formId.nameRadio.value;
               if (name == "abc"){
                   location.replace("file.html");
               } else {
                   // Submit a form
                   document.formId.submit();
               }
           }
      </script>
   </body>
</html>


问:
How to append content to an array in a php file
I have a PHP file a configuration file coming from a Yii2 message translation file which contains this:

```<code>return[

   'Juventus' => '尤文图斯',
   'Milan' => '米兰',
];
</code>```

I want to append values to the array so i can get something like below:

```<code>return[

  'Juventus' => '尤文图斯',
  'Milan' => '米兰',
  'Chelsea' => '切尔西',
];
</code>```

Note: Another element added to the array
But then below is the result i got rather

```<code>return[

  'Juventus' => '尤文图斯',
  'Milan' => '米兰',
];

'Chelsea' => '切尔西',
</code>```

The new element rather was added outside of the array

I'm using file_put_contents() to append the file like this..

```<code>file_put_contents($file, "'Chelsea' => '切尔西'," . PHP_EOL, FILE_APPEND);
</code>```

How can i solve the problem or what's the better away of doing this.. Any help will be appreciated

答:
Read the file, insert the line you want before the ] line, and write the result back to the file.

```<code>$contents = file_get_contents($file);
str_replace('];', "'Chelsea' => '切尔西'," . PHP_EOL . '];', $contents);
file_put_contents($file, $contents);
</code>```

It would probably be better if you made it a data file instead of a PHP script. You can format using json_encode() or serialize().

Body:
I have a PHP file a configuration file coming from a Yii2 message translation file which contains this:

return[

   'Juventus' => '尤文图斯',
   'Milan' => '米兰',
];

I want to append values to the array so i can get something like below:

return[

  'Juventus' => '尤文图斯',
  'Milan' => '米兰',
  'Chelsea' => '切尔西',
];

Note: Another element added to the array
But then below is the result i got rather

return[

  'Juventus' => '尤文图斯',
  'Milan' => '米兰',
];

'Chelsea' => '切尔西',

The new element rather was added outside of the array

I'm using file_put_contents() to append the file like this..

file_put_contents($file, "'Chelsea' => '切尔西'," . PHP_EOL, FILE_APPEND);

How can i solve the problem or what's the better away of doing this.. Any help will be appreciated

Body:
Read the file, insert the line you want before the ] line, and write the result back to the file.

$contents = file_get_contents($file);
str_replace('];', "'Chelsea' => '切尔西'," . PHP_EOL . '];', $contents);
file_put_contents($file, $contents);

It would probably be better if you made it a data file instead of a PHP script. You can format using json_encode() or serialize().


问:
Tail multiple logs fluentd
I'm trying to tail multiple logs in fluentd with the following configuration: </p>

```<code><source>
  type tail
  tag es.workers.worker1

  format /^\[(?<timestamp>.*? .*?) (?<log_level>[INFO|ERROR][^\]]*)\] (?<message>.*)$/

  path /var/log/upstart/worker1.log
  pos_file /var/lib/fluentd/pos/-var-log-upstart-worker1.log.pos

</source>
<source>
  type tail
  tag es.workers.worker2

  format /^\[(?<timestamp>.*? .*?) (?<log_level>[INFO|ERROR][^\]]*)\] (?<message>.*)$/

  path /var/log/upstart/worker2.log
  pos_file /var/lib/fluentd/pos/-var-log-upstart-worker2.log.pos

</source>
<source>
  type tail
  tag es.workers.worker3

  format /^\[(?<timestamp>.*? .*?) (?<log_level>[INFO|ERROR][^\]]*)\] (?<message>.*)$/

  path /var/log/upstart/worker3.log
  pos_file /var/lib/fluentd/pos/-var-log-upstart-worker3.log.pos

</source>
<source>
  type tail
  tag es.workers.worker4

  format /^\[(?<timestamp>.*? .*?) (?<log_level>[INFO|ERROR][^\]]*)\] (?<message>.*)$/

  path /var/log/upstart/worker4.log
  pos_file /var/lib/fluentd/pos/-var-log-upstart-worker4.log.pos

</source>
</code>```

<p>This isn't working. Usually (but not always), I'm only getting logs of the first file. Sometimes it's a different file, but it's always only one. Any ideas as to what's going on? I'm not getting any meaningful errors in the fluentd error log. </p>

答:
tailing multiple files can be done like this (the tag will be based in the file name)

```<code><source>
  @type tail
  @id in_tail_container_logs
  path /var/lib/docker/containers/*/*-json.log
  pos_file /fluentd/log/containers.log.pos
  time_format "%Y-%m-%dT%H:%M:%S.%L%Z"
  keep_time_key true
  read_from_head true
  tag "docker.*"
  format json
</source>
</code>```

or like this

```<code><source>
  @type tail
  @id in_tail_fos_logs
  @label @LOGS
  path /www/web/log/*.log,/www/web2/log/*.log,/www/web3/log/*.log
  exclude_path ["/www/web/log/logstash_*.log"]
  pos_file /var/log/td-agent/logs.log.pos
  time_format "%Y-%m-%dT%H:%M:%S.%L%Z"
  read_from_head true
  tag "rowlogs.*"
  format none
</source>
</code>```

Title: Tail multiple logs fluentd

Body:
I'm trying to tail multiple logs in fluentd with the following configuration:

<source>
  type tail
  tag es.workers.worker1

  format /^\[(?<timestamp>.*? .*?) (?<log_level>[INFO|ERROR][^\]]*)\] (?<message>.*)$/

  path /var/log/upstart/worker1.log
  pos_file /var/lib/fluentd/pos/-var-log-upstart-worker1.log.pos

</source>
<source>
  type tail
  tag es.workers.worker2

  format /^\[(?<timestamp>.*? .*?) (?<log_level>[INFO|ERROR][^\]]*)\] (?<message>.*)$/

  path /var/log/upstart/worker2.log
  pos_file /var/lib/fluentd/pos/-var-log-upstart-worker2.log.pos

</source>
<source>
  type tail
  tag es.workers.worker3

  format /^\[(?<timestamp>.*? .*?) (?<log_level>[INFO|ERROR][^\]]*)\] (?<message>.*)$/

  path /var/log/upstart/worker3.log
  pos_file /var/lib/fluentd/pos/-var-log-upstart-worker3.log.pos

</source>
<source>
  type tail
  tag es.workers.worker4

  format /^\[(?<timestamp>.*? .*?) (?<log_level>[INFO|ERROR][^\]]*)\] (?<message>.*)$/

  path /var/log/upstart/worker4.log
  pos_file /var/lib/fluentd/pos/-var-log-upstart-worker4.log.pos

</source>

This isn't working. Usually (but not always), I'm only getting logs of the first file. Sometimes it's a different file, but it's always only one. Any ideas as to what's going on? I'm not getting any meaningful errors in the fluentd error log.

Body:
tailing multiple files can be done like this (the tag will be based in the file name)

<source>
  @type tail
  @id in_tail_container_logs
  path /var/lib/docker/containers/*/*-json.log
  pos_file /fluentd/log/containers.log.pos
  time_format "%Y-%m-%dT%H:%M:%S.%L%Z"
  keep_time_key true
  read_from_head true
  tag "docker.*"
  format json
</source>

or like this

<source>
  @type tail
  @id in_tail_fos_logs
  @label @LOGS
  path /www/web/log/*.log,/www/web2/log/*.log,/www/web3/log/*.log
  exclude_path ["/www/web/log/logstash_*.log"]
  pos_file /var/log/td-agent/logs.log.pos
  time_format "%Y-%m-%dT%H:%M:%S.%L%Z"
  read_from_head true
  tag "rowlogs.*"
  format none
</source>


问:
Darksky Loop through one year of daily data - Datetime Error
I attempt to loop through daily weather data in 2019 using forecastiopy but the error keeps showing. Not sure what the problem is.

```<code>import pandas as pd
import requests
import json
from forecastiopy import *
from datetime import date, timedelta, datetime
import datetime

key = 'xxxxx'

city = [40.730610, -73.935242]
start = datetime.datetime(2019, 1, 1)

for day in range(1,365):
    fio = ForecastIO.ForecastIO(key,
                        units=ForecastIO.ForecastIO.UNITS_SI,
                        lang=ForecastIO.ForecastIO.LANG_ENGLISH,
                        latitude=city[0],
                        longitude=city[1],
                        time=start+datetime.timedelta(day))
    daily = FIODaily.FIODaily(fio)
    print ('Max Temperature', daily.get_day(day)['temperatureMax'])
    print ('Min Temperature:', daily.get_day(day)['temperatureMin'])
    print ('Precipitation Pobability:', daily.get_day(day)['precipProbability'])
    print ('Precipitation Intensity', daily.get_day(day)['precipIntensity'])
</code>```

The error shown is below.

答:
```<code>ForecastIO.ForecastIO(key,
    ...,
    time=start+datetime.timedelta(day))
</code>```

Here, the time argument is supposed to be a string that is directly mapped to the Dark Sky API:

time

Either be a UNIX time (that is, seconds since midnight
  GMT on 1 Jan 1970) or a string formatted as follows:
  [YYYY]-[MM]-[DD]T[HH]:[MM]:[SS][timezone]. [...]

Therefore, you could format the datetime object using isoformat()

```<code>ForecastIO.ForecastIO(key,
    ...,
    time=(start+datetime.timedelta(day)).isoformat())
</code>```

Body:
I attempt to loop through daily weather data in 2019 using forecastiopy but the error keeps showing. Not sure what the problem is.

import pandas as pd
import requests
import json
from forecastiopy import *
from datetime import date, timedelta, datetime
import datetime

key = 'xxxxx'

city = [40.730610, -73.935242]
start = datetime.datetime(2019, 1, 1)

for day in range(1,365):
    fio = ForecastIO.ForecastIO(key,
                        units=ForecastIO.ForecastIO.UNITS_SI,
                        lang=ForecastIO.ForecastIO.LANG_ENGLISH,
                        latitude=city[0],
                        longitude=city[1],
                        time=start+datetime.timedelta(day))
    daily = FIODaily.FIODaily(fio)
    print ('Max Temperature', daily.get_day(day)['temperatureMax'])
    print ('Min Temperature:', daily.get_day(day)['temperatureMin'])
    print ('Precipitation Pobability:', daily.get_day(day)['precipProbability'])
    print ('Precipitation Intensity', daily.get_day(day)['precipIntensity'])

The error shown is below.

Body:
ForecastIO.ForecastIO(key,
    ...,
    time=start+datetime.timedelta(day))

Here, the time argument is supposed to be a string that is directly mapped to the Dark Sky API:

time

Either be a UNIX time (that is, seconds since midnight
  GMT on 1 Jan 1970) or a string formatted as follows:
  [YYYY]-[MM]-[DD]T[HH]:[MM]:[SS][timezone]. [...]

Therefore, you could format the datetime object using isoformat()

ForecastIO.ForecastIO(key,
    ...,
    time=(start+datetime.timedelta(day)).isoformat())


问:
How to stub assets in Sprockets 4 without breaking everything?
I have a few different stylesheets that are supposed to be mutually exclusive, let's call them light.css.scss and dark.css.scss. Up until now, my asset pipeline consisted of:

Creating the files in the app/assets/stylesheets folder:

```<code>application.css
light.css.scss
dark.css.scss
</code>```

Including them in my initializers/assets.rb:

```<code>Rails.application.config.assets.precompile += %w( light.css.scss )
Rails.application.config.assets.precompile += %w( dark.css.scss )
</code>```

Stubbing them out in my application.css file:

```<code>/*
 *= require_self
 *= require_tree .
 *= stub dark.css.scss
 *= stub light.css.scss
 */
</code>```

And then manually requiring them when needed:

```<code><% if subdomain == "light" %>
  <%= stylesheet_link_tag "light" %>
<% else %>
  <%= stylesheet_link_tag "dark" %>
<% end %>
</code>```

This worked great, but then I upgraded my Sprockets gem to 4.0, and everything broke. It turns out I need a assets/config/manifest.js file, but literally the only information I can find on that file is this, where the guy says he couldn't find any info on it either and that his app worked fine with a blank one. With a blank file, I'm getting errors like this:

```<code>#<ActionView::Template::Error: Asset `favicons/dark.png` was not declared to be precompiled in production.
</code>```

implying the manifest file is responsible for precompiling all assets. But when I input the boiler plate code into it:

```<code>#manifest.js
//= link_tree ../images
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css
</code>```

I get this:

```<code>#<ActionView::Template::Error: couldn't find file 'dark.css.scss' with type 'text/css'
</code>```

And I get all sorts of similar unfound file errors no matter what I do. I don't get errors when I unstub the stylesheet files from my application.css, but then the styles all mix together and it's a design nightmare. I gather that application.css is "hiding" the files and then manifest.js is confused when it can't find them, but I don't know what to do about it. I tried unstubbing them from application.css and stubbing them in manifest.js, but that didn't work either. What's really weird is I can't find any information about how the manifest.js file is supposed to work.

Anyone know how I can keep my stylesheet files stubbed and not break my whole pipeline?

答:
The answer actually turned out to be pretty simple, the problem was the require_tree . in my application.css. I just deleted everything in it, and added my stylesheets one by one in manifest.js, using .css not .css.scss, like so:

```<code>//= link dark.css
//= link light.css
</code>```

and then included the files as needed, as before. Now they're both precompiled but don't interfere with each other.

Body:
I have a few different stylesheets that are supposed to be mutually exclusive, let's call them light.css.scss and dark.css.scss. Up until now, my asset pipeline consisted of:

Creating the files in the app/assets/stylesheets folder:

application.css
light.css.scss
dark.css.scss

Including them in my initializers/assets.rb:

Rails.application.config.assets.precompile += %w( light.css.scss )
Rails.application.config.assets.precompile += %w( dark.css.scss )

Stubbing them out in my application.css file:

/*
 *= require_self
 *= require_tree .
 *= stub dark.css.scss
 *= stub light.css.scss
 */

And then manually requiring them when needed:

<% if subdomain == "light" %>
  <%= stylesheet_link_tag "light" %>
<% else %>
  <%= stylesheet_link_tag "dark" %>
<% end %>

This worked great, but then I upgraded my Sprockets gem to 4.0, and everything broke. It turns out I need a assets/config/manifest.js file, but literally the only information I can find on that file is this, where the guy says he couldn't find any info on it either and that his app worked fine with a blank one. With a blank file, I'm getting errors like this:

#<ActionView::Template::Error: Asset `favicons/dark.png` was not declared to be precompiled in production.

implying the manifest file is responsible for precompiling all assets. But when I input the boiler plate code into it:

#manifest.js
//= link_tree ../images
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css

I get this:

#<ActionView::Template::Error: couldn't find file 'dark.css.scss' with type 'text/css'

And I get all sorts of similar unfound file errors no matter what I do. I don't get errors when I unstub the stylesheet files from my application.css, but then the styles all mix together and it's a design nightmare. I gather that application.css is "hiding" the files and then manifest.js is confused when it can't find them, but I don't know what to do about it. I tried unstubbing them from application.css and stubbing them in manifest.js, but that didn't work either. What's really weird is I can't find any information about how the manifest.js file is supposed to work.

Anyone know how I can keep my stylesheet files stubbed and not break my whole pipeline?

Body:
The answer actually turned out to be pretty simple, the problem was the require_tree . in my application.css. I just deleted everything in it, and added my stylesheets one by one in manifest.js, using .css not .css.scss, like so:

//= link dark.css
//= link light.css

and then included the files as needed, as before. Now they're both precompiled but don't interfere with each other.


问:
How to do "call by reference" in Java?

How to do "call by reference" in Java?  (Assume that we are using that term in the same way that it has been used in peer-reviewed CS literature since the 1960's; see this Wikipedia page for a simple explanation.)

Since Java doesn't support pointers, how is it possible to call a function by reference in Java like we do in C and C++??

答:
Real pass-by-reference is impossible in Java. Java passes everything by value, including references. But you can simulate it with container Objects.

Use any of these as a method parameter:

an array

a Collection

an AtomicXYZ class

And if you change its contents in a method, the changed contents will be available to the calling context.

Oops, you apparently mean calling a method by reference. This is also not possible in Java, as methods are no first-level citizens in Java. This may change in JDK 8, but for the time being, you will have to use interfaces to work around this limitation.

```<code>public interface Foo{
    void doSomeThing();
}

public class SomeFoo implements Foo{
    public void doSomeThing(){
       System.out.println("foo");
    }
}

public class OtherFoo implements Foo{
    public void doSomeThing(){
       System.out.println("bar");
    }
}
</code>```

Use Foo in your code, so you can easily substitute SomeFoo with OtherFoo.

Title: How to do "call by reference" in Java?

Body:
Real pass-by-reference is impossible in Java. Java passes everything by value, including references. But you can simulate it with container Objects.

Use any of these as a method parameter:

an array

a Collection

an AtomicXYZ class

And if you change its contents in a method, the changed contents will be available to the calling context.

Oops, you apparently mean calling a method by reference. This is also not possible in Java, as methods are no first-level citizens in Java. This may change in JDK 8, but for the time being, you will have to use interfaces to work around this limitation.

public interface Foo{
    void doSomeThing();
}

public class SomeFoo implements Foo{
    public void doSomeThing(){
       System.out.println("foo");
    }
}

public class OtherFoo implements Foo{
    public void doSomeThing(){
       System.out.println("bar");
    }
}

Use Foo in your code, so you can easily substitute SomeFoo with OtherFoo.


问:
flutter app - firebase public access security rules
I'm making a simple app using firestore data but am thoroughly confused about security. Every course I took says maybe they'll "get to it later" but they never do.

So, to allow public access - ie; anyone that installs the app can read all the documents, but not write, is this all I need to do:

```<code>match /{document=**} {
  allow read;
}
</code>```

This is very confusing, I don't have users or require a login.

答: You are correct. That will allow anybody to read any part of your database.</p>

Body:
I'm making a simple app using firestore data but am thoroughly confused about security. Every course I took says maybe they'll "get to it later" but they never do.

So, to allow public access - ie; anyone that installs the app can read all the documents, but not write, is this all I need to do:

match /{document=**} {
  allow read;
}

This is very confusing, I don't have users or require a login.


问:
How to update all array value in document at once
Actually am trying to update an array in my document which have read property is set to false
here what i have done so far.

```<code>const user = await User.update(
    {
      _id: req.userData.id
    },
    {
      $set: {
        "notifications.$[elem].read": true
      },
      arrayFilters: [
        {
          "elem.read": false
        }
      ], multi : true
    }
  );
</code>```

but am getting an error

```<code>(node:12572) UnhandledPromiseRejectionWarning: MongoError: No array filter found for identifier 'elem' in path 'notifications.$[elem].read'
</code>```

答:
arrayFilters should be defined in options.

Try below code:

```<code>const user = await User.update(
  {
    _id: req.userData.id
  },
  {
    $set: {
      "notifications.$[elem].read": true
    }
  },
  {
    arrayFilters: [
      {
        "elem.read": false
      }
    ],
    multi : true
  }
);
</code>```

Body:
Actually am trying to update an array in my document which have read property is set to false
here what i have done so far.

const user = await User.update(
    {
      _id: req.userData.id
    },
    {
      $set: {
        "notifications.$[elem].read": true
      },
      arrayFilters: [
        {
          "elem.read": false
        }
      ], multi : true
    }
  );

but am getting an error

(node:12572) UnhandledPromiseRejectionWarning: MongoError: No array filter found for identifier 'elem' in path 'notifications.$[elem].read'

Body:
arrayFilters should be defined in options.

Try below code:

const user = await User.update(
  {
    _id: req.userData.id
  },
  {
    $set: {
      "notifications.$[elem].read": true
    }
  },
  {
    arrayFilters: [
      {
        "elem.read": false
      }
    ],
    multi : true
  }
);


问:
Show number of edges between two nodes on plot
I am making a network graph from a dataframe, as shown below

```<code>import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt

data = {'source': ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'],
        'target': ['B', 'B', 'C', 'D', 'E', 'B', 'C', 'E', 'F', 'C']}
df = pd.DataFrame(data=data)

G = nx.from_pandas_edgelist(df, source='source', create_using=nx.Graph(), target='target')
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos, with_labels=False, node_color='#1f0ee3', node_size=150,
                 edge_color='r', width=1, alpha=0.6, style='dashed',
                 font_color='k', font_size=15, font_weight=20)
# Offset for node labels
offset = 0.15
pos_labels = {}
keys = pos.keys()
for key in keys:
    x, y = pos[key]
    pos_labels[key] = (x, y + offset)
nx.draw_networkx_labels(G, pos=pos_labels, fontsize=2)

plt.xlim(-1.25, 1.25)
plt.ylim(-1.25, 1.25)
plt.title('Example')
plt.show()
</code>```

Which produces

What this doesn't show, however, is how may connections there are between each node. For example, A->B actually has three edges. nx.MultiGraph() will make some edges appear thicker than others, but what I actually want is the actual number of edges between two nodes displayed on the plot. Such that the label for 'B' is 'B (3)' (or something like that).

I know that nx.Graph.number_of_edges() can tell me the amount edges between nodes, but I want to display the number of edges between two nodes as a count on the plot programmatically.

答:
You can use nx.draw_networkx_edge_labels to label edges. Provide a dictionary with edges as keys and number of edges as value:

```<code>counts = df.groupby('source')['target'].value_counts().to_dict()
nx.draw_networkx_edge_labels(G, pos, edge_labels=counts)
</code>```

Body:
I am making a network graph from a dataframe, as shown below

import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt

data = {'source': ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'],
        'target': ['B', 'B', 'C', 'D', 'E', 'B', 'C', 'E', 'F', 'C']}
df = pd.DataFrame(data=data)

G = nx.from_pandas_edgelist(df, source='source', create_using=nx.Graph(), target='target')
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos, with_labels=False, node_color='#1f0ee3', node_size=150,
                 edge_color='r', width=1, alpha=0.6, style='dashed',
                 font_color='k', font_size=15, font_weight=20)
# Offset for node labels
offset = 0.15
pos_labels = {}
keys = pos.keys()
for key in keys:
    x, y = pos[key]
    pos_labels[key] = (x, y + offset)
nx.draw_networkx_labels(G, pos=pos_labels, fontsize=2)

plt.xlim(-1.25, 1.25)
plt.ylim(-1.25, 1.25)
plt.title('Example')
plt.show()

Which produces

What this doesn't show, however, is how may connections there are between each node. For example, A->B actually has three edges. nx.MultiGraph() will make some edges appear thicker than others, but what I actually want is the actual number of edges between two nodes displayed on the plot. Such that the label for 'B' is 'B (3)' (or something like that).

I know that nx.Graph.number_of_edges() can tell me the amount edges between nodes, but I want to display the number of edges between two nodes as a count on the plot programmatically.

Body:
You can use nx.draw_networkx_edge_labels to label edges. Provide a dictionary with edges as keys and number of edges as value:

counts = df.groupby('source')['target'].value_counts().to_dict()
nx.draw_networkx_edge_labels(G, pos, edge_labels=counts)


问:
Copy and paste after the last row VBA issue
I have a problem with my code. It does the trick of copy/paste correctly. However, I think there is something tricky. When I try to update my dynamic table it displays a message that the WB I'm currently working in already has data and if I want to replace it. When I choose "Yes/No" it immediately displays another column in my table that says that 81 registers are not been used in UTILITY. When I do everything by hand there are no problems. So, I guess there´s something wrong with my macro.

```<code>Option Explicit

Sub DailyTrans_MDM()

    Call CopyPaste
End Sub

Sub CopyPaste()

    Dim vFile As Variant
    Dim folderPath As String
    Dim wbCopyTo As Workbook
    Dim wsCopyTo As Worksheet
    Dim wbCopyFrom  As Workbook
    Dim wsCopyFrom As Worksheet

    vFile = Dir(folderPath & "*.xl*")
    Set wbCopyTo = ActiveWorkbook
    Set wsCopyTo = ActiveSheet
        Do While vFile <> ""
            Application.ScreenUpdating = False
            vFile = Application.GetOpenFilename("Daily Reports (*.xl*)," & "*.xl*", 1, "Select Report", "Open File", False)
            If TypeName(vFile) = "Boolean" Then
                Exit Sub
            Else
                Set wbCopyFrom = Workbooks.Open(vFile)
                Set wsCopyFrom = wbCopyFrom.Worksheets("ReporteCifrasControl")
            End If
    '--------------------------------------------------------------------------------------
            wsCopyFrom.Range("A2:M" & wsCopyFrom.Range("A" & Rows.Count).End(xlUp).row).Copy
            wsCopyTo.Range("A" & wsCopyTo.Range("A" & Rows.Count).End(xlUp).row + 1).PasteSpecial xlPasteValuesAndNumberFormats
            wbCopyFrom.Close SaveChanges:=False

            Dim rngCopy As Range, rngPaste As Range
                With ActiveSheet
                    Set rngCopy = .Range(.Range("A2"), Cells(2, Columns.Count).End(xlToLeft))
                    Set rngPaste = .Range(.Range("A2"), .Cells(Rows.Count, 1).End(xlUp)).Resize(, rngCopy.Columns.Count)
                End With
            rngCopy.Copy
            rngPaste.PasteSpecial xlPasteFormats
            Application.CutCopyMode = False
        Loop

End Sub

</code>```

答:
I believe you want to do this

Copy row 2 from Column A to Last Used Column (LC)

Paste this in the first Non-Used Row (LR) in Column A

```<code>Dim LC As Long
Dim LR As Long

With ActiveSheet
    LC = .Cells(2, .Columns.Count).End(xlToLeft).Column
    LR = .Range("A" & .Rows.Count).End(xlUp).Row

    Set rngCopy = .Range(.Cells(1, 2), .Cells(LC, 2))
    Set rngPaste = .Range("A" & LR)
End With

rngCopy.Copy
rngPaste.PasteSpecial xlPasteFormats
</code>```

You missed some objects to be qualified in your code. No point in using the With Block if you are not going to use the With Block

Just realized you have multiple copy/pastes in your code. If this is the wrong one, use the format here to modify the other one.

Body:
I have a problem with my code. It does the trick of copy/paste correctly. However, I think there is something tricky. When I try to update my dynamic table it displays a message that the WB I'm currently working in already has data and if I want to replace it. When I choose "Yes/No" it immediately displays another column in my table that says that 81 registers are not been used in UTILITY. When I do everything by hand there are no problems. So, I guess there´s something wrong with my macro.

Option Explicit

Sub DailyTrans_MDM()

    Call CopyPaste
End Sub

Sub CopyPaste()

    Dim vFile As Variant
    Dim folderPath As String
    Dim wbCopyTo As Workbook
    Dim wsCopyTo As Worksheet
    Dim wbCopyFrom  As Workbook
    Dim wsCopyFrom As Worksheet

    vFile = Dir(folderPath & "*.xl*")
    Set wbCopyTo = ActiveWorkbook
    Set wsCopyTo = ActiveSheet
        Do While vFile <> ""
            Application.ScreenUpdating = False
            vFile = Application.GetOpenFilename("Daily Reports (*.xl*)," & "*.xl*", 1, "Select Report", "Open File", False)
            If TypeName(vFile) = "Boolean" Then
                Exit Sub
            Else
                Set wbCopyFrom = Workbooks.Open(vFile)
                Set wsCopyFrom = wbCopyFrom.Worksheets("ReporteCifrasControl")
            End If
    '--------------------------------------------------------------------------------------
            wsCopyFrom.Range("A2:M" & wsCopyFrom.Range("A" & Rows.Count).End(xlUp).row).Copy
            wsCopyTo.Range("A" & wsCopyTo.Range("A" & Rows.Count).End(xlUp).row + 1).PasteSpecial xlPasteValuesAndNumberFormats
            wbCopyFrom.Close SaveChanges:=False

            Dim rngCopy As Range, rngPaste As Range
                With ActiveSheet
                    Set rngCopy = .Range(.Range("A2"), Cells(2, Columns.Count).End(xlToLeft))
                    Set rngPaste = .Range(.Range("A2"), .Cells(Rows.Count, 1).End(xlUp)).Resize(, rngCopy.Columns.Count)
                End With
            rngCopy.Copy
            rngPaste.PasteSpecial xlPasteFormats
            Application.CutCopyMode = False
        Loop

End Sub

Body:
I believe you want to do this

Copy row 2 from Column A to Last Used Column (LC)

Paste this in the first Non-Used Row (LR) in Column A

Dim LC As Long
Dim LR As Long

With ActiveSheet
    LC = .Cells(2, .Columns.Count).End(xlToLeft).Column
    LR = .Range("A" & .Rows.Count).End(xlUp).Row

    Set rngCopy = .Range(.Cells(1, 2), .Cells(LC, 2))
    Set rngPaste = .Range("A" & LR)
End With

rngCopy.Copy
rngPaste.PasteSpecial xlPasteFormats

You missed some objects to be qualified in your code. No point in using the With Block if you are not going to use the With Block

Just realized you have multiple copy/pastes in your code. If this is the wrong one, use the format here to modify the other one.


问:
Returning value from fastlane fastfile
My shell script would trigger a fastlane action (ruby) and I need return some value back to the shell script

One option being suggested everywhere is to set it as a env variable.
But unable to print the value in shell script.

Fastlane action

```<code>platform :ios do
  desc "Description of what the lane does"
  lane :getData do
        ENV['FL_VALUE'] = "Test"
  end
end
</code>```

Sample shell script

```<code>!/bin/sh
...
bundle exec fastlane getData
...
echo $FL_VALUE
</code>```

other suggestions were to write the data into some file and read it from the shell script. But would prefer to use the env variable.

答:
The project I am working on calls fastlane scripts from Groovy scripts. We have the lanes take an output_file option and write their results there. The Groovy scripts then read the results from the file. Cumbersome, but effective.

BTW: we also have an error_file option so errors can be written out similarly...

Title: Returning value from fastlane fastfile

Body:
My shell script would trigger a fastlane action (ruby) and I need return some value back to the shell script

One option being suggested everywhere is to set it as a env variable.
But unable to print the value in shell script.

Fastlane action

platform :ios do
  desc "Description of what the lane does"
  lane :getData do
        ENV['FL_VALUE'] = "Test"
  end
end

Sample shell script

!/bin/sh
...
bundle exec fastlane getData
...
echo $FL_VALUE

other suggestions were to write the data into some file and read it from the shell script. But would prefer to use the env variable.


问:
ef core attach same entity multiple times
I'm sure this was asked before, I don't know what to search for, so it's probably duplicate.
I have code that adds new entity to database. This entity has reference to another entity(Role), and I get it via service. Service creates another instance of dbContext, so I have to attach role to the context after I fetch it. The problem is, when I try to attach two same roles, I get this exception:

'Role' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'

How should I do it? Code below:

```<code>using (var context = new TenantContext(schemaName, connectionString))
{
    ApprovalTemplates templates = new ApprovalTemplates();
    ApprovalTemplate template = new ApprovalTemplate();
    template.Approvers = new List<StageTemplate>();

    foreach (var stage in request.Stages)
    {
        var temp = new StageTemplate();
        temp.Order = stage.Order;
        temp.Name = stage.Name;
        var role = roleService.GetById(stage.RoleId, schemaName);//here I get the role
        temp.AvailableActions = new List<ApprovalActionTemplate>();

        foreach (var actionId in stage.Actions)
            temp.AvailableActions.Add(context.ApprovalActions.First(a => a.Id == actionId));

        //when I try to add already attached role, exception is thrown
        context.TenantRoles.Attach(role);
        temp.Role = role;
        template.Approvers.Add(temp);
    }

    templates.PRApprovalTemplate = template;
    context.ApprovalTemplates.Add(templates);
    context.SaveChanges();
}
</code>```

答:
I would share potential approach for this and similar cases with Attach - the rule is very simple, you should never attach Entity with the same Id twice. Good point that there is an easy way to check if it's already attached and if it's attached, you can just use that entity, so best way is to always check local entities before attaching any Entity.
For your case in place of

```<code>var role = roleService.GetById(stage.RoleId, schemaName);//here I get the role
</code>```

it may be:

```<code>var localRole = context.Set<TenantRole>().Local.FirstOrDefault(entry => entry.Id.Equals(stage.RoleId));
if (localRole == null)
{
    localRole = new TenantRole
    {
        Id = stage.RoleId,
    };
    Context.TenantRoles.Attach(localRole);
}
...
temp.Role = localRole;
</code>```

Because if you know RoleId, you do not need to make DB call just to attach TenantRole to the Context.

Given code works fine, but once someone have many-many places like this, it's becomes to heavy. Potential solution for this would be creating extension method for your Context:

```<code>public static class RepositoryExtensions
{
    public static T LocalContextEntitiesFinder<T>(this TenantContext context, Guid id) where T : class, ISomeInterfaceThatAllYourDBModelsImplements, new()
    {
        var localObj = context.Set<T>().Local.FirstOrDefault(entry => entry.Id.Equals(id));
        if (localObj != null)
        {
            return localObj;
        }
        localObj = new T
        {
            Id = id
        };
        context.Set<T>().Attach(localObj);
        return localObj;
    }
}
</code>```

So you will be able to re-write your code to something like:

```<code>...
temp.Role = context.LocalContextEntitiesFinder<TenantRole>(id: stage.RoleId);
...
</code>```

To make it work, you should add interface ISomeInterfaceThatAllYourDBModelsImplements similar to this (in place of Guid you can use any other type you like):

```<code>public interface ISomeInterfaceThatAllYourDBModelsImplements
{
    public Guid Id { get; set; }
}
</code>```

And update TenantRole

```<code>public class TenantRole: ISomeInterfaceThatAllYourDBModelsImplements
{
    [Key]
    public Guid Id { get; set; }
...
</code>```

I hope this may help somebody.

Body:
I'm sure this was asked before, I don't know what to search for, so it's probably duplicate.
I have code that adds new entity to database. This entity has reference to another entity(Role), and I get it via service. Service creates another instance of dbContext, so I have to attach role to the context after I fetch it. The problem is, when I try to attach two same roles, I get this exception:

'Role' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'

How should I do it? Code below:

using (var context = new TenantContext(schemaName, connectionString))
{
    ApprovalTemplates templates = new ApprovalTemplates();
    ApprovalTemplate template = new ApprovalTemplate();
    template.Approvers = new List<StageTemplate>();

    foreach (var stage in request.Stages)
    {
        var temp = new StageTemplate();
        temp.Order = stage.Order;
        temp.Name = stage.Name;
        var role = roleService.GetById(stage.RoleId, schemaName);//here I get the role
        temp.AvailableActions = new List<ApprovalActionTemplate>();

        foreach (var actionId in stage.Actions)
            temp.AvailableActions.Add(context.ApprovalActions.First(a => a.Id == actionId));

        //when I try to add already attached role, exception is thrown
        context.TenantRoles.Attach(role);
        temp.Role = role;
        template.Approvers.Add(temp);
    }

    templates.PRApprovalTemplate = template;
    context.ApprovalTemplates.Add(templates);
    context.SaveChanges();
}

Body:
I would share potential approach for this and similar cases with Attach - the rule is very simple, you should never attach Entity with the same Id twice. Good point that there is an easy way to check if it's already attached and if it's attached, you can just use that entity, so best way is to always check local entities before attaching any Entity.
For your case in place of

var role = roleService.GetById(stage.RoleId, schemaName);//here I get the role

it may be:

var localRole = context.Set<TenantRole>().Local.FirstOrDefault(entry => entry.Id.Equals(stage.RoleId));
if (localRole == null)
{
    localRole = new TenantRole
    {
        Id = stage.RoleId,
    };
    Context.TenantRoles.Attach(localRole);
}
...
temp.Role = localRole;

Because if you know RoleId, you do not need to make DB call just to attach TenantRole to the Context.

Given code works fine, but once someone have many-many places like this, it's becomes to heavy. Potential solution for this would be creating extension method for your Context:

public static class RepositoryExtensions
{
    public static T LocalContextEntitiesFinder<T>(this TenantContext context, Guid id) where T : class, ISomeInterfaceThatAllYourDBModelsImplements, new()
    {
        var localObj = context.Set<T>().Local.FirstOrDefault(entry => entry.Id.Equals(id));
        if (localObj != null)
        {
            return localObj;
        }
        localObj = new T
        {
            Id = id
        };
        context.Set<T>().Attach(localObj);
        return localObj;
    }
}

So you will be able to re-write your code to something like:

...
temp.Role = context.LocalContextEntitiesFinder<TenantRole>(id: stage.RoleId);
...

To make it work, you should add interface ISomeInterfaceThatAllYourDBModelsImplements similar to this (in place of Guid you can use any other type you like):

public interface ISomeInterfaceThatAllYourDBModelsImplements
{
    public Guid Id { get; set; }
}

And update TenantRole

public class TenantRole: ISomeInterfaceThatAllYourDBModelsImplements
{
    [Key]
    public Guid Id { get; set; }
...

I hope this may help somebody.


问:
Calling an overloaded C# method that takes an Action or a Action from F#
Here are the signatures of the two overloads.

```<code>public static IServiceCollection AddDbContextPool<TContext>(
    this IServiceCollection serviceCollection,
    Action<DbContextOptionsBuilder> optionsAction,
    int poolSize = 128) where TContext : DbContext { ...

public static IServiceCollection AddDbContextPool<TContext>(
    this IServiceCollection serviceCollection,
    Action<IServiceProvider, DbContextOptionsBuilder> optionsAction,
    int poolSize = 128)
    where TContext : DbContext { ...
</code>```

Here is the 2nd overload being called in C#

But when I try to call the 2nd overload from F#, I get this error:

How can I fix this? Thanks!

答:
Try passing:</p>

```<code>fun (sp: IServiceProvider) (optionsBuilder: ...) -> ...
</code>```

Title: Calling an overloaded C# method that takes an Action<A> or a Action<A,B> from F#

Body:
Here are the signatures of the two overloads.

public static IServiceCollection AddDbContextPool<TContext>(
    this IServiceCollection serviceCollection,
    Action<DbContextOptionsBuilder> optionsAction,
    int poolSize = 128) where TContext : DbContext { ...

public static IServiceCollection AddDbContextPool<TContext>(
    this IServiceCollection serviceCollection,
    Action<IServiceProvider, DbContextOptionsBuilder> optionsAction,
    int poolSize = 128)
    where TContext : DbContext { ...

Here is the 2nd overload being called in C#

But when I try to call the 2nd overload from F#, I get this error:

How can I fix this? Thanks!

Body:
Try passing:

fun (sp: IServiceProvider) (optionsBuilder: ...) -> ...


问:
How can I disable threading in Flask?
I have the following bit of code:

```<code>import sqlite3
from flask import Flask

app = Flask(__name__)
db = sqlite3.connect('/etc/db.sqlite')

@app.route('/')
def handle():
    # run a query and return a response

if __name__ == '__main__':
    app.run('0.0.0.0', 8080, debug=True)
</code>```

However, when I try to perform some operations on the database object in the request handler, I get the following exception from sqlite3 because it is not a thread-safe library and the query is run from a different thread that Flask spawns, and not from the main thread:

```<code>sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 139886422697792 and this is thread id 139886332843776
</code>```

I am aware that the "proper" way to do this is to have a function to create an instance of the sqlite3.Connection object and store it in the Flask g global, as outlined here: http://flask.pocoo.org/docs/1.0/patterns/sqlite3/. However, when running this application on production, I use gunicorn -w 4 -b 0.0.0.0:8080 app:app, and there it works fine, because the threads are spawned at the beginning in this case.

While the Flask g global method works in all cases, I would really like to avoid the overhead of creating and destroying sqlite3.Connection objects with every request. So, I would like to disable threading in Flask so that the above code can run without causing issues.

However, even when I change the last line of the above code to app.run(..., threaded=False), I am unable to avoid this error. It seems that Flask still spawns a thread for handling requests.

So, how can I disable threading with Flask?

答:
Use scoped_session to avoid this:</p>

```<code>session = scoped_session(sessionmaker(bind=engine))()
</code>```

Title: How can I disable threading in Flask?

Body:
I have the following bit of code:

import sqlite3
from flask import Flask

app = Flask(__name__)
db = sqlite3.connect('/etc/db.sqlite')

@app.route('/')
def handle():
    # run a query and return a response

if __name__ == '__main__':
    app.run('0.0.0.0', 8080, debug=True)

However, when I try to perform some operations on the database object in the request handler, I get the following exception from sqlite3 because it is not a thread-safe library and the query is run from a different thread that Flask spawns, and not from the main thread:

sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 139886422697792 and this is thread id 139886332843776

I am aware that the "proper" way to do this is to have a function to create an instance of the sqlite3.Connection object and store it in the Flask g global, as outlined here: http://flask.pocoo.org/docs/1.0/patterns/sqlite3/. However, when running this application on production, I use gunicorn -w 4 -b 0.0.0.0:8080 app:app, and there it works fine, because the threads are spawned at the beginning in this case.

While the Flask g global method works in all cases, I would really like to avoid the overhead of creating and destroying sqlite3.Connection objects with every request. So, I would like to disable threading in Flask so that the above code can run without causing issues.

However, even when I change the last line of the above code to app.run(..., threaded=False), I am unable to avoid this error. It seems that Flask still spawns a thread for handling requests.

So, how can I disable threading with Flask?

Body:
Use scoped_session to avoid this:

session = scoped_session(sessionmaker(bind=engine))()


问:
Is it possible to fix the port number for graphql altair?
I'm using Django as backend providing a GraphQL API. I'm using Django's builtin support for Cross Site Request Forgery protection (CSRF protection) and django-cors-headers to enable the use of the Cross-origin resource sharing (CORS) mechanism. To debug the API I'm using Altair. Can I define a fixed port number for altair that I can consider altair as trusted origin in the Django settings.py file (CSRF_TRUSTED_ORIGINS).

答:
I'm a maintainer of the Altair GraphQL Client. Depending on how you choose to use Altair (with the browser extensions, or with the desktop apps), it might be possible to get past the CORS protection. By default, the browser extensions don't follow the CORS protection and can make requests with the same origin policy. If you're using the desktop apps, you can set the Origin header to get the requests to appear as coming from the same origin.

As for the CSRF token-based protection, one of the techniques you can use to solve it would be using pre request scripts as described in this article: https://sirmuel.design/pre-requests-now-available-in-altair-graphql-client-c3b28892059c.


问:
How do I get the next day's date in JS in YYYY-MM-DD format?
Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.

Basically, if I have a date like the following:

```<code>2018-04-06
</code>```

I want to be able to get the next day's date as such:

```<code>2018-04-07
</code>```

I found the following snippet on SO for doing this (kind of):

```<code>var date = new Date('2018-04-06');
date.setDate(date + 1);
</code>```

The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.

I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.

答:
As it was suggested by @chrisbyte, have your tried to use toUTCString method instead of toString() method ?

As a reminder , toString is the default used when you display the date object withim the console for example

I think the "problem" you're assuming is just an incomplete understanding how Date.toString() method behaves: this method seems to to return string representing a Date object but seems to use timezone as mentionned here (on the comment in 1st example)

Here my snippet to understand more:

  const originalDate = new Date('2018-04-06');
    // retrieving the original timestamp
    const originalTimestamp = originalDate.valueOf()

    // displaying the original date (non UTC / UTC)
    console.log(`original date (timezone dependent): ${originalDate.toString()}`)
        console.log(`original date (timezone independent): ${originalDate.toUTCString()}`)

    // we add one more day
    originalDate.setDate(originalDate.getDate() +1)
    const dayAfterTimestamp = originalDate.valueOf()

   // displaying the original date (non UTC / UTC)
    console.log(`updated date (timezone dependent): ${originalDate.toString()}`)
        console.log(`updated date (timezone independent): ${originalDate.toUTCString()}`)

    // check the differences (in milliseconds)
    console.log(`difference: ${(dayAfterTimestamp-originalTimestamp)}`)

       // displaying the original format (timezone independent)```

At last if you want to return the date string as a YYYY-MM-DD format you may have to implement it yourself :-/ , or use toLocaleFormat method but it isn't standardized.

Body:
Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.

Basically, if I have a date like the following:

2018-04-06

I want to be able to get the next day's date as such:

2018-04-07

I found the following snippet on SO for doing this (kind of):

var date = new Date('2018-04-06');
date.setDate(date + 1);

The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.

I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.

Body:
As it was suggested by @chrisbyte, have your tried to use toUTCString method instead of toString() method ?

As a reminder , toString is the default used when you display the date object withim the console for example

I think the "problem" you're assuming is just an incomplete understanding how Date.toString() method behaves: this method seems to to return string representing a Date object but seems to use timezone as mentionned here (on the comment in 1st example)

Here my snippet to understand more:

  const originalDate = new Date('2018-04-06');
    // retrieving the original timestamp
    const originalTimestamp = originalDate.valueOf()

    // displaying the original date (non UTC / UTC)
    console.log(`original date (timezone dependent): ${originalDate.toString()}`)
        console.log(`original date (timezone independent): ${originalDate.toUTCString()}`)

    // we add one more day
    originalDate.setDate(originalDate.getDate() +1)
    const dayAfterTimestamp = originalDate.valueOf()

   // displaying the original date (non UTC / UTC)
    console.log(`updated date (timezone dependent): ${originalDate.toString()}`)
        console.log(`updated date (timezone independent): ${originalDate.toUTCString()}`)

    // check the differences (in milliseconds)
    console.log(`difference: ${(dayAfterTimestamp-originalTimestamp)}`)

       // displaying the original format (timezone independent)

At last if you want to return the date string as a YYYY-MM-DD format you may have to implement it yourself :-/ , or use toLocaleFormat method but it isn't standardized.


问:
boost::interprocess_exception - library_error exception when creating shared_memory_object
In some rare cases (in fact on a single client's computer) code below throws an exception "library_error":

```<code>namespace ipc = boost::interprocess;
ipc::shared_memory_object m_shm;
...
bool initAsServer(size_t sharedMemSize)
{
    ipc::permissions perm;
    perm.set_unrestricted();

    try
    {
        m_shm = ipc::shared_memory_object(
            ipc::create_only,
            CNameGenHelper::genUniqueNameUtf8().c_str(), // static std::string genUniqueNameUtf8()
            ipc::read_write, perm);
    }
    catch(const ipc::interprocess_exception& ex)
    {
        logError("failed with exception \"%s\"", ex.what());
        return false;
    }
    ...
}
</code>```

In log file:
[ERR]     failed with exception "boost::interprocess_exception::library_error"

Boost v1.58, platform win32, vs13.

I'll be very grateful if you help me in solving this problem. Thank you in advance!

答:
You can #define BOOST_INTERPROCESS_BOOTSTAMP_IS_SESSION_MANAGER_BASED or BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME to switch to either registry or WMI based boot time detection.
Alternatively, you can use BOOST_INTERPROCESS_SHARED_DIR_PATH, but it's kind of useless on Windows since it uses hardcoded path. BOOST_INTERPROCESS_SHARED_DIR_FUNC is much better option since it lets you define a function that returns path to the shared directory.</p>

Body:
In some rare cases (in fact on a single client's computer) code below throws an exception "library_error":

namespace ipc = boost::interprocess;
ipc::shared_memory_object m_shm;
...
bool initAsServer(size_t sharedMemSize)
{
    ipc::permissions perm;
    perm.set_unrestricted();

    try
    {
        m_shm = ipc::shared_memory_object(
            ipc::create_only,
            CNameGenHelper::genUniqueNameUtf8().c_str(), // static std::string genUniqueNameUtf8()
            ipc::read_write, perm);
    }
    catch(const ipc::interprocess_exception& ex)
    {
        logError("failed with exception \"%s\"", ex.what());
        return false;
    }
    ...
}

In log file:
[ERR]     failed with exception "boost::interprocess_exception::library_error"

Boost v1.58, platform win32, vs13.

I'll be very grateful if you help me in solving this problem. Thank you in advance!


问:
Plot one vector as a function of another in R
I have a df w/ 3 variables: VOT, K, G. I want to make a plot of the K and G responses as a function of VOT. Any ideas for the best way to do this?

Here is some code I tried:

```<code>plot.K.Responses <- ggplot(mydf, aes(VOT, K,  group=VOT)) +
  geom_line() +
  geom_point() +
  facet_wrap(~VOT)
plot.K.Responses
pdf("plot.K.Responses", 18, 18, bg="transparent")
plot(plot.ID)
dev.off()
</code>```

答:
Is this the result you are looking for? I made the df longer so it separately contains all the VOT and K and G observations. This makes it easier to graph using a grouped option like color.

```<code>library(tidyverse)
mydf <- data.frame(VOT = runif(10), K = runif(10), G = runif(10))

mydf <- mydf %>%
  pivot_longer(cols = c("K", "G"))

plot.K.Responses <- ggplot(mydf, aes(y = VOT, x = value, color = name)) +
                             geom_point() +
                             geom_line()

plot.K.Responses
</code>```

Body:
I have a df w/ 3 variables: VOT, K, G. I want to make a plot of the K and G responses as a function of VOT. Any ideas for the best way to do this?

Here is some code I tried:

plot.K.Responses <- ggplot(mydf, aes(VOT, K,  group=VOT)) +
  geom_line() +
  geom_point() +
  facet_wrap(~VOT)
plot.K.Responses
pdf("plot.K.Responses", 18, 18, bg="transparent")
plot(plot.ID)
dev.off()

Body:
Is this the result you are looking for? I made the df longer so it separately contains all the VOT and K and G observations. This makes it easier to graph using a grouped option like color.

library(tidyverse)
mydf <- data.frame(VOT = runif(10), K = runif(10), G = runif(10))

mydf <- mydf %>%
  pivot_longer(cols = c("K", "G"))

plot.K.Responses <- ggplot(mydf, aes(y = VOT, x = value, color = name)) +
                             geom_point() +
                             geom_line()

plot.K.Responses


问:
WINDOW function alternative in HAVING Clause
I'm trying to get the oldest processing date on each product like this:

```<code>select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
from dim_product
where prod_name in ('xxx', 'yyy', 'zzz')
having prod_date = min_prod_date
</code>```

This gives me the error:

ORA-00904: "min_prod_date": invalid identifier

So I tried to use the min() function in the having clause which gave me the error:

ORA-30483: window  functions are not allowed here

As an alternative I modified my query like this:

```<code>with temp as(
select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
    from dim_product
    where prod_name in ('xxx', 'yyy', 'zzz')
    having prod_date = min_prod_date))
select * from temp where prod_date = min_prod_date
</code>```

Is this the right way to do things or Is there any other efficient method?

答:
One method uses rank() in a subquery:

```<code>select *
from (
    select
        prod_id,
        prod_name,
        prod_date,
        rank() over(partition by prod_id order by prod_date) rn
    from dim_product
    where prod_name in ('xxx', 'yyy', 'zzz')
) t
where rn = 1
</code>```

As an alternative, you may also want to consider filtering with a correlated subquery:

```<code>select prod_id, prod_id, prod_date
from dim_product d
where d.prod_name in ('xxx', 'yyy', 'zzz') and d.prod_date = (
    select min(d1.prod_date)
    from dim_product d1
    where d1.prod_id = d.prod_id and d1.prod_name in ('xxx', 'yyy', 'zzz')
)
</code>```

For efficiency in the latter query, you want an index on (prod_name, prod_id, prod_date).

Body:
I'm trying to get the oldest processing date on each product like this:

select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
from dim_product
where prod_name in ('xxx', 'yyy', 'zzz')
having prod_date = min_prod_date

This gives me the error:

ORA-00904: "min_prod_date": invalid identifier

So I tried to use the min() function in the having clause which gave me the error:

ORA-30483: window  functions are not allowed here

As an alternative I modified my query like this:

with temp as(
select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
    from dim_product
    where prod_name in ('xxx', 'yyy', 'zzz')
    having prod_date = min_prod_date))
select * from temp where prod_date = min_prod_date

Is this the right way to do things or Is there any other efficient method?

Body:
One method uses rank() in a subquery:

select *
from (
    select
        prod_id,
        prod_name,
        prod_date,
        rank() over(partition by prod_id order by prod_date) rn
    from dim_product
    where prod_name in ('xxx', 'yyy', 'zzz')
) t
where rn = 1

As an alternative, you may also want to consider filtering with a correlated subquery:

select prod_id, prod_id, prod_date
from dim_product d
where d.prod_name in ('xxx', 'yyy', 'zzz') and d.prod_date = (
    select min(d1.prod_date)
    from dim_product d1
    where d1.prod_id = d.prod_id and d1.prod_name in ('xxx', 'yyy', 'zzz')
)

For efficiency in the latter query, you want an index on (prod_name, prod_id, prod_date).


问:
How to understand the assembly result of the tiny c function?
Function in c:

```<code>PHPAPI char *php_pcre_replace(char *regex,   int regex_len,
                              char *subject, int subject_len,
                              zval *replace_val, int is_callable_replace,
                              int *result_len, int limit, int *replace_count TSRMLS_DC)
{
    pcre_cache_entry    *pce;               /* Compiled regular expression */

    /* Compile regex or get it from cache. */
    if ((pce = pcre_get_compiled_regex_cache(regex, regex_len TSRMLS_CC)) == NULL) {
        return NULL;
    }

    return php_pcre_replace_impl(pce, subject, subject_len, replace_val,
        is_callable_replace, result_len, limit, replace_count TSRMLS_CC);
}
</code>```

Its assembly:

```<code>php5ts!php_pcre_replace:
1015db70 8b442408        mov     eax,dword ptr [esp+8]
1015db74 8b4c2404        mov     ecx,dword ptr [esp+4]
1015db78 56              push    esi
1015db79 8b74242c        mov     esi,dword ptr [esp+2Ch]
1015db7d 56              push    esi
1015db7e 50              push    eax
1015db7f 51              push    ecx
1015db80 e8cbeaffff      call    php5ts!pcre_get_compiled_regex_cache (1015c650)
1015db85 83c40c          add     esp,0Ch
1015db88 85c0            test    eax,eax
1015db8a 7502            jne     php5ts!php_pcre_replace+0x1e (1015db8e)

php5ts!php_pcre_replace+0x1c:
1015db8c 5e              pop     esi
1015db8d c3              ret

php5ts!php_pcre_replace+0x1e:
1015db8e 8b542428        mov     edx,dword ptr [esp+28h]
1015db92 8b4c2424        mov     ecx,dword ptr [esp+24h]
1015db96 56              push    esi
1015db97 52              push    edx
1015db98 8b542428        mov     edx,dword ptr [esp+28h]
1015db9c 51              push    ecx
1015db9d 8b4c2428        mov     ecx,dword ptr [esp+28h]
1015dba1 52              push    edx
1015dba2 8b542428        mov     edx,dword ptr [esp+28h]
1015dba6 51              push    ecx
1015dba7 8b4c2428        mov     ecx,dword ptr [esp+28h]
1015dbab 52              push    edx
1015dbac 8b542428        mov     edx,dword ptr [esp+28h]
1015dbb0 51              push    ecx
1015dbb1 52              push    edx
1015dbb2 50              push    eax
1015dbb3 e808000000      call    php5ts!php_pcre_replace_impl (1015dbc0)
1015dbb8 83c424          add     esp,24h
1015dbbb 5e              pop     esi
1015dbbc c3              ret
</code>```

As we can see that pcre_get_compiled_regex_cache takes 2 parameters,but why 3 parameters are pushed into the stack?

```<code>1015db7d 56              push    esi
1015db7e 50              push    eax
1015db7f 51              push    ecx
1015db80 e8cbeaffff      call    php5ts!pcre_get_compiled_regex_cache (1015c650)
</code>```

答: I guess the TSRMLS_DC and TSRMLS_CC macros contain some hidden extra parameters. A quick google showed up these macros in PHP programming as global state data. It makes sense, the macro in the function declaration must have a parameter which is at [esp+02ch] on the stack - the tenth parameter - you have nine already, and is passed as the first value on the stack (values are pushed right to left), followed by regex_len and then regex.

Body:
Function in c:

PHPAPI char *php_pcre_replace(char *regex,   int regex_len,
                              char *subject, int subject_len,
                              zval *replace_val, int is_callable_replace,
                              int *result_len, int limit, int *replace_count TSRMLS_DC)
{
    pcre_cache_entry    *pce;               /* Compiled regular expression */

    /* Compile regex or get it from cache. */
    if ((pce = pcre_get_compiled_regex_cache(regex, regex_len TSRMLS_CC)) == NULL) {
        return NULL;
    }

    return php_pcre_replace_impl(pce, subject, subject_len, replace_val,
        is_callable_replace, result_len, limit, replace_count TSRMLS_CC);
}

Its assembly:

php5ts!php_pcre_replace:
1015db70 8b442408        mov     eax,dword ptr [esp+8]
1015db74 8b4c2404        mov     ecx,dword ptr [esp+4]
1015db78 56              push    esi
1015db79 8b74242c        mov     esi,dword ptr [esp+2Ch]
1015db7d 56              push    esi
1015db7e 50              push    eax
1015db7f 51              push    ecx
1015db80 e8cbeaffff      call    php5ts!pcre_get_compiled_regex_cache (1015c650)
1015db85 83c40c          add     esp,0Ch
1015db88 85c0            test    eax,eax
1015db8a 7502            jne     php5ts!php_pcre_replace+0x1e (1015db8e)

php5ts!php_pcre_replace+0x1c:
1015db8c 5e              pop     esi
1015db8d c3              ret

php5ts!php_pcre_replace+0x1e:
1015db8e 8b542428        mov     edx,dword ptr [esp+28h]
1015db92 8b4c2424        mov     ecx,dword ptr [esp+24h]
1015db96 56              push    esi
1015db97 52              push    edx
1015db98 8b542428        mov     edx,dword ptr [esp+28h]
1015db9c 51              push    ecx
1015db9d 8b4c2428        mov     ecx,dword ptr [esp+28h]
1015dba1 52              push    edx
1015dba2 8b542428        mov     edx,dword ptr [esp+28h]
1015dba6 51              push    ecx
1015dba7 8b4c2428        mov     ecx,dword ptr [esp+28h]
1015dbab 52              push    edx
1015dbac 8b542428        mov     edx,dword ptr [esp+28h]
1015dbb0 51              push    ecx
1015dbb1 52              push    edx
1015dbb2 50              push    eax
1015dbb3 e808000000      call    php5ts!php_pcre_replace_impl (1015dbc0)
1015dbb8 83c424          add     esp,24h
1015dbbb 5e              pop     esi
1015dbbc c3              ret

As we can see that pcre_get_compiled_regex_cache takes 2 parameters,but why 3 parameters are pushed into the stack?

1015db7d 56              push    esi
1015db7e 50              push    eax
1015db7f 51              push    ecx
1015db80 e8cbeaffff      call    php5ts!pcre_get_compiled_regex_cache (1015c650)