问:
How do I scroll into a item in a list by search operation using react?
So, I made a react app that displays a list of items from a json file as in the pic.
I want to implement a search feature where i can enter the name and it checks for the name in list and scrolls to it.

A person told me about scroll-into-view , but I'm not understand how to make it compare the search term to the names in list.

My App.js code

```<code>import React,{useState} from 'react';
import Notes from './Notes';
import './App.css';

function App() {

  const [notes] = useState([]);
  const handleSubmit= ()=>{
      //Upon submitting I want the search functionality to be implemented here . If thats the way to do it.
  }

  return (
    <div className="App">

      <div className="App-header">
        <form><input type="text" placeholder="Start Typing.." onSubmit={handleSubmit} ></input></form>
        <div className="pageTitle">Song Notes :</div>
        <Notes thisNotes={notes}/>
      </div>

    </div>
  );
  }

export default App;
</code>```

My Notes.js code:

```<code>import React from 'react';
const Notes = ({notes})=>{
    const jsonNotes = require('./Notes.json');
    const songNotes = jsonNotes.map(note => {
        return(
            <div key={note.id}>
            <li class="noteAsList">

            <div className="songTitle">{note.Name}</div>

            ```

{note.Notes}```
            </li>
            </div>
        )
    })

    return(
        <div className="noteStyle">
          {songNotes}
        </div>
    )
}

export default Notes;
</code>```

I'm looking to implement such a feature. Either scrolling into view in the page or just displaying the item I asked for.

Thanks for the help in advance.

答:
Codesandbox

My App.js code

```<code>import React, { useState } from "react";
import Notes from "./Notes";
import "./App.css";

const jsonNotes = require("./Notes.json");

const App = () => {
  const [notes] = useState([]);
  const handleSubmit = event => {
    if (event.key === "Enter") {
      console.log(event.target.value);
      const obj = jsonNotes.find(item => item.Name === event.target.value);
      const el = document.getElementById(obj.id);
      if (el)
        el.scrollIntoView({
          behavior: "smooth",
          block: "start",
          inline: "center"
        });
    }
  };

  return (
    <div className="App">
      <div className="App-header">
        <input
          type="text"
          placeholder="Start Typing.."
          onKeyPress={handleSubmit}
        />
        <div className="pageTitle">Song Notes :</div>
        <Notes thisNotes={notes} />
      </div>
    </div>
  );
};

export default App;
</code>```

My Notes.js code:

```<code>import React from "react";
const jsonNotes = require("./Notes.json");

const Notes = ({ notes }) => {
  const songNotes = jsonNotes.map(note => {
    return (
      <div id={note.id} key={note.id}>
        <li className="noteAsList">
          <div className="songTitle">{note.Name}</div>
          ```

            {note.Notes}
          ```
        </li>
      </div>
    );
  });

  return <div className="noteStyle">{songNotes}</div>;
};

export default Notes;
</code>```

Body:
So, I made a react app that displays a list of items from a json file as in the pic.
I want to implement a search feature where i can enter the name and it checks for the name in list and scrolls to it.

A person told me about scroll-into-view , but I'm not understand how to make it compare the search term to the names in list.

My App.js code

import React,{useState} from 'react';
import Notes from './Notes';
import './App.css';

function App() {

  const [notes] = useState([]);
  const handleSubmit= ()=>{
      //Upon submitting I want the search functionality to be implemented here . If thats the way to do it.
  }

  return (

        <form><input type="text" placeholder="Start Typing.." onSubmit={handleSubmit} ></input></form>

Song Notes :

        <Notes thisNotes={notes}/>

  );
  }

export default App;

My Notes.js code:

import React from 'react';
const Notes = ({notes})=>{
    const jsonNotes = require('./Notes.json');
    const songNotes = jsonNotes.map(note => {
        return(

{note.Name}

{note.Notes}

        )
    })

    return(

          {songNotes}

    )
}

export default Notes;

I'm looking to implement such a feature. Either scrolling into view in the page or just displaying the item I asked for.

Thanks for the help in advance.

Body:
Codesandbox

My App.js code

import React, { useState } from "react";
import Notes from "./Notes";
import "./App.css";

const jsonNotes = require("./Notes.json");

const App = () => {
  const [notes] = useState([]);
  const handleSubmit = event => {
    if (event.key === "Enter") {
      console.log(event.target.value);
      const obj = jsonNotes.find(item => item.Name === event.target.value);
      const el = document.getElementById(obj.id);
      if (el)
        el.scrollIntoView({
          behavior: "smooth",
          block: "start",
          inline: "center"
        });
    }
  };

  return (
    <div className="App">
      <div className="App-header">
        <input
          type="text"
          placeholder="Start Typing.."
          onKeyPress={handleSubmit}
        />
        <div className="pageTitle">Song Notes :</div>
        <Notes thisNotes={notes} />
      </div>
    </div>
  );
};

export default App;

My Notes.js code:

import React from "react";
const jsonNotes = require("./Notes.json");

const Notes = ({ notes }) => {
  const songNotes = jsonNotes.map(note => {
    return (
      <div id={note.id} key={note.id}>
        <li className="noteAsList">
          <div className="songTitle">{note.Name}</div>
          <pre>
            <br />
            {note.Notes}
          </pre>
        </li>
      </div>
    );
  });

  return <div className="noteStyle">{songNotes}</div>;
};

export default Notes;


来源: stackexchange

问:
Trying to send a json encoded array from php to a js file, "Unexpected end of input"
So im trying to send an object array to a js function anytime I push a button.

```<code><button onclick="actualizarProcesos(<?php echo json_encode($p_array)?>);">X</button>
</code>```

I've made sure my json isnt sending any weird characters as it is mostly int except for the object attribute "name" which is string.

That function is in a different js file:

```<code>   function actualizarProcesos(p_array){
    var p = JSON.parse(p_array);
}
</code>```

At the moment I'm trying to send make sure the function is receiving the data but it keeps throwing the error Uncaught SyntaxError: Unexpected end of inputSo I'm stuck trying to find out how to fix the error.

I plan afterwards on sending that array to another php file using ajax, something like this:

```<code>$.ajax({
            type: "POST",
            url: "post.php",
            data: JSON.stringify(values),
            success: function(data){
                alert(data)
            }
    });
</code>```

This is the full json I'm trying to send

