问:
Use GitHub GraphQL to retrieve all open milestones and all issues (open and closed) for the milestone
I understand that GitHub's GraphQL-based v4 API is much more efficient than the v3 API.

I would like to use the GraphQL API to retrieve, for a given repo:

All of the open milestones.

For each milestone, its title, description, all of its issues (open and closed)

For each issue, its title, description, status, and all messages.

Is there a straightforward way to do this?

答:
Yes. It is straightforward to do so . The query looks like :

```<code>{
  repository(owner: "gatsbyjs", name: "gatsby") {
    description
    url
    milestones(states: [OPEN],first:2) {
      nodes{
        title
        description
        url
        issues(states:[OPEN,CLOSED], first:2){
          nodes{
            title
            state
            url
            comments(first:2){
              nodes{
                url
                body
                createdAt
              }
              pageInfo{
                hasNextPage
                endCursor
              }
            }
          }
          pageInfo{
             endCursor
             hasNextPage
          }
        }
      }
      pageInfo{
        endCursor
        hasNextPage
      }
    }
  }
}
</code>```

Note:

For the repository which the url is https://github.com/gatsbyjs/gatsby , its owner is gatsbyjs and its name is  gatsby

Go to its API Explorer to try and fine tune the query.Click Ctrl+Space will auto-suggest the available fields that can be retrieved.

Do the paginating by yourself to loop through all records by adjusting the starting cursor and the number of records to be returned in first , after.

It gives you the following :

```<code>{
  "data": {
    "repository": {
      "description": "Build blazing fast, modern apps and websites with React",
      "url": "https://github.com/gatsbyjs/gatsby",
      "milestones": {
        "nodes": [
          {
            "title": "Next Major",
            "description": "Issues that will require a breaking change, and which would constitute being done in the next major version of Gatsby.",
            "url": "https://github.com/gatsbyjs/gatsby/milestone/5",
            "issues": {
              "nodes": [
                {
                  "title": "Make accessibility warnings errors",
                  "state": "OPEN",
                  "url": "https://github.com/gatsbyjs/gatsby/issues/19945",
                  "comments": {
                    "nodes": [
                      {
                        "url": "https://github.com/gatsbyjs/gatsby/issues/19945#issuecomment-568891716",
                        "body": "Hiya!\n\nThis issue has gone quiet. Spooky quiet. \n\nWe get a lot of issues, so we currently close issues after 30 days of inactivity. It’s been at least 20 days since the last update here.\nIf we missed this issue or if you want to keep it open, please reply here. You can also add the label \"not stale\" to keep this issue open!\nAs a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out [gatsby.dev/contribute](https://www.gatsbyjs.org/contributing/how-to-contribute/) for more information about opening PRs, triaging issues, and contributing!\n\nThanks for being a part of the Gatsby community! ",
                        "createdAt": "2019-12-25T12:02:26Z"
                      },
                      {
                        "url": "https://github.com/gatsbyjs/gatsby/issues/19945#issuecomment-570779866",
                        "body": "Hey again!\n\nIt’s been 30 days since anything happened on this issue, so our friendly neighborhood robot (that’s me!) is going to close it.\nPlease keep in mind that I’m only a robot, so if I’ve closed this issue in error, I’m `HUMAN_EMOTION_SORRY`. Please feel free to reopen this issue or create a new one if you need anything else.\nAs a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out [gatsby.dev/contribute](https://www.gatsbyjs.org/contributing/how-to-contribute/) for more information about opening PRs, triaging issues, and contributing!\n\nThanks again for being part of the Gatsby community! ",
                        "createdAt": "2020-01-04T12:02:28Z"
                      }
                    ],
                    "pageInfo": {
                      "hasNextPage": false,
                      "endCursor": "Y3Vyc29yOnYyOpHOIgVo2g=="
                    }
                  }
                },
                {
                  "title": "Configurable output folder",
                  "state": "OPEN",
                  "url": "https://github.com/gatsbyjs/gatsby/issues/1878",
                  "comments": {
                    "nodes": [
                      {
                        "url": "https://github.com/gatsbyjs/gatsby/issues/1878#issuecomment-324062470",
                        "body": "Do you have a specific use case in mind? This has been discussed before but no one has come up with a concrete use case that justified adding a new option.\r\n\r\nEvery option we add to Gatsby makes the project more complex which has all sorts of long-term costs so unless something is really valuable, I'd rather people handle this sort of thing themselves e.g. just copy the files to the output directory you want or create a symlink. This could easily be turned into a plugin that people could install, etc.",
                        "createdAt": "2017-08-22T15:27:41Z"
                      },
                      {
                        "url": "https://github.com/gatsbyjs/gatsby/issues/1878#issuecomment-324074853",
                        "body": "Yes, I have a use-case. I am going to use Gatsby for a documentation part as a part of complex project. All static files (Gatsby output, plus some others) should be placed into one folder `build`, that will be deployed somehow later. In other words, the Gatsby output is only one subfolder in my setup.\r\n\r\nSo far I have worked this around in `postbuild` step, but it looks hacky:\r\n\r\n```\r\n\"build\": \"gatsby build\",\r\n\"postbuild\": \"mv public build/gatsby-subsite\"\r\n```\r\nAdding configurable output folder will reduce this complexity and will help me not to move files around one more time.",
                        "createdAt": "2017-08-22T16:08:21Z"
                      }
                    ],
                    "pageInfo": {
                      "hasNextPage": true,
                      "endCursor": "Y3Vyc29yOnYyOpHOE1D9ZQ=="
                    }
                  }
                }
              ],
              "pageInfo": {
                "endCursor": "Y3Vyc29yOnYyOpLPgAAAAAAAArvODwULXA==",
                "hasNextPage": true
              }
            }
          }
        ],
        "pageInfo": {
          "endCursor": "Y3Vyc29yOnYyOpHOAEEbsw==",
          "hasNextPage": false
        }
      }
    }
  }
}
</code>```

Body:
Yes. It is straightforward to do so . The query looks like :

{
  repository(owner: "gatsbyjs", name: "gatsby") {
    description
    url
    milestones(states: [OPEN],first:2) {
      nodes{
        title
        description
        url
        issues(states:[OPEN,CLOSED], first:2){
          nodes{
            title
            state
            url
            comments(first:2){
              nodes{
                url
                body
                createdAt
              }
              pageInfo{
                hasNextPage
                endCursor
              }
            }
          }
          pageInfo{
             endCursor
             hasNextPage
          }
        }
      }
      pageInfo{
        endCursor
        hasNextPage
      }
    }
  }
}

Note:

For the repository which the url is https://github.com/gatsbyjs/gatsby , its owner is gatsbyjs and its name is  gatsby

Go to its API Explorer to try and fine tune the query.Click Ctrl+Space will auto-suggest the available fields that can be retrieved.

Do the paginating by yourself to loop through all records by adjusting the starting cursor and the number of records to be returned in first , after.

It gives you the following :

{
  "data": {
    "repository": {
      "description": "Build blazing fast, modern apps and websites with React",
      "url": "https://github.com/gatsbyjs/gatsby",
      "milestones": {
        "nodes": [
          {
            "title": "Next Major",
            "description": "Issues that will require a breaking change, and which would constitute being done in the next major version of Gatsby.",
            "url": "https://github.com/gatsbyjs/gatsby/milestone/5",
            "issues": {
              "nodes": [
                {
                  "title": "Make accessibility warnings errors",
                  "state": "OPEN",
                  "url": "https://github.com/gatsbyjs/gatsby/issues/19945",
                  "comments": {
                    "nodes": [
                      {
                        "url": "https://github.com/gatsbyjs/gatsby/issues/19945#issuecomment-568891716",
                        "body": "Hiya!\n\nThis issue has gone quiet. Spooky quiet. \n\nWe get a lot of issues, so we currently close issues after 30 days of inactivity. It’s been at least 20 days since the last update here.\nIf we missed this issue or if you want to keep it open, please reply here. You can also add the label \"not stale\" to keep this issue open!\nAs a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out [gatsby.dev/contribute](https://www.gatsbyjs.org/contributing/how-to-contribute/) for more information about opening PRs, triaging issues, and contributing!\n\nThanks for being a part of the Gatsby community! ",
                        "createdAt": "2019-12-25T12:02:26Z"
                      },
                      {
                        "url": "https://github.com/gatsbyjs/gatsby/issues/19945#issuecomment-570779866",
                        "body": "Hey again!\n\nIt’s been 30 days since anything happened on this issue, so our friendly neighborhood robot (that’s me!) is going to close it.\nPlease keep in mind that I’m only a robot, so if I’ve closed this issue in error, I’m `HUMAN_EMOTION_SORRY`. Please feel free to reopen this issue or create a new one if you need anything else.\nAs a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out [gatsby.dev/contribute](https://www.gatsbyjs.org/contributing/how-to-contribute/) for more information about opening PRs, triaging issues, and contributing!\n\nThanks again for being part of the Gatsby community! ",
                        "createdAt": "2020-01-04T12:02:28Z"
                      }
                    ],
                    "pageInfo": {
                      "hasNextPage": false,
                      "endCursor": "Y3Vyc29yOnYyOpHOIgVo2g=="
                    }
                  }
                },
                {
                  "title": "Configurable output folder",
                  "state": "OPEN",
                  "url": "https://github.com/gatsbyjs/gatsby/issues/1878",
                  "comments": {
                    "nodes": [
                      {
                        "url": "https://github.com/gatsbyjs/gatsby/issues/1878#issuecomment-324062470",
                        "body": "Do you have a specific use case in mind? This has been discussed before but no one has come up with a concrete use case that justified adding a new option.\r\n\r\nEvery option we add to Gatsby makes the project more complex which has all sorts of long-term costs so unless something is really valuable, I'd rather people handle this sort of thing themselves e.g. just copy the files to the output directory you want or create a symlink. This could easily be turned into a plugin that people could install, etc.",
                        "createdAt": "2017-08-22T15:27:41Z"
                      },
                      {
                        "url": "https://github.com/gatsbyjs/gatsby/issues/1878#issuecomment-324074853",
                        "body": "Yes, I have a use-case. I am going to use Gatsby for a documentation part as a part of complex project. All static files (Gatsby output, plus some others) should be placed into one folder `build`, that will be deployed somehow later. In other words, the Gatsby output is only one subfolder in my setup.\r\n\r\nSo far I have worked this around in `postbuild` step, but it looks hacky:\r\n\r\n```\r\n\"build\": \"gatsby build\",\r\n\"postbuild\": \"mv public build/gatsby-subsite\"\r\n```\r\nAdding configurable output folder will reduce this complexity and will help me not to move files around one more time.",
                        "createdAt": "2017-08-22T16:08:21Z"
                      }
                    ],
                    "pageInfo": {
                      "hasNextPage": true,
                      "endCursor": "Y3Vyc29yOnYyOpHOE1D9ZQ=="
                    }
                  }
                }
              ],
              "pageInfo": {
                "endCursor": "Y3Vyc29yOnYyOpLPgAAAAAAAArvODwULXA==",
                "hasNextPage": true
              }
            }
          }
        ],
        "pageInfo": {
          "endCursor": "Y3Vyc29yOnYyOpHOAEEbsw==",
          "hasNextPage": false
        }
      }
    }
  }
}


