问:
Retrieving data from local storage not working
I can save to local storage, but when I add code to retrieve the data it does not work. I can see the code has been saved as I have checked using F12 in chrome. Any guidance would be appreciated.

```<code> <!DOCTYPE html>
 <html>
 <head>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet"
 href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
 <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-
 1.4.5.min.js"></script>
 </head>
 <body>
 <form>
 <input type="text" id="task" placeholder="name">
 <input type="text" id="date" placeholder="dd/mm/yyyy">
 <input type="button" class="add-row" value="Add Row">

 </form>
 <table id="task_table">
 <thead>
    <tr>
        <th>Name</th>
        <th>Date</th>
    </tr>
 </thead>
 <tbody>
    <tr>
        <td>steve</td>
        <td>13/12/1956</td>
    </tr>

 </tbody>

 </table>
 <button id="saveAll">Save List</button>

 <script>$("#saveAll").click(function(e) {

 var listBirthdays = [];
 $("table td").each(function(){
   listBirthdays.push(this.innerHTML);
 })
 localStorage.setItem('birthdayList', JSON.stringify(listBirthdays));
 });

 </script>

 <script>
 $(document).ready(function(){
 $(".add-row").on('click',function(){
    var task = $("#task").val();
    var date = $("#date").val();
    var markup = "<tr><td>" + task + "</td><td>" + date + "</td></tr>";
    $('table tbody').append(markup);

 });

            }
     );

;

</script>
</code>```

Below is shown the code that I tried to use to reload the data from storage.

```<code>loadList();

function loadList() {
if (localStorage.getItem('birthdayList')){
    var listBirthdays = JSON.parse(localStorage.getItem('birthdayList'));
    $("table td").each(function(i){
      this.innerHTML = listBirthdays [i];
    })
}
</code>```

}
   });

When i add code that should retrieve the data it does not add it back to the table.

答:
As @helb already explained the problem with your code. There is an alternate solution to the problem, just change your loadList function to this:-</p>

```<code> function loadList() {

    if (localStorage.getItem('birthdayList')) {

        var listBirthdays = JSON.parse(localStorage.getItem('birthdayList'));

        $("#task_table").find("tr").remove();

        for (i = 0; i < listBirthdays.length - 1; i = i + 2) {
            $('#task_table tbody').append('<tr>' + '<td>' + listBirthdays[i] + '</td>' + '<td>' + listBirthdays[i + 1] + '</td>' + '</tr>');
        }

    }
}
</code>```

Body:
I can save to local storage, but when I add code to retrieve the data it does not work. I can see the code has been saved as I have checked using F12 in chrome. Any guidance would be appreciated.

 <!DOCTYPE html>

 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet"
 href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

 <form>
 <input type="text" id="task" placeholder="name">
 <input type="text" id="date" placeholder="dd/mm/yyyy">
 <input type="button" class="add-row" value="Add Row">

 </form>

        Name
        Date

        steve
        13/12/1956

 <button id="saveAll">Save List</button>

Below is shown the code that I tried to use to reload the data from storage.

loadList();

function loadList() {
if (localStorage.getItem('birthdayList')){
    var listBirthdays = JSON.parse(localStorage.getItem('birthdayList'));
    $("table td").each(function(i){
      this.innerHTML = listBirthdays [i];
    })
}

}
   });

When i add code that should retrieve the data it does not add it back to the table.

Body:
As @helb already explained the problem with your code. There is an alternate solution to the problem, just change your loadList function to this:-

 function loadList() {

    if (localStorage.getItem('birthdayList')) {

        var listBirthdays = JSON.parse(localStorage.getItem('birthdayList'));

        $("#task_table").find("tr").remove();

        for (i = 0; i < listBirthdays.length - 1; i = i + 2) {
            $('#task_table tbody').append('<tr>' + '<td>' + listBirthdays[i] + '</td>' + '<td>' + listBirthdays[i + 1] + '</td>' + '</tr>');
        }

    }
}


来源: stackexchange

问:
Git commit messages if I split a single task into 2 commits
For example, if I haven’t finished a task at the end of a day but want to commit and push my work. The next day I’ll finish the task and commit the finished task again. What should the 2 commit messages look like?

For example Apply new Changes (Part1) and Apply new Changes (Part2) looks not like a good commit message to me.

答: Better not push such commits to the target branch. You could commit as often as possible with whatever commit messages you like. Consider them as drafts. You will have little chance to lose your changes. Every commit stays long enough. You could push them to a backup branch or a backup repository in another host if you don't think the local repository is safe enough. When you finish one task, squash all the related draft commits into one, with git reset --soft && git commit, git rebase -i, or git merge --squash. Write the message carefully to include helpful and well-formatted infomation for this formal commit.

ContentLicense: CC BY-SA 3.0


问:
Push notification in Web pages
Can a web notification be implemented in web sites? I'm using a environment of jsp's with jquery, vue and angular.js for the front side. There's a way to implement web notifications with this environment?</p>

答:
use for example:
https://github.com/mqttjs

then in your js:

```<code>    this.client = mqtt.connect(url, options);

    if(topics.length>0)
        this.client.subscribe(topics);

    this.client.on("message", (topic:any, payload:any)=>{
        console.log('CONNECTED', payload);
    });

    this.client.on("connect", function (connack: any) {
        console.log('CONNECTED', connack);
    });
</code>```

And use some server side message broker eg: rabbitMQ or other message router

read this
https://www.rabbitmq.com/web-mqtt.html

Title: Push notification in Web pages

Body:
use for example:
https://github.com/mqttjs

then in your js:

    this.client = mqtt.connect(url, options);

    if(topics.length>0)
        this.client.subscribe(topics);

    this.client.on("message", (topic:any, payload:any)=>{
        console.log('CONNECTED', payload);
    });

    this.client.on("connect", function (connack: any) {
        console.log('CONNECTED', connack);
    });

And use some server side message broker eg: rabbitMQ or other message router

read this
https://www.rabbitmq.com/web-mqtt.html


问:
set origin coordinates for react-konva stage
I am using react-konva for drawing purposes. I have configured the stage and I am drawing certain shapes in that stage container. The problem I am facing is that the origin coordinates(0,0) are at the top left of the stage container. I want the center of the stage to be the origin(0,0). Here is the present code:

```<code><Stage
  height={800}
  width={1200}
  style={{ backgroundColor: '#fff', border: 'solid'}}>
  {
    this.state.circlePoints.length !== 0 &&
    <LineComponent
      startX={1200/2}
      startY={800/2}
      endX={this.state.circlePoints[0].pointX*1.3}
      endY={this.state.circlePoints[0].pointY*1.3}
      startColor={firstCircle[0].outerColor}
      endColor={pmData[0].outerColor}
    />
  }
  <CircleComponent
    x={1200/2}
    y={800/2}
    outerRadius={firstCircle[0].weight*1200}
    outerColor={firstCircle[0].outerColor}
    innerRadius={firstCircle[0].weight*1200*0.3}
    innerColor={firstCircle[0].innerColor}
    shadowColor={firstCircle[0].innerColor}
    getCirclePoints={this.getCirclePoints}
  />
  {
    this.state.circlePoints.length !== 0 &&
    <CircleComponent
      x={this.state.circlePoints[0].pointX*1.3}
      y={this.state.circlePoints[0].pointY*1.3}
      outerRadius={pmData[0].weight*1200}
      outerColor={pmData[0].outerColor}
      innerRadius={pmData[0].weight*1200*0.3}
      innerColor={pmData[0].innerColor}
      shadowColor={pmData[0].innerColor}
    />
  }
</Stage>
</code>```

答:
Use the layer offset command to re-position the layer on the stage. In the example below you can see that I add the x and y axis then offset the layer 200px in to the page. Finally I draw a circle on the layer at (0,0) to confirm that the layer co-ordinates remain based on this location so that you do not have to do any translation on your drawing co-ordinates.

var stage = new Konva.Stage({
      container: 'container',
      width: 600,
      height: 400
    });

var layer = new Konva.Layer();
stage.add(layer)

var axisX = new Konva.Line({
      points: [-200, 0, 200, 0],
      stroke: 'red',
      strokeWidth: 2,
      lineCap: 'round',
      lineJoin: 'round'
    });

var axisY = new Konva.Line({
      points: [0, 200, 0, -200],
      stroke: 'red',
      strokeWidth: 2,
      lineCap: 'round',
      lineJoin: 'round'
    });

layer.add(axisX)
layer.add(axisY)

// offset the layer on the stage
layer.offsetX(-200)
layer.offsetY(-200)

// draw a circle at 0,0

    var circle = new Konva.Circle({
      x: 0,
      y: 0,
      radius: 70,
      stroke: 'black',
      strokeWidth: 4
    });

    // add the shape to the layer
    layer.add(circle);

layer.draw();
stage.draw();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
  <div id="container"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
    <script type="text/javascript" src="test.js"></script>

</body>
</html></code>```

Body:
I am using react-konva for drawing purposes. I have configured the stage and I am drawing certain shapes in that stage container. The problem I am facing is that the origin coordinates(0,0) are at the top left of the stage container. I want the center of the stage to be the origin(0,0). Here is the present code:

<Stage
  height={800}
  width={1200}
  style={{ backgroundColor: '#fff', border: 'solid'}}>
  {
    this.state.circlePoints.length !== 0 &&
    <LineComponent
      startX={1200/2}
      startY={800/2}
      endX={this.state.circlePoints[0].pointX*1.3}
      endY={this.state.circlePoints[0].pointY*1.3}
      startColor={firstCircle[0].outerColor}
      endColor={pmData[0].outerColor}
    />
  }
  <CircleComponent
    x={1200/2}
    y={800/2}
    outerRadius={firstCircle[0].weight*1200}
    outerColor={firstCircle[0].outerColor}
    innerRadius={firstCircle[0].weight*1200*0.3}
    innerColor={firstCircle[0].innerColor}
    shadowColor={firstCircle[0].innerColor}
    getCirclePoints={this.getCirclePoints}
  />
  {
    this.state.circlePoints.length !== 0 &&
    <CircleComponent
      x={this.state.circlePoints[0].pointX*1.3}
      y={this.state.circlePoints[0].pointY*1.3}
      outerRadius={pmData[0].weight*1200}
      outerColor={pmData[0].outerColor}
      innerRadius={pmData[0].weight*1200*0.3}
      innerColor={pmData[0].innerColor}
      shadowColor={pmData[0].innerColor}
    />
  }
</Stage>

Body:
Use the layer offset command to re-position the layer on the stage. In the example below you can see that I add the x and y axis then offset the layer 200px in to the page. Finally I draw a circle on the layer at (0,0) to confirm that the layer co-ordinates remain based on this location so that you do not have to do any translation on your drawing co-ordinates.

var stage = new Konva.Stage({
      container: 'container',
      width: 600,
      height: 400
    });

var layer = new Konva.Layer();
stage.add(layer)

var axisX = new Konva.Line({
      points: [-200, 0, 200, 0],
      stroke: 'red',
      strokeWidth: 2,
      lineCap: 'round',
      lineJoin: 'round'
    });

var axisY = new Konva.Line({
      points: [0, 200, 0, -200],
      stroke: 'red',
      strokeWidth: 2,
      lineCap: 'round',
      lineJoin: 'round'
    });

layer.add(axisX)
layer.add(axisY)

// offset the layer on the stage
layer.offsetX(-200)
layer.offsetY(-200)

// draw a circle at 0,0

    var circle = new Konva.Circle({
      x: 0,
      y: 0,
      radius: 70,
      stroke: 'black',
      strokeWidth: 4
    });

    // add the shape to the layer
    layer.add(circle);

layer.draw();
stage.draw();

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
  <div id="container"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
    <script type="text/javascript" src="test.js"></script>

</body>
</html>


问:
Java jpcap opendevice error, setRoutingOption
I was messing a lot around with networking and raw sockets. I installed Jpcap and I tried some example code. When I tried the code to send a message with UDP, I got some errors with opening a device.
First, the devices are getting stored.

NetworkInterface[] devices = JpcapCaptor.getDeviceList();

Next the first device is tried to open, and that is the line of the error.

JpcapSender sender=JpcapSender.openDevice(devices[0]);

This is the error I got:

```<code>java.lang.NoSuchMethodError: setRoutingOption
     at jpcap.JpcapSender.nativeOpenDevice(Native Method)
     at jpcap.JpcapSender.openDevice(JpcapSender.java:38)
     at Test.main(Test.java:15)
 Exception in thread "main"