```<code>[{"name":"A","t_arrival":7,"t_est":25,"state":1,"pages":5,"mem_data":[[1,8,13,5,0,1],[0,0,0,0,0,0],[1,11,17,3,1,1],[1,12,16,4,0,1],[0,0,0,0,0,0]],"t_rem":25,"t_wait":0,"rem_quantum":0},{"name":"B","t_arrival":6,"t_est":13,"state":2,"pages":4,"mem_data":[[0,0,0,0,0,0],[1,9,16,5,0,1],[1,7,14,6,1,0],[0,0,0,0,0,0]],"t_rem":13,"t_wait":0,"rem_quantum":0},{"name":"C","t_arrival":8,"t_est":37,"state":3,"pages":3,"mem_data":[[1,9,12,2,0,0],[0,0,0,0,0,0],[1,13,21,7,0,1]],"t_rem":37,"t_wait":0,"rem_quantum":0}]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So im trying to send an object array to a js function anytime I push a button.

<button onclick="actualizarProcesos(<?php echo json_encode($p_array)?>);">X</button>

I've made sure my json isnt sending any weird characters as it is mostly int except for the object attribute "name" which is string.

That function is in a different js file:

   function actualizarProcesos(p_array){
    var p = JSON.parse(p_array);
}

At the moment I'm trying to send make sure the function is receiving the data but it keeps throwing the error Uncaught SyntaxError: Unexpected end of inputSo I'm stuck trying to find out how to fix the error.

I plan afterwards on sending that array to another php file using ajax, something like this:

$.ajax({
            type: "POST",
            url: "post.php",
            data: JSON.stringify(values),
            success: function(data){
                alert(data)
            }
    });

This is the full json I'm trying to send

[{"name":"A","t_arrival":7,"t_est":25,"state":1,"pages":5,"mem_data":[[1,8,13,5,0,1],[0,0,0,0,0,0],[1,11,17,3,1,1],[1,12,16,4,0,1],[0,0,0,0,0,0]],"t_rem":25,"t_wait":0,"rem_quantum":0},{"name":"B","t_arrival":6,"t_est":13,"state":2,"pages":4,"mem_data":[[0,0,0,0,0,0],[1,9,16,5,0,1],[1,7,14,6,1,0],[0,0,0,0,0,0]],"t_rem":13,"t_wait":0,"rem_quantum":0},{"name":"C","t_arrival":8,"t_est":37,"state":3,"pages":3,"mem_data":[[1,9,12,2,0,0],[0,0,0,0,0,0],[1,13,21,7,0,1]],"t_rem":37,"t_wait":0,"rem_quantum":0}]

Body:
Tested working fine. Hope this help you.

    <?php
     $p_array = [
       [
             "name" => "A",
             "t_arrival" => 7,
             "t_est" => 25,
             "state" => 1,
             "pages" => 5,
             "mem_data" => [
                [
                   1,
                   8,
                   13,
                   5,
                   0,
                   1
                ],
                [
                      0,
                      0,
                      0,
                      0,
                      0,
                      0
                   ],
                [
                         1,
                         11,
                         17,
                         3,
                         1,
                         1
                      ],
                [
                            1,
                            12,
                            16,
                            4,
                            0,
                            1
                         ],
                [
                               0,
                               0,
                               0,
                               0,
                               0,
                               0
                            ]
             ],
             "t_rem" => 25,
             "t_wait" => 0,
             "rem_quantum" => 0
          ],
       [
                                  "name" => "B",
                                  "t_arrival" => 6,
                                  "t_est" => 13,
                                  "state" => 2,
                                  "pages" => 4,
                                  "mem_data" => [
                                     [
                                        0,
                                        0,
                                        0,
                                        0,
                                        0,
                                        0
                                     ],
                                     [
                                           1,
                                           9,
                                           16,
                                           5,
                                           0,
                                           1
                                        ],
                                     [
                                              1,
                                              7,
                                              14,
                                              6,
                                              1,
                                              0
                                           ],
                                     [
                                                 0,
                                                 0,
                                                 0,
                                                 0,
                                                 0,
                                                 0
                                              ]
                                  ],
                                  "t_rem" => 13,
                                  "t_wait" => 0,
                                  "rem_quantum" => 0
                               ],
       [
                                                    "name" => "C",
                                                    "t_arrival" => 8,
                                                    "t_est" => 37,
                                                    "state" => 3,
                                                    "pages" => 3,
                                                    "mem_data" => [
                                                       [
                                                          1,
                                                          9,
                                                          12,
                                                          2,
                                                          0,
                                                          0
                                                       ],
                                                       [
                                                             0,
                                                             0,
                                                             0,
                                                             0,
                                                             0,
                                                             0
                                                          ],
                                                       [
                                                                1,
                                                                13,
                                                                21,
                                                                7,
                                                                0,
                                                                1
                                                             ]
                                                    ],
                                                    "t_rem" => 37,
                                                    "t_wait" => 0,
                                                    "rem_quantum" => 0
                                                 ]
    ];
    $p_array = json_encode($p_array);
    ?>
    <button onclick='actualizarProcesos(<?php echo $p_array ?>)' >X</button>
    <script>
    function actualizarProcesos(arr){
        console.log(arr);
    }
</script>


问:
How can I use preg_match in jQuery?
Can I use preg_match to validate phone number in jQuery? Here is my code which does not work:

```<code>if (!preg_match("/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/", phone.val() ))  {
            phone.addClass("needsfilled");
            phone.val(phonerror);
        }
</code>```

HTML
<input id="phone" type="text" value=""  name="phone" />

答:
RegExp.exec(string) will work.

try this:

```<code>var pattern= "/your pattern/";
var result = pattern.exec ( $("#phone").val() );
// true if match
</code>```

src: http://javascriptkit.com/javatutors/redev3.shtml

Title: How can I use preg_match in jQuery?

Body:
Can I use preg_match to validate phone number in jQuery? Here is my code which does not work:

if (!preg_match("/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/", phone.val() ))  {
            phone.addClass("needsfilled");
            phone.val(phonerror);
        }

HTML
<input id="phone" type="text" value=""  name="phone" />

Body:
RegExp.exec(string) will work.

try this:

var pattern= "/your pattern/";
var result = pattern.exec ( $("#phone").val() );
// true if match

src: http://javascriptkit.com/javatutors/redev3.shtml

ContentLicense: CC BY-SA 3.0


问:
Xcode/Mac: keyboard shortcut to type the "OR" sign "||" (double vertical bar)?
Each time I have to copy paste "||" from elsewhere when I want to type the double vertical bar of the OR sign.

Is there a keyboard shortcut to type it?

答:
For macs with German keyboards, press:

ALT + 7


问:
Work on a remote project with Eclipse via SSH
I have the following boxes:

a) A Windows box with Eclipse CDT,

b) A Linux box, accessible for me only via SSH.

Both the compiler and the hardware required to build and run my project is only on machine B.

I'd like to work "transparently" from a Windows box on that project using Eclipse CDT and be able to build, run and debug the project remotely from within the IDE.

How do I set up that:

The building will work? Any simpler solutions than writing a local makefile which would rsync the project and then call a remote makefile to initiate the actual build? Does Eclipse managed build have a feature for that?

The debugging will work?

Preferably - the Eclipse CDT code indexing will work? Do I have to copy all required header files from machine B to machine A and add them to include path manually?

答:
How to edit in Eclipse locally, but use a git-based script I wrote (sync_git_repo_from_pc1_to_pc2.sh) to synchronize and build remotely

The script I wrote to do this is sync_git_repo_from_pc1_to_pc2.sh.

Readme: README_git-sync_repo_from_pc1_to_pc2.md

Update: see also this alternative/competitor: GitSync:

How to use Sublime over SSH

https://github.com/jachin/GitSync

This answer currently only applies to using two Linux computers [or maybe works on Mac too?--untested on Mac] (syncing from one to the other) because I wrote this synchronization script in bash. It is simply a wrapper around git, however, so feel free to take it and convert it into a cross-platform Python solution or something if you wish

This doesn't directly answer the OP's question, but it is so close I guarantee it will answer many other peoples' question who land on this page (mine included, actually, as I came here first before writing my own solution), so I'm posting it here anyway.

I want to:

develop code using a powerful IDE like Eclipse on a light-weight Linux computer, then

build that code via ssh on a different, more powerful Linux computer (from the command-line, NOT from inside Eclipse)

Let's call the first computer where I write the code "PC1" (Personal Computer 1), and the 2nd computer where I build the code "PC2". I need a tool to easily synchronize from PC1 to PC2. I tried rsync, but it was insanely slow for large repos and took tons of bandwidth and data.

So, how do I do it? What workflow should I use? If you have this question too, here's the workflow that I decided upon. I wrote a bash script to automate the process by using git to automatically push changes from PC1 to PC2 via a remote repository, such as github. So far it works very well and I'm very pleased with it. It is far far far faster than rsync, more trustworthy in my opinion because each PC maintains a functional git repo, and uses far less bandwidth to do the whole sync, so it's easily doable over a cell phone hot spot without using tons of your data.

Setup:

Install the script on PC1 (this solution assumes ~/bin is in your $PATH):

 git clone https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.git
 cd eRCaGuy_dotfiles/useful_scripts
 mkdir -p ~/bin
 ln -s "${PWD}/sync_git_repo_from_pc1_to_pc2.sh" ~/bin/sync_git_repo_from_pc1_to_pc2
 cd ..
 cp -i .sync_git_repo ~/.sync_git_repo
```
</li>
<li><p>Now edit the "~/.sync_git_repo" file you just copied above, and update its parameters to fit your case. Here are the parameters it contains:</p>
<pre class="lang-bash prettyprint-override"><code> # The git repo root directory on PC2 where you are syncing your files TO; this dir must *already exist*
 # and you must have *already `git clone`d* a copy of your git repo into it!
 # - Do NOT use variables such as `$HOME`. Be explicit instead. This is because the variable expansion will
 #   happen on the local machine when what we need is the variable expansion from the remote machine. Being
 #   explicit instead just avoids this problem.
 PC2_GIT_REPO_TARGET_DIR="/home/gabriel/dev/eRCaGuy_dotfiles" # explicitly type this out; don't use variables

 PC2_SSH_USERNAME="my_username" # explicitly type this out; don't use variables
 PC2_SSH_HOST="my_hostname"     # explicitly type this out; don't use variables
</code>```

Git clone your repo you want to sync on both PC1 and PC2.

Ensure your ssh keys are all set up to be able to push and pull to the remote repo from both PC1 and PC2. Here's some helpful links:

https://help.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh

https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

Ensure your ssh keys are all set up to ssh from PC1 to PC2.

Now cd into any directory within the git repo on PC1, and run:

 sync_git_repo_from_pc1_to_pc2
```

That's it! About 30 seconds later everything will be magically synced from PC1 to PC2, and it will be printing output the whole time to tell you what it's doing and where it's doing it on your disk and on which computer. It's safe too, because it doesn't overwrite or delete anything that is uncommitted. It backs it up first instead! Read more below for how that works.

Here's the process this script uses (ie: what it's actually doing)

From PC1: It checks to see if any uncommitted changes are on PC1. If so, it commits them to a temporary commit on the current branch. It then force pushes them to a remote SYNC branch. Then it uncommits its temporary commit it just did on the local branch, then it puts the local git repo back to exactly how it was by staging any files that were previously staged at the time you called the script. Next, it rsyncs a copy of the script over to PC2, and does an ssh call to tell PC2 to run the script with a special option to just do PC2 stuff.