来源: stackexchange

问:
How can i fill this matrix (then generalize it to an 3D-array) whit a loop and using conditions too? in R
I just want to fill this matrix, I know this is a very easy problem, but I'm not good at all.
I won't use these numbers in the matrix.
I had tried with for loop, but the problem is this loop only shows the last iteration.
I repeat, I don't want the numbers from 1 to 9.
I have this:

```<code>(mat<-matrix(0, nrow = 3, ncol = 3))
for (i in 1:3) {
  for (j in 1:3) {
    if (j==1 & i==1) {
      mat[i,j]=6
    } else if (j==1 & i==2) {
      mat[i,j]=7
    } else if (j==1 & i==3) {
      mat[i,j]=8
    }
  }
}
</code>```

I want a code whithout put the conditions & i==1, & i==2, & i==3.
I want to make another variable k from 1 to 3. I tried this, but the loop only show me the value in 3.
Thank you so much.

Edit: I'm going to show you an example abou I want to solve. You will see that's about the same problem. I have the next data frame:

```<code>base2<-c(  20, 15, 17, 23, 19, 21, 16, 22, 18)
base2.1<-c( 6,  5,  3,  4,  1,  7,  2,  9,  8)
base3<-data.frame(base2,base2.1)
names(base3)=c("age","mean")

base3
</code>```

I want to fill a vector vec where vec[1]=5 (because as you can see,age=15), vec[2]=2 (because ,age=16) and so on, so on.

I have tried this just for the first element:

```<code>(vec<-c(rep(0,length(base3$mean))))

for (i in 1:length(base3$mean)) {
  if (base3$age[i]==15) {
    vec[1]=base3$mean[which(base3$age==15)]
      }
}
vec
</code>```

Of course, I don't want to put number 1 on this part of the loop: vec[1]=base3$mean[which(base3$age==15)

If I want to fill the entire vector, I have this:

```<code>for (i in 1:length(base3$mean)) {
  for (j in sort(base3$age)) {
vec[i]=base3$mean[which(base3$age==j)]
 }
}
vec
</code>```

But the foor loop only show me the last iteration:

```<code># [1] 4 4 4 4 4 4 4 4 4
</code>```

I want the next result:

```<code>[1] 5 2 3 8 1 6 7 9 4
</code>```

答:
This is simply to order vector age and use the index returned to index vector mean.

```<code>i <- order(base3$age)
vec <- base3$mean[i]

vec
#[1] 5 2 3 8 1 6 7 9 4
</code>```

See help("order"), and the difference to sort.

A one-liner is

```<code>vec <- base3$mean[order(base3$age)]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I just want to fill this matrix, I know this is a very easy problem, but I'm not good at all.
I won't use these numbers in the matrix.
I had tried with for loop, but the problem is this loop only shows the last iteration.
I repeat, I don't want the numbers from 1 to 9.
I have this:

(mat<-matrix(0, nrow = 3, ncol = 3))
for (i in 1:3) {
  for (j in 1:3) {
    if (j==1 & i==1) {
      mat[i,j]=6
    } else if (j==1 & i==2) {
      mat[i,j]=7
    } else if (j==1 & i==3) {
      mat[i,j]=8
    }
  }
}

I want a code whithout put the conditions & i==1, & i==2, & i==3.
I want to make another variable k from 1 to 3. I tried this, but the loop only show me the value in 3.
Thank you so much.

Edit: I'm going to show you an example abou I want to solve. You will see that's about the same problem. I have the next data frame:

base2<-c(  20, 15, 17, 23, 19, 21, 16, 22, 18)
base2.1<-c( 6,  5,  3,  4,  1,  7,  2,  9,  8)
base3<-data.frame(base2,base2.1)
names(base3)=c("age","mean")

base3

I want to fill a vector vec where vec[1]=5 (because as you can see,age=15), vec[2]=2 (because ,age=16) and so on, so on.

I have tried this just for the first element:

(vec<-c(rep(0,length(base3$mean))))

for (i in 1:length(base3$mean)) {
  if (base3$age[i]==15) {
    vec[1]=base3$mean[which(base3$age==15)]
      }
}
vec

Of course, I don't want to put number 1 on this part of the loop: vec[1]=base3$mean[which(base3$age==15)

If I want to fill the entire vector, I have this:

for (i in 1:length(base3$mean)) {
  for (j in sort(base3$age)) {
vec[i]=base3$mean[which(base3$age==j)]
 }
}
vec

But the foor loop only show me the last iteration:

# [1] 4 4 4 4 4 4 4 4 4

I want the next result:

[1] 5 2 3 8 1 6 7 9 4

Body:
This is simply to order vector age and use the index returned to index vector mean.

i <- order(base3$age)
vec <- base3$mean[i]

vec
#[1] 5 2 3 8 1 6 7 9 4

See help("order"), and the difference to sort.

A one-liner is

vec <- base3$mean[order(base3$age)]


问:
Attempting to save todo list items to local storage
I have a pretty simple to do app that creates to dos and displays them to the screen. However, I wan't to save these to local storage so if someone leaves the page and returns, reloads the page, etc. the to do items remain.

I'm having trouble wrapping my head around how to use local storage though. I know relatively what I need to do, represented in pseudo code in my JavaScript document, but I can't seem to make it work. Any guidance would be greatly appreciated.

https://codepen.io/constequalsexcel/pen/GRJpzoE

function addTodo() {
  let todoItem = document.createElement('li');
  todoItem.setAttribute('class', 'list-item');
  let text = document.getElementById('todo-input').value;
  if (text.length < 1) return;
  let textnode = document.createElement('span');
  textnode.innerText = text;
  // Create delete todo button
  let deleteButton = document.createElement('button');
  let deleteButtonX = document.createTextNode('X');
  deleteButton.appendChild(deleteButtonX);
  deleteButton.addEventListener('click', removeNode);
  // Create strike through radio input
  let StrikeThroughRadio = document.createElement('input');
  StrikeThroughRadio.setAttribute('id', 'checkbox-styles');
  StrikeThroughRadio.setAttribute('type', 'checkbox');
  StrikeThroughRadio.addEventListener('click', function(e) {
    StrikeThroughRadio.checked ?
      e.target.nextElementSibling.classList.add('strike-text') :
      e.target.nextElementSibling.classList.remove('strike-text');
  });

  todoItem.appendChild(StrikeThroughRadio);
  todoItem.appendChild(textnode);
  todoItem.appendChild(deleteButton);
  enter code here

  document.getElementById('display').appendChild(todoItem);

// get saved todos from local storage and save it in a variable
// if saved todos variable is null then re-assign saved todoso variable equal to an empty array
// add current todo text to the saved todos array variable
// re-save saved todos into local storage (using the setItem() method)
    }
    function removeNode(e) {
      e.target.parentElement.remove();
    }
    `enter code here`

    function ClearInputOnSubmit() {
      document.getElementById('todo-input').value = '';
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>

    <html lang="en">

    <head>
      <meta charset="utf-8" />

      <title>To-Do App</title>

      <link rel="stylesheet" href="styles.css" />
      <link href="https://fonts.googleapis.com/css?family=Roboto+Mono&display=swap" rel="stylesheet" />
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />
    </head>

    <body>
      <h1 id="header">TO DO LIST</h1>
      <div class="main">
        <form class="container" class="needs-validation" novalidate>
          <div class="input-group-prepend">
            <input type="text" id="todo-input" class="form-control input-group shadow-lg" aria-describedby="button-addon2" required />
            <input type="button" value="Add ToDo" id="todo-button" id="button-addon2" class="btn btn-info btn-sm" onclick="addTodo(); ClearInputOnSubmit()" />
          </div>
        </form>
        <div class="todo-container">
          <h4 id="display" class="list-group">TODOS</h4>
        </div>
      </div>
      <script src="scripts.js"></script>
    </body>

</html></code>```

答:
The local storage runs as a way to store JavaScript objects. However, if the user clears their browser data, the objects will be lost.

localStorage.setItem("storage", todoitem)
localStorage.getItem("storage")

Looking at the need you have here, you may want to make a loop or array to store all of the todoitems an user creates. If you are stuck on how you would do that, I can help. I actually started a project related to this issue.

Here is a good reference if you are looking for more information.

Body:
I have a pretty simple to do app that creates to dos and displays them to the screen. However, I wan't to save these to local storage so if someone leaves the page and returns, reloads the page, etc. the to do items remain.

I'm having trouble wrapping my head around how to use local storage though. I know relatively what I need to do, represented in pseudo code in my JavaScript document, but I can't seem to make it work. Any guidance would be greatly appreciated.

https://codepen.io/constequalsexcel/pen/GRJpzoE

function addTodo() {
  let todoItem = document.createElement('li');
  todoItem.setAttribute('class', 'list-item');
  let text = document.getElementById('todo-input').value;
  if (text.length < 1) return;
  let textnode = document.createElement('span');
  textnode.innerText = text;
  // Create delete todo button
  let deleteButton = document.createElement('button');
  let deleteButtonX = document.createTextNode('X');
  deleteButton.appendChild(deleteButtonX);
  deleteButton.addEventListener('click', removeNode);
  // Create strike through radio input
  let StrikeThroughRadio = document.createElement('input');
  StrikeThroughRadio.setAttribute('id', 'checkbox-styles');
  StrikeThroughRadio.setAttribute('type', 'checkbox');
  StrikeThroughRadio.addEventListener('click', function(e) {
    StrikeThroughRadio.checked ?
      e.target.nextElementSibling.classList.add('strike-text') :
      e.target.nextElementSibling.classList.remove('strike-text');
  });

  todoItem.appendChild(StrikeThroughRadio);
  todoItem.appendChild(textnode);
  todoItem.appendChild(deleteButton);
  enter code here

  document.getElementById('display').appendChild(todoItem);

// get saved todos from local storage and save it in a variable
// if saved todos variable is null then re-assign saved todoso variable equal to an empty array
// add current todo text to the saved todos array variable
// re-save saved todos into local storage (using the setItem() method)
    }
    function removeNode(e) {
      e.target.parentElement.remove();
    }
    `enter code here`

    function ClearInputOnSubmit() {
      document.getElementById('todo-input').value = '';
    }

    <!DOCTYPE html>

      <meta charset="utf-8" />

      <title>To-Do App</title>

      <link rel="stylesheet" href="styles.css" />
      <link href="https://fonts.googleapis.com/css?family=Roboto+Mono&display=swap" rel="stylesheet" />
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />

TO DO LIST

        <form class="container" class="needs-validation" novalidate>

            <input type="text" id="todo-input" class="form-control input-group shadow-lg" aria-describedby="button-addon2" required />
            <input type="button" value="Add ToDo" id="todo-button" id="button-addon2" class="btn btn-info btn-sm" onclick="addTodo(); ClearInputOnSubmit()" />

        </form>

TODOS