</code>```

I have been looking around, but I could not find a solution that worked for me,
hopefully you can help me.

答:
You should use the latest version of Jpcap 0.7 :

http://jpcap.gitspot.com/jpcap-0.7.zip

Body:
I was messing a lot around with networking and raw sockets. I installed Jpcap and I tried some example code. When I tried the code to send a message with UDP, I got some errors with opening a device.
First, the devices are getting stored.

NetworkInterface[] devices = JpcapCaptor.getDeviceList();

Next the first device is tried to open, and that is the line of the error.

JpcapSender sender=JpcapSender.openDevice(devices[0]);

This is the error I got:

java.lang.NoSuchMethodError: setRoutingOption
     at jpcap.JpcapSender.nativeOpenDevice(Native Method)
     at jpcap.JpcapSender.openDevice(JpcapSender.java:38)
     at Test.main(Test.java:15)
 Exception in thread "main"

I have been looking around, but I could not find a solution that worked for me,
hopefully you can help me.


问:
Accesing JavaScript variable in JSP
I have a JavaScript variable and I want to access it in JSP without using submit button. Actually I have a javascript variable and i want to use it for running a query in JSP to fetch a value from database and again using the value from JSP to javascript.

I do not want to have a button in the form tag for submitting the value and then getting it as a paramneter in JSP. Is there any other way of doing that.

Actually i have atextbox where username is coming. I want to use that variable so that i can run a query in JSP and find its user Id. Code for getting value of text box is.

```<code>var selUserInfo = thisFrm.SelUser.value
</code>```

Now i want to pass this selUserInfo to a JSP.

答:
Not possible unless you send a GET or POST request. See this explanation.

Edit: after understanding that you're aiming for an autocompletion text-input, I would recommend to look for a jQuery solution like this one, and using an Ajax request to retrieve the data from your database (inside a .ready() event).

Title: Accesing JavaScript variable in JSP

Body:
I have a JavaScript variable and I want to access it in JSP without using submit button. Actually I have a javascript variable and i want to use it for running a query in JSP to fetch a value from database and again using the value from JSP to javascript.

I do not want to have a button in the form tag for submitting the value and then getting it as a paramneter in JSP. Is there any other way of doing that.

Actually i have atextbox where username is coming. I want to use that variable so that i can run a query in JSP and find its user Id. Code for getting value of text box is.

var selUserInfo = thisFrm.SelUser.value

Now i want to pass this selUserInfo to a JSP.


问:
Use Json file for d3.js-graph
I'am new in d3.js and want to use the line-chart example:
line-chart-example
with a external json file, which is located in the same folder like the index.html.

When I change the source to .json I only get a blank page as result. How do I have to change the section to use the json data?

```<code>    d3.tsv("data.tsv", function(d) {
  d.date = parseTime(d.date);
  d.close = +d.close;
  return d;
}, function(error, data) {
  if (error) throw error;
</code>```

答:
The issue here is simple: d3.json does not accept a row function. It has to be just:

d3.json(url[, callback])

Given your code:

```<code>d3.tsv("data.tsv", function(d) {
            d.date = parseTime(d.date);
            d.close = +d.close;
            return d;
        }, function(error, data) {
            if (error) throw error;
</code>```

The "JSON" version of it has to be:

```<code>d3.json("data.json", function(error, data) {
    if (error) throw error;
</code>```

So, move the row function...

```<code>function(d) {
    d.date = parseTime(d.date);
    d.close = +d.close;
    return d;
},
</code>```

... to a forEach loop, inside the callback.

Title: Use Json file for d3.js-graph

Body:
I'am new in d3.js and want to use the line-chart example:
line-chart-example
with a external json file, which is located in the same folder like the index.html.

When I change the source to .json I only get a blank page as result. How do I have to change the section to use the json data?

    d3.tsv("data.tsv", function(d) {
  d.date = parseTime(d.date);
  d.close = +d.close;
  return d;
}, function(error, data) {
  if (error) throw error;

Body:
The issue here is simple: d3.json does not accept a row function. It has to be just:

d3.json(url[, callback])

Given your code:

d3.tsv("data.tsv", function(d) {
            d.date = parseTime(d.date);
            d.close = +d.close;
            return d;
        }, function(error, data) {
            if (error) throw error;

The "JSON" version of it has to be:

d3.json("data.json", function(error, data) {
    if (error) throw error;

So, move the row function...

function(d) {
    d.date = parseTime(d.date);
    d.close = +d.close;
    return d;
},

... to a forEach loop, inside the callback.


问:
How do you get the number of words in a NSTextStorage/NSString?
So my question is basically how do you get the number of words in a NSTextStorage/NSString?  I don't want the character length but the word length.  Thanks.</p>

答: CFStringTokenizer is your friend.

ContentLicense: CC BY-SA 2.5

Body: CFStringTokenizer is your friend.


问:
Calling node from a PHP script
I'm trying to call a node script from a PHP script using exec:

```<code>$output = exec("/usr/bin/node /home/user/nodescript.js");
</code>```

The nodescript.js being:

```<code>var Scraper = require('google-images-scraper');

var keywords = process.argv[2];

var scraper = new Scraper({
    keyword: keywords,
    rlimit: 10, // 10 p second
});
console.log("foo");
scraper.list(10).then(function (res) {
    console.log("bar");
    console.log(res);
});
setTimeout(function () {
    process.exit(1);
}, 20000)
</code>```

But what I receive is the string "foo", and not the "bar". If I run the node script from command line, I do get "foo" and "bar". Somehow I don't receive any console output inside the function. What am I doing wrong?

答:
PHP 5.6 is bundled with the phpdbg interactive debugger.
However, the documentation URL points to an expired domain, at the moment, so, yeah.

Source: https://stackoverflow.com/a/36131176/370786

Title: Calling node from a PHP script

Body:
I'm trying to call a node script from a PHP script using exec:

$output = exec("/usr/bin/node /home/user/nodescript.js");

The nodescript.js being:

var Scraper = require('google-images-scraper');

var keywords = process.argv[2];

var scraper = new Scraper({
    keyword: keywords,
    rlimit: 10, // 10 p second
});
console.log("foo");
scraper.list(10).then(function (res) {
    console.log("bar");
    console.log(res);
});
setTimeout(function () {
    process.exit(1);
}, 20000)

But what I receive is the string "foo", and not the "bar". If I run the node script from command line, I do get "foo" and "bar". Somehow I don't receive any console output inside the function. What am I doing wrong?


问:
Hyperlink navigation via Ctrl+click in Eclipse Oxygen does not work
After upgrading from Eclipse Neon to Oxygen I noticed that I can no longer navigate around the code by clicking on definitions while holding the Ctrl key down. The indexer itself works fine, and I can still jump around by pressing F3 or using the context menu.

I am using Eclipse CDT with C++.

The following screenshot proves that the feature is enabled:

What am I missing?

答: In addition to the first solution, increase the "Maximum number of tokens per translation unit" in your Eclipse.


问:
How to Wait for a Redirect Chain to Settle using Selenium WebDriver where final page loaded is not predictable?
I want to automate a script which verify certain contents in the webpage.

The login page redirected several times before landing on an application page and these redirects were causing issues occasionally. The issue was definately related to timing. So how can webdriver wait until the final page is fully loaded or settled ?

A typical solution is to wait for an element on the target page to become available. Unfortunately, we use 100+ unique urls  therefore there is no predictable landing page.

So how can an ExpectedCondition be implemented, that waits for the application to stabilize with respect to redirects ?

The main agenda is, I have a set of URL's and i wanted to verify that all these URL's are valid by checking the content in it. All these are direct URL's of learning contents to which my organization has partnered eg Lynda, skillsoft,etc. So when we launch these URL through automated scrip first it will ask authentication(My organizational credential) and after that it will redirect to corresponding sites. During these redirect, in certain cases there is multiple redirection happening and finally the content page is loaded. This is the scenario. My script fails mainly due to the wait i guess

答:
As you mentioned multiple redirection happening and finally the content page is loaded and the script fails mainly due to the wait is pretty much possible. In these cases we need to induce ExplicitWait i.e. WebDriverWait with expected_conditions clause set to either of the following :

Java :

urlToBe: An expectation for checking the current url is an exact match.

```<code>new WebDriverWait(driver, 10).until(ExpectedConditions.urlToBe("https://www.facebook.com/"));
</code>```

urlContains: An expectation for checking that the current url contains a case-sensitive substring.

```<code>new WebDriverWait(driver, 10).until(ExpectedConditions.urlContains("facebook"));
</code>```

urlMatches: An expectation for checking the current url pattern is the expected pattern which must be an exact match.

```<code>new WebDriverWait(driver, 10).until(ExpectedConditions.urlMatches("my_regex"));
</code>```

Python :

url_to_be:  An expectation for the URL of the current page to be a specific url.

```<code>WebDriverWait(driver, 10).until(EC.url_to_be("https://www.google.co.in/"))
</code>```

url_matches: An expectation for the URL to match a specific regular expression.

```<code>WebDriverWait(driver, 10).until(EC.url_matches("my_regex"))
</code>```

url_contains: An expectation for the URL of the current page to contain specific text.

```<code>WebDriverWait(driver, 10).until(EC.url_contains("google"))
</code>```

url_changes: An expectation for checking the current url which must not be an exact match.

```<code>WebDriverWait(driver, 10).until(EC.url_changes("https://www.google.co.in/"))
</code>```

Body:
As you mentioned multiple redirection happening and finally the content page is loaded and the script fails mainly due to the wait is pretty much possible. In these cases we need to induce ExplicitWait i.e. WebDriverWait with expected_conditions clause set to either of the following :

Java :

urlToBe: An expectation for checking the current url is an exact match.

new WebDriverWait(driver, 10).until(ExpectedConditions.urlToBe("https://www.facebook.com/"));

urlContains: An expectation for checking that the current url contains a case-sensitive substring.

new WebDriverWait(driver, 10).until(ExpectedConditions.urlContains("facebook"));

urlMatches: An expectation for checking the current url pattern is the expected pattern which must be an exact match.

new WebDriverWait(driver, 10).until(ExpectedConditions.urlMatches("my_regex"));

Python :

url_to_be:  An expectation for the URL of the current page to be a specific url.

WebDriverWait(driver, 10).until(EC.url_to_be("https://www.google.co.in/"))

url_matches: An expectation for the URL to match a specific regular expression.

WebDriverWait(driver, 10).until(EC.url_matches("my_regex"))

url_contains: An expectation for the URL of the current page to contain specific text.

WebDriverWait(driver, 10).until(EC.url_contains("google"))

url_changes: An expectation for checking the current url which must not be an exact match.

WebDriverWait(driver, 10).until(EC.url_changes("https://www.google.co.in/"))

ContentLicense: CC BY-SA 4.0


问:
Where is the documentation for the internals of Qt and the design patterns used for building it
Please point the docs for understanding the internals of Qt such as the design of the QObject class, The patterns choosen for the Qt classes. The reason for using QVariant class, e.t.c. Although Qt comes with very good documentation and examples, they mostly explain how to use them not why it is being done that way.</p>

答:
Here is a blog entry that at least explains the use of private classes and d-pointers in Qt.
Qt-Howto</p>


问:
Avoid tensorflow print on standard error
anyone knows if there is a method to prevent tensorflow from polluting standard error with gpus' memory allocation log?.
I noted that when the following command is executed:

```<code>with tf.Session() as sess:
</code>```

tensorflow prints on standard error a log about memory and gpu resources allocation. Something like:

```<code>I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 48
Graphics Device pciBusID 0000:02:00.0
Free memory: 11.75GiB
...
</code>```

For important reasons, I wanna avoid this printing.

答: Defaults to 0, so all logs are shown. Set TF_CPP_MIN_LOG_LEVEL to 1 to filter out INFO logs, 2 to additionall filter out WARNING, 3 to additionally filter out ERROR.

Body:
anyone knows if there is a method to prevent tensorflow from polluting standard error with gpus' memory allocation log?.
I noted that when the following command is executed:

with tf.Session() as sess:

tensorflow prints on standard error a log about memory and gpu resources allocation. Something like:

I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 48
Graphics Device pciBusID 0000:02:00.0
Free memory: 11.75GiB
...

For important reasons, I wanna avoid this printing.


问:
How to debug task scheduler on win 10?
I'm trying to exectute the following bat every 15 minutes on my pc:

```<code>@ECHO OFF

SETLOCAL enabledelayedexpansion

SET host=http://dnsad.de/rest/
SET slideshowurl=http://dnsad.de/display/currentSlideshow/mac/
SET slideshowfolder=C:\Slideshow
SET ieprocess="iexplore.exe"
SET ignore_result=INFORMATION:

FOR /f "delims=" %%a IN ('getmac /v ^|find /i "Realtek"') DO (
    FOR %%b IN (%%a) DO (
        SET element=%%b
        IF "!element:~2,1!!element:~5,1!!element:~8,1!"=="---" set mac=%%b
    )
)

SET formattedmac=%mac:-=:%
SET macpath=%mac:-=_%

FOR /f "delims=" %%a IN ('curl -X GET %host%%formattedmac%') DO (
    FOR %%b IN (%%a) DO (
        SET update=%%b
    )
)

IF "%update%"=="[true]" (
    CD %ProgramFiles%\WinHTTrack\
    httrack %slideshowurl%%formattedmac% -q -O "C:\Slideshow" -s0 -B -a
    curl -X PUT %host%%formattedmac%

    START iexplore -k %slideshowfolder%\dnsad.de\display\currentSlideshow\mac\%macpath%.html
)

EXIT
</code>```

The script works as it should when executed. Im getting the device's mac address, getting the expected server responses from curl, WinHTTrack is backing up the data correctly, curl updates the server fields and then the internet explorer gets opened with the updated,local html.

When scheduled as Task with win 7 it works as it should as well. When running the bat from Task Scheduler on Win 10 the last thing it does is the curl PUT, but the Internet Exploerer is never opened. The task is marked as succesful.

I am logged in as admin on Win 7 and Win 10. I tested pretty much every setting within the taskscheduler. Nothing seems to be working. Why doesnt the internet explorer start ?

[EDIT]

It seems that the option "Run whether user is logged on or not" causes the problem. But here is the catch:
I'm displaying slideshows in Internet Explorer Kiosk Mode and need to get updated Data from my server to Display new Slideshows regularly. The mentioned option prevents the console from popping up when executing the bat file. If i "only execute if user is logged on" i do get the updated Data to display in Internet Explorer, but every 15 minutes a console window pops up for a second.

I tried exectuing with cmd /c "update" /min "PATH TO BAT" which dosesn't solve the problem.

答:
As mentioned in my [Edit] the problem was the option "run whether user is logged on or not", which i used to prevent the command line window to pop up.  When i use the option "only execute if user is logged on" i need to "wrap" the bat in a VBScript which doesnt open the cli. So by scheduling a vbs with the following lines:

```<code>Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /c PATH\TO\BAT", 0, True
</code>```

i can execute the bat without a flashing cli.

Title: How to debug task scheduler on win 10?

Body:
I'm trying to exectute the following bat every 15 minutes on my pc:

@ECHO OFF

SETLOCAL enabledelayedexpansion

SET host=http://dnsad.de/rest/
SET slideshowurl=http://dnsad.de/display/currentSlideshow/mac/
SET slideshowfolder=C:\Slideshow
SET ieprocess="iexplore.exe"
SET ignore_result=INFORMATION:

FOR /f "delims=" %%a IN ('getmac /v ^|find /i "Realtek"') DO (
    FOR %%b IN (%%a) DO (
        SET element=%%b
        IF "!element:~2,1!!element:~5,1!!element:~8,1!"=="---" set mac=%%b
    )
)

SET formattedmac=%mac:-=:%
SET macpath=%mac:-=_%

FOR /f "delims=" %%a IN ('curl -X GET %host%%formattedmac%') DO (
    FOR %%b IN (%%a) DO (
        SET update=%%b
    )
)

IF "%update%"=="[true]" (
    CD %ProgramFiles%\WinHTTrack\
    httrack %slideshowurl%%formattedmac% -q -O "C:\Slideshow" -s0 -B -a
    curl -X PUT %host%%formattedmac%

    START iexplore -k %slideshowfolder%\dnsad.de\display\currentSlideshow\mac\%macpath%.html
)

EXIT

The script works as it should when executed. Im getting the device's mac address, getting the expected server responses from curl, WinHTTrack is backing up the data correctly, curl updates the server fields and then the internet explorer gets opened with the updated,local html.

When scheduled as Task with win 7 it works as it should as well. When running the bat from Task Scheduler on Win 10 the last thing it does is the curl PUT, but the Internet Exploerer is never opened. The task is marked as succesful.

I am logged in as admin on Win 7 and Win 10. I tested pretty much every setting within the taskscheduler. Nothing seems to be working. Why doesnt the internet explorer start ?

[EDIT]

It seems that the option "Run whether user is logged on or not" causes the problem. But here is the catch:
I'm displaying slideshows in Internet Explorer Kiosk Mode and need to get updated Data from my server to Display new Slideshows regularly. The mentioned option prevents the console from popping up when executing the bat file. If i "only execute if user is logged on" i do get the updated Data to display in Internet Explorer, but every 15 minutes a console window pops up for a second.

I tried exectuing with cmd /c "update" /min "PATH TO BAT" which dosesn't solve the problem.

Body:
As mentioned in my [Edit] the problem was the option "run whether user is logged on or not", which i used to prevent the command line window to pop up.  When i use the option "only execute if user is logged on" i need to "wrap" the bat in a VBScript which doesnt open the cli. So by scheduling a vbs with the following lines:

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /c PATH\TO\BAT", 0, True

i can execute the bat without a flashing cli.


问:
Domain with www on different IP than non-www
I'm doing my best to learn and understand how DNS works. On my journey, I found something interesting. I've seen several cases, including chanel.com and prada.com, where the website redirects from domain.com to www.domain.com. That's understandable and I've explored this debatable subject in the past. What's new though is that in these cases, the www version is on another IP. So if we open the chanel.com, it makes a 301 redirection to www.chanel.com, which happens to have different IP. What are the potential benefits and reasons of this idea?</p>

答:
A lot of companies have seperate servers or applications to handle redirects, so the real website is only listening to www.example.com and the domain example.com is pointing to the redirect server who is giving the redirect.

This is useful for managing all your redirects in one place, for example you got the domain www.example2.com that should redirect to www.example.com you can handle that easily on the same server. and even redirect to a specific page like www.example.com/example2

Cheers!


问:
Problems with hosting reportviewer reports vs2010
I am having a prob with a report in vs2010:

An error occurred during local report processing.
  The definition of the report 'Report1.rdlc' is invalid.
  An unexpected error occurred in Report Processing.
  Could not load file or assembly 'Microsoft.ReportViewer.ProcessingObjectModel, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I have added the other reportviewer dlls to the bin but I am struggling to find this one.

I am hosting with cyberyhost pro if anybody has experience of that.

Also reports are in local mode.

I have tried to extract the dll from the reportviewer distributable setup but I dont know what I am doing :) and failed miserably.

Thanks in advance
Roger

答:
I was able to find the DLL in the assembly cache.

Open Add Reference and navigate to:
(Windows/assembly/Microsoft.ReportViewer.ProcessingObjectModel).

Choose the folder that starts with 10.0.0.0 and select the DLL.


问:
composer identity issue Authorization failure error hyperldeger composer v0.15.0
I had the same issue which discussed here, and based on comments I fixed the problem by removing .composer-credentials directory and deploying my network again. Now I am using the new version of composer(v0.15.0). I already removed two directories (.composer-credentials and .composer-connection-profiles), but again when I run

composer identity issue -c admin@test-network -f membercard -u member -a "resource:org..."

I get the same error --> fabric-ca request register failed with errors [[{"code":400,"message":"Authorization failure"}]].

答:
We don't have a full history of what you have done but the following sequence should help.

With v0.15.0 we have moved to the business network cards, and you are using them on your command line with the -c option.
Having deleted the ~/.composer-credentials and ~/.composer-connection-profiles folders associated with older versions I assume that you also created the PeerAdmin card using the  createPeerAdminCard.sh script from fabric tools.

I assume that you have executed the 2 commands:
composer runtime install ... and
composer network start ...

and then run:
composer card import ... to import the card of the Network Admin that you created with the composer network start command.

To diagnose you problem further I would sugggest:
composer card list
and
composer card list --name
to confirm the cards you have

Then ping to confirm your Network Admin works OK
composer network ping...

Now try
composer network list ...
The list which will show you the participants you have (amongst other things) and the participants should match up with the data you are passing with -a in the composer identity issue command.

At this point you should have seen if the Network Admin ID that was originally causing the access problem works OK, or should have more information to follow up with.


问:
How to assign object's for loop output to a variable
While I'm converting the array to object, I found a critical mistake that I can't solve. When we use map method to an array, it returns something but with the object, it doesn't return anything.

```<code>let output = for(var key in taggedOnes) { <- this is not a good approach at all.
// But I'm looking for similar logic.
      let item = taggedOnes[key];
      ...
      if(id===this.state.selectedClothId) {
        return ( <- I can't return it? :(
          <View
            key={id}
            style={{
              top,
              left,
              height: thumbSize,
              width: thumbSize,
              borderWidth: 2,
              borderColor: 'yellow'
            }}
          />
        );
      } else {
        return (
          <View
            key={id}
            style={{
              top,
              left,
              height: thumbSize,
              width: thumbSize,
              borderWidth: 2,
              borderColor: 'white'
            }}
          />
        );
      }
    }
    return output; <- I want to return whole React Elements in one element like array.
</code>```

答:
You can use Object.keys to get an array with the keys in your taggedOnes object.
Then, you can call Array.prototype.map on this array to browse your array and return another array.

I don't know where do you create your id variable, but you can easily adapt the following example:

```<code>const output = Object.keys(taggedOnes).map(key => {
      const item = taggedOnes[key];

      if (id === this.state.selectedClothId) {
        return (
          <View
            key={id}
            style={{
              top,
              left,
              height: thumbSize,
              width: thumbSize,
              borderWidth: 2,
              borderColor: 'yellow'
            }}
          />
        );
      } else {
        return (
          <View
            key={id}
            style={{
              top,
              left,
              height: thumbSize,
              width: thumbSize,
              borderWidth: 2,
              borderColor: 'white'
            }}
          />
        );
      }
    }
});
</code>```

Body:
While I'm converting the array to object, I found a critical mistake that I can't solve. When we use map method to an array, it returns something but with the object, it doesn't return anything.

let output = for(var key in taggedOnes) { <- this is not a good approach at all.
// But I'm looking for similar logic.
      let item = taggedOnes[key];
      ...
      if(id===this.state.selectedClothId) {
        return ( <- I can't return it? :(
          <View
            key={id}
            style={{
              top,
              left,
              height: thumbSize,
              width: thumbSize,
              borderWidth: 2,
              borderColor: 'yellow'
            }}
          />
        );
      } else {
        return (
          <View
            key={id}
            style={{
              top,
              left,
              height: thumbSize,
              width: thumbSize,
              borderWidth: 2,
              borderColor: 'white'
            }}
          />
        );
      }
    }
    return output; <- I want to return whole React Elements in one element like array.

Body:
You can use Object.keys to get an array with the keys in your taggedOnes object.
Then, you can call Array.prototype.map on this array to browse your array and return another array.

I don't know where do you create your id variable, but you can easily adapt the following example:

const output = Object.keys(taggedOnes).map(key => {
      const item = taggedOnes[key];

      if (id === this.state.selectedClothId) {
        return (
          <View
            key={id}
            style={{
              top,
              left,
              height: thumbSize,
              width: thumbSize,
              borderWidth: 2,
              borderColor: 'yellow'
            }}
          />
        );
      } else {
        return (
          <View
            key={id}
            style={{
              top,
              left,
              height: thumbSize,
              width: thumbSize,
              borderWidth: 2,
              borderColor: 'white'
            }}
          />
        );
      }
    }
});


问:
Spring mvc : Changing default Response format from xml to json
I have gone through other similar asked questions but nothing worked for me.

All my API's return JSON as response by Default:

Because of some XML API,  i had to add jackson-xml

```<code>    <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>
</code>```

Now by default "Without accept header" All responses are XML.

I would like to have JSON as default Response format .

As stated in the doc here:

https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

I implemented the following config :

```<code>@Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true)
                .useJaf(false).defaultContentType(MediaType.APPLICATION_JSON)
                .mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
    }
</code>```

Case 1: if i make the ignoreAcceptHeader(true)    then everything is JSON even the XML API returning JSON.

Case 2: when ignoreAcceptHeader(false) is then default is XML.

I forget to mention my API's look like this:

```<code>@RequestMapping(value = "/getXml", method = RequestMethod.GET)
public ResponseEntity<String> getXml( HttpServletRequest request)
        throws JAXBException {
    return returnXml();
}
</code>```

I am quite lost here, All i want is Default(Without AcceptHeader) should be JSON.  (API returns XML as String)

And when Accept Header : "Application/xml" is defined then response should be XML.

Any advice would be of great help.

Thanks.

答:
For me, adding

```<code>@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
    }

}
</code>```

solved the problem.

Now by default all RestControllers return JSON, if no Accept header in the request.
Also if Accept: application/xml header is passed, then result is XML.

Also, worth reading: https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

Body:
I have gone through other similar asked questions but nothing worked for me.

All my API's return JSON as response by Default:

Because of some XML API,  i had to add jackson-xml

    <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>

Now by default "Without accept header" All responses are XML.

I would like to have JSON as default Response format .

As stated in the doc here:

https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

I implemented the following config :

@Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true)
                .useJaf(false).defaultContentType(MediaType.APPLICATION_JSON)
                .mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
    }

Case 1: if i make the ignoreAcceptHeader(true)    then everything is JSON even the XML API returning JSON.

Case 2: when ignoreAcceptHeader(false) is then default is XML.

I forget to mention my API's look like this:

@RequestMapping(value = "/getXml", method = RequestMethod.GET)
public ResponseEntity<String> getXml( HttpServletRequest request)
        throws JAXBException {
    return returnXml();
}

I am quite lost here, All i want is Default(Without AcceptHeader) should be JSON.  (API returns XML as String)

And when Accept Header : "Application/xml" is defined then response should be XML.

Any advice would be of great help.

Thanks.

Body:
For me, adding

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
    }

}

solved the problem.

Now by default all RestControllers return JSON, if no Accept header in the request.
Also if Accept: application/xml header is passed, then result is XML.

Also, worth reading: https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc


问:
Julian to gregorian date with OutOfBoundsDatetime
I'm working with a pandas dataframe and I have a DATE column that contains a julian date. I want to convert every value of that column to a gregorian date.

To achieve that I used the following code:

```<code>df[['DATE']] = df[['DATE']].apply(lambda x: pd.to_datetime(x - pd.Timestamp(0).to_julian_date(), unit='D'))
</code>```

Unfortunately, I get an error that looks like this:

```<code>OutOfBoundsDatetime: ("cannot convert input 381088.5 with the unit 'D'", u'occurred at index MXPLD_DATE')
</code>```

When I look for the input value that causing problem in the dataframe, it doesn't exist at all, I don't know where 381088.5 come from.

Can you tell me what I'm doing wrong?

Thank you.

EDIT 1

I tried @jezrael solution but I still got a similar error.

```<code>df['DATE'] = pd.to_datetime(df['DATE'], unit='D', origin='julian')
</code>```

Error:

```<code>---------------------------------------------------------------------------
OutOfBoundsDatetime                       Traceback (most recent call last)
<ipython-input-18-4353e2be1ced> in <module>()
----> 1 df['DATE'] = pd.to_datetime(df['DATE'], unit='D', origin='julian')

/opt/anaconda2/lib/python2.7/site-packages/pandas/core/tools/datetimes.pyc in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin)
    469             raise tslib.OutOfBoundsDatetime(
    470                 "{original} is Out of Bounds for "
--> 471                 "origin='julian'".format(original=original))
    472
    473     elif origin not in ['unix', 'julian']:

OutOfBoundsDatetime: 0          2457184
1          2457155
2          2457155
3          2457155
4          2457155
5          2457155
6          2457155
7          2457155
8          2457155
9          2457155
10         2457155
11         2457155
12         2457155
13         2457155
14         2457155
15         2457155
16         2457155
17         2457155
18         2457155
19         2457155
20         2457155
21         2457155
22         2457155
23         2457155
24         2457155
25         2457155
26         2457155
27         2457155
28         2457701
29         2457701
            ...
4597928    2457724
4597929    2457724
4597930    2457724
4597931    2457724
4597932    2457724
4597933    2457724
4597934    2457724
4597935    2457724
4597936    2457724
4597937    2457724
4597938    2457724
4597939    2457724
4597940    2457724
4597941    2457724
4597942    2457724
4597943    2457724
4597944    2457724
4597945    2457724
4597946    2457724
4597947    2457724
4597948    2457724
4597949    2457724
4597950    2457724
4597951    2457724
4597952    2457724
4597953    2457724
4597954    2457724
4597955    2457724
4597956    2457724
4597957    2457724
Name: DATE, Length: 4597958, dtype: int64 is Out of Bounds for origin='julian'
</code>```

答:
I believe you need to_datetime with parameter origin:

```<code>df = pd.DataFrame({'julian':[2458072.5, 2458073.5]})