Here's what PC2 does: it cds into the repo, and checks to see if any local uncommitted changes exist. If so, it creates a new backup branch forked off of the current branch (sample name: my_branch_SYNC_BAK_20200220-0028hrs-15sec <-- notice that's YYYYMMDD-HHMMhrs--SSsec), and commits any uncommitted changes to that branch with a commit message such as DO BACKUP OF ALL UNCOMMITTED CHANGES ON PC2 (TARGET PC/BUILD MACHINE). Now, it checks out the SYNC branch, pulling it from the remote repository if it is not already on the local machine. Then, it fetches the latest changes on the remote repository, and does a hard reset to force the local SYNC repository to match the remote SYNC repository. You might call this a "hard pull". It is safe, however, because we already backed up any uncommitted changes we had locally on PC2, so nothing is lost!

That's it! You now have produced a perfect copy from PC1 to PC2 without even having to ensure clean working directories, as the script handled all of the automatic committing and stuff for you! It is fast and works very well on huge repositories. Now you have an easy mechanism to use any IDE of your choice on one machine while building or testing on another machine, easily, over a wifi hot spot from your cell phone if needed, even if the repository is dozens of gigabytes and you are time and resource-constrained.

Resources:

The whole project: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles

See tons more links and references in the source code itself within this project.

How to do a "hard pull", as I call it: How do I force "git pull" to overwrite local files?

Related:

git repository sync between computers, when moving around?

ContentLicense: CC BY-SA 2.5

Body:
How to edit in Eclipse locally, but use a git-based script I wrote (sync_git_repo_from_pc1_to_pc2.sh) to synchronize and build remotely

The script I wrote to do this is sync_git_repo_from_pc1_to_pc2.sh.

Readme: README_git-sync_repo_from_pc1_to_pc2.md

Update: see also this alternative/competitor: GitSync:

How to use Sublime over SSH

https://github.com/jachin/GitSync

This answer currently only applies to using two Linux computers [or maybe works on Mac too?--untested on Mac] (syncing from one to the other) because I wrote this synchronization script in bash. It is simply a wrapper around git, however, so feel free to take it and convert it into a cross-platform Python solution or something if you wish

This doesn't directly answer the OP's question, but it is so close I guarantee it will answer many other peoples' question who land on this page (mine included, actually, as I came here first before writing my own solution), so I'm posting it here anyway.

I want to:

develop code using a powerful IDE like Eclipse on a light-weight Linux computer, then

build that code via ssh on a different, more powerful Linux computer (from the command-line, NOT from inside Eclipse)

Let's call the first computer where I write the code "PC1" (Personal Computer 1), and the 2nd computer where I build the code "PC2". I need a tool to easily synchronize from PC1 to PC2. I tried rsync, but it was insanely slow for large repos and took tons of bandwidth and data.

So, how do I do it? What workflow should I use? If you have this question too, here's the workflow that I decided upon. I wrote a bash script to automate the process by using git to automatically push changes from PC1 to PC2 via a remote repository, such as github. So far it works very well and I'm very pleased with it. It is far far far faster than rsync, more trustworthy in my opinion because each PC maintains a functional git repo, and uses far less bandwidth to do the whole sync, so it's easily doable over a cell phone hot spot without using tons of your data.

Setup:

Install the script on PC1 (this solution assumes ~/bin is in your $PATH):

 git clone https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.git
 cd eRCaGuy_dotfiles/useful_scripts
 mkdir -p ~/bin
 ln -s "${PWD}/sync_git_repo_from_pc1_to_pc2.sh" ~/bin/sync_git_repo_from_pc1_to_pc2
 cd ..
 cp -i .sync_git_repo ~/.sync_git_repo

Now edit the "~/.sync_git_repo" file you just copied above, and update its parameters to fit your case. Here are the parameters it contains:

 # The git repo root directory on PC2 where you are syncing your files TO; this dir must *already exist*
 # and you must have *already `git clone`d* a copy of your git repo into it!
 # - Do NOT use variables such as `$HOME`. Be explicit instead. This is because the variable expansion will
 #   happen on the local machine when what we need is the variable expansion from the remote machine. Being
 #   explicit instead just avoids this problem.
 PC2_GIT_REPO_TARGET_DIR="/home/gabriel/dev/eRCaGuy_dotfiles" # explicitly type this out; don't use variables

 PC2_SSH_USERNAME="my_username" # explicitly type this out; don't use variables
 PC2_SSH_HOST="my_hostname"     # explicitly type this out; don't use variables

Git clone your repo you want to sync on both PC1 and PC2.

Ensure your ssh keys are all set up to be able to push and pull to the remote repo from both PC1 and PC2. Here's some helpful links:

https://help.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh

https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

Ensure your ssh keys are all set up to ssh from PC1 to PC2.

Now cd into any directory within the git repo on PC1, and run:

 sync_git_repo_from_pc1_to_pc2

That's it! About 30 seconds later everything will be magically synced from PC1 to PC2, and it will be printing output the whole time to tell you what it's doing and where it's doing it on your disk and on which computer. It's safe too, because it doesn't overwrite or delete anything that is uncommitted. It backs it up first instead! Read more below for how that works.

Here's the process this script uses (ie: what it's actually doing)

From PC1: It checks to see if any uncommitted changes are on PC1. If so, it commits them to a temporary commit on the current branch. It then force pushes them to a remote SYNC branch. Then it uncommits its temporary commit it just did on the local branch, then it puts the local git repo back to exactly how it was by staging any files that were previously staged at the time you called the script. Next, it rsyncs a copy of the script over to PC2, and does an ssh call to tell PC2 to run the script with a special option to just do PC2 stuff.

Here's what PC2 does: it cds into the repo, and checks to see if any local uncommitted changes exist. If so, it creates a new backup branch forked off of the current branch (sample name: my_branch_SYNC_BAK_20200220-0028hrs-15sec <-- notice that's YYYYMMDD-HHMMhrs--SSsec), and commits any uncommitted changes to that branch with a commit message such as DO BACKUP OF ALL UNCOMMITTED CHANGES ON PC2 (TARGET PC/BUILD MACHINE). Now, it checks out the SYNC branch, pulling it from the remote repository if it is not already on the local machine. Then, it fetches the latest changes on the remote repository, and does a hard reset to force the local SYNC repository to match the remote SYNC repository. You might call this a "hard pull". It is safe, however, because we already backed up any uncommitted changes we had locally on PC2, so nothing is lost!

That's it! You now have produced a perfect copy from PC1 to PC2 without even having to ensure clean working directories, as the script handled all of the automatic committing and stuff for you! It is fast and works very well on huge repositories. Now you have an easy mechanism to use any IDE of your choice on one machine while building or testing on another machine, easily, over a wifi hot spot from your cell phone if needed, even if the repository is dozens of gigabytes and you are time and resource-constrained.

Resources:

The whole project: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles

See tons more links and references in the source code itself within this project.

How to do a "hard pull", as I call it: How do I force "git pull" to overwrite local files?

Related:

git repository sync between computers, when moving around?


问:
How can I get the UTC-converted Java timestamp of current local time?
Could somebody please help with getting UTC-converted Java timestamp of current local time?
The main goal is to get current date and time, convert into UTC Timestamp and then store in Ignite cache as a Timestamp yyyy-MM-dd hh:mm:ss[.nnnnnnnnn].

My attempt was Timestamp.from(Instant.now()). However, it still considers my local timezone +03:00. I am getting '2020-02-20 10:57:56' as a result instead of desirable '2020-02-20 07:57:56'.

How can I get UTC-converted Timestamp?

答:
You can do it like this :</p>

```<code>LocalDateTime localDateTime = Instant.now().atOffset(ZoneOffset.UTC).toLocalDateTime();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    System.out.println(localDateTime.format(formatter));
</code>```

Body:
You can do it like this :

LocalDateTime localDateTime = Instant.now().atOffset(ZoneOffset.UTC).toLocalDateTime();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    System.out.println(localDateTime.format(formatter));


问:
Creating Excel or CSV reports from Oracle Database with Python
I want to connect Oracle Db via python and take query results data and create excel or csv reports by using these data. I never tried before and did not see anyone who did something like this around me, do you have any recommendations or ideas for that case?

Regards

答:
You can connect Oracle db with python cx_Oracle library using syntax below for connection string. You should be aware that your connection_oracle_textfile.txt file and your .py file which had your python code must be in the samefolder for start.

connection_oracle_textfile.txt -> username/password@HOST:PORT/SERVICE_NAME(you can find all of them but username and password in tnsnames.ora file)