问:
Cannot debug outlook 2007 project on outlook 2007?
I'm getting the error 'You cannot debug or run this project, because the required version of Microsoft Office application is not installed'

The project was created as an Outlook 2007 add-in and Outlook 2007 is definitely installed. I can even manually deploy it by running the VSTO file after building the project, but still get that message when attempting to debug.

is there a value I have to change somewhere to make it work again?

答:
Have you check the condition in your project build rules that triggered this error? (which line in .vcproj file?)

If it's not a new project, you could try to create a new one, check whether it works and compare your project with the new one for differences (.vcproj file)

ContentLicense: CC BY-SA 3.0


问:
.htaccess RewriteRule blocked/ignored for .css and .js extension?
I have switched servers and suddenly some of my .htaccess rules stopped working. One of them is the one bellow which redirects /scripts.js to my /includes/load_js.php file.

```<code># NOT WORKING
RewriteCond %{REQUEST_URI} scripts.js
RewriteRule . includes/load_js.php [L]
</code>```

The strange part is that, if (for testing purposes only) I rename the rule from scripts.js into, lets say scripts.tst then is working, I can change the extension into anything except .js or .css and is working, otherwise for .js and .css I get 404 Not Found.

```<code># WORKING BUT NOT NEEDED, I NEED .JS
RewriteCond %{REQUEST_URI} scripts.tst
RewriteRule . includes/load_js.php [L]
</code>```

Any help is much appreciated!
Thank you!

答:
It looks like the server was running both Nginx and Apache and there was some sort of conflict in serving files. While Apache using my .htaccess file was successfully honoring some of the redirects, others, on the other hand were "stolen" by NGINX (*.jpg, *.png, *.js, *.css) and this way the request never had the chance to even reach my .htaccess to process the redirect rules.

TL;DR: Server configuration: both Apache and NGINX == NO-NO, results in fighting over requests, nobody wins.

"SOLUTION" <- (notice the quotes): The WebMaster removed NGINX and only Apache remained standing, this way, processing my .htaccess and all rules working like on the previous server.

Body:
I have switched servers and suddenly some of my .htaccess rules stopped working. One of them is the one bellow which redirects /scripts.js to my /includes/load_js.php file.

# NOT WORKING
RewriteCond %{REQUEST_URI} scripts.js
RewriteRule . includes/load_js.php [L]

The strange part is that, if (for testing purposes only) I rename the rule from scripts.js into, lets say scripts.tst then is working, I can change the extension into anything except .js or .css and is working, otherwise for .js and .css I get 404 Not Found.

# WORKING BUT NOT NEEDED, I NEED .JS
RewriteCond %{REQUEST_URI} scripts.tst
RewriteRule . includes/load_js.php [L]

Any help is much appreciated!
Thank you!


问:
jquery and css hint needed $("elemet").css();
I am trying to move the shape 200px  down using $("#shape").css("top","200px");
and it does not work, any advice?

```<code>> <style type="text/css">
>         #shape{
>             width: 200px;
>             height: 200px;
>             background-color: red;
>             display: none;
>             position: :relative;
>
>         }
>
>     </style>
</code>```

```

答:
do like this</p>

```<code><!DOCTYPE html>
<html>
<head>
   <title>your title</title>
</head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style type="text/css">
  #shape{ width: 200px; height: 200px; background-color: red; display: none;
  position:relative;

 }

</style>
<body>
  <div id="shape"></div>
  <script type="text/javascript">
  function appear(){
    $("#shape").css("top","200px");
    $("#shape").css("display","block");
    start=new Date().getTime();
 }
appear()
</script>
</body>
</html>
</code>```

Body:
I am trying to move the shape 200px  down using $("#shape").css("top","200px");
and it does not work, any advice?

>

Body:
do like this

<!DOCTYPE html>
<html>
<head>
   <title>your title</title>
</head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style type="text/css">
  #shape{ width: 200px; height: 200px; background-color: red; display: none;
  position:relative;

 }

</style>
<body>
  <div id="shape"></div>
  <script type="text/javascript">
  function appear(){
    $("#shape").css("top","200px");
    $("#shape").css("display","block");
    start=new Date().getTime();
 }
appear()
</script>
</body>
</html>


问:
How to capture the full stack trace when logging in Julia
I am trying to write a custom logger. Currently, when I log, I just get the name of the error and what line it occurred on. If I want to log the full stack trace, I thought I would use the LogLevel from the docs but it's not clear how I would use that to capture a full stack trace. I have the following right now: </p>

```<code>using Logging
io = open("log.txt", "w+")
LogLevel(1000001) # see https://github.com/JuliaLang/julia/blob/2d5741174ce3e6a394010d2e470e4269ca54607f/base/logging.jl#L90-L98
logger = SimpleLogger(io)
global_logger(logger)

try
    a+1
catch e
    @warn "failure" exception=e
    @info("a global log message")
end

close(io)
</code>```

答:
As the docs say:

An associated backtrace bt may be attached using the tuple exception=(ex,bt)

So try

```<code>@warn "failure" exception=(e, catch_backtrace())
</code>```

Body:
I am trying to write a custom logger. Currently, when I log, I just get the name of the error and what line it occurred on. If I want to log the full stack trace, I thought I would use the LogLevel from the docs but it's not clear how I would use that to capture a full stack trace. I have the following right now:

using Logging
io = open("log.txt", "w+")
LogLevel(1000001) # see https://github.com/JuliaLang/julia/blob/2d5741174ce3e6a394010d2e470e4269ca54607f/base/logging.jl#L90-L98
logger = SimpleLogger(io)
global_logger(logger)

try
    a+1
catch e
    @warn "failure" exception=e
    @info("a global log message")
end

close(io)

Body:
As the docs say:

An associated backtrace bt may be attached using the tuple exception=(ex,bt)

So try

@warn "failure" exception=(e, catch_backtrace())


问:
How do you create an excel document in WIX that can be shared and updated?
I creating my first web site using WIX and know little about programming. I would like to have an excel log that can be shared and updated by those who visit my web site. Can anyone help me with this?</p>

答: Try a google docs spreadsheet, those can be shared and updated. https://docs.google.com/#home</p>


问:
Webpack unable to find babel-loader
I'm having a bit of trouble adding react to a legacy application. While I found plenty of materials on getting started, I ran into a bunch of issues related to my particular configuration and exacerbated by my utter lack of webpack knowledge (so much time relying on react cli tools makes one lax).

My configuration:

./docs/jslib = my node_modules, that's where yarn installs modules

./docs/jscripts = my general js folder, various js scripts go there

./docs/jscripts/mini = my dist folder, some things get built/packed by gulp and end up here. This is where the built things are expected to go

./docs/jscripts/react(/react.js) = my desired root for react things, where the react.js is the entrypoint for DOM selection and rendering (at least for the first attempt).

My webpack config:

```<code>const path = require("path");

module.exports = {
    entry: "./docs/jscript/react/react.js",
    output: {
        path: path.resolve(__dirname, "./docs/jscript/mini"),
        filename: "react.js"
    },
    resolve: {
        extensions: [".js", ".jsx"],
        modules: [
            path.resolve(__dirname, "./docs/jslib")
        ],
        alias: {
            'babel-loader': path.resolve(__dirname, "./docs/jslib/babel-loader")
        }
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                include: [
                    path.resolve(__dirname, "./docs/jscript/react")
                ],
                exclude: [
                    path.resolve(__dirname, "./docs/jslib")
                ],
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    }
};
</code>```

The error I get on running webpack:

yarn run v1.21.1
$ ./docs/jslib/babel-loader/node_modules/.bin/webpack --mode production

Insufficient number of arguments or no entry found.
Alternatively, run 'webpack(-cli) --help' for usage info.

Hash: 210250af48f3cf84fa4a
Version: webpack 4.41.6
Time: 75ms
Built at: 02/14/2020 9:23:09 AM

ERROR in Entry module not found: Error: Can't resolve 'babel-loader' in '/var/www/html'
```

I have webpack-cli, I can run webpack straight, I can run it from the modules bin folder, it's all the same problem - it can't find babel-loader even though babel-loader brings its own webpack script which I use, so the loader is obviously there in the "node_modules" that's actually on a different path.