df['date'] = pd.to_datetime(df['julian'], unit='D', origin='julian')
print (df)
      julian       date
0  2458072.5 2017-11-15
1  2458073.5 2017-11-16
</code>```

EDIT:

There is problem some datetime OutOfBounds.

So first checked timestamp limitations:

```<code>In [66]: pd.Timestamp.min
Out[66]: Timestamp('1677-09-21 00:12:43.145225')

In [67]: pd.Timestamp.max
Out[67]: Timestamp('2262-04-11 23:47:16.854775807')
</code>```

And then get minimal julian datetimes (by convertin online, e.g. here):

```<code>maxdate = 2547338
mindate = 2333836
</code>```

Then add NaN for dates out of range, e.g. by where:

```<code> df = pd.DataFrame({'julian':[2821676, 2547338, 1, 2333836]})
maxdate = 2547338
mindate = 2333836

clean_dates = df['julian'].where(df['julian'].between(mindate, maxdate))
print (clean_dates)
0          NaN
1    2547338.0
2          NaN
3    2333836.0

df['date'] = pd.to_datetime(clean_dates, unit='D', origin='julian')
print (df)
    julian                date
0  2821676                 NaT
1  2547338 2262-04-10 12:00:00
2        1                 NaT
3  2333836 1677-09-21 12:00:00
</code>```

And last apply solution to your data - there are 2 values converted to NaT:

```<code>print (df['MXPLD_DATE'][~df['MXPLD_DATE'].between(mindate, maxdate)])

1217806    2821676
3167148    2821676
Name: MXPLD_DATE, dtype: int64