```<code>import cx_Oracle as cx_Oracle
import pandas as pd

def get_oracle_table_from_dbm(sql_text):
    if 'connection_oracle' not in  globals():
        print('connection does not exist. Try to connect it...')
        f = open('connection_oracle_textfile.txt', "r")
        fx = f.read()
     ####
     global connection_oracle
     connection_oracle = cx_Oracle.connect(fx)
     ####
     print('connection established!!')

     print('Already have connection. Just fetch data!!')
     return pd.read_sql(sql_text, con=connection_oracle)

 df=get_oracle_table_from_dbm('select * from dual')
</code>```

Body:
You can connect Oracle db with python cx_Oracle library using syntax below for connection string. You should be aware that your connection_oracle_textfile.txt file and your .py file which had your python code must be in the samefolder for start.

connection_oracle_textfile.txt -> username/password@HOST:PORT/SERVICE_NAME(you can find all of them but username and password in tnsnames.ora file)

import cx_Oracle as cx_Oracle
import pandas as pd

def get_oracle_table_from_dbm(sql_text):
    if 'connection_oracle' not in  globals():
        print('connection does not exist. Try to connect it...')
        f = open('connection_oracle_textfile.txt', "r")
        fx = f.read()
     ####
     global connection_oracle
     connection_oracle = cx_Oracle.connect(fx)
     ####
     print('connection established!!')

     print('Already have connection. Just fetch data!!')
     return pd.read_sql(sql_text, con=connection_oracle)

 df=get_oracle_table_from_dbm('select * from dual')


问:
code does not work in Dialogflow fulfillment
I have some code which I tested and it works in my environment, I changed agent.add(value) with console.log(value), and the result is printed. However, when I try it in dialogflow fulfillment, it does not run the response and the body is always undefined. </p>

<p>Does anyone has any idea what can make the code not run in Dialogflow Fulfillment. Thanks. </p>

```<code> function SearchKnowwledgeBaseMethod(intention){
    var username = "something";
    var password = "something";
    var auth = "Basic " + Buffer.from(username + ":" + password).toString('base64');
    var result;
    return new Promise(function(resolve, reject){
      rq(
        {
          url : `https://xxxxxx/api/now/table/kb_knowledge?sysparm_query=textCONTAINS${intention}`,
          headers : {
            "Authorization" : auth
          }
        },
        function (error, response, body) {
          if (!error && response.statusCode == 200) {
            if (typeof body !== undefined) {
              const obj = JSON.parse(body);
              if (obj.result.length > 0){
                result = obj.result[0].text;
              }
            }
          }else {
            reject("I have a problem");
          }
          resolve(result);
        });
    });
  }

  function SearchKnowledgeBase(agent){
    var intention = agent.parameters.intention;
        return SearchKnowwledgeBaseMethod(intention).then(function(result){
            if (result !== undefined){
                console.log(result);
                return agent.add(result);
            } else {
                var stringArray = intention.split(' ');
                stringArray.forEach(function (item) {
                    return SearchKnowwledgeBaseMethod(item).then(function(answer){
                        console.log(answer);
                        return console.log(answer);
                    });
                });
            }
        });
    }

  let intentMap = new Map();
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('search_knowledge_base', SearchKnowledgeBase);
  // intentMap.set('your intent name here', yourFunctionHandler);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
</code>```

答:
I found the answer to the question, which is very simple. The reason is that I am using the free version of Firebase so it does not allow calling external API, when I switch to Pay as you go plan then the API request works fine.
credit to this video on Youtube: https://www.youtube.com/watch?v=n4IPOeFCDxI&t=591s</p>

Body:
I have some code which I tested and it works in my environment, I changed agent.add(value) with console.log(value), and the result is printed. However, when I try it in dialogflow fulfillment, it does not run the response and the body is always undefined.

Does anyone has any idea what can make the code not run in Dialogflow Fulfillment. Thanks.

 function SearchKnowwledgeBaseMethod(intention){
    var username = "something";
    var password = "something";
    var auth = "Basic " + Buffer.from(username + ":" + password).toString('base64');
    var result;
    return new Promise(function(resolve, reject){
      rq(
        {
          url : `https://xxxxxx/api/now/table/kb_knowledge?sysparm_query=textCONTAINS${intention}`,
          headers : {
            "Authorization" : auth
          }
        },
        function (error, response, body) {
          if (!error && response.statusCode == 200) {
            if (typeof body !== undefined) {
              const obj = JSON.parse(body);
              if (obj.result.length > 0){
                result = obj.result[0].text;
              }
            }
          }else {
            reject("I have a problem");
          }
          resolve(result);
        });
    });
  }

  function SearchKnowledgeBase(agent){
    var intention = agent.parameters.intention;
        return SearchKnowwledgeBaseMethod(intention).then(function(result){
            if (result !== undefined){
                console.log(result);
                return agent.add(result);
            } else {
                var stringArray = intention.split(' ');
                stringArray.forEach(function (item) {
                    return SearchKnowwledgeBaseMethod(item).then(function(answer){
                        console.log(answer);
                        return console.log(answer);
                    });
                });
            }
        });
    }

  let intentMap = new Map();
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('search_knowledge_base', SearchKnowledgeBase);
  // intentMap.set('your intent name here', yourFunctionHandler);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);


问:
Can't get innerHTML of tag on IE8
I am trying to get the innerhtml of class name current_page_item[0]... And this is working  fine in FF and even in IE9 also. But in IE 8 it seems to be some javascript error in line" var classelem=document.getElementsByClassName('current_page_item')[0].innerHTML;.

I tried to put alert after the above line. But it is not displaying the message "Hello again".

Any idea how to solve the browser issue for this? Is it something that document.getElementsByClassName wont work in IE8?

```<code><html>
<head>
<script type="text/javascript">
function updatesidebar()
{
alert("Hello");
var classelem=document.getElementsByClassName('current_page_item')[0].innerHTML;

alert("Hello again");

}
</script>

</head>
<body>
<div id="main">

<div class="menu_main">

                      <ul class='mainmenu' id='root'>
<li><a href="/home" class="">Home</a></li>
<li><a href="/solutions" class="">Solutions</a>
</li><li><a href="/services" class="">Services</a></li>
<li><a href="/about-us" class="current_page_item">About Us</a></li>
<li><a href="/news" class="">News and Events</a></li>
<li><a href="/careers" class="">Careers</a></li>
<li><a href="/contact-us" class="">Contact Us</a></li>
</ul>

                </div>

</div>
<script type="text/javascript">
window.onload=updatesidebar();
</script>

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

答:
Not all browsers natively support getElementsByClassName although the situation is improving. You could use a function which checks for the native implementation and uses it if found or else grabs all the elements and checks each one for the classname, returning an array of those that match.

```<code>function getElementsByClassName( className, context ) {
    //the context is the container we will confine our search to (optional)
    context = context || document;
    //use native implimentation if it exists
    if( context.getElementsByClassName ) {
        return context.getElementsByClassName( className ); //returns a nodeList
    }
    //we have to do it ourselves if we get here
    var candidates = context.getElementsByTagName( '*' );
    var found = [];
    //regular expression to match the classname as per comments
    var rxp = new RegExp( "(?:^|\\s)" + className + "(?:\\s|$)");
    for( var i = 0, l = candidates.length; i < l; i++ ) {
        if( rxp.test( className ) {
            found.push( candidates[i] );
        }
    }
    return found; //returns an array of nodes
}
</code>```

Title: Can't get innerHTML of tag on IE8

Body:
I am trying to get the innerhtml of class name current_page_item[0]... And this is working  fine in FF and even in IE9 also. But in IE 8 it seems to be some javascript error in line" var classelem=document.getElementsByClassName('current_page_item')[0].innerHTML;.

I tried to put alert after the above line. But it is not displaying the message "Hello again".

Any idea how to solve the browser issue for this? Is it something that document.getElementsByClassName wont work in IE8?

Home

Solutions

Services

About Us

News and Events

Careers

Contact Us

Body:
Not all browsers natively support getElementsByClassName although the situation is improving. You could use a function which checks for the native implementation and uses it if found or else grabs all the elements and checks each one for the classname, returning an array of those that match.

function getElementsByClassName( className, context ) {
    //the context is the container we will confine our search to (optional)
    context = context || document;
    //use native implimentation if it exists
    if( context.getElementsByClassName ) {
        return context.getElementsByClassName( className ); //returns a nodeList
    }
    //we have to do it ourselves if we get here
    var candidates = context.getElementsByTagName( '*' );
    var found = [];
    //regular expression to match the classname as per comments
    var rxp = new RegExp( "(?:^|\\s)" + className + "(?:\\s|$)");
    for( var i = 0, l = candidates.length; i < l; i++ ) {
        if( rxp.test( className ) {
            found.push( candidates[i] );
        }
    }
    return found; //returns an array of nodes
}


问:
Cryptography error in Django run on Docker
I'm trying to deploy a web site which has a backend developed in Django. I've set two Docker containers which contain a Django instance and a MySQL instance. I've set also a network between containers in order to create a communication. The problem is that when I start the MySQL container with the parameter MYSQL_ROOT_PASSWORD Django gives me the error below:

return Database.connect(**conn_params)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
app    |     return Connection(*args, **kwargs)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__
app    |     self.connect()
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 599, in connect
app    |     self._request_authentication()
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 882, in _request_authentication
app    |     auth_packet = _auth.caching_sha2_password_auth(self, auth_packet)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/_auth.py", line 264, in caching_sha2_password_auth
app    |     data = sha2_rsa_encrypt(conn.password, conn.salt, conn.server_public_key)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/_auth.py", line 142, in sha2_rsa_encrypt
app    |     raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password")
app    | RuntimeError: cryptography is required for sha256_password or caching_sha2_password
```

<p>I've checked that the 3306 port is available on my PC, and yes it is.
On the other hand, if I start MySQL container with MYSQL_ALLOW_EMPTY_PASSWORD, and set a blank password in settings.py, it works.</p>

<p>Here there is my settings.py</p>

<pre class="lang-python prettyprint-override"><code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname',
        'USER': 'username',
        'PASSWORD': 'userpwd',
        'HOST': 'db',
        'PORT': '3306'
    }
}
</code>```

Instead, this is my docker-compose.yml file

version: "3"
services:
  app:
    build:
      context: .
    container_name: app
    ports:
      - "8000:8000"
    networks:
      - backend_split
    depends_on:
      - db
    restart: always
    volumes:
      - ./app:/app
    command:
      sh -c "python manage.py runserver 0.0.0.0:8000"
  db:
    image: mysql
    container_name: db
    expose:
      - "3306"
    networks:
      - backend_split
    environment:
      - MYSQL_ROOT_PASSWORD=rootpwd
      - MYSQL_DATABASE=databasename
      - MYSQL_USER=username
      - MYSQL_PASSWORD=userpwd

networks:
  backend_split:
```