From what I gathered, all I had to do was to add my custom node_modules path to the webpack config under the resolve settings, which has solved my initial errors related to packages not found (yet webpack still can't find the loader).

Note: if I symlink my ./docs/jslib as ./node_modules, it works as expected.

Is there something I'm missing?

Thanks!

答:
After some digging, I found a solution and some details that other might want to keep in mind when configuring webpack in a rather non-standard context:

resolve: points to modules that are directly required in various scripts

resolveLoader: should point to the same, for the purpose of accessing loaders (which is what I needed)

Solution:

```<code>    resolveLoader: {
        extensions: ['.js', '.json', '.jsx'],
        modules: [
            path.resolve(__dirname, "./docs/jslib")
        ],
        mainFields: ['loader', 'main']
    }
</code>```

Title: Webpack unable to find babel-loader

Body:
I'm having a bit of trouble adding react to a legacy application. While I found plenty of materials on getting started, I ran into a bunch of issues related to my particular configuration and exacerbated by my utter lack of webpack knowledge (so much time relying on react cli tools makes one lax).

My configuration:

./docs/jslib = my node_modules, that's where yarn installs modules

./docs/jscripts = my general js folder, various js scripts go there

./docs/jscripts/mini = my dist folder, some things get built/packed by gulp and end up here. This is where the built things are expected to go

./docs/jscripts/react(/react.js) = my desired root for react things, where the react.js is the entrypoint for DOM selection and rendering (at least for the first attempt).

My webpack config:

const path = require("path");

module.exports = {
    entry: "./docs/jscript/react/react.js",
    output: {
        path: path.resolve(__dirname, "./docs/jscript/mini"),
        filename: "react.js"
    },
    resolve: {
        extensions: [".js", ".jsx"],
        modules: [
            path.resolve(__dirname, "./docs/jslib")
        ],
        alias: {
            'babel-loader': path.resolve(__dirname, "./docs/jslib/babel-loader")
        }
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                include: [
                    path.resolve(__dirname, "./docs/jscript/react")
                ],
                exclude: [
                    path.resolve(__dirname, "./docs/jslib")
                ],
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    }
};

The error I get on running webpack:

yarn run v1.21.1
$ ./docs/jslib/babel-loader/node_modules/.bin/webpack --mode production

Insufficient number of arguments or no entry found.
Alternatively, run 'webpack(-cli) --help' for usage info.

Hash: 210250af48f3cf84fa4a
Version: webpack 4.41.6
Time: 75ms
Built at: 02/14/2020 9:23:09 AM

ERROR in Entry module not found: Error: Can't resolve 'babel-loader' in '/var/www/html'

I have webpack-cli, I can run webpack straight, I can run it from the modules bin folder, it's all the same problem - it can't find babel-loader even though babel-loader brings its own webpack script which I use, so the loader is obviously there in the "node_modules" that's actually on a different path.

From what I gathered, all I had to do was to add my custom node_modules path to the webpack config under the resolve settings, which has solved my initial errors related to packages not found (yet webpack still can't find the loader).

Note: if I symlink my ./docs/jslib as ./node_modules, it works as expected.

Is there something I'm missing?

Thanks!

Body:
After some digging, I found a solution and some details that other might want to keep in mind when configuring webpack in a rather non-standard context:

resolve: points to modules that are directly required in various scripts

resolveLoader: should point to the same, for the purpose of accessing loaders (which is what I needed)

Solution:

    resolveLoader: {
        extensions: ['.js', '.json', '.jsx'],
        modules: [
            path.resolve(__dirname, "./docs/jslib")
        ],
        mainFields: ['loader', 'main']
    }


问:
Display data in nice format in Python for elementary classroom project
I am working on a project to use in an elementary school where teachers and students will submit a list of adjectives and nouns that we will then use in a creative LEGO build challenge each week.

I am trying to learn python so please bear with me. I created a program asking people to submit 26 adjectives and 10 nouns. I want to take the screenshot and use as a the guide for the kids to build with.

I am not sure how to create a table or other structure to display the information all on one screen and more readable.

I would love any help! My code is below.

```<code>print("Thank you for helping with a creative LEGO project")
print("Please remember to keep words school safe and readable for elementary students")

adj1 = input("Give me a adjective ")
adj2 = input("Give me a adjective ")
adj3 = input("Give me a adjective ")
adj4 = input("Give me a adjective ")
adj5 = input("Give me a adjective ")
adj6 = input("Give me a adjective ")
adj7 = input("Give me a adjective ")
adj8 = input("Give me a adjective ")
adj9 = input("Give me a adjective ")
adj10 = input("Give me a adjective ")
adj11 = input("Give me a adjective ")
adj12 = input("Give me a adjective ")
adj13 = input("Give me a adjective ")
adj14 = input("Give me a adjective ")
adj15 = input("Give me a adjective ")
adj16 = input("Give me a adjective ")
adj17 = input("Give me a adjective ")
adj18 = input("Give me a adjective ")
adj19 = input("Give me a adjective ")
adj20 = input("Give me a adjective ")
adj21 = input("Give me a adjective ")
adj22 = input("Give me a adjective ")
adj23 = input("Give me a adjective ")
adj24 = input("Give me a adjective ")
adj25 = input("Give me a adjective ")
adj26 = input("Give me a adjective ")

print("Nice job coming up with all of those adjectives")
print("Now we are moving on to nouns")
print("Here we go!")

noun1 = input("Give me a noun ")
noun2 = input("Give me a noun ")
noun3 = input("Give me a noun ")
noun4 = input("Give me a noun ")
noun5 = input("Give me a noun ")
noun6 = input("Give me a noun ")
noun7 = input("Give me a noun ")
noun8 = input("Give me a noun ")
noun9 = input("Give me a noun ")
noun10 = input("Give me a noun ")

print("A = " + adj1)
print("B = " + adj2)
print("C = " + adj3)
print("D = " + adj4)
print("E = " + adj5)
print("F = " + adj6)
print("G = " + adj7)
print("H = " + adj8)
print("I = " + adj9)
print("J = " + adj10)
print("K = " + adj11)
print("L = " + adj12)
print("M = " + adj13)
print("N = " + adj14)
print("O = " + adj15)
print("P = " + adj16)
print("Q = " + adj17)
print("R = " + adj18)
print("S = " + adj19)
print("T = " + adj20)
print("U = " + adj21)
print("V = " + adj22)
print("W = " + adj23)
print("X = " + adj24)
print("Y = " + adj25)
print("Z = " + adj26)

print("1-3 = " + noun1)
print("4-6 = " + noun2)
print("7-9 = " + noun3)
print("10-12 = " + noun4)
print("13-15 = " + noun5)
print("16-18 = " + noun6)
print("19-21 = " + noun7)
print("22-25 = " + noun8)
print("26-28 = " + noun9)
print("29-31 = " + noun10)
</code>```

答:
This is a much more succinct (and general) way to do what you're already doing.</p>

```<code>print("Thank you for helping with a creative LEGO project")
print("Please remember to keep words school safe and readable for elementary students")

num_adjectives = 26
adjectives = [input() for _ in range(num_adjectives)]

print("Nice job coming up with all of those adjectives")
print("Now we are moving on to nouns")
print("Here we go!")

num_nouns = 10
nouns = [input() for _ in range(num_nouns)]

alphabet = 'ABCEFGHIJKLMNOPQRSTUVWXYZ'
for idx,letter in enumerate(alphabet):
    print(f'{letter} = {adjectives[idx]}')

for idx,noun in enumerate(nouns):
    print(f'{idx*3+1}-{idx*3+3} = {noun}')
</code>```

Body:
I am working on a project to use in an elementary school where teachers and students will submit a list of adjectives and nouns that we will then use in a creative LEGO build challenge each week.

I am trying to learn python so please bear with me. I created a program asking people to submit 26 adjectives and 10 nouns. I want to take the screenshot and use as a the guide for the kids to build with.

I am not sure how to create a table or other structure to display the information all on one screen and more readable.

I would love any help! My code is below.

print("Thank you for helping with a creative LEGO project")
print("Please remember to keep words school safe and readable for elementary students")

adj1 = input("Give me a adjective ")
adj2 = input("Give me a adjective ")
adj3 = input("Give me a adjective ")
adj4 = input("Give me a adjective ")
adj5 = input("Give me a adjective ")
adj6 = input("Give me a adjective ")
adj7 = input("Give me a adjective ")
adj8 = input("Give me a adjective ")
adj9 = input("Give me a adjective ")
adj10 = input("Give me a adjective ")
adj11 = input("Give me a adjective ")
adj12 = input("Give me a adjective ")
adj13 = input("Give me a adjective ")
adj14 = input("Give me a adjective ")
adj15 = input("Give me a adjective ")
adj16 = input("Give me a adjective ")
adj17 = input("Give me a adjective ")
adj18 = input("Give me a adjective ")
adj19 = input("Give me a adjective ")
adj20 = input("Give me a adjective ")
adj21 = input("Give me a adjective ")
adj22 = input("Give me a adjective ")
adj23 = input("Give me a adjective ")
adj24 = input("Give me a adjective ")
adj25 = input("Give me a adjective ")
adj26 = input("Give me a adjective ")

print("Nice job coming up with all of those adjectives")
print("Now we are moving on to nouns")
print("Here we go!")

noun1 = input("Give me a noun ")
noun2 = input("Give me a noun ")
noun3 = input("Give me a noun ")
noun4 = input("Give me a noun ")
noun5 = input("Give me a noun ")
noun6 = input("Give me a noun ")
noun7 = input("Give me a noun ")
noun8 = input("Give me a noun ")
noun9 = input("Give me a noun ")
noun10 = input("Give me a noun ")

print("A = " + adj1)
print("B = " + adj2)
print("C = " + adj3)
print("D = " + adj4)
print("E = " + adj5)
print("F = " + adj6)
print("G = " + adj7)
print("H = " + adj8)
print("I = " + adj9)
print("J = " + adj10)
print("K = " + adj11)
print("L = " + adj12)
print("M = " + adj13)
print("N = " + adj14)
print("O = " + adj15)
print("P = " + adj16)
print("Q = " + adj17)
print("R = " + adj18)
print("S = " + adj19)
print("T = " + adj20)
print("U = " + adj21)
print("V = " + adj22)
print("W = " + adj23)
print("X = " + adj24)
print("Y = " + adj25)
print("Z = " + adj26)

print("1-3 = " + noun1)
print("4-6 = " + noun2)
print("7-9 = " + noun3)
print("10-12 = " + noun4)
print("13-15 = " + noun5)
print("16-18 = " + noun6)
print("19-21 = " + noun7)
print("22-25 = " + noun8)
print("26-28 = " + noun9)
print("29-31 = " + noun10)

Body:
This is a much more succinct (and general) way to do what you're already doing.

print("Thank you for helping with a creative LEGO project")
print("Please remember to keep words school safe and readable for elementary students")

num_adjectives = 26
adjectives = [input() for _ in range(num_adjectives)]

print("Nice job coming up with all of those adjectives")
print("Now we are moving on to nouns")
print("Here we go!")

num_nouns = 10
nouns = [input() for _ in range(num_nouns)]

alphabet = 'ABCEFGHIJKLMNOPQRSTUVWXYZ'
for idx,letter in enumerate(alphabet):
    print(f'{letter} = {adjectives[idx]}')

for idx,noun in enumerate(nouns):
    print(f'{idx*3+1}-{idx*3+3} = {noun}')


答:
Just iterate through all the elements:</p>

```<code>for d in person_dict['Department']:
    for k,v in d.items():
        print("Key =", k ,"Value =", v)

</code>```

Title: Read JSON Array in Python

Body:
I'm trying to read department array in python. I can read the first element of the array. how can I read the rest for example the values for "aaa", "bbb", "ccc"? Any suggestions?

import json

person2 = '{"FirstName":"2018 Q1 (JAN-MAR)","LastName":"aaaaaaaaaaaaaaaaaaaaaaaa","Phone":"2222222222222222","Department":[{"cpt":"A0001","aaa":"1","bbb":"2","ccc":"3","ddd":"4","eee":"5"},{"cpt":"A0002","aaa":"6","bbb":"7","ccc":"8","ddd":"9","eee":"10"},{"cpt":"A0003","aaa":"11","bbb":"21","ccc":"31","ddd":"44","eee":"55"},{"cpt":"A0004","aaa":"101","bbb":"22","ccc":"33","ddd":"44","eee":"55"},{"cpt":"A0005","ffs":"100","mmc":"23","med":"34","oth":"45","duo":"56"},{"cpt":"A0006","aaa":"111","bbb":"24","ccc":"34","ddd":"44","eee":"54"}],"checkAgree":true}'
person_dict = json.loads(person2)

#Example of how to read JSON array elements in python
print(person_dict['Department'][0]["cpt"]);

print(person_dict['Department'][1]["cpt"]);

print(person_dict['Department'][3]["cpt"]);

print(person_dict['Department'][4]["cpt"]);

print(person_dict['Department'][5]["cpt"]);

"Department": [
    {
      "cpt": "A0001",
      "aaa": "1",
      "bbb": "2",
      "ccc": "3",
      "ddd": "4",
      "eee": "5"
    },
    {
      "cpt": "A0002",
      "aaa": "6",
      "bbb": "7",
      "ccc": "8",
      "ddd": "9",
      "eee": "10"
    },
    {
      "cpt": "A0003",
      "aaa": "11",
      "bbb": "21",
      "ccc": "31",
      "ddd": "44",
      "eee": "55"
    },
    {
      "cpt": "A0004",
      "aaa": "101",
      "bbb": "22",
      "ccc": "33",
      "ddd": "44",
      "eee": "55"
    },
    {
      "cpt": "A0005",
      "aaa": "100",
      "bbb": "23",
      "ccc": "34",
      "ddd": "45",
      "eee": "56"
    },
    {
      "cpt": "A0006",
      "aaa": "111",
      "bbb": "24",
      "ccc": "34",
      "ddd": "44",
      "eee": "54"
    }
  ],

Body:
Just iterate through all the elements:

for d in person_dict['Department']:
    for k,v in d.items():
        print("Key =", k ,"Value =", v)


问:
Matrix and Vector multiplication without NumPy
Well, I want to implement a multiplication matrix by a vector in Python without NumPy.
So given a matrix for example (2x2) in this format:

```<code>A = [ [2, 1],
      [5, 7] ]
</code>```

And given a vector for example (2x1) in this format:

```<code>b = [ [11],
      [13] ]
</code>```

And I want to get this vector (2x1):

```<code>с = [ [35],
      [146] ]
</code>```

What I tried:

```<code>def myzeros(n): # create zero vector
    res = []
    for i in range(n):
        res.append([0])

    return res

def mydot(A, B):
    res = myzeros(len(B)) # create zero vector of size B
    for i in range(len(A)):
        res.append( sum(A[i][j]*B[j] for j in range(len(A[0]))) )
    return res
</code>```

And corresponding error:

res.append( sum(A[i][j]*B[j] for j in range(len(A[0]))) )
  TypeError: unsupported operand type(s) for +: 'int' and 'list'
```

Where's the mistake?

答:
Let's define vectors as Python lists, and matrices as lists of lists.

```<code>b = [11, 13]
A = [ [2, 1],
      [5, 7] ]
</code>```

Then, you could use

```<code>def mydot(v1, v2):
     return sum([x*y for x,y in zip(v1, v2)])

def matmulvec(M, v):
    return [mydot(r,v) for r in M]
</code>```

to get

```<code>matmulvec(A, b)
    [35, 146]
</code>```

Body:
Well, I want to implement a multiplication matrix by a vector in Python without NumPy.
So given a matrix for example (2x2) in this format:

A = [ [2, 1],
      [5, 7] ]

And given a vector for example (2x1) in this format:

b = [ [11],
      [13] ]

And I want to get this vector (2x1):

с = [ [35],
      [146] ]

What I tried:

def myzeros(n): # create zero vector
    res = []
    for i in range(n):
        res.append([0])

    return res

def mydot(A, B):
    res = myzeros(len(B)) # create zero vector of size B
    for i in range(len(A)):
        res.append( sum(A[i][j]*B[j] for j in range(len(A[0]))) )
    return res

And corresponding error:

res.append( sum(A[i][j]*B[j] for j in range(len(A[0]))) )
  TypeError: unsupported operand type(s) for +: 'int' and 'list'

Where's the mistake?

Body:
Let's define vectors as Python lists, and matrices as lists of lists.

b = [11, 13]
A = [ [2, 1],
      [5, 7] ]

Then, you could use

def mydot(v1, v2):
     return sum([x*y for x,y in zip(v1, v2)])

def matmulvec(M, v):
    return [mydot(r,v) for r in M]

to get

matmulvec(A, b)
    [35, 146]


问:
Assistance with BS3 Typeahead with .get as source
Hello:  I was able to get a simple typeahead working (bootstrap3) where the 'source' is a simple hard coded array.  Here is that code:

```<code>$(document).ready(function(){
var data =   [{'name':'Gerard'},{'name':'sravan'},{'name':'brent'},]

console.log(data)
var $input = $(".typeahead");
$input.typeahead({
  source: data,
  autoSelect: true

});
</code>```

For the remote source, I have an endpoint which delivers the json of the same array (/portal/billing/locationLookup)

So I am trying to get my typeahead to do a get request against that endpoint for the 'source'

I have been looking at lots of examples but cannot get anything to work so I am hoping someone can help out.  Thanks!

答:
Figured it out!  Here is my code:</p>

```<code>$(document).ready(function(){
$.get("/portal/billing/locationLookup", function(data){
$("#myta").typeahead({ source:data, autoSelect: true });
 },'json');
 })
</code>```

Body:
Hello:  I was able to get a simple typeahead working (bootstrap3) where the 'source' is a simple hard coded array.  Here is that code:

$(document).ready(function(){
var data =   [{'name':'Gerard'},{'name':'sravan'},{'name':'brent'},]

console.log(data)
var $input = $(".typeahead");
$input.typeahead({
  source: data,
  autoSelect: true

});

For the remote source, I have an endpoint which delivers the json of the same array (/portal/billing/locationLookup)

So I am trying to get my typeahead to do a get request against that endpoint for the 'source'

I have been looking at lots of examples but cannot get anything to work so I am hoping someone can help out.  Thanks!

Body:
Figured it out!  Here is my code:

$(document).ready(function(){
$.get("/portal/billing/locationLookup", function(data){
$("#myta").typeahead({ source:data, autoSelect: true });
 },'json');
 })


问:
How can I turn this jquery into a function?
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the href> tag somewhere.

html code

```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="linkpage.htm" class="newslink1">Link 1</a></li>
    <li><a href="linkpage.htm" class="newslink2">Link 2</a></li>
    <li><a href="linkpage.htm" class="newslink3">Link 3</a></li>
</ul>
</code>```

jquery

```<code>$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});
</code>```

答:
You can do this without changing the markup at all:</p>

```<code>$('a[class^="newslink"]').bind('mouseover', function (e) {
    var num = this.className.match(/newslink(\d+)/i)[1];
    $('img#storyimg').attr('src', num + '.png');
});
</code>```

Body:
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the  tag somewhere.

html code

Link 1

Link 2

Link 3

jquery

$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});

Body:
You can do this without changing the markup at all:

$('a[class^="newslink"]').bind('mouseover', function (e) {
    var num = this.className.match(/newslink(\d+)/i)[1];
    $('img#storyimg').attr('src', num + '.png');
});


问:
How to properly add elements to an array in Python
I have two arrays as the code shows below (A and B). I would like to take as output C = [[1, 2, 3, 11], [4, 5, 6, 12], [7, 8, 9, 13]]

I'm trying to, but the only thing I could reach was this:

```<code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [11, 12, 13]
C = [[x, y] for x, y in zip(A, B)]

print(C)
# Output: [[[1, 2, 3], 11], [[4, 5, 6], 12], [[7, 8, 9], 13]]
</code>```

答:
You just need to make an array of a single element (y) and then add the two lists together

```<code> [x + [y] for x, y in zip(A, B)]
</code>```

Body:
I have two arrays as the code shows below (A and B). I would like to take as output C = [[1, 2, 3, 11], [4, 5, 6, 12], [7, 8, 9, 13]]

I'm trying to, but the only thing I could reach was this:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [11, 12, 13]
C = [[x, y] for x, y in zip(A, B)]

print(C)
# Output: [[[1, 2, 3], 11], [[4, 5, 6], 12], [[7, 8, 9], 13]]

Body:
You just need to make an array of a single element (y) and then add the two lists together

 [x + [y] for x, y in zip(A, B)]


问:
How to pass Base64 image string from Flask Python code to HTML?
I have a Flask server and I want to render a base64 image in HTML page.

Flask Code:

```<code>new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
return render_template('perspective_result.html', img_data=new_image_string)
</code>```

HTML CODE:

```<code><img src="data:image/jpeg;base64,+img_data" alt="img_data"  id="imgslot"/>
</code>```

I am getting the below error from browser console:

```<code>GET data:image/jpeg;base64,+img_data 0 ()
</code>```

Where did I go wrong?

答:
1.First Add A empty Image Tag Without A Source

2.Then With Javascript preprocess the base64 data string

3.update the Image src with updated base64 data

```<code><img src="" id="img" alt="Chart" height="100" width="100">

<script>
    data = "{{data}}"
    data = data.replace("b'", "") //to get rid of start curly brace code
    data = data.replace("'", "")  //to get rid of end curly bracecode

    document.getElementById("img").src = "data:image/png;base64,"+data; // set src
</script>
</code>```

Body:
I have a Flask server and I want to render a base64 image in HTML page.

Flask Code:

new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
return render_template('perspective_result.html', img_data=new_image_string)

HTML CODE:

I am getting the below error from browser console:

GET data:image/jpeg;base64,+img_data 0 ()

Where did I go wrong?

Body:
1.First Add A empty Image Tag Without A Source

2.Then With Javascript preprocess the base64 data string

3.update the Image src with updated base64 data

<img src="" id="img" alt="Chart" height="100" width="100">

<script>
    data = "{{data}}"
    data = data.replace("b&#39;", "") //to get rid of start curly brace code
    data = data.replace("&#39;", "")  //to get rid of end curly bracecode

    document.getElementById("img").src = "data:image/png;base64,"+data; // set src
</script>


问:
Error after accidentally deleting Podfile
I made a huge mistake by deleting one podFile I had in my Xcode iOS application. I thought that the error was coming from that file when Instead it was another.
Long story short, I deleted the LevelDB pod and now the application is giving me this error after trying to launch it:

```<code>duplicate symbol '_pb_field_iter_find' in:
/Users/andreagualandris/Library/Developer/Xcode/DerivedData/InstagramClone-agfsqctheamzqfcdwrbfiaaauqhd/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/nanopb.build/Objects-normal/x86_64/pb_common 2.o
/Users/andreagualandris/Library/Developer/Xcode/DerivedData/InstagramClone-agfsqctheamzqfcdwrbfiaaauqhd/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/nanopb.build/Objects-normal/x86_64/pb_common.o.
ld: 3 duplicate symbols for architecture x86_64
</code>```

I don't know how to move from here; Do I have to reinstall the podfile? Can I solve this problem by doing something else? thank you to whoever can help me.

答: In the terminal, run pod install in your project directory and it should be OK.

Body:
I made a huge mistake by deleting one podFile I had in my Xcode iOS application. I thought that the error was coming from that file when Instead it was another.
Long story short, I deleted the LevelDB pod and now the application is giving me this error after trying to launch it:

duplicate symbol '_pb_field_iter_find' in:
/Users/andreagualandris/Library/Developer/Xcode/DerivedData/InstagramClone-agfsqctheamzqfcdwrbfiaaauqhd/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/nanopb.build/Objects-normal/x86_64/pb_common 2.o
/Users/andreagualandris/Library/Developer/Xcode/DerivedData/InstagramClone-agfsqctheamzqfcdwrbfiaaauqhd/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/nanopb.build/Objects-normal/x86_64/pb_common.o.
ld: 3 duplicate symbols for architecture x86_64

I don't know how to move from here; Do I have to reinstall the podfile? Can I solve this problem by doing something else? thank you to whoever can help me.


问:
forEach loop assigns the same random number
In typescript, I am trying to assign a random number to a property of each object in an array.  I have tried the following code

```<code>uniqueItems.forEach(unique => {
  unique.humanCode = Math.floor(1000 + Math.random() * 9000).toString();
});
</code>```

If I console.log inside the forEach loop, I get a different number but when I console.log the array of objects after the forEach, all of the random numbers are the same.

Edit: I had originally created my array of objects by using

```<code>for (let i = 0; i < this.quantity; i++) {
  this.uniqueItems.push(uniqueItem);
}
</code>```

This made an array of the same object.  This meant that my array was being assigned the last random number.  I fixed this by using the spread operator when I created my array.

```<code>for (let i = 0; i < this.quantity; i++) {
  this.uniqueItems.push({ ...this.uniqueItem });
}
</code>```

答:
I have tried the below code and it works for me.

let uniqueItems = [{
    humanCode: 0,
  },
  {
    humanCode: 0,
  },
  {
    humanCode: 0,
  },
]
uniqueItems.forEach(unique => {
  unique.humanCode = Math.floor(1000 + Math.random() * 9000).toString();
});

console.log(uniqueItems);```

Body:
In typescript, I am trying to assign a random number to a property of each object in an array.  I have tried the following code

uniqueItems.forEach(unique => {
  unique.humanCode = Math.floor(1000 + Math.random() * 9000).toString();
});

If I console.log inside the forEach loop, I get a different number but when I console.log the array of objects after the forEach, all of the random numbers are the same.

Edit: I had originally created my array of objects by using

for (let i = 0; i < this.quantity; i++) {
  this.uniqueItems.push(uniqueItem);
}

This made an array of the same object.  This meant that my array was being assigned the last random number.  I fixed this by using the spread operator when I created my array.

for (let i = 0; i < this.quantity; i++) {
  this.uniqueItems.push({ ...this.uniqueItem });
}


问:
UIImage picker controller works only the second time through
Hi I have had a working UIImage picker controller and suddenly it now only shows the photo on the view the second time i select USE.

Here's the code

header

```<code>@interface UpdatePriceView : UIViewController  <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITableViewDelegate, UITextFieldDelegate, CLLocationManagerDelegate > {

    UIImagePickerController *myPhoto;

}

@property (nonatomic,retain) UIImagePickerController *myPhoto;
</code>```

implementation

```<code>- (IBAction)Photo{

    self.myPhoto = [[UIImagePickerController alloc] init];
    self.myPhoto.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.myPhoto.delegate = self;
    self.myPhoto.allowsEditing = NO;
    self.myPhoto.showsCameraControls = YES;

    [self presentModalViewController:self.myPhoto animated:YES];

}

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"didFinishPickingMediaWithInfo method");

    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

    NSLog (@"Image = %@",image);

    [self.PhotoView setImage:image];

    [self dismissModalViewControllerAnimated:YES];

}
</code>```

What am i Doing wrong

答:
Try to do that:

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    self.photo = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissModalViewControllerAnimated:NO];
    [picker release];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    imgView.image = photo;
}
```

Body:
Hi I have had a working UIImage picker controller and suddenly it now only shows the photo on the view the second time i select USE.

Here's the code

header

@interface UpdatePriceView : UIViewController  <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITableViewDelegate, UITextFieldDelegate, CLLocationManagerDelegate > {

    UIImagePickerController *myPhoto;

}

@property (nonatomic,retain) UIImagePickerController *myPhoto;

implementation

- (IBAction)Photo{

    self.myPhoto = [[UIImagePickerController alloc] init];
    self.myPhoto.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.myPhoto.delegate = self;
    self.myPhoto.allowsEditing = NO;
    self.myPhoto.showsCameraControls = YES;

    [self presentModalViewController:self.myPhoto animated:YES];

}

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"didFinishPickingMediaWithInfo method");

    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

    NSLog (@"Image = %@",image);

    [self.PhotoView setImage:image];

    [self dismissModalViewControllerAnimated:YES];

}

What am i Doing wrong


问:
Django context returned by get_object
```<code>class ListDetailView(DetailView):
    context_object_name = 'aaaa'

    def get_object(self, queryset=None):
        return List.objects.get(unique_list_id=self.kwargs['unique_list_id'])