clean_dates = df['MXPLD_DATE'].where(df['MXPLD_DATE'].between(mindate, maxdate))
df['MXPLD_DATE'] = pd.to_datetime(clean_dates, unit='D', origin='julian')
print (df['MXPLD_DATE'])
0         2015-06-10 12:00:00
1         2015-05-12 12:00:00
2         2015-05-12 12:00:00
3         2015-05-12 12:00:00
4         2015-05-12 12:00:00
5         2015-05-12 12:00:00
6         2015-05-12 12:00:00
7         2015-05-12 12:00:00
8         2015-05-12 12:00:00
9         2015-05-12 12:00:00
10        2015-05-12 12:00:00
</code>```

Body:
I'm working with a pandas dataframe and I have a DATE column that contains a julian date. I want to convert every value of that column to a gregorian date.

To achieve that I used the following code:

df[['DATE']] = df[['DATE']].apply(lambda x: pd.to_datetime(x - pd.Timestamp(0).to_julian_date(), unit='D'))

Unfortunately, I get an error that looks like this:

OutOfBoundsDatetime: ("cannot convert input 381088.5 with the unit 'D'", u'occurred at index MXPLD_DATE')

When I look for the input value that causing problem in the dataframe, it doesn't exist at all, I don't know where 381088.5 come from.

Can you tell me what I'm doing wrong?

Thank you.

EDIT 1

I tried @jezrael solution but I still got a similar error.

df['DATE'] = pd.to_datetime(df['DATE'], unit='D', origin='julian')

Error:

---------------------------------------------------------------------------
OutOfBoundsDatetime                       Traceback (most recent call last)
<ipython-input-18-4353e2be1ced> in <module>()
----> 1 df['DATE'] = pd.to_datetime(df['DATE'], unit='D', origin='julian')

/opt/anaconda2/lib/python2.7/site-packages/pandas/core/tools/datetimes.pyc in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin)
    469             raise tslib.OutOfBoundsDatetime(
    470                 "{original} is Out of Bounds for "
--> 471                 "origin='julian'".format(original=original))
    472
    473     elif origin not in ['unix', 'julian']:

OutOfBoundsDatetime: 0          2457184
1          2457155
2          2457155
3          2457155
4          2457155
5          2457155
6          2457155
7          2457155
8          2457155
9          2457155
10         2457155
11         2457155
12         2457155
13         2457155
14         2457155
15         2457155
16         2457155
17         2457155
18         2457155
19         2457155
20         2457155
21         2457155
22         2457155
23         2457155
24         2457155
25         2457155
26         2457155
27         2457155
28         2457701
29         2457701
            ...
4597928    2457724
4597929    2457724
4597930    2457724
4597931    2457724
4597932    2457724
4597933    2457724
4597934    2457724
4597935    2457724
4597936    2457724
4597937    2457724
4597938    2457724
4597939    2457724
4597940    2457724
4597941    2457724
4597942    2457724
4597943    2457724
4597944    2457724
4597945    2457724
4597946    2457724
4597947    2457724
4597948    2457724
4597949    2457724
4597950    2457724
4597951    2457724
4597952    2457724
4597953    2457724
4597954    2457724
4597955    2457724
4597956    2457724
4597957    2457724
Name: DATE, Length: 4597958, dtype: int64 is Out of Bounds for origin='julian'

Body:
I believe you need to_datetime with parameter origin:

df = pd.DataFrame({'julian':[2458072.5, 2458073.5]})

df['date'] = pd.to_datetime(df['julian'], unit='D', origin='julian')
print (df)
      julian       date
0  2458072.5 2017-11-15
1  2458073.5 2017-11-16

EDIT:

There is problem some datetime OutOfBounds.

So first checked timestamp limitations:

In [66]: pd.Timestamp.min
Out[66]: Timestamp('1677-09-21 00:12:43.145225')

In [67]: pd.Timestamp.max
Out[67]: Timestamp('2262-04-11 23:47:16.854775807')

And then get minimal julian datetimes (by convertin online, e.g. here):

maxdate = 2547338
mindate = 2333836

Then add NaN for dates out of range, e.g. by where:

 df = pd.DataFrame({'julian':[2821676, 2547338, 1, 2333836]})
maxdate = 2547338
mindate = 2333836

clean_dates = df['julian'].where(df['julian'].between(mindate, maxdate))
print (clean_dates)
0          NaN
1    2547338.0
2          NaN
3    2333836.0

df['date'] = pd.to_datetime(clean_dates, unit='D', origin='julian')
print (df)
    julian                date
0  2821676                 NaT
1  2547338 2262-04-10 12:00:00
2        1                 NaT
3  2333836 1677-09-21 12:00:00

And last apply solution to your data - there are 2 values converted to NaT:

print (df['MXPLD_DATE'][~df['MXPLD_DATE'].between(mindate, maxdate)])

1217806    2821676
3167148    2821676
Name: MXPLD_DATE, dtype: int64

clean_dates = df['MXPLD_DATE'].where(df['MXPLD_DATE'].between(mindate, maxdate))
df['MXPLD_DATE'] = pd.to_datetime(clean_dates, unit='D', origin='julian')
print (df['MXPLD_DATE'])
0         2015-06-10 12:00:00
1         2015-05-12 12:00:00
2         2015-05-12 12:00:00
3         2015-05-12 12:00:00
4         2015-05-12 12:00:00
5         2015-05-12 12:00:00
6         2015-05-12 12:00:00
7         2015-05-12 12:00:00
8         2015-05-12 12:00:00
9         2015-05-12 12:00:00
10        2015-05-12 12:00:00


问:
Passing element ID from HTML to TypeScript
I have the following form where each option has an ID. I would like to read each ID into TypeScript. How do I approach such a scenario?

HTML file

```<code>  <div class="form-group" style="width: 350px">
      <label for="form_periodicity"><b>Periodicity</b></label><br>
      <select class="form-control" id="periodicity"
       style="width: 222px">
        <option id="opt_eod">EOD</option>
        <option id="opt_daily">Daily</option>
        <option id="opt_weekly">Weekly</option>
        <option id="opt_monthly">Monthly</option>
        <option id="opt_strict_run">Strict run</option>
      </select>
  </div>
</code>```

I would like to store the id's in a string variable in TypeScript.

答:
You can find all of the options for a select element using getElementByTagName. You can loop over those and get all of their ids:

```<code>const selectElement = <HTMLSelectElement>document.getElementById('periodicity');
const optionElements = selectElement.getElementsByTagName('option');
const ids = [];

for (let i = 0; i < optionElements.length; i++) {
    const optionElement = optionElements[i];
    ids.push(optionElement.id);
}

alert(ids.join(','));
</code>```

Body:
I have the following form where each option has an ID. I would like to read each ID into TypeScript. How do I approach such a scenario?

HTML file

      Periodicity

      <select class="form-control" id="periodicity"
       style="width: 222px">
        <option id="opt_eod">EOD</option>
        <option id="opt_daily">Daily</option>
        <option id="opt_weekly">Weekly</option>
        <option id="opt_monthly">Monthly</option>
        <option id="opt_strict_run">Strict run</option>
      </select>

I would like to store the id's in a string variable in TypeScript.

Body:
You can find all of the options for a select element using getElementByTagName. You can loop over those and get all of their ids:

const selectElement = <HTMLSelectElement>document.getElementById('periodicity');
const optionElements = selectElement.getElementsByTagName('option');
const ids = [];

for (let i = 0; i < optionElements.length; i++) {
    const optionElement = optionElements[i];
    ids.push(optionElement.id);
}

alert(ids.join(','));


问:
iPhone X and bottom safe area inset
I am working on layout for iPhoneX and have an issue with action sheets and Safari browser. This is an extra space. I need that my action sheets display more at the bottom ? How can I do that? I guess I need to disable safe area but how can I do it?

The reason why it happens probably that I use 2 UIWindows: one for all content and the second to display banner at the bottom of the screen.

the space that is outlined - is something to hide my app from everyone :) It does not exist in the app!

I want the action sheet be closer to the bottom. It works well on all devices except iPhoneX. I have 2 UIWindows (one for all content and the second one for ad at the bottom). So, for iPhoneX the content window has probably some safe area inset and becaise of that action sheet shows not from the bottom edge

答:
You don't have to disable the Safe Areas for the View Controller. They are still useful for the top, trailing and leading edges.

To remove the grey bar all you need is to set the bottomAnchor or your containing view to your superView instead of the bottom safe area with a constant of what you need.

You can also further adjust safe area insets with additionalSafeAreaInsets. https://developer.apple.com/documentation/uikit/uiviewcontroller/2902284-additionalsafeareainsets That allows you to leave them as is for the edges that you don't want to modify.

Title: iPhone X and bottom safe area inset


问:
Project search is not working in Android Studio
I have used Android Studio project search for a long time now, but it stopped working recently. It always issues an error message stating "Cannot preview regular expression search yet"

How do fix this ?

答:
You can use search button or double shift its work for android studio 2.3.3 never check android studio 3.0

https://stackoverflow.com/a/47305871/4549220


问:
Selenium Webdriver - How to handle Facebook alter dialog after Login

This is the image which is showing pop up when I login into facebook.
The question is how should I dismiss the pop up with the help of Webdriver in Java.

I have tried with alert/popup but both are not working.

答:
This is not alert or popup. This is chrome notification which can be disabled by ChromeOptions.

Use below code snippet to disable all notifications.

```<code>ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver","path/to/driver/exe");
WebDriver driver =new ChromeDriver(options);
</code>```

Body:
This is not alert or popup. This is chrome notification which can be disabled by ChromeOptions.

Use below code snippet to disable all notifications.

ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver","path/to/driver/exe");
WebDriver driver =new ChromeDriver(options);


问:
How to have Nested Map RDD's in Spark
I have a text file like:-

```<code>ID,Hour,Ratio
100775,0.0,1.0
100775,1.0,1.0560344797302321
100775,2.0,1.1333317975785973
100775,3.0,1.1886133302168074
100776,4.0,1.2824427440125867
</code>```

I want a structure like MAP{Hour,MAP{ID,Ratio}}, to be stored as a RDD. The closest structure I could find was JavaPairRDD. I tried implementing a structure like  JavaPairRDD{Hour,MAP{ID,Ratio}}, however, this structure offers lookup() functionality, which returns LIST{MAP{ID,RATIO}}, which does not solve my use-case, as I essentially want to do

```<code>ratio = MAP.get(Hour).get(ID)
</code>```

Any pointers on how to best get this done.

UPDATE:-

After Ramesh's answer, I tried the following:-

```<code>JavaRDD<Map<String,Map<String,String>>> mapRDD =  data.map(line -> line.split(",")).map(array-> Collections
              .singletonMap(array[0],
                Collections
                .singletonMap
                (array[1],array[2])));
</code>```

However, there is no lookup() like functionality available here, correct?

答:
Here's what you can do

```<code>scala> val rdd = sc.textFile("path to the csv file")
rdd: org.apache.spark.rdd.RDD[String] = path to csv file MapPartitionsRDD[7] at textFile at <console>:24