I've been stuck with this error for days.

Thank you in advance.

答:
You can solve it by installing this dependency:

$ pip install django-cryptographic-fields

Add then add "cryptographic_fields" to your INSTALLED_APPS setting like this:

```<code>INSTALLED_APPS = (
...
'cryptographic_fields',
)
</code>```

Body:
I'm trying to deploy a web site which has a backend developed in Django. I've set two Docker containers which contain a Django instance and a MySQL instance. I've set also a network between containers in order to create a communication. The problem is that when I start the MySQL container with the parameter MYSQL_ROOT_PASSWORD Django gives me the error below:

return Database.connect(**conn_params)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
app    |     return Connection(*args, **kwargs)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__
app    |     self.connect()
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 599, in connect
app    |     self._request_authentication()
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 882, in _request_authentication
app    |     auth_packet = _auth.caching_sha2_password_auth(self, auth_packet)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/_auth.py", line 264, in caching_sha2_password_auth
app    |     data = sha2_rsa_encrypt(conn.password, conn.salt, conn.server_public_key)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/_auth.py", line 142, in sha2_rsa_encrypt
app    |     raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password")
app    | RuntimeError: cryptography is required for sha256_password or caching_sha2_password

I've checked that the 3306 port is available on my PC, and yes it is.
On the other hand, if I start MySQL container with MYSQL_ALLOW_EMPTY_PASSWORD, and set a blank password in settings.py, it works.

Here there is my settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname',
        'USER': 'username',
        'PASSWORD': 'userpwd',
        'HOST': 'db',
        'PORT': '3306'
    }
}

Instead, this is my docker-compose.yml file

version: "3"
services:
  app:
    build:
      context: .
    container_name: app
    ports:
      - "8000:8000"
    networks:
      - backend_split
    depends_on:
      - db
    restart: always
    volumes:
      - ./app:/app
    command:
      sh -c "python manage.py runserver 0.0.0.0:8000"
  db:
    image: mysql
    container_name: db
    expose:
      - "3306"
    networks:
      - backend_split
    environment:
      - MYSQL_ROOT_PASSWORD=rootpwd
      - MYSQL_DATABASE=databasename
      - MYSQL_USER=username
      - MYSQL_PASSWORD=userpwd

networks:
  backend_split:

I've been stuck with this error for days.

Thank you in advance.

Body:
You can solve it by installing this dependency:

$ pip install django-cryptographic-fields

Add then add "cryptographic_fields" to your INSTALLED_APPS setting like this:

INSTALLED_APPS = (
...
'cryptographic_fields',
)


问:
How to create user and loging mongodb database on docker via docker-compose?
I have a running mongodb on docker. I created user on it but I couldn't login with user credentials from docker-compose.

Here is my configurations:

Create user:

```<code>use database
db.createUser({user: "username", pwd: "password", roles: [{role: "readWrite", db: "database"}]});
</code>```

docker-compose.yml

```<code>mongo:
  container_name: container
  image: mongo:latest
  env_file: .env
  entrypoint:
    MONGO_INITDB_ROOT_USERNAME: ${MONGODB_AUTH_USER}
    MONGO_INITDB_ROOT_PASSWORD: ${MONGODB_AUTH_PASS}
</code>```

But I am getting below error when trying to run docker-compose up command:

```<code>ERROR: for 177f1a769910_smartcap-mongodb  Cannot start service mongo: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"MONGO_INITDB_ROOT_USERNAME:username\": executable file not found in $PATH": unknown
</code>```

How can I solve this problem? Could you help me?

答:
Change entrypoint to environment, like so:

```<code>mongo:
  container_name: container
  image: mongo:latest
  environment:
    MONGO_INITDB_ROOT_USERNAME: ${MONGODB_AUTH_USER}
    MONGO_INITDB_ROOT_PASSWORD: ${MONGODB_AUTH_PASS}
</code>```

Body:
I have a running mongodb on docker. I created user on it but I couldn't login with user credentials from docker-compose.

Here is my configurations:

Create user:

use database
db.createUser({user: "username", pwd: "password", roles: [{role: "readWrite", db: "database"}]});

docker-compose.yml

mongo:
  container_name: container
  image: mongo:latest
  env_file: .env
  entrypoint:
    MONGO_INITDB_ROOT_USERNAME: ${MONGODB_AUTH_USER}
    MONGO_INITDB_ROOT_PASSWORD: ${MONGODB_AUTH_PASS}

But I am getting below error when trying to run docker-compose up command:

ERROR: for 177f1a769910_smartcap-mongodb  Cannot start service mongo: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"MONGO_INITDB_ROOT_USERNAME:username\": executable file not found in $PATH": unknown

How can I solve this problem? Could you help me?

Body:
Change entrypoint to environment, like so:

mongo:
  container_name: container
  image: mongo:latest
  environment:
    MONGO_INITDB_ROOT_USERNAME: ${MONGODB_AUTH_USER}
    MONGO_INITDB_ROOT_PASSWORD: ${MONGODB_AUTH_PASS}


问:
antd cascader's default value if not working if set it in useEffect
it works if hard code it like :

  <Cascader
        defaultValue={["County"]}
        className="custom_select"
        expandTrigger="hover"
        options={options_3}
        onChange={onChange}
        placeholder="Please select"
        changeOnSelect
        disabled={true}
      />
```

<p>but if I use setDefaultValue() in useEffect, it is not working :</p>

<pre class="lang-js prettyprint-override"><code>
  const [defaultValue, setDefaultValue] = useState([]);

  useEffect(()=>{
    setDefaultValue(['Global'])
  },[defaultValue[0]])

</code>```

online demo
it's a bug or I use it in a wrong way?

答:
The defaultValue prop in AntD is used only on first render, since useEffect runs after first render, you end up without a default value for the cascader. Setting it afterwards does not have any effect. If you want to use defaultValue, you can make sure that when cascader renders, you will already have set the default value.

```<code>const [defaultVal, setDefaultVal] = useState();
useEffect(() => {
  setDefaultVal(['zhejiang', 'hangzhou', 'xihu']);
}, []);
return (
  <div>
      {defaultVal && (
        <Cascader
          defaultValue={defaultVal}
          options={options}
          onChange={onChange}
        />
      )}
  </div>
)
</code>```

You can also use a controlled component with value if you want the cascader rendered at all times.

Codesandbox

Body:
it works if hard code it like :

  <Cascader
        defaultValue={["County"]}
        className="custom_select"
        expandTrigger="hover"
        options={options_3}
        onChange={onChange}
        placeholder="Please select"
        changeOnSelect
        disabled={true}
      />

but if I use setDefaultValue() in useEffect, it is not working :

  const [defaultValue, setDefaultValue] = useState([]);

  useEffect(()=>{
    setDefaultValue(['Global'])
  },[defaultValue[0]])

online demo
it's a bug or I use it in a wrong way?