</code>```

In template I have two equal contexts:

```<code>{{ object.list_name }}
{{ aaaa.list_name }}
</code>```

How to override get_object() to return only context specified by context_object_name = 'aaaa'?
Why I have 2 contexts?

答:
This is not determined by the get_object method [Django-doc], but determined by the implementation of the get_context_data method [Django-doc] of the DetailView [Django-doc]. Indeed, for views that inherit from the SingleObjectMixin [Django-doc], it is implemented as [GitHub]:

```<code>def get_context_data(self, **kwargs):
    """Insert the single object into the context dict."""
    context = {}
    if self.object:
        <b>context['object'] = self.object</b>
        context_object_name = self.get_context_object_name(self.object)
        if context_object_name:
            context[context_object_name] = self.object
    context.update(kwargs)
    return super().get_context_data(**context)</code>```

So it will always set the object to the self.object (if that object exists), and if there is a context_object_name, to that name as well.

You can slightly update that, by removing it from the dictionary, like:

```<code>class ListDetailView(DetailView):
    context_object_name = 'aaaa'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        <b>context.pop('object', None)</b>
        return context

    def get_object(self, queryset=None):
        return List.objects.get(unique_list_id=self.kwargs['unique_list_id'])</code>```

That being said, I don't see any benefit to remove it. It refers to the same object. The query is not done twice: these are two names in the context that refer to the object. It makes the context more uniform, such that a base template can work on the object value as well.

Note that even if you remove this, you can still access the object through:

```<code>{{ <b>view.object</b>.list_name }}</code>```

Since the basic implementation of get_context_name will add the view variable to the context that refers to the instance constructed of the view.

Title: Django context returned by get_object

Body:
class ListDetailView(DetailView):
    context_object_name = 'aaaa'

    def get_object(self, queryset=None):
        return List.objects.get(unique_list_id=self.kwargs['unique_list_id'])

In template I have two equal contexts:

{{ object.list_name }}
{{ aaaa.list_name }}

How to override get_object() to return only context specified by context_object_name = 'aaaa'?
Why I have 2 contexts?

Body:
This is not determined by the get_object method [Django-doc], but determined by the implementation of the get_context_data method [Django-doc] of the DetailView [Django-doc]. Indeed, for views that inherit from the SingleObjectMixin [Django-doc], it is implemented as [GitHub]:

def get_context_data(self, **kwargs):
    """Insert the single object into the context dict."""
    context = {}
    if self.object:
        context['object'] = self.object
        context_object_name = self.get_context_object_name(self.object)
        if context_object_name:
            context[context_object_name] = self.object
    context.update(kwargs)
    return super().get_context_data(**context)

So it will always set the object to the self.object (if that object exists), and if there is a context_object_name, to that name as well.

You can slightly update that, by removing it from the dictionary, like:

class ListDetailView(DetailView):
    context_object_name = 'aaaa'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context.pop('object', None)
        return context

    def get_object(self, queryset=None):
        return List.objects.get(unique_list_id=self.kwargs['unique_list_id'])

That being said, I don't see any benefit to remove it. It refers to the same object. The query is not done twice: these are two names in the context that refer to the object. It makes the context more uniform, such that a base template can work on the object value as well.

Note that even if you remove this, you can still access the object through:

{{ view.object.list_name }}

Since the basic implementation of get_context_name will add the view variable to the context that refers to the instance constructed of the view.


问:
PuPHPet Error: install php7.0-mysqlnd' returned 100
I got a problem running a PuPHPet Box, the PHP Service does not start, I get the following error after vagrant up:

Error: Execution of '/usr/bin/apt-get -q -y -o DPkg::Options::=--force-confold install php7.0-mysqlnd' returned 100: Reading package lists...

After This, the php service fails to start:

```<code>==>  Reading state information...
==>  The following NEW packages will be installed:
==>    php7.0-mysql
==>  0 upgraded, 1 newly installed, 0 to remove and 109 not upgraded.
==>  Need to get 124 kB of archives.
==>  After this operation, 486 kB of additional disk space will be used.
==>  Get:1 http://ppa.launchpad.net/ondrej/php/ubuntu xenial/main amd64 php7.0-mysql amd64 7.0.33-20+ubuntu16.04.1+deb.sury.org+1 [124 kB]
==>  Fetched 124 kB in 0s (570 kB/s)
==>  Selecting previously unselected package php7.0-mysql.
(Reading database ... 54197 files and directories currently installed.)
==>  Preparing to unpack .../php7.0-mysql_7.0.33-20+ubuntu16.04.1+deb.sury.org+1_amd64.deb ...
==>  Unpacking php7.0-mysql (7.0.33-20+ubuntu16.04.1+deb.sury.org+1) ...
==>  Processing triggers for php7.0-fpm (7.0.33-20+ubuntu16.04.1+deb.sury.org+1) ...
==>  Job for php7.0-fpm.service failed because a timeout was exceeded. See "systemctl status php7.0-fpm.service" and "journalctl -xe" for details.
</code>```

The machine is starting and I can ssh into it, manually installing php also fails.

I am using Virtual Box on Windows 10 and Git Bash. I tried all available PHP-Versions (7.0, 7.1, 7.2), tried several times provisioning, destroying the machine, going through the creation process on PuPHPet.com. Any suggestions?

答:
I've had a similar issue the past couple of days. After SSHing into the box and running journalctl -u php7.0-fpm I got this log:

```<code>Feb 14 09:53:47 vagrant systemd[1]: Starting The PHP 7.0 FastCGI Process Manager...
Feb 14 09:53:47 vagrant update-alternatives[10343]: update-alternatives: error: alternative path /run/php/php7.0-fpm.sock doesn't exist
Feb 14 09:53:47 vagrant systemd[1]: php7.0-fpm.service: PID file /run/php/php7.0-fpm.pid not readable (yet?) after start-post: No such file or directory
Feb 14 09:55:17 vagrant systemd[1]: php7.0-fpm.service: Start-post operation timed out. Stopping.
Feb 14 09:55:17 vagrant systemd[1]: Failed to start The PHP 7.0 FastCGI Process Manager.
Feb 14 09:55:17 vagrant systemd[1]: php7.0-fpm.service: Unit entered failed state.
Feb 14 09:55:17 vagrant systemd[1]: php7.0-fpm.service: Failed with result 'timeout'.
Feb 14 09:55:22 vagrant systemd[1]: Stopped The PHP 7.0 FastCGI Process Manager.
</code>```

Turns out the PID file path is wrong.

You can update the PID file $pid_file variable within the params.pp.
File path:puphpet/puppet/modules/puphpet/manifests/php/params.pp

Updating this value to run/php/php7.0-fpm.pid then destroying and running vagrant up fixed this issue for me.

There's also a pull request within the puphpet repo with this change: https://github.com/AOEpeople/puppet-puphpet/commit/e3b50ce72b922c2649ac82979b02edfd4e3b8c0a

Body:
I got a problem running a PuPHPet Box, the PHP Service does not start, I get the following error after vagrant up:

Error: Execution of '/usr/bin/apt-get -q -y -o DPkg::Options::=--force-confold install php7.0-mysqlnd' returned 100: Reading package lists...

After This, the php service fails to start:

==>  Reading state information...
==>  The following NEW packages will be installed:
==>    php7.0-mysql
==>  0 upgraded, 1 newly installed, 0 to remove and 109 not upgraded.
==>  Need to get 124 kB of archives.
==>  After this operation, 486 kB of additional disk space will be used.
==>  Get:1 http://ppa.launchpad.net/ondrej/php/ubuntu xenial/main amd64 php7.0-mysql amd64 7.0.33-20+ubuntu16.04.1+deb.sury.org+1 [124 kB]
==>  Fetched 124 kB in 0s (570 kB/s)
==>  Selecting previously unselected package php7.0-mysql.
(Reading database ... 54197 files and directories currently installed.)
==>  Preparing to unpack .../php7.0-mysql_7.0.33-20+ubuntu16.04.1+deb.sury.org+1_amd64.deb ...
==>  Unpacking php7.0-mysql (7.0.33-20+ubuntu16.04.1+deb.sury.org+1) ...
==>  Processing triggers for php7.0-fpm (7.0.33-20+ubuntu16.04.1+deb.sury.org+1) ...
==>  Job for php7.0-fpm.service failed because a timeout was exceeded. See "systemctl status php7.0-fpm.service" and "journalctl -xe" for details.

The machine is starting and I can ssh into it, manually installing php also fails.

I am using Virtual Box on Windows 10 and Git Bash. I tried all available PHP-Versions (7.0, 7.1, 7.2), tried several times provisioning, destroying the machine, going through the creation process on PuPHPet.com. Any suggestions?

Body:
I've had a similar issue the past couple of days. After SSHing into the box and running journalctl -u php7.0-fpm I got this log:

Feb 14 09:53:47 vagrant systemd[1]: Starting The PHP 7.0 FastCGI Process Manager...
Feb 14 09:53:47 vagrant update-alternatives[10343]: update-alternatives: error: alternative path /run/php/php7.0-fpm.sock doesn't exist
Feb 14 09:53:47 vagrant systemd[1]: php7.0-fpm.service: PID file /run/php/php7.0-fpm.pid not readable (yet?) after start-post: No such file or directory
Feb 14 09:55:17 vagrant systemd[1]: php7.0-fpm.service: Start-post operation timed out. Stopping.
Feb 14 09:55:17 vagrant systemd[1]: Failed to start The PHP 7.0 FastCGI Process Manager.
Feb 14 09:55:17 vagrant systemd[1]: php7.0-fpm.service: Unit entered failed state.
Feb 14 09:55:17 vagrant systemd[1]: php7.0-fpm.service: Failed with result 'timeout'.
Feb 14 09:55:22 vagrant systemd[1]: Stopped The PHP 7.0 FastCGI Process Manager.

Turns out the PID file path is wrong.

You can update the PID file $pid_file variable within the params.pp.
File path:puphpet/puppet/modules/puphpet/manifests/php/params.pp

Updating this value to run/php/php7.0-fpm.pid then destroying and running vagrant up fixed this issue for me.

There's also a pull request within the puphpet repo with this change: https://github.com/AOEpeople/puppet-puphpet/commit/e3b50ce72b922c2649ac82979b02edfd4e3b8c0a


问:
Knit only until a specific chunk
Is there a way to knit a html_document until a specific chunk?

Suppose I have this .Rmd and I want only to knit a html_document until the cars chunk:

```<code>---
title: "Untitled"
author: "Igor Kuivjogi Fernandes"
date: "14/02/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