scala> val maps = rdd.map(line => line.split(",")).map(array => (array(1), Map(array(0) -> array(2)))).collectAsMap()
maps: scala.collection.Map[String,scala.collection.immutable.Map[String,String]] = Map(1.0 -> Map(100775 -> 1.0560344797302321), 4.0 -> Map(100776 -> 1.2824427440125867), 0.0 -> Map(100775 -> 1.0), 3.0 -> Map(100775 -> 1.1886133302168074), 2.0 -> Map(100775 -> 1.1333317975785973))
</code>```

If you require RDD[Map[String, Map[String, String]]] then you can do the following.

```<code>scala> val rddMaps = rdd.map(line => line.split(",")).map(array => Map(array(1) -> Map(array(0) -> array(2)))).collect
rddMaps: Array[scala.collection.immutable.Map[String,scala.collection.immutable.Map[String,String]]] = Array(Map(0.0 -> Map(100775 -> 1.0)), Map(1.0 -> Map(100775 -> 1.0560344797302321)), Map(2.0 -> Map(100775 -> 1.1333317975785973)), Map(3.0 -> Map(100775 -> 1.1886133302168074)), Map(4.0 -> Map(100776 -> 1.2824427440125867)))
</code>```

I hope the answer is helpful

Title: How to have Nested Map RDD's in Spark

Body:
I have a text file like:-

ID,Hour,Ratio
100775,0.0,1.0
100775,1.0,1.0560344797302321
100775,2.0,1.1333317975785973
100775,3.0,1.1886133302168074
100776,4.0,1.2824427440125867

I want a structure like MAP{Hour,MAP{ID,Ratio}}, to be stored as a RDD. The closest structure I could find was JavaPairRDD. I tried implementing a structure like  JavaPairRDD{Hour,MAP{ID,Ratio}}, however, this structure offers lookup() functionality, which returns LIST{MAP{ID,RATIO}}, which does not solve my use-case, as I essentially want to do

ratio = MAP.get(Hour).get(ID)

Any pointers on how to best get this done.

UPDATE:-

After Ramesh's answer, I tried the following:-

JavaRDD<Map<String,Map<String,String>>> mapRDD =  data.map(line -> line.split(",")).map(array-> Collections
              .singletonMap(array[0],
                Collections
                .singletonMap
                (array[1],array[2])));

However, there is no lookup() like functionality available here, correct?

Body:
Here's what you can do

scala> val rdd = sc.textFile("path to the csv file")
rdd: org.apache.spark.rdd.RDD[String] = path to csv file MapPartitionsRDD[7] at textFile at <console>:24

scala> val maps = rdd.map(line => line.split(",")).map(array => (array(1), Map(array(0) -> array(2)))).collectAsMap()
maps: scala.collection.Map[String,scala.collection.immutable.Map[String,String]] = Map(1.0 -> Map(100775 -> 1.0560344797302321), 4.0 -> Map(100776 -> 1.2824427440125867), 0.0 -> Map(100775 -> 1.0), 3.0 -> Map(100775 -> 1.1886133302168074), 2.0 -> Map(100775 -> 1.1333317975785973))

If you require RDD[Map[String, Map[String, String]]] then you can do the following.

scala> val rddMaps = rdd.map(line => line.split(",")).map(array => Map(array(1) -> Map(array(0) -> array(2)))).collect
rddMaps: Array[scala.collection.immutable.Map[String,scala.collection.immutable.Map[String,String]]] = Array(Map(0.0 -> Map(100775 -> 1.0)), Map(1.0 -> Map(100775 -> 1.0560344797302321)), Map(2.0 -> Map(100775 -> 1.1333317975785973)), Map(3.0 -> Map(100775 -> 1.1886133302168074)), Map(4.0 -> Map(100776 -> 1.2824427440125867)))

I hope the answer is helpful


答:
What you need is Object.keys(taggedOnes).map. A for loop doesn't return anything it just loops over the values, a return statement inside a for loop will return the current function.

Map, on the other hand, transforms each element of the array using the provided function, in your case it is/was transforming it to a list of react components.

Title: How to assign object's for loop output to a variable


问:
Core Data - Memory Management?
```<code>[myArray addObject:myObject];
[object release];
</code>```

In obvjective c every time you add an object with retain count of 1 to an array, you must release it right after to prevent a leak.

Does this apply to NSManagedObjects ?
Because in the code above if myObject is an instance of NSManagedObject I get "EXC_BAD_ACCESS"

答:
Your blanket statement about releasing objects is absolutely wrong. In fact, even thinking about the retain count of an object is wrong. If you own an object, and you are dropping your reference to the owned object, you must release it. That's the basic rule. If you don't own the object, you have no business releasing it. For more detail, read the Cocoa Memory Management Programming Guide.

As for your core question of "is memory management of Core Data objects the same as everything else?", the answer is yes. Core Data itself holds onto various objects and there's some intricacies with the faulting behavior, but the ownership rules are exactly the same as the rest of Cocoa.

Title: Core Data - Memory Management?

Body:
[myArray addObject:myObject];
[object release];

In obvjective c every time you add an object with retain count of 1 to an array, you must release it right after to prevent a leak.

Does this apply to NSManagedObjects ?
Because in the code above if myObject is an instance of NSManagedObject I get "EXC_BAD_ACCESS"


问:
Python2/3 give different answers to the same math operation...why? (calculating percent difference)
Python 2 and Python 3 seem to arrive at different answers for the very simple math operation of finding percentage difference between two quantities.

For example:

```<code># Python 2.7.10
>>> def percent_difference(qty1, qty2):
...     diff = max(qty1, qty2) - min(qty1, qty2)
...     print(diff)
...     percent = diff / ( (qty1 + qty2) / 2)
...     print(percent)
...
>>> percent_difference(1, 2)
1
1

# Python 3.6.2

>>> def percent_difference(qty1, qty2):
...     diff = max(qty1, qty2) - min(qty1, qty2)
...     print(diff)
...     percent = diff / ( (qty1 + qty2) / 2)
...     print(percent)
...
>>> percent_difference(1, 2)
1
0.6666666666666666
</code>```

What's going on here?

(Python3 is correct)

答:
Python 3 changed the behaviour of the / operator. It used to depend on the used types (i.e. integer / integer is integer division, if one of the operands is a float you get float division).

The rationale for the change is explained in the Python Enhancement Proposal PEP-0238:

The correct work-around is subtle: casting an argument to float() is wrong if it could be a complex number; adding 0.0 to an argument doesn't preserve the sign of the argument if it was minus zero. The only solution without either downside is multiplying an argument (typically the first) by 1.0. This leaves the value and sign unchanged for float and complex, and turns int and long into a float with the corresponding value.

Body:
Python 2 and Python 3 seem to arrive at different answers for the very simple math operation of finding percentage difference between two quantities.

For example:

# Python 2.7.10
>>> def percent_difference(qty1, qty2):
...     diff = max(qty1, qty2) - min(qty1, qty2)
...     print(diff)
...     percent = diff / ( (qty1 + qty2) / 2)
...     print(percent)
...
>>> percent_difference(1, 2)
1
1

# Python 3.6.2

>>> def percent_difference(qty1, qty2):
...     diff = max(qty1, qty2) - min(qty1, qty2)
...     print(diff)
...     percent = diff / ( (qty1 + qty2) / 2)
...     print(percent)
...
>>> percent_difference(1, 2)
1
0.6666666666666666

What's going on here?

(Python3 is correct)


答:
You can use Object.keys(taggedOnes).map to convert the taggedOnes object to an array of its transformed values.

```<code>let output = Object.keys(taggedOnes).map(key => {
  let item = taggedOnes[key];
  ...
  if (id===this.state.selectedClothId) {
    return ...
  } else {
    return ...
  }
});
</code>```

Body:
You can use Object.keys(taggedOnes).map to convert the taggedOnes object to an array of its transformed values.

let output = Object.keys(taggedOnes).map(key => {
  let item = taggedOnes[key];
  ...
  if (id===this.state.selectedClothId) {
    return ...
  } else {
    return ...
  }
});


问:
Woocommerce: Add Price Suffix incl. Hyperlink
is it possible to add a Hyperlink to the Price Suffix of WooCommerce?

To add a Suffix, I used this Code

```<code>add_filter( 'woocommerce_get_price_html', 'custom_price_suffix', 100, 2 );

function custom_price_suffix( $price, $product ){
        $price = $price . 'zzgl. Versandkosten' ;
            return apply_filters( 'woocommerce_get_price', $price );
}
</code>```

To Show the Text "zzgl. Versandkosten". I want to add a Hyperlink to "zzgl. Versandkosten" where Customers can read a PDF Documentation about our Shipping prices.

Thanks

Mauro

答:
Simply add an anchor tag to the appended text like so:

```<code>add_filter( 'woocommerce_get_price_html', 'custom_price_suffix', 100, 2 );