Body:
The defaultValue prop in AntD is used only on first render, since useEffect runs after first render, you end up without a default value for the cascader. Setting it afterwards does not have any effect. If you want to use defaultValue, you can make sure that when cascader renders, you will already have set the default value.

const [defaultVal, setDefaultVal] = useState();
useEffect(() => {
  setDefaultVal(['zhejiang', 'hangzhou', 'xihu']);
}, []);
return (
  <div>
      {defaultVal && (
        <Cascader
          defaultValue={defaultVal}
          options={options}
          onChange={onChange}
        />
      )}
  </div>
)

You can also use a controlled component with value if you want the cascader rendered at all times.

Codesandbox


问:
How to set up Yarn on OpenServer?
My problem described in the title.

But in addition, I have set in the next directiory C:\OpenServer\modules\yarn Yarn and I don't know what to do next.

I hope for your help because I didn't find anything on Google or in the net.

答:
I found it! Yeh!

We need to change in settings on the 'server' tab one option and create a file that will say which programs OpenServer must get and prefetch.

Title: How to set up Yarn on OpenServer?


问:
How to generate aws cloudfront url through Spring Rest api?
My requirement is that, I want to upload a file into AWS S3 bucket through Spring REST api. This api should first generate a Cloudfront url and upload the file using the url generated and finally in the response I should get the complete filepath : cloudfront-url/filename.
Please let me know the steps and configuration required to achieve this.

Thank you.

答:
If the server uploads the file from client to s3, it will create unnecessary overhead on the server.  Better approach is the return pre-signed URL to client (browser) and it directly uploads to S3.

See details on how to do it here.

If that bucket is configured for cloudfront then the cloudfront url can be used directly.

See details here for setting up cloudfront for s3.


问:
USE (NLP) GATE TOOL FOR NAMED-ENTITY
Can I use GATE http://gate.ac.uk/ within my java program to extract named-entity. If yes, could you give any examples or guide me to some sources. Thank you </p>

答:
Your question is really two questions: how to use GATE to find named entities and maybe how to embed GATE into your application.

Named entity recognition or classification is a huge field of research and depending on what named entities you want to find, different approaches may be most effective. GATE provides a very basic gazetteer list and rule based approach for finding some categories of named entities in English text: ANNIE.
If the categories found by ANNIE are those interesting to you, one way to start might be to understand and improve what is already provided by ANNIE.
The ANNIE pipeline will create annotations for Person, Organization etc in your document and you only need to use or write a PR that accesses those annotations and does whatever you need with the features or the text of those annotations.
Look at the GATE manual http://gate.ac.uk/sale/tao/split.html it explains ANNIE and also has some documentation on how to embed GATE (how to use GATE directly from your Java program without running the GUI).

Title: USE (NLP) GATE TOOL FOR NAMED-ENTITY


问:
C++ LinkedList problems. Conflict between datatypes? No matching Constructor?
so I'm writing a program that receives string input from user and performs some basic operations on that such as getlength, get index, append to another string and test if it sub match. Most of my code is base on my professor's sample code, I just write extra methods to performs the operations that I listed earlier. However, I receives the error from LinkedChar.h and Node.h that I repeatedly made but couldn't find solutions. I will note the big ERRORS! word in the comment section in my code.

```<code>    #include <iomanip>
    #include "LinkedChar.h"

    // Function prototype
    bool isCreated(const LinkedChar<char>* charPtr);
    LinkedChar<char> toLinkedChar(const string &items);

    /************************************************************************
    *                                 main                                  *
    ************************************************************************/
    int main()
    {
        bool done = false; // A finish flag
        int choice; // Menu choice

        cout << " This program solves an ADT character string.  \n";

        LinkedChar<char>* charPtr = nullptr;
        string firstString;
        char aChar;

        while (!done)
        {
            // Display the menu and get the user's choice
            cout << "=========================================================\n"
                << "Operations\n\n";
            cout << setw(5) << "1. New the first string\n";
            cout << setw(5) << "2. Get the length from the first string\n";
            cout << setw(5) << "3. Find index of character in the first string\n";
            cout << setw(5) << "4. Append another string to the first string\n";
            cout << setw(5) << "5. Test if another string is submatch of the first string\n";
            cout << setw(5) << "6. Quit\n"
                <<"=========================================================\n\n";
            cout << "Enter your Choice (1-6): ";
            cin >> choice;
            cin.ignore();

            // Validate and process the menu choice
            if (choice == 1)
            {
                cout << "Please enter a string: ";
                getline(cin, firstString);

                charPtr = new LinkedChar<char>(firstString);
                cout << "The first string has been created. \n\n";
            }
            else if (choice == 6)
            {
                // Set the program is finished
                done = true;
            }
            else if (choice > 1 && choice < 6)
            {
                if (isCreated(charPtr))
                    // Execute the correct set of actions
                    switch (choice)
                    {
                        case 2:
                            cout << "The length of the first string \"" <<  charPtr->toString() << "\" is " << charPtr->length() << ".\n\n";
                            break;
                        case 3:
                            cout << "Please enter a character to find: ";
                            cin >> aChar;
                            cout << "The index of \"" << aChar << "\" is " << charPtr->index(aChar) << "\n\n";
                            break;
                        case 4:
                            cout << "Please enter another string to append: ";
                            getline(cin, firstString);
                            charPtr->append(toLinkedChar(firstString));
                            cout << "The string changes to \"" << charPtr->toString() << "\".\n\n";

                            break;
                        case 5:
                            cout << "Please enter another string to test: ";
                            getline(cin, firstString);
                            cout << "The string \"" << firstString << "\" is ";
                            if (!charPtr->submatch(toLinkedChar(firstString)))
                                cout << "not ";
                            cout << "submatch of the first string \"" << charPtr->toString() << "\".\n\n";
                            break;
                    }
            }
            else
            {
                cout << "The valid choices are 1 through 6.\n\n";
            }
        }

        return 0;
    }

    bool isCreated(const LinkedChar<char>* charPtr)
    {
        if (charPtr == nullptr)
        {
            std::cout << "Please choose 1 to create the first string before start!\n\n";
            return false;
        }
        else
        {
            return true;
        }
    }

    LinkedChar<char> toLinkedChar(const string &items)
    {
        return LinkedChar<char>(items);
    }
</code>```

Node.h

```<code>        #ifndef NODE_H
        #define NODE_H

        template<class ItemType>
        class Node
        {
        private:
            ItemType item;
            Node<ItemType>* next; // Pointer to next node

        public:
            Node() {
                next = nullptr;
            }
            Node(const ItemType& anItem)
            {
                //  ----------- ERRORS ------------//
                item(anItem);    //Called object type 'char' is not a function or function
                                 //pointer
                next(nullptr);   //Called object type 'Node<char> *' is not a function or
                                //function pointer

                                  /*This copy constructor is also exposed an error that I
                                 could not understand. I think that I declare the item as a
                                 template so later I could determine that datatype for item is
                                either string or char*/
                 // --------------------------------//
            }
            Node(const ItemType& anItem, Node<ItemType>* nextNodePtr)
            {
                item(anItem);
                next(nextNodePtr);
            }

            void setItem(const ItemType& anItem)
            {
                item = anItem;
            }
            void setNext(Node<ItemType>* nextNodePtr)
            {
                next = nextNodePtr;
            }

            ItemType getItem()  const {
                return item;
            }
            Node<ItemType>* getNext() const {
                return next;
            }
        }; // end Node
        #endif
</code>```

LinkedChar.h