<h2>R Markdown</h2>

<p>This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.</p>

<p>When you click the <strong>Knit</strong> button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:</p>

```summary(cars)
```

<h2>Including Plots</h2>

<p>You can also embed plots, for example:</p>

```plot(pressure)
```

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

答:
This

```<code>---
title: "Test"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r cars}
summary(cars)
```

```{r pressure, echo=FALSE}
plot(pressure)
```
</code>```

produces this:

And if you add one chunk that controls the global options...

```<code>---
title: "Test"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r cars}
summary(cars)
```

```{r setup2, include=FALSE}
knitr::opts_chunk$set(eval = FALSE)
```

```{r pressure, echo=FALSE}
plot(pressure)
```
</code>```

...then the last code chunk is not executed and there is not plot:

Title: Knit only until a specific chunk

Body:
Is there a way to knit a html_document until a specific chunk?

Suppose I have this .Rmd and I want only to knit a html_document until the cars chunk:

---
title: "Untitled"
author: "Igor Kuivjogi Fernandes"
date: "14/02/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)

Including Plots

You can also embed plots, for example:

plot(pressure)

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Body:
This

---
title: "Test"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r cars}
summary(cars)
```

```{r pressure, echo=FALSE}
plot(pressure)
```

produces this:

And if you add one chunk that controls the global options...

---
title: "Test"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r cars}
summary(cars)
```