function custom_price_suffix( $price, $product ){
    $price = $price . '<a href="/">zzgl. Versandkosten</a>';
    return apply_filters( 'woocommerce_get_price', $price );
}
</code>```

You can replace the '/' in the a tag with the URL you want to go to.

Body:
is it possible to add a Hyperlink to the Price Suffix of WooCommerce?

To add a Suffix, I used this Code

add_filter( 'woocommerce_get_price_html', 'custom_price_suffix', 100, 2 );

function custom_price_suffix( $price, $product ){
        $price = $price . 'zzgl. Versandkosten' ;
            return apply_filters( 'woocommerce_get_price', $price );
}

To Show the Text "zzgl. Versandkosten". I want to add a Hyperlink to "zzgl. Versandkosten" where Customers can read a PDF Documentation about our Shipping prices.

Thanks

Mauro

Body:
Simply add an anchor tag to the appended text like so:

add_filter( 'woocommerce_get_price_html', 'custom_price_suffix', 100, 2 );

function custom_price_suffix( $price, $product ){
    $price = $price . '<a href="/">zzgl. Versandkosten</a>';
    return apply_filters( 'woocommerce_get_price', $price );
}

You can replace the '/' in the a tag with the URL you want to go to.


问:
Cannot use Swift Package Manager
I have the latest release versions of Swift and Xcode.

I am trying to use the Swift Package Manager to use this:

```<code>.package(url: "https://github.com/matejkosiarcik/Stopwatch.git", from: "0.1.0")
</code>```

However, I have spent multiple days trying how to figure out how to embed this in my command line tool, or even in a brand new command line tool so that in Main.swift it doesn't give the error:

No such module 'Stopwatch'.

Would someone please explain how to do it for this exact package?

Thank you.

答:
Note that the modules in a Swift Package are specified as targets, not as products.

Suppose you have the following product spec in your Package.swift:

```<code>products: [ .library(name: "MyProduct", targets: ["MyTarget1", "MyTarget2"])]
</code>```

Then in some other package you use this product as a dependency in Package.swift:

```<code>.target(name: "TargetInSomeOtherPackage", dependencies: ["MyProduct"])
</code>```

And in swift code you import modules:

```<code>import MyTarget1
import MyTarget2
</code>```

In your case, you defined your product: .library(name: "Stopwatch", targets: ["lib"]). This means that you can use Stopwatch as a dependency, and import module lib in your Swift code. There is no module Stopwatch that you can import.

Title: Cannot use Swift Package Manager

Body:
I have the latest release versions of Swift and Xcode.

I am trying to use the Swift Package Manager to use this:

.package(url: "https://github.com/matejkosiarcik/Stopwatch.git", from: "0.1.0")

However, I have spent multiple days trying how to figure out how to embed this in my command line tool, or even in a brand new command line tool so that in Main.swift it doesn't give the error:

No such module 'Stopwatch'.

Would someone please explain how to do it for this exact package?

Thank you.

Body:
Note that the modules in a Swift Package are specified as targets, not as products.

Suppose you have the following product spec in your Package.swift:

products: [ .library(name: "MyProduct", targets: ["MyTarget1", "MyTarget2"])]

Then in some other package you use this product as a dependency in Package.swift:

.target(name: "TargetInSomeOtherPackage", dependencies: ["MyProduct"])

And in swift code you import modules:

import MyTarget1
import MyTarget2

In your case, you defined your product: .library(name: "Stopwatch", targets: ["lib"]). This means that you can use Stopwatch as a dependency, and import module lib in your Swift code. There is no module Stopwatch that you can import.


Title: Loop within string in r to output expressions with vectorized values

Body:
Example data:

> DF
   A  B  C
1 11 22 88
2 11 22 47
3  2 30 21
4  3 30 21

> r
[1] "A==A[i] & B==B[i] "           "A==A[i] & C==C[i] "
[3] "B==B[i] & C==C[i] "           "A==A[i] & B==B[i] & C==C[i] "

Executed code:

> output=list()
> for (j in r){
+   for (i in 1:nrow(DF)){
+
+     output[[j]][i]=j
+   }
+ }
> output
$`A==A[i] & B==B[i] `
[1] "A==A[i] & B==B[i] " "A==A[i] & B==B[i] " "A==A[i] & B==B[i] "
[4] "A==A[i] & B==B[i] "

$`A==A[i] & C==C[i] `
[1] "A==A[i] & C==C[i] " "A==A[i] & C==C[i] " "A==A[i] & C==C[i] "
[4] "A==A[i] & C==C[i] "

$`B==B[i] & C==C[i] `
[1] "B==B[i] & C==C[i] " "B==B[i] & C==C[i] " "B==B[i] & C==C[i] "
[4] "B==B[i] & C==C[i] "

$`A==A[i] & B==B[i] & C==C[i] `
[1] "A==A[i] & B==B[i] & C==C[i] " "A==A[i] & B==B[i] & C==C[i] "
[3] "A==A[i] & B==B[i] & C==C[i] " "A==A[i] & B==B[i] & C==C[i] "

> output=purrr::flatten_chr(output)
> output
 [1] "A==A[i] & B==B[i] "           "A==A[i] & B==B[i] "
 [3] "A==A[i] & B==B[i] "           "A==A[i] & B==B[i] "
 [5] "A==A[i] & C==C[i] "           "A==A[i] & C==C[i] "
 [7] "A==A[i] & C==C[i] "           "A==A[i] & C==C[i] "
 [9] "B==B[i] & C==C[i] "           "B==B[i] & C==C[i] "
[11] "B==B[i] & C==C[i] "           "B==B[i] & C==C[i] "
[13] "A==A[i] & B==B[i] & C==C[i] " "A==A[i] & B==B[i] & C==C[i] "
[15] "A==A[i] & B==B[i] & C==C[i] " "A==A[i] & B==B[i] & C==C[i] "

My target was to get the same output with the specific values A[i], B[i] and C[i] from DF, i.e., the final output would be the following:

> output
[1] "A==11 & B==22 "            "A==11 & B==22 "
[3] "A==2 & B==30 "             "A==3 & B==30 "
[5] "A==11 & C==88 "            "A==11 & C==47 "
[7] "A==2 & C==21 "             "A==3 & C==21 "
[9] "B==22 & C==88 "            "B==22 & C==47 "
[11] "B==30 & C==21 "           "B==30 & C==21 "
[13] "A==11 & B==22 & C==88 "   "A==11 & B==22 & C==47 "
[15] "A==2 & B==30 & C==21 "    "A==3 & B==30 & C==21 "

I would be grateful if someone could help me with this matter.

Body:
Is this output what you are after?

DF <- data.frame(A = c(11, 11, 2, 3),
                 B = c(22, 22, 30, 30),
                 C = c(88, 47, 21, 21))

r <- c("A==A[i] & B==B[i]", "A==A[i] & C==C[i]",
       "B==B[i] & C==C[i]", "A==A[i] & B==B[i] & C==C[i]")

output=list()
for (j in r){
  for (i in 1:nrow(DF))
    output[[j]][[i]] <- DF[with(DF, eval(parse(text = j))), ]
}

output

$`A==A[i] & B==B[i]`
$`A==A[i] & B==B[i]`[[1]]
   A  B  C
1 11 22 88
2 11 22 47

$`A==A[i] & B==B[i]`[[2]]
   A  B  C
1 11 22 88
2 11 22 47

$`A==A[i] & B==B[i]`[[3]]
  A  B  C
3 2 30 21

$`A==A[i] & B==B[i]`[[4]]
  A  B  C
4 3 30 21

$`A==A[i] & C==C[i]`
$`A==A[i] & C==C[i]`[[1]]
   A  B  C
1 11 22 88
...


问:
Hide Command Window of .BAT file that Executes Another .EXE File
This is a batch file in Windows.

Here is my .bat file

```<code>@echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"

"C:\ThirdParty.exe"
</code>```

This works fine except the .bat file leaves the command window open the whole time the "ThirdParty" application is running.

I need the command window to close.

I would use the short-cut for the application but I must be able to run this copy command first (it actually changes which data base and server to use for the application).

The ThirdParty application does not allow the user to change the source of the db or the application server.

We're doing this to allow users to change from a test environment to the production environment.

答:
Or you can use:

```<code>Start /d "the directory of the executable" /b "the name of the executable" "parameters of the executable" %1
</code>```

If %1 is a file then it is passed to your executable. For example in notepad.exe foo.txt %1 is "foo.txt".

The /b parameter of the start command does this:

Starts an application without opening a new Command Prompt window. CTRL+C handling is ignored unless the application enables CTRL+C processing. Use CTRL+BREAK to interrupt the application.

Which is exactly what we want.

OwnerDisplayName: Guiness

Body:
This is a batch file in Windows.

Here is my .bat file

@echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"

"C:\ThirdParty.exe"

This works fine except the .bat file leaves the command window open the whole time the "ThirdParty" application is running.

I need the command window to close.

I would use the short-cut for the application but I must be able to run this copy command first (it actually changes which data base and server to use for the application).

The ThirdParty application does not allow the user to change the source of the db or the application server.

We're doing this to allow users to change from a test environment to the production environment.

LastEditorDisplayName: VonC

Body:
Or you can use:

Start /d "the directory of the executable" /b "the name of the executable" "parameters of the executable" %1

If %1 is a file then it is passed to your executable. For example in notepad.exe foo.txt %1 is "foo.txt".

The /b parameter of the start command does this:

Starts an application without opening a new Command Prompt window. CTRL+C handling is ignored unless the application enables CTRL+C processing. Use CTRL+BREAK to interrupt the application.

Which is exactly what we want.


问:
Issue writing file to sftp - carriage return removed
I have a simple requirement where i have to write a csv to linux sftp . In the current implementation Which I have done CR-'carriage return' is being removed when writting the csv to sftp using mulesoft sftp connector . I have set encoding=US-ASCII on the sftp connector , in the dataweave , even in the property file as mule.encoding=US-ASCII.
 Nothing seems like working in cloud hub , but surprisingly the same works fine in my local .
 I understand after reading few blogs/ white papers that trasfer type should be 'ASCII' when writing to Linux SFTP .
 This is clearly an issue with cloudHub I believe . Any help is much appreciated .</p>

答: Explicitly setting %output application/csv lineSeparator="\r\n" worked for me. Thanks </p>


问:
windows start service failure on logging as different user?
I've logged into the visual studio as a different user while debugging the project encountered with error as:

"Windows service start failure"

But when I run with my own credentials working fine. I've tried by giving admin permissions to the particular user on the service but the result is same as below.

Can anyone help me on this?.

click here to see the issue

答:
Ensure your service has a 'ServiceProcessInstaller' (right-click designer-surface of your service.cs and select 'Add Installer'), then change the account property for the service process installer to whatever suits your needs best (Network Service, Local System or Local Service). You may also need to specify the startup type of the service installer class.

To install it do the following steps:

Run Visual Studio Command Prompt as administrator.

Change the directory to the output directory of the service (where the executable file is located) - 'cd C:\directory'

Perform the following command 'installutil service_name.exe'

The service should then startup based on the startup type you specified. You may need to start it manually.


问:
Does SSL protect documents sent over it?
If I understand correctly, SSL will protect (encrypt) HTTP transfer sent over it. But does this apply only to HTTP commands and responses?

If I GET a plain text file and someone intercepts my transaction, do they see plain text or encrypted text?

答:
Everything in the HTTP message is encrypted, including the headers, and the request/response load. [...] A possible attacker can only know the fact that a connection is taking place between the two, known to him, parties; the domain name and IP addresses.

See also: http://en.wikipedia.org/wiki/Https#Network_layers


问:
Shuffle array key and values php
I want to randomly shuffle the keys and values of a php array. I've already found solution to shuffle the order, but I want to shuffle the keys and values themselves.

The array array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour') would for example become array('oui' => 'yes, 'no' => 'non', 'bonjour' => 'hello'). Note that the first and last value have randomly swapped key and value.

I know you can use array_flip to flip the keys and values in an array. But this flips all keys and values, while I want to randomly flip a few keys and values. How would I do this?

答:
```<code>$array = array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour');

foreach($array as $key => $value) {
    if (0 === rand(0,1)) {
        $array[$value] = $key;
        unset($array[$key]);
    }
}
</code>```

Title: Shuffle array key and values php


问:
Does PACKAGE_USAGE_STATS permission effect auto update?
I am adding PACKAGE_USAGE_STATS permission to my app. Since this is a special permission that the user needs to grant from a special settings page, I would not expect it to appear in the Google Play permission list when they install the app - and thus I expect it not to enforce manual update for my app. Will it enforce manual update for my app or it will allow auto update for existing users?</p>

答:
Adding a permission will cause, that users will have to update the app manually.
All the permissions, which are in your manifest file are listed on Google Play.
Doesn't matter if it's runtime permission or not.</p>


问:
Set interval for Automatic (Delayed Start) Windows Services
I am working on Windows Server 2008 R2. I need to change the delayed start time, that is used in automatic delayed start mode, to 5 mins.

Any pointer as how to do this?

答:
When the startup type of the service is set to "Automatic (Delayed start)", the value of DelayedAutostart is set to 1
           HKLM\SYSTEM\CurrentControlSet\services\\DelayedAutostart

To increase the default delay of 120 seconds, right click the registry key and add new key AutoStartDelay (DWORD (32-bit)

```<code>      **HKLM\SYSTEM\CurrentControlSet\services\<service name>\AutoStartDelay**
</code>```

Its value can be set to decimal 240 for example.

Body:
When the startup type of the service is set to "Automatic (Delayed start)", the value of DelayedAutostart is set to 1
           HKLM\SYSTEM\CurrentControlSet\services\\DelayedAutostart

To increase the default delay of 120 seconds, right click the registry key and add new key AutoStartDelay (DWORD (32-bit)

      **HKLM\SYSTEM\CurrentControlSet\services\<service name>\AutoStartDelay**

Its value can be set to decimal 240 for example.


答:
Python2 and Python3 treat the div operation for integers differently.

In python3 the div operation will treat integers and floats the same:

```<code>2/3 = 1.5
2.0/3 = 1.5
2/3.0 = 1.5
2.0/3.0 = 1.5
</code>```

In python2 it will truncate the number after the floating points if both operands are integers:

```<code>2/3 = 1
2.0/3 = 1.5
2/3.0 = 1.5
2.0/3.0 = 1.5
</code>```

Title: Python2/3 give different answers to the same math operation...why? (calculating percent difference)

Body:
Python2 and Python3 treat the div operation for integers differently.

In python3 the div operation will treat integers and floats the same:

2/3 = 1.5
2.0/3 = 1.5
2/3.0 = 1.5
2.0/3.0 = 1.5

In python2 it will truncate the number after the floating points if both operands are integers:

2/3 = 1
2.0/3 = 1.5
2/3.0 = 1.5
2.0/3.0 = 1.5


问:
How to do an ODBC connection to OmniTracker?
I am set to do some statistics in Excel based on ticket and timeregistration data from OmniTracker (ITSM)

Does anybody know how to do an odbc connection to OmniTracker? I have googled it and found ODBC items - but not related to OmniTracker.

答:
Starting with Omnitracker 10.6 there is a feature called, 'DB Views'.

Your Omnitracker administrator should be able to set up DB Views on your behalf, which should be more convenient for you to query.


问:
Set variable on shub deploy project
I'm trying to setup scrapy settings to work with test and production environment on local and also on scrapinghub.
And I would like to know if there is any way to set this variable (for example as the following) on shub deploy:

And then at settings.py:

```<code>if env == "test":
     var1 = some_ip
     var2 = username