```<code>        // Created by
        //
        #ifndef LINKEDCHAR_H
        #define LINKEDCHAR_H

        #include <iostream>
        #include <string>
        #include "Node.h"

        using namespace std;

        template<class ItemType>
        class LinkedChar
        {
        private:
            Node<ItemType>* headPtr;
            int itemCount;
        public:
            LinkedChar() {
                headPtr = nullptr;
                itemCount = 0;
            }
            LinkedChar(string items) {

                itemCount = int(items.size());

                headPtr = nullptr;

                for (int i = itemCount - 1; i >= 0; i--)
                {
                    if (headPtr == nullptr)
                    {
                        // Copy first node
                        headPtr = new Node<ItemType>();
                        headPtr->setItem(items[i]);
                    } else {
                        // Create a new node containing the next item
                        Node<ItemType>* newNodePtr = new Node<ItemType>(items[i]);
                        newNodePtr->setNext(headPtr);  // New node points to chain

                        headPtr = newNodePtr;          // New node is now first node
                    }
                }
            }
            virtual ~LinkedChar() {
                clear();
            }

            int length() {
                return itemCount;
            }
            int index(const ItemType& anItem) const {
                int index = 0;
                Node<ItemType>* curPtr = headPtr;

                while (curPtr != nullptr)
                {
                    if (anItem == curPtr->getItem())
                    {
                        return index;

                    } // end if
                    index++;
                    curPtr = curPtr->getNext();
                }
                return -1;
            }; // -1 if no match
            void append(const LinkedChar& lc) {
                  // -------------- ERRORS ------------------ //

                itemCount += lc.length(); // This is when I got the error guys, it says
                                          // " 'this' argument to member function 'length' has
                                          //type 'const LinkedChar<char>', but function is not
                                           marked const "
                 // ------------------------------------------//
                Node<ItemType>* newChainPtr = headPtr;
                while (newChainPtr != nullptr && newChainPtr->getNext() != nullptr)
                {
                    newChainPtr = newChainPtr->getNext();
                }

                Node<ItemType>* origChainPtr = lc.headPtr;
                while (origChainPtr != nullptr)
                {
                    // Get next item from original chain
                    ItemType nextItem = origChainPtr->getItem();

                    // Create a new node containing the next item

                   // ---------------- ERRORS -------------------- //

                    Node<ItemType>* newNodePtr = new Node<ItemType>(nextItem);
                                               ^^
                                               ||
                                               ||
                   // ERROR: The Error of no matching constructor for initialization of Node<Char>
                   //This happens to me alot previously, my solution is just put new Node(' ')
                   //But in this case seem inappropriate
                   // ---------------------------------------------  //

                    // Link new node to end of new chain
                    newChainPtr->setNext(newNodePtr);

                    // Advance pointer to new last node
                    newChainPtr = newChainPtr->getNext();

                    // Advance original-chain pointer
                    origChainPtr = origChainPtr->getNext();
                }
                newChainPtr->setNext(nullptr);
            }
            bool submatch(const LinkedChar& lc) const {
                bool found = false;
                Node<ItemType>* curPtr = headPtr;
                Node<ItemType>* origChainPtr = lc.headPtr;

                ItemType anItem;

                while (origChainPtr != nullptr && curPtr != nullptr)
                {
                    anItem = origChainPtr->getItem();

                    while (curPtr != nullptr)
                    {
                        if (anItem == curPtr->getItem())
                        {
                            found = true;
                            curPtr = curPtr->getNext();
                            break;
                        }
                        else if (found)
                        {
                            found = false;
                            break;
                        }

                        curPtr = curPtr->getNext();
                    }
                    if (!found)
                        origChainPtr = lc.headPtr;
                    else
                        origChainPtr = origChainPtr->getNext();
                }

                return found && (origChainPtr == nullptr);
            }

            void clear() {
                Node<ItemType>* curPtr = headPtr;
                while (headPtr != nullptr)
                {
                    headPtr = headPtr->getNext();

                    // Return node to the system
                    curPtr->setNext(nullptr);
                    delete curPtr;

                    curPtr = headPtr;
                }

                itemCount = 0;
            }

            string toString() const {
                std::string aString;
                Node<ItemType>* curPtr = headPtr;

                while ((curPtr != nullptr))
                {
                    aString += (curPtr->getItem());
                    curPtr = curPtr->getNext();
                }

                return aString;
            }
        };

        //#include "LinkedChar.cpp"
        #endif //LINKEDCHAR_H
</code>```

答:
You're getting overwhelmed by error messages. You should take each one in turn, starting with the first. Understand what it's telling you. Fix it, recompile to make sure. And move on to the next one.

For starters:

Make length() const

```<code>int length() const {
</code>```

Change

```<code>next(nullptr);
</code>```

to

```<code>setNext(nullptr);
</code>```

Change

```<code>item(anItem);
</code>```

to

```<code>setItem(anItem);
</code>```

Body:
so I'm writing a program that receives string input from user and performs some basic operations on that such as getlength, get index, append to another string and test if it sub match. Most of my code is base on my professor's sample code, I just write extra methods to performs the operations that I listed earlier. However, I receives the error from LinkedChar.h and Node.h that I repeatedly made but couldn't find solutions. I will note the big ERRORS! word in the comment section in my code.

    #include <iomanip>
    #include "LinkedChar.h"

    // Function prototype
    bool isCreated(const LinkedChar<char>* charPtr);
    LinkedChar<char> toLinkedChar(const string &items);

    /************************************************************************
    *                                 main                                  *
    ************************************************************************/
    int main()
    {
        bool done = false; // A finish flag
        int choice; // Menu choice

        cout << " This program solves an ADT character string.  \n";

        LinkedChar<char>* charPtr = nullptr;
        string firstString;
        char aChar;

        while (!done)
        {
            // Display the menu and get the user's choice
            cout << "=========================================================\n"
                << "Operations\n\n";
            cout << setw(5) << "1. New the first string\n";
            cout << setw(5) << "2. Get the length from the first string\n";
            cout << setw(5) << "3. Find index of character in the first string\n";
            cout << setw(5) << "4. Append another string to the first string\n";
            cout << setw(5) << "5. Test if another string is submatch of the first string\n";
            cout << setw(5) << "6. Quit\n"
                <<"=========================================================\n\n";
            cout << "Enter your Choice (1-6): ";
            cin >> choice;
            cin.ignore();

            // Validate and process the menu choice
            if (choice == 1)
            {
                cout << "Please enter a string: ";
                getline(cin, firstString);

                charPtr = new LinkedChar<char>(firstString);
                cout << "The first string has been created. \n\n";
            }
            else if (choice == 6)
            {
                // Set the program is finished
                done = true;
            }
            else if (choice > 1 && choice < 6)
            {
                if (isCreated(charPtr))
                    // Execute the correct set of actions
                    switch (choice)
                    {
                        case 2:
                            cout << "The length of the first string \"" <<  charPtr->toString() << "\" is " << charPtr->length() << ".\n\n";
                            break;
                        case 3:
                            cout << "Please enter a character to find: ";
                            cin >> aChar;
                            cout << "The index of \"" << aChar << "\" is " << charPtr->index(aChar) << "\n\n";
                            break;
                        case 4:
                            cout << "Please enter another string to append: ";
                            getline(cin, firstString);
                            charPtr->append(toLinkedChar(firstString));
                            cout << "The string changes to \"" << charPtr->toString() << "\".\n\n";

                            break;
                        case 5:
                            cout << "Please enter another string to test: ";
                            getline(cin, firstString);
                            cout << "The string \"" << firstString << "\" is ";
                            if (!charPtr->submatch(toLinkedChar(firstString)))
                                cout << "not ";
                            cout << "submatch of the first string \"" << charPtr->toString() << "\".\n\n";
                            break;
                    }
            }
            else
            {
                cout << "The valid choices are 1 through 6.\n\n";
            }
        }

        return 0;
    }

    bool isCreated(const LinkedChar<char>* charPtr)
    {
        if (charPtr == nullptr)
        {
            std::cout << "Please choose 1 to create the first string before start!\n\n";
            return false;
        }
        else
        {
            return true;
        }
    }

    LinkedChar<char> toLinkedChar(const string &items)
    {
        return LinkedChar<char>(items);
    }

Node.h

        #ifndef NODE_H
        #define NODE_H

        template<class ItemType>
        class Node
        {
        private:
            ItemType item;
            Node<ItemType>* next; // Pointer to next node

        public:
            Node() {
                next = nullptr;
            }
            Node(const ItemType& anItem)
            {
                //  ----------- ERRORS ------------//
                item(anItem);    //Called object type 'char' is not a function or function
                                 //pointer
                next(nullptr);   //Called object type 'Node<char> *' is not a function or
                                //function pointer

                                  /*This copy constructor is also exposed an error that I
                                 could not understand. I think that I declare the item as a
                                 template so later I could determine that datatype for item is
                                either string or char*/
                 // --------------------------------//
            }
            Node(const ItemType& anItem, Node<ItemType>* nextNodePtr)
            {
                item(anItem);
                next(nextNodePtr);
            }

            void setItem(const ItemType& anItem)
            {
                item = anItem;
            }
            void setNext(Node<ItemType>* nextNodePtr)
            {
                next = nextNodePtr;
            }

            ItemType getItem()  const {
                return item;
            }
            Node<ItemType>* getNext() const {
                return next;
            }
        }; // end Node
        #endif