```{r setup2, include=FALSE}
knitr::opts_chunk$set(eval = FALSE)
```

```{r pressure, echo=FALSE}
plot(pressure)
```

...then the last code chunk is not executed and there is not plot:


问:
data boxes not displayed by gnuplot
I'd like to do a bar chart using gnuplot.

I used this settings

```<code>set style data boxes
set style fill solid
plot 'foo.dat' using 1:2:(1) linewidth 2
</code>```

with the content of foo.dat being

```<code>8 1
10 1
11 4
12 4
</code>```

gnuplot only displays the bars corresponding to the last two lines.

Why ?
Is there an other solution than adding "9 0" into my data file ?

Thank you in advance

答:
By default your graph will be autoscaled in y from 1 to 4. That's why you can't see the first two bars.

The solution: set your y-range properly.

```<code>set yrange[0:5]
</code>```

Edit: @Christoph's good suggestion set yrange[0:*] will conveniently autoscale the upper end. However, here from [0:4] which will not look nice with the boxes touching the upper x-axis.
Therefore, I recommend to add some margins set offsets 0,0,1,0   # left,right,top,bottom. Check help margins.

Code:

```<code>### plot boxes
reset session

$Data <<EOD
8 1
10 1
11 4
12 4
EOD

set style data boxes
set style fill solid
set yrange [0:*]
set offsets 0,0,1,0   # left,right,top,bottom

plot $Data using 1:2:(1) w boxes linewidth 2
### end of code
</code>```

Result:

Title: data boxes not displayed by gnuplot

Body:
I'd like to do a bar chart using gnuplot.

I used this settings

set style data boxes
set style fill solid
plot 'foo.dat' using 1:2:(1) linewidth 2

with the content of foo.dat being

8 1
10 1
11 4
12 4

gnuplot only displays the bars corresponding to the last two lines.

Why ?
Is there an other solution than adding "9 0" into my data file ?

Thank you in advance

Body:
By default your graph will be autoscaled in y from 1 to 4. That's why you can't see the first two bars.

The solution: set your y-range properly.

set yrange[0:5]

Edit: @Christoph's good suggestion set yrange[0:*] will conveniently autoscale the upper end. However, here from [0:4] which will not look nice with the boxes touching the upper x-axis.
Therefore, I recommend to add some margins set offsets 0,0,1,0   # left,right,top,bottom. Check help margins.

Code:

### plot boxes
reset session

$Data <<EOD
8 1
10 1
11 4
12 4
EOD

set style data boxes
set style fill solid
set yrange [0:*]
set offsets 0,0,1,0   # left,right,top,bottom

plot $Data using 1:2:(1) w boxes linewidth 2
### end of code

Result:


问:
Javascript filter array by another array of filters
I have a filtersArray which is a bunch of {id, value} and I want to filter my data (also array of JSON objects) to get back only the elements that match all of the filters? Is there a better way to do this than iterating through the arrayOfFilters with each filter using a for loop and doing a filter on each criteria?

the data is an array of JSON objects - ie

```<code>[{formID:1234, name:"sam", email:"sam@gmail.com", status:"open", phone: "333-444-5555"},
 {formID:2155, name:"charlie", email:"charlie@gmail.com", status:"closed", phone: "888-323-1234"},...]
</code>```

and the filtersArray [{"status":"closed"}, {"name":"charlie"}, {"id":2155}...]

I have tried doing

```<code>for(var criteria in arrayOfFilters){
   this.data = this.data.filter( d => d.status === criteria.status)
                    .filter(d => d.name === criteria.name)
                    .filter(d => d.address === criteria.address)...
}
</code>```

it does not work real well since criteria is a JSON object like {"status":"closed"}, {"name":"charlie"}...

答:
if id is unique u can do:</p>

```<code>const filteredArray = arrayOfData.filter( data => arrayOfFilters.map( filter => filter.id ).includes( data.id ) )
</code>```

Body:
I have a filtersArray which is a bunch of {id, value} and I want to filter my data (also array of JSON objects) to get back only the elements that match all of the filters? Is there a better way to do this than iterating through the arrayOfFilters with each filter using a for loop and doing a filter on each criteria?

the data is an array of JSON objects - ie

[{formID:1234, name:"sam", email:"sam@gmail.com", status:"open", phone: "333-444-5555"},
 {formID:2155, name:"charlie", email:"charlie@gmail.com", status:"closed", phone: "888-323-1234"},...]

and the filtersArray [{"status":"closed"}, {"name":"charlie"}, {"id":2155}...]

I have tried doing

for(var criteria in arrayOfFilters){
   this.data = this.data.filter( d => d.status === criteria.status)
                    .filter(d => d.name === criteria.name)
                    .filter(d => d.address === criteria.address)...
}

it does not work real well since criteria is a JSON object like {"status":"closed"}, {"name":"charlie"}...

Body:
if id is unique u can do:

const filteredArray = arrayOfData.filter( data => arrayOfFilters.map( filter => filter.id ).includes( data.id ) )


问:
How to retrieve an element from a set without removing it?
Suppose the following:

```<code>>>> s = set([1, 2, 3])
</code>```

How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.

Quick and dirty:

```<code>>>> elem = s.pop()
>>> s.add(elem)
</code>```

But do you know of a better way? Ideally in constant time.

答:
Least code would be:

```<code>>>> s = set([1, 2, 3])
>>> list(s)[0]
1
</code>```

Obviously this would create a new list which contains each member of the set, so not great if your set is very large.

OwnerDisplayName: Daren Thomas

Body:
Suppose the following:

>>> s = set([1, 2, 3])

How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.

Quick and dirty:

>>> elem = s.pop()
>>> s.add(elem)

But do you know of a better way? Ideally in constant time.

Body:
Least code would be:

>>> s = set([1, 2, 3])
>>> list(s)[0]
1

Obviously this would create a new list which contains each member of the set, so not great if your set is very large.

OwnerDisplayName: John

ContentLicense: CC BY-SA 2.5


问:
is this correct re returning a date re memory management?
is this correct re returning a date re memory management?

The assumption here I have is I want to return a date back to the caller, but I don't want the caller to be able to be change the date and impact the method's date, hence I thought I would return a copy.

So the code in the method I have is:

```<code>- (NSDate*)dateForMyTest {
     return [[self.endDate copy] autorelease];
}
</code>```

I was assuming I have to autorelease it so the caller doesn't have to, as they would not have called an init/copy/etc themselves.

答: Yes, that is correct. Because the method name didn't include init/copy/new, you should autorelease.</p>

Body:
is this correct re returning a date re memory management?

The assumption here I have is I want to return a date back to the caller, but I don't want the caller to be able to be change the date and impact the method's date, hence I thought I would return a copy.