elif env == "prod":
     var1 = some_ip
     var2 = username
</code>```

Or... maybe there is a cleaner way to this?

Thank you for reading!

PS: I want to automate the settings depending of the environment where is the spider/project located instead of changing the variables manually.

EDIT: Found a better solution. Check the answer.

答:
Finally, I solved my problem following these steps:

Implement this example.

So now my settings look like this:

And then my __init__.py look like this:

Next, modified _environment.py as the following:

I hope I have been helpful!

PS: Remember that you need to have two projects on scrapinghub, one for production and one for testing to do this, also you need to deploy from the same project as the following:

And then you just have to (reference):

shub deploy test Deploys to test.

shub deploy prod Deploys to production.

shub deploy Deploys to test.

Title: Set variable on shub deploy project

Body:
I'm trying to setup scrapy settings to work with test and production environment on local and also on scrapinghub.
And I would like to know if there is any way to set this variable (for example as the following) on shub deploy:

And then at settings.py:

if env == "test":
     var1 = some_ip
     var2 = username
elif env == "prod":
     var1 = some_ip
     var2 = username

Or... maybe there is a cleaner way to this?

Thank you for reading!

PS: I want to automate the settings depending of the environment where is the spider/project located instead of changing the variables manually.

EDIT: Found a better solution. Check the answer.


问:
Twitter box is not auto filling with quote
I was working on a project 'quote generator'. Everything works fine except the Twitter button. It's opening a new window with a new tweet box but it is not filling the box with the desired quote in it. I'm a bit confused here. I tried everything. So a little help would be much appreciated. Thank you.

Here's my project: https://codepen.io/buzz_lightyear/pen/BmdzaZ

var quotes = ["The Way Get Started Is To Quit Talking And Begin Doing.", "The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty.", "Don't Let Yesterday Take Up Too Much Of Today.", "You Learn More From Failure Than From Success. Don't Let It Stop You. Failure Builds Character.", "It's Not Whether You Get Knocked Down, It's Whether You Get Up.", "If You Are Working On Something That You Really Care About, You Don't Have To Be Pushed. The Vision Pulls You.", "People Who Are Crazy Enough To Think They Can Change The World, Are The Ones Who Do", "Failure Will Never Overtake Me If My Determination To Succeed Is Strong Enough.", "Entrepreneurs Are Great At Dealing With Uncertainty And Also Very Good At Minimizing Risk. That's The Classic Entrepreneur", "We May Encounter Many Defeats But We Must Not Be Defeated", "Knowing Is Not Enough; We Must Apply. Wishing Is Not Enough; We Must Do", "Imagine Your Life Is Perfect In Every Respect; What Would It Look Like?"];

function makeId() {
  var randomNumber = Math.floor(Math.random() * quotes.length);
  $("#quote > h1").html(quotes[randomNumber]);
}

$(document).ready(function() {
  $("#press > button").click(function() {
    $("#quote > i").fadeOut("slow").fadeIn("slow");
    $("#quote > h1").fadeOut("slow", function() {
      makeId();
      $(this).fadeIn("slow");
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Encode+Sans+Expanded" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="style.css" rel="stylesheet">

<div id="header">
  <h1>My Quote Machine</h1>
</div>

<div id="quote">
  <i class="fa fa-quote-left" aria-hidden="true" style="font-size: 15px; bottom: 10px;"></i>
  <h1>I shall not waste my days in trying to prolong them.</h1>
</div>
<div id="press">
  <div id="icon">
    <i class="fa fa-twitter fa-2x" id="twitterid" style="color: white"></i>
  </div>
  <button class="btn btn-lg">Quote</button>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript.js" type="text/javascript"></script></code>```

答:
You were leaving the text attribute in the tweet intent empty.

You need to supply this initially (as you have the first quote hardcoded in the HTML).

Then in your makeId function dynamically change the text attribute.

https://codepen.io/anon/pen/YExdNY

HTML (I moved the twitterid to the actual link instead of the icon):

```<code><a id="twitterid" href="https://twitter.com/intent/tweet/?text=I shall not waste my days in trying to prolong them." target="_blank">
  <i class="fa fa-twitter fa-2x"  style="color: white"></i>
</a>
</code>```

JS:

```<code>function makeId() {
  var randomNumber = Math.floor(Math.random() * quotes.length);
  $("#quote > h1").html(quotes[randomNumber]);

  // get the twitter intent link
  var twitterid = $("#twitterid");
  // remove existing text attribute with quote
  // change with the newly generated quote
  twitterid.attr("href", twitterid.attr("href").split("text=")[0] + "text=" +
  quotes[randomNumber]);
}
</code>```

Edit: This line of code:

```<code>twitterid.attr("href", twitterid.attr("href").split("text=")[0] + "text="
+ quotes[randomNumber]);
</code>```

Gets the href attribute from the twitterid link, splits the href's value by the text attribute, then adds it back again but uses the next quote.

Body:
I was working on a project 'quote generator'. Everything works fine except the Twitter button. It's opening a new window with a new tweet box but it is not filling the box with the desired quote in it. I'm a bit confused here. I tried everything. So a little help would be much appreciated. Thank you.

Here's my project: https://codepen.io/buzz_lightyear/pen/BmdzaZ

var quotes = ["The Way Get Started Is To Quit Talking And Begin Doing.", "The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty.", "Don't Let Yesterday Take Up Too Much Of Today.", "You Learn More From Failure Than From Success. Don't Let It Stop You. Failure Builds Character.", "It's Not Whether You Get Knocked Down, It's Whether You Get Up.", "If You Are Working On Something That You Really Care About, You Don't Have To Be Pushed. The Vision Pulls You.", "People Who Are Crazy Enough To Think They Can Change The World, Are The Ones Who Do", "Failure Will Never Overtake Me If My Determination To Succeed Is Strong Enough.", "Entrepreneurs Are Great At Dealing With Uncertainty And Also Very Good At Minimizing Risk. That's The Classic Entrepreneur", "We May Encounter Many Defeats But We Must Not Be Defeated", "Knowing Is Not Enough; We Must Apply. Wishing Is Not Enough; We Must Do", "Imagine Your Life Is Perfect In Every Respect; What Would It Look Like?"];

function makeId() {
  var randomNumber = Math.floor(Math.random() * quotes.length);
  $("#quote > h1").html(quotes[randomNumber]);
}

$(document).ready(function() {
  $("#press > button").click(function() {
    $("#quote > i").fadeOut("slow").fadeIn("slow");
    $("#quote > h1").fadeOut("slow", function() {
      makeId();
      $(this).fadeIn("slow");
    });
  });
});

<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Encode+Sans+Expanded" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="style.css" rel="stylesheet">

My Quote Machine

I shall not waste my days in trying to prolong them.

  <button class="btn btn-lg">Quote</button>

Body:
You were leaving the text attribute in the tweet intent empty.

You need to supply this initially (as you have the first quote hardcoded in the HTML).

Then in your makeId function dynamically change the text attribute.

https://codepen.io/anon/pen/YExdNY

HTML (I moved the twitterid to the actual link instead of the icon):

<a id="twitterid" href="https://twitter.com/intent/tweet/?text=I shall not waste my days in trying to prolong them." target="_blank">
  <i class="fa fa-twitter fa-2x"  style="color: white"></i>
</a>

JS:

function makeId() {
  var randomNumber = Math.floor(Math.random() * quotes.length);
  $("#quote > h1").html(quotes[randomNumber]);

  // get the twitter intent link
  var twitterid = $("#twitterid");
  // remove existing text attribute with quote
  // change with the newly generated quote
  twitterid.attr("href", twitterid.attr("href").split("text=")[0] + "text=" +
  quotes[randomNumber]);
}

Edit: This line of code:

twitterid.attr("href", twitterid.attr("href").split("text=")[0] + "text="
+ quotes[randomNumber]);

Gets the href attribute from the twitterid link, splits the href's value by the text attribute, then adds it back again but uses the next quote.


问:
Django template: pass a variable to view {{ dic.{{ a.d }} }}
Django template: pass a variable to view {{ dic.{{ a.d }} }} // Access a dictionary

I need to pass a variable to dic, and this variable come from {{ a.d }}

So, what is the best way to do that?

Ok, I need to look up a dictionary.

{{ a.d }} returns a key.

so {{ dic.key }} will work.

答:
```<code>{% with a.d as key %}
 ...
  {{ dic.key }}
 ...
{% endwith %}
</code>```


问:
How to make 0 in all column in a specific table where value is null using MSSQL
Let the table name is "MyTable"

My current data looks like:

Following, I need after a query on above table:

Actually I need to update all column where value is "NULL", in a single query.

答:
Use ISNULL if you want to see the NULL as 0. Like this

```<code>SELECT ISNULL(Column1,0) FROM YourTable
</code>```

or what you need is to update the value as 0 if NULL and keep the value as it is otherwise. these use a case in the update statement. Like this

```<code>Update YourTable
SET Column1 = CASE WHEN Column1 IS NULL THEN 0 ELSE Column1 END,
Column2 = CASE WHEN Column2 IS NULL THEN 0 ELSE Column2 END
</code>```

and so on for the rest of the columns. Or this is also possible

```<code>Update YourTable
    SET Column1 = ISNULL(Column1,0),
cOLUMN2 = ISNULL(Column2,0)
</code>```

Body:
Use ISNULL if you want to see the NULL as 0. Like this

SELECT ISNULL(Column1,0) FROM YourTable

or what you need is to update the value as 0 if NULL and keep the value as it is otherwise. these use a case in the update statement. Like this

Update YourTable
SET Column1 = CASE WHEN Column1 IS NULL THEN 0 ELSE Column1 END,
Column2 = CASE WHEN Column2 IS NULL THEN 0 ELSE Column2 END

and so on for the rest of the columns. Or this is also possible

Update YourTable
    SET Column1 = ISNULL(Column1,0),
cOLUMN2 = ISNULL(Column2,0)