LinkedChar.h

        // Created by
        //
        #ifndef LINKEDCHAR_H
        #define LINKEDCHAR_H

        #include <iostream>
        #include <string>
        #include "Node.h"

        using namespace std;

        template<class ItemType>
        class LinkedChar
        {
        private:
            Node<ItemType>* headPtr;
            int itemCount;
        public:
            LinkedChar() {
                headPtr = nullptr;
                itemCount = 0;
            }
            LinkedChar(string items) {

                itemCount = int(items.size());

                headPtr = nullptr;

                for (int i = itemCount - 1; i >= 0; i--)
                {
                    if (headPtr == nullptr)
                    {
                        // Copy first node
                        headPtr = new Node<ItemType>();
                        headPtr->setItem(items[i]);
                    } else {
                        // Create a new node containing the next item
                        Node<ItemType>* newNodePtr = new Node<ItemType>(items[i]);
                        newNodePtr->setNext(headPtr);  // New node points to chain

                        headPtr = newNodePtr;          // New node is now first node
                    }
                }
            }
            virtual ~LinkedChar() {
                clear();
            }

            int length() {
                return itemCount;
            }
            int index(const ItemType& anItem) const {
                int index = 0;
                Node<ItemType>* curPtr = headPtr;

                while (curPtr != nullptr)
                {
                    if (anItem == curPtr->getItem())
                    {
                        return index;

                    } // end if
                    index++;
                    curPtr = curPtr->getNext();
                }
                return -1;
            }; // -1 if no match
            void append(const LinkedChar& lc) {
                  // -------------- ERRORS ------------------ //

                itemCount += lc.length(); // This is when I got the error guys, it says
                                          // " 'this' argument to member function 'length' has
                                          //type 'const LinkedChar<char>', but function is not
                                           marked const "
                 // ------------------------------------------//
                Node<ItemType>* newChainPtr = headPtr;
                while (newChainPtr != nullptr && newChainPtr->getNext() != nullptr)
                {
                    newChainPtr = newChainPtr->getNext();
                }

                Node<ItemType>* origChainPtr = lc.headPtr;
                while (origChainPtr != nullptr)
                {
                    // Get next item from original chain
                    ItemType nextItem = origChainPtr->getItem();

                    // Create a new node containing the next item

                   // ---------------- ERRORS -------------------- //

                    Node<ItemType>* newNodePtr = new Node<ItemType>(nextItem);
                                               ^^
                                               ||
                                               ||
                   // ERROR: The Error of no matching constructor for initialization of Node<Char>
                   //This happens to me alot previously, my solution is just put new Node(' ')
                   //But in this case seem inappropriate
                   // ---------------------------------------------  //

                    // Link new node to end of new chain
                    newChainPtr->setNext(newNodePtr);

                    // Advance pointer to new last node
                    newChainPtr = newChainPtr->getNext();

                    // Advance original-chain pointer
                    origChainPtr = origChainPtr->getNext();
                }
                newChainPtr->setNext(nullptr);
            }
            bool submatch(const LinkedChar& lc) const {
                bool found = false;
                Node<ItemType>* curPtr = headPtr;
                Node<ItemType>* origChainPtr = lc.headPtr;

                ItemType anItem;

                while (origChainPtr != nullptr && curPtr != nullptr)
                {
                    anItem = origChainPtr->getItem();

                    while (curPtr != nullptr)
                    {
                        if (anItem == curPtr->getItem())
                        {
                            found = true;
                            curPtr = curPtr->getNext();
                            break;
                        }
                        else if (found)
                        {
                            found = false;
                            break;
                        }

                        curPtr = curPtr->getNext();
                    }
                    if (!found)
                        origChainPtr = lc.headPtr;
                    else
                        origChainPtr = origChainPtr->getNext();
                }

                return found && (origChainPtr == nullptr);
            }

            void clear() {
                Node<ItemType>* curPtr = headPtr;
                while (headPtr != nullptr)
                {
                    headPtr = headPtr->getNext();

                    // Return node to the system
                    curPtr->setNext(nullptr);
                    delete curPtr;

                    curPtr = headPtr;
                }

                itemCount = 0;
            }

            string toString() const {
                std::string aString;
                Node<ItemType>* curPtr = headPtr;

                while ((curPtr != nullptr))
                {
                    aString += (curPtr->getItem());
                    curPtr = curPtr->getNext();
                }

                return aString;
            }
        };

        //#include "LinkedChar.cpp"
        #endif //LINKEDCHAR_H

Body:
You're getting overwhelmed by error messages. You should take each one in turn, starting with the first. Understand what it's telling you. Fix it, recompile to make sure. And move on to the next one.

For starters:

Make length() const

int length() const {

Change

next(nullptr);

to

setNext(nullptr);

Change

item(anItem);

to

setItem(anItem);


问:
How to automatically log into another site if CSRF-Token is required (PHP, SSO, LDAP)
I'm trying to create an intranet site where, if possible, all parts of it should be SSO in a way that a user who is logged into his Active Directory account in Windows would immediately be signed on with that same account in all pages of my site through LDAP.
Now the main component of this site is built with a CMS and from there the user should be able to click the links on this site to get to the other tools we're using, like for example the ticket system.
The CMS and the ticket-system software both are able to connect through LDAP themselves but I want a SSO solution for this.

So I searched and found this for the apache server: mod_authnz_sspi
This apparently lets you use $_SERVER['REMOTE_USER'] in PHP to get the windows user signed on right now.
Now I'm stuck since I'm not really sure how to use this to automatically log the user into the sites.
What do I have to do with this to get the SSO solution that I want?

I thought about creating a simple HTML form with the same fields like the one from the ticket-system form I'm trying to log into. I would then try to send the POST-data to the form of the ticket-system and log the user in automatically. For the username I would send $_SERVER['PHP_AUTH_USER'] and for the password $_SERVER['PHP_AUTH_PW']. However, the ticket system is protected with a CSRF-Token which I would have to include into the sent POST-data but can't know in advance since it is generated in the moment of accessing the page.

So it would be really helpful if someone could tell me how to get a SSO working with the mod_authnz_sspi tool (or another).
If there isn't any other way than through using a HTML-form that sends the POST data like I tried, then it would be helpful if someone knew a workaround to the CSRF-Token problem!

答: You can create an AUTH application that administrate your users (details, permissions, etc.). When an user access other application if it are not logged in redirect it to the AUTH application. AUTH application check user credentials, generate an access_token and redirect user back to the application that try to access. More info you find here https://www.mutuallyhuman.com/blog/choosing-an-sso-strategy-saml-vs-oauth2/</p>


问:
Creating dynamic angular 8 components and html element and rearranging them
I have the following problem. I have an array with angular 8 component names and html elements. Currently it is creating the angular 8 components and the html elements but does not arrange them like they are sorted in the array.
This is my code:

```<code>for (var i = 0; i < res.length; i++) {
            var val = res[i];
            if (val.value.Type) {
                //Getting the factory for the component
                const factories = Array.from(this.resolver['_factories'].keys());
                const factoryClass = <Type<any>>factories.find((x: any) => x.name === val.editor.alias);

                const factory = this.resolver.resolveComponentFactory(factoryClass);
                //Creating the component
                this.Container.createComponent(factory);
            } else {
                this.$Element.append(val.value);
            }
}
</code>```

My DOM looks the following

The angular components always get inserted directly after the .content div. I already tried using Container.insert but it does not work either.

答:
To add your dynamic created component to the DOM you can use JQuery:

```<code>const factory = this.resolver.resolveComponentFactory(factoryClass);
//Creating the component
var component = factory.create(this.Container.parentInjector);
//Appending the component node to the register element
this.Container.insert(component.hostView);
this.$RootElement.parent().append(component.hostView["rootNodes"][0]);
</code>```

This will create the element and insert the html tags with JQuery

Body:
I have the following problem. I have an array with angular 8 component names and html elements. Currently it is creating the angular 8 components and the html elements but does not arrange them like they are sorted in the array.
This is my code:

for (var i = 0; i < res.length; i++) {
            var val = res[i];
            if (val.value.Type) {
                //Getting the factory for the component
                const factories = Array.from(this.resolver['_factories'].keys());
                const factoryClass = <Type<any>>factories.find((x: any) => x.name === val.editor.alias);

                const factory = this.resolver.resolveComponentFactory(factoryClass);
                //Creating the component
                this.Container.createComponent(factory);
            } else {
                this.$Element.append(val.value);
            }
}

My DOM looks the following

The angular components always get inserted directly after the .content div. I already tried using Container.insert but it does not work either.

Body:
To add your dynamic created component to the DOM you can use JQuery:

const factory = this.resolver.resolveComponentFactory(factoryClass);
//Creating the component
var component = factory.create(this.Container.parentInjector);
//Appending the component node to the register element
this.Container.insert(component.hostView);
this.$RootElement.parent().append(component.hostView["rootNodes"][0]);

This will create the element and insert the html tags with JQuery


问:
How to dump or search in call stacks of ALL threads in Visual Studio
How to dump or search in call stacks of ALL threads in Visual Studio? We have a server process to debug and it has hundreds of threads running, so it should be hard to manually check each threads.

I know "thread apply" in gdb can do this kind of things. So I was wondering is there anything similar available in visual studio's debugger.

Also I was using visual studio 2005, so please give a solution for VS 2005 ( search in all call stack is provided in VS 2010...).

答:
I just had the same problem, also in VS2005. I found a simpler solution:
While debugging open the command window of VS and use the command:
Debug.ListCallStack /AllThreads

I found this on:
https://web.archive.org/web/20150627064016/http://blogs.msdn.com/b/greggm/archive/2005/08/02/446899.aspx