So the code in the method I have is:

- (NSDate*)dateForMyTest {
     return [[self.endDate copy] autorelease];
}

I was assuming I have to autorelease it so the caller doesn't have to, as they would not have called an init/copy/etc themselves.


问:
Convert Arabic numbers in a Pandas column to integers
I have been given a survey for analysis. Unfortunately, some of the participants have used Arabic/Farsi numbers to fill some values. For example:

import pandas as pd

pd.DataFrame(["24", "۱۲", "45", "۳۲"], columns=["age"])
```

<p>and what I want is to convert all the values to Python integers:</p>

```[24, 12, 45, 32]
```

What is the most canonical/performant way to do this

答:
Apply unidecode first through your numbers, and then convert using pd.to_numeric

```<code>pip install unidecode
from unidecode import unidecode

df['numbers'] = pd.to_numeric(df.age.apply(unidecode), errors='coerce')
</code>```

```<code>  age  numbers
0  24       24
1  ۱۲       12
2  45       45
3  ۳۲       32
</code>```

Body:
I have been given a survey for analysis. Unfortunately, some of the participants have used Arabic/Farsi numbers to fill some values. For example:

import pandas as pd

pd.DataFrame(["24", "۱۲", "45", "۳۲"], columns=["age"])

and what I want is to convert all the values to Python integers:

[24, 12, 45, 32]

What is the most canonical/performant way to do this

Body:
Apply unidecode first through your numbers, and then convert using pd.to_numeric

pip install unidecode
from unidecode import unidecode

df['numbers'] = pd.to_numeric(df.age.apply(unidecode), errors='coerce')

  age  numbers
0  24       24
1  ۱۲       12
2  45       45
3  ۳۲       32


问:
NLog not logging debug messages
I'm having a problem with logging Debug level messages in a .NET Core 3.1 Worker Service project. Neither my file target or console are getting Debug level messages logged. Information level events are written as expected. I have reviewed an older question with the same title to ensure all those boxes are checked.

NLog.config

```<code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="%appdata%\FileTransferService\nlog-internal.log">

  <variable name="logdir" value="${specialfolder:folder=ApplicationData}/FileTransferService"/>
  <variable name="stdlayout" value="${longdate}|${level:uppercase=true}|${message:exceptionSeparator=|}${exception:format=ToString}"/>

  <targets>
    <target name="default" xsi:type="AsyncWrapper" overflowAction="Block">
      <target name="defaultlog" xsi:type="File"
              fileName="${logdir}/dftslog.txt"
              layout="${stdlayout}"
              archiveEvery="Month" concurrentWrites="false"/>
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="default"/>
  </rules>
</nlog>
</code>```

appsettings.json

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}
</code>```

I've tried setting both the Microsoft and Microsoft.Hosting.Lifetime also to Debug, but that had no effect.

Program.CreateHostBuilder method

```<code>public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseWindowsService()
        .ConfigureLogging((context, logBuilder) => {
            logBuilder.ClearProviders();
            logBuilder.AddConfiguration(context.Configuration.GetSection("Logging"));
            logBuilder.SetMinimumLevel(LogLevel.Debug);
            logBuilder.AddConsole();
            logBuilder.AddNLog();
        })
        .ConfigureServices((hostContext, services) => {
            services.AddHostedService<Worker>();
            services.AddTransient(typeof(ITransferService), typeof(TransferService));
        });
</code>```

Here are a few additional notes:

I tried calling SetMinimumLevel with no effect.

The NLog.config is set to Copy Always.

I get the same results without AddConsole. That was actually added after I saw that debug messages weren't getting logged.

答:
The problem appears to be with Visual Studio 2019.

Although the problem itself persists, the debug level events are written to both the console and the flat file when I run the application outside of Visual Studio. This is not due to the debugger as I might have expected, because it exhibits the same behavior if I run it without the debugger within Visual Studio.

I looked through Visual Studio settings and did a quick search, but I couldn't find anything related. That said, knowing that the events will be logged outside of Visual Studio solves my problem to the extent necessary.

Title: NLog not logging debug messages

Body:
I'm having a problem with logging Debug level messages in a .NET Core 3.1 Worker Service project. Neither my file target or console are getting Debug level messages logged. Information level events are written as expected. I have reviewed an older question with the same title to ensure all those boxes are checked.

NLog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="%appdata%\FileTransferService\nlog-internal.log">

  <variable name="logdir" value="${specialfolder:folder=ApplicationData}/FileTransferService"/>
  <variable name="stdlayout" value="${longdate}|${level:uppercase=true}|${message:exceptionSeparator=|}${exception:format=ToString}"/>

  <targets>
    <target name="default" xsi:type="AsyncWrapper" overflowAction="Block">
      <target name="defaultlog" xsi:type="File"
              fileName="${logdir}/dftslog.txt"
              layout="${stdlayout}"
              archiveEvery="Month" concurrentWrites="false"/>
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="default"/>
  </rules>
</nlog>

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

I've tried setting both the Microsoft and Microsoft.Hosting.Lifetime also to Debug, but that had no effect.

Program.CreateHostBuilder method

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseWindowsService()
        .ConfigureLogging((context, logBuilder) => {
            logBuilder.ClearProviders();
            logBuilder.AddConfiguration(context.Configuration.GetSection("Logging"));
            logBuilder.SetMinimumLevel(LogLevel.Debug);
            logBuilder.AddConsole();
            logBuilder.AddNLog();
        })
        .ConfigureServices((hostContext, services) => {
            services.AddHostedService<Worker>();
            services.AddTransient(typeof(ITransferService), typeof(TransferService));
        });

Here are a few additional notes:

I tried calling SetMinimumLevel with no effect.

The NLog.config is set to Copy Always.

I get the same results without AddConsole. That was actually added after I saw that debug messages weren't getting logged.


问:
Runtime error in line 25: Char 35: runtime error: member access within null pointer of type 'struct HASH_TABLE' (solution.c)
```<code>#define SIZE 50

typedef struct{
    int key;
    int value;
}HASH_TABLE;

HASH_TABLE* hashArray[SIZE];

int hashCode(int key) {
   return key % SIZE;
}

bool containsDuplicate(int* nums, int numsSize){

    int count = 1,i=0;

    HASH_TABLE* data  = (HASH_TABLE*)malloc(sizeof(HASH_TABLE*));
    data->value = count;

    for(i=0;i<numsSize;i++)
    {
        int hashIndex = hashCode(nums[i]);
        hashArray[hashIndex]->key = nums[i];
        hashArray[hashIndex]->value = data->value;

        ++hashIndex;
        hashIndex %= SIZE;

        if(hashArray[hashIndex]->key == nums[i])
        {
            data->value++;
        }

    }
    if(data->value>0)
        return true;

    return false;
}
</code>```

I'm trying to code for finding duplicates using hash table algorithm in C.

The code should work in following ways

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true
Example 2:

Input: [1,2,3,4]
Output: false
Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

please help me resolving my error

Thank you

答:
You have several errors in your code:

You have given space for only one value for each hash entry in the table.  This means you are comparing the numbers by their hash value only and not by their integer value.  Let's say you enter 1 and later on you have 51.  Both have the same hash value, as you compute the remainder modulo 50 as the hash value, so they will go in the same table entry (the entry with index 1), this is the second entry.  When you read the number 51, you change the value in the field data to 51, and, if later on, arrives another 1, you'll end losing it as the first 1 you had before,  just flied out when you added the 51 number.  The hash table allows you to get faster access, but you have to store all the keys you can have, despite of the hash value they have.  So each table entry must support a list of entries all with hash value x, and the list must have all the entries that share the same hash, and compare the individual keys to see which one is the one you are comparing.

You should use malloc(sizeof *data) or malloc(sizeof(HASHTABLE)), better than what you do.  In your code you allocate bytes to hold a pointer (you specify the size of a pointer, not the size of a record).  sizeof *data is the size of the pointed to data (yes, you can use it after a sizeof operator, even if it has not been allocated yet, the compiler is not interested in the value pointed, just in the data size of it)

Never, never never, cast the value returned from malloc(3).  This is not what you want.  It allows you to forget to #include <stdlib.h> (where a proper prototype of malloc(3) is given) and so, hide further errors, and this is far more dangerous than the error you want to avoid.  Malloc always returns a pointer, but if you don't use a prototype (and this happens if you have casted the value returned and forgotten to #include <stdlib.h>, the compiler will assume malloc() returns an int (which is not true) and will generate code to convert the value returned into a pointer to HASH_TABLE, and this will trash the data returned by malloc() in the best case.  In a 64bit architecture, pointers are 64bit, while integers are only 32.  In this architecture the value returned by malloc is 64 bit wide... the compiler will generate code to convert the 32 bits of a (undefined behaviour) 32 bit data, and convert it (extending with undefined behaviour) that data to 64bit, and making a pointer with (undefined behaviour) that data.  You'll most probably receive a segmentation fault and a program crash, when you try to use your pointer for anything else than printing its value.

if you are using so simple hash function, then you had better to use a prime number for the number of elements in the hash table, so you'll not get some entries crowded of data, while others are empty.  Using a prime number allows for better distribution of numbers (although it is better to select a better hash table function)

Body:
#define SIZE 50

typedef struct{
    int key;
    int value;
}HASH_TABLE;

HASH_TABLE* hashArray[SIZE];

int hashCode(int key) {
   return key % SIZE;
}

bool containsDuplicate(int* nums, int numsSize){

    int count = 1,i=0;

    HASH_TABLE* data  = (HASH_TABLE*)malloc(sizeof(HASH_TABLE*));
    data->value = count;

    for(i=0;i<numsSize;i++)
    {
        int hashIndex = hashCode(nums[i]);
        hashArray[hashIndex]->key = nums[i];
        hashArray[hashIndex]->value = data->value;

        ++hashIndex;
        hashIndex %= SIZE;

        if(hashArray[hashIndex]->key == nums[i])
        {
            data->value++;
        }

    }
    if(data->value>0)
        return true;

    return false;
}

I'm trying to code for finding duplicates using hash table algorithm in C.

The code should work in following ways

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true
Example 2:

Input: [1,2,3,4]
Output: false
Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

please help me resolving my error

Thank you


答:
Possible with numpy

```<code>import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = np.array([[11, 12, 13]]).T
C = np.append(A,B,axis=1)
</code>```

Possibly you will have to transpose C according to the shape you want.

Title: How to properly add elements to an array in Python

Body:
I have two arrays as the code shows below (A and B). I would like to take as output C = [[1, 2, 3, 11], [4, 5, 6, 12], [7, 8, 9, 13]]

I'm trying to, but the only thing I could reach was this:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [11, 12, 13]
C = [[x, y] for x, y in zip(A, B)]

print(C)
# Output: [[[1, 2, 3], 11], [[4, 5, 6], 12], [[7, 8, 9], 13]]

Body:
Possible with numpy

import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = np.array([[11, 12, 13]]).T
C = np.append(A,B,axis=1)

Possibly you will have to transpose C according to the shape you want.