问:
React useState not triggering re-render of child component
I cant seem to figure out why my MovieDetailCard component will not re-render when the movie state changes. I am passing in the movie object. When I update the state the log outputs correctly in the useEffect but the MovieDetailsCard never receives the updated object.

```<code>    const MovieDetails = () => {
    const [movie, setMovie] = useState({});
    const { id } = useParams();
    const { poster } = useParams();

  useEffect(() => {
    const fetchMovie = async () => {
      const response = await fetch(
        `http://www.randyconnolly.com/funwebdev/3rd/api/movie/movies.php?id=${id}`
      );

      const data = await response.json();

      setMovie({ ...data });
    };

    fetchMovie();
  }, []);

  useEffect(() => {
    console.log(movie); // this successfully outputs when movie updates
  }, [movie]);

  return (
    <div className="row">
      <div className="col s12 m6">
        <MovieDetailsCard poster={poster} movie={movie} /> // this does not update
      </div>
      <div className="col s12 m6">
        <CastCrewCard />
      </div>
    </div>
  );
};
</code>```

Below is the MovieDeatailsCard. In the useEffect the console.log(movie) always returns null.

```<code>const MovieDetailsCard = ({ poster, movie }) => {
  useEffect(() => {
    console.log("in details");

    console.log(movie);
  }, []);
  return (
    <div className="card">
      <div className="card-content">
        <div className="row">
          <div className="col s6">
            <span className="card-title">Movie Title</span>
          </div>
          <div className="col s6 favouriteButton">
            <FavouriteButton className="waves-effect waves-light btn">
              <i className="material-icons">favorite</i>
            </FavouriteButton>
          </div>
        </div>

        <div className="row">
          <div className="col s12 m6">
            <img src={`https://image.tmdb.org/t/p/w342/${poster}.jpg`} alt="" />
          </div>
          <div className="col s12 m6">
            <p>{movie.title}</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MovieDetailsCard;
</code>```

答: Thanks guys for the input. This seems to be resolved now. before I was setting data by setData(data) but when I changed to setData({...data}) that worked!</p>

Body:
I cant seem to figure out why my MovieDetailCard component will not re-render when the movie state changes. I am passing in the movie object. When I update the state the log outputs correctly in the useEffect but the MovieDetailsCard never receives the updated object.

    const MovieDetails = () => {
    const [movie, setMovie] = useState({});
    const { id } = useParams();
    const { poster } = useParams();

  useEffect(() => {
    const fetchMovie = async () => {
      const response = await fetch(
        `http://www.randyconnolly.com/funwebdev/3rd/api/movie/movies.php?id=${id}`
      );

      const data = await response.json();

      setMovie({ ...data });
    };

    fetchMovie();
  }, []);

  useEffect(() => {
    console.log(movie); // this successfully outputs when movie updates
  }, [movie]);

  return (

        <MovieDetailsCard poster={poster} movie={movie} /> // this does not update

        <CastCrewCard />

  );
};

Below is the MovieDeatailsCard. In the useEffect the console.log(movie) always returns null.

const MovieDetailsCard = ({ poster, movie }) => {
  useEffect(() => {
    console.log("in details");

    console.log(movie);
  }, []);
  return (

            Movie Title

            <FavouriteButton className="waves-effect waves-light btn">
              favorite
            </FavouriteButton>

            <img src={`https://image.tmdb.org/t/p/w342/${poster}.jpg`} alt="" />

{movie.title}

  );
};

export default MovieDetailsCard;


来源: stackexchange

问:
CORS "SyntaxError: Unexpected end of input at" with fetch API vs PHP
```<code>/*
* @version: 1.0.0
* @author: Murod Parmonov
* @licence: MIT
*/

class HTTP{

    // post request
    post(url, data){
        return new Promise((resolve, reject) => {
                fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-type': 'application/json'
                    },
                    body: JSON.stringify(data),
                    'mode': 'no-cors'
                }).
                **then(response => response.json()).then(data => resolve(data)).
                catch(err => reject(err));**
            }
        );
    }

}

const ht = new HTTP;  // http  fetch API class
ht.post('https://correctserverurl.com/', data).then(resData => console.log(resData))    .catch(err => console.log(err));
</code>```

error I got from the server
the noted with double stars line in js code is the line error.

```<code><?php
header('Access-Control-Allow-Origin: correctdomain.com');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers:  X-Requested-With");

$ping = file_get_contents("php://input");
file_put_contents('ping.json', $ping);
$ping = json_decode($ping, 1);
echo json_encode($data = [
    'status' => 'success'
]);
</code>```

I included whole class of fetch API even I think it is unneccessary.
I think I provide every detail needed.
I ensured that the code works on others server but only on my server something is wrong.
what am I doing wrong here?
what should I do to solve the problem?

答:
header('Access-Control-Allow-Headers: X-PINGOTHER, Content-Type');
actually, this was worth to do a little bit research.
the magic line helped me to solve the the same problem.

ContentLicense: CC BY-SA 4.0

Body:
/*
* @version: 1.0.0
* @author: Murod Parmonov
* @licence: MIT
*/

class HTTP{

    // post request
    post(url, data){
        return new Promise((resolve, reject) => {
                fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-type': 'application/json'
                    },
                    body: JSON.stringify(data),
                    'mode': 'no-cors'
                }).
                **then(response => response.json()).then(data => resolve(data)).
                catch(err => reject(err));**
            }
        );
    }

}

const ht = new HTTP;  // http  fetch API class
ht.post('https://correctserverurl.com/', data).then(resData => console.log(resData))    .catch(err => console.log(err));

error I got from the server
the noted with double stars line in js code is the line error.

<?php
header('Access-Control-Allow-Origin: correctdomain.com');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers:  X-Requested-With");

$ping = file_get_contents("php://input");
file_put_contents('ping.json', $ping);
$ping = json_decode($ping, 1);
echo json_encode($data = [
    'status' => 'success'
]);

I included whole class of fetch API even I think it is unneccessary.
I think I provide every detail needed.
I ensured that the code works on others server but only on my server something is wrong.
what am I doing wrong here?
what should I do to solve the problem?


问:
Java - Parse Yaml to Json
Python and Ruby have very nice libraries for parsing a Yaml file into a JSON object.

The parser needs to support Yaml Anchor and References.

Input

```<code>info: &info
  legs: 4 legs
  type: pet
dog: *info
cat: *info
</code>```

Desired output:

```<code>{
  "info": {
    "legs": "4 legs",
    "type": "pet"
  },
  "dog": {
    "legs": "4 legs",
    "type": "pet"
  },
  "cat": {
    "legs": "4 legs",
    "type": "pet"
  }
}

</code>```

I first tried the Jackson YAMLFactory.  That library did not generically support anchors and references.

What is a good solution in Java for parsing Yaml into a JSON object?

答:
The following solution seemed to work.

```<code>import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.yaml.snakeyaml.Yaml;

public class YamlParser {

     public static void main(String[] argv) {
        File f = new File("my.yml");
        final Yaml yaml = new Yaml();

        try {
            final Object loadedYaml = yaml.load(new FileReader(f));
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(loadedYaml,LinkedHashMap.class);

            System.out.println(json);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

</code>```

With the following maven dependencies.

```<code>        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.21</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>

</code>```

Title: Java - Parse Yaml to Json

Body:
Python and Ruby have very nice libraries for parsing a Yaml file into a JSON object.

The parser needs to support Yaml Anchor and References.

Input

info: &info
  legs: 4 legs
  type: pet
dog: *info
cat: *info

Desired output:

{
  "info": {
    "legs": "4 legs",
    "type": "pet"
  },
  "dog": {
    "legs": "4 legs",
    "type": "pet"
  },
  "cat": {
    "legs": "4 legs",
    "type": "pet"
  }
}

I first tried the Jackson YAMLFactory.  That library did not generically support anchors and references.

What is a good solution in Java for parsing Yaml into a JSON object?

Body:
The following solution seemed to work.

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.yaml.snakeyaml.Yaml;

public class YamlParser {

     public static void main(String[] argv) {
        File f = new File("my.yml");
        final Yaml yaml = new Yaml();

        try {
            final Object loadedYaml = yaml.load(new FileReader(f));
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(loadedYaml,LinkedHashMap.class);

            System.out.println(json);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

With the following maven dependencies.

        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.21</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>


问:
Errors when running tests in parallel
Multiple issues arise when I try to run tests in parallel.

According to the docs, "test_" is prepended to the database name specified in DATABASES. I used the name "postgres", so the database created when running tests is called test_postgres. When running tests in parallel, the following databases are created (which is expected): test_postgres_1, test_postgres_2, test_postgres_3, and test_postgres_4. When running all tests with the --parallel=4 option, however, every test fails with the following message: django.db.utils.OperationalError: FATAL:  database "postgres_x" does not exist where x can be 1, 2, 3 or 4. I can see that the following databases have been created: test_postgres_x where x can be 1, 2, 3 or 4. Where's "postgres_x" coming from? Why isn't "test_" being prepended to these?

Furthermore, if I manually create the expected databases postgres_x (x = 1 to 4), the migrations applied to the "main" database aren't applied to the clones. This results in errors like this: django.db.utils.ProgrammingError: relation "users_user" does not exist. Roughly 1/4 tests pass when using 4 cores.

Lastly, if I try to migrate postgres_x by using migrate --database=postgres_x, I get: django.db.utils.ConnectionDoesNotExist: The connection postgres_x doesn't exist.

I have ensured that all tests are isolated just so I can run them in parallel. What am I supposed to do?

答: Instead of building your test harness yourself I suggest using pytest and pytest-django and pytest-xdist this will handle the db creation and migration for each parallel worker. (pytest can run Django UnitTest tests without modification)

Title: Errors when running tests in parallel


问:
C++ omp no significant improvement
I am on MSVC 2019 with the default compiler. The code I am working on is a Mandelbrot image. Relevant bits of my code looks like:

```<code>#pragma omp parallel for
for (int y = 0; y < HEIGHT; y++)
    {
       for (int x = 0; x < WIDTH; x++)
           {
               unsigned int retVal = mandel(x_val + x_incr * x, y_val + y_incr * y);
               mtest.setPixels(x, y,
                        static_cast<unsigned char>(retVal / 6),
                        static_cast<unsigned char>(retVal / 5),
                        static_cast<unsigned char>(retVal / 4));

           }
     }
</code>```

All of the variables outside of the loop are constexpr, eliminating any dependencies. The mandel function does about 1000 iterations with each call. I would expect the outer loop to run on several threads but my msvc records each run at about 5-6 seconds with or without the omp directive.

Edit (The mandel function):

```<code>unsigned int mandel(long double x, long double y)
{
    long double z_x = 0;
    long double z_y = 0;

    for (int i = 0; i < ITER; i++)
    {
        long double temp = z_x;
        z_x = (z_x * z_x) - (z_y * z_y) + x;
        z_y = 2 * temp * z_y + y;

        if ((z_x * z_x + z_y * z_y) > 4)
            return i;
    }
    return ITER; //ITER is a #define macro
}
</code>```

答:
This is not an answer, but please do this:

```<code>unsigned int mandel(long double x, long double y)
{
    long double z_x = 0;
    long double z_y = 0;
    long double z_x_squared = 0;
    long double z_y_squared = 0;

    for (int i = 0; i < ITER; i++)
    {
        long double temp = z_x;
        z_x = z_x_squared - z_y_squared + x;
        z_y = 2 * temp * z_y + y;

        z_x_squared = z_x * z_x;
        z_y_squared = z_y * z_u;

        if ((z_x_squared + z_y_squared) > 4)
            return i;
    }
    return ITER; //ITER is a #define macro
}
</code>```

Also, try inverting the order of your two for loops.

Title: C++ omp no significant improvement

Body:
I am on MSVC 2019 with the default compiler. The code I am working on is a Mandelbrot image. Relevant bits of my code looks like:

#pragma omp parallel for
for (int y = 0; y < HEIGHT; y++)
    {
       for (int x = 0; x < WIDTH; x++)
           {
               unsigned int retVal = mandel(x_val + x_incr * x, y_val + y_incr * y);
               mtest.setPixels(x, y,
                        static_cast<unsigned char>(retVal / 6),
                        static_cast<unsigned char>(retVal / 5),
                        static_cast<unsigned char>(retVal / 4));

           }
     }

All of the variables outside of the loop are constexpr, eliminating any dependencies. The mandel function does about 1000 iterations with each call. I would expect the outer loop to run on several threads but my msvc records each run at about 5-6 seconds with or without the omp directive.

Edit (The mandel function):

unsigned int mandel(long double x, long double y)
{
    long double z_x = 0;
    long double z_y = 0;

    for (int i = 0; i < ITER; i++)
    {
        long double temp = z_x;
        z_x = (z_x * z_x) - (z_y * z_y) + x;
        z_y = 2 * temp * z_y + y;

        if ((z_x * z_x + z_y * z_y) > 4)
            return i;
    }
    return ITER; //ITER is a #define macro
}

Body:
This is not an answer, but please do this:

unsigned int mandel(long double x, long double y)
{
    long double z_x = 0;
    long double z_y = 0;
    long double z_x_squared = 0;
    long double z_y_squared = 0;

    for (int i = 0; i < ITER; i++)
    {
        long double temp = z_x;
        z_x = z_x_squared - z_y_squared + x;
        z_y = 2 * temp * z_y + y;

        z_x_squared = z_x * z_x;
        z_y_squared = z_y * z_u;

        if ((z_x_squared + z_y_squared) > 4)
            return i;
    }
    return ITER; //ITER is a #define macro
}

Also, try inverting the order of your two for loops.


问:
Is there a way to allow only the branch creator to push on it in Github?

I have a Github organization.

I created a repository and a team to work on it.

I want to restrict push to any branch to it's creator by the default.

So that no one can push to someone's else branch.

Is there any method to do that other than adding rule for every branch manually?

I tried to add rules manually, but it's time consuming cause there are many people joining the team.

Update:

I went to my organization -> teams.

Selected the team, went to members, selected a member.

Clicked on "manage access" next to one repository, clicked "edit".

Set "Base permissions" to "Write".

Set "Repository creation" to "Disabled".

Everything else is left unchecked.

答:
I won't comment on whether or not this is a good idea.
Suffice to say I was annoyed once leading me to create the following update hook to apply to the canonical repo (note however that Github does not allow custom update hooks so you're out of luck there):

```<code>#!/usr/bin/env python
import os
import re
import sys
from pathlib import Path
from subprocess import check_output

branch = sys.argv[1]
old_commit = sys.argv[2]
new_commit = sys.argv[3]
zero = "0000000000000000000000000000000000000000"
branch_pattern = 'feature/.+'

def get_author(commit):
    return str(check_output(['git', '--no-pager', 'show', '-s', "--format='%an'", commit]).strip(), 'utf-8')

def allow(message=None):
    if message:
        print(message)
    exit(0)

def deny(message=None):
    if message:
        print(message)
    exit(1)

# if this isn't a feature branch bail
if not re.match(branch_pattern, branch):
    allow()

# if the update is a delete bail
if new_commit == zero:
    allow("update: deleting branch '%s': OK" % branch)

# if this is the first commit on the branch bail
if old_commit == zero:
    allow("update: creating branch '%s': OK" % branch)

branch_log = Path('.git', 'logs', 'refs', 'heads').joinpath(*branch.split(os.path.sep))
with open(branch_log, 'r') as log:
    first_commit = log.readline(81).split(sep=' ', maxsplit=1)[1]

branch_author = get_author(first_commit)
new_commit_author = get_author(new_commit)

print("update: branch = '%s'; branch author = %s; commit author = %s" % (branch, branch_author, new_commit_author))

if new_commit_author == branch_author:
    allow("update: commit author == branch author: OK")
else:
    deny(
        "update: branch author != commit author: REJECTED\n"
        "update: create a branch for your changes from the tip of %s and request a pull instead"
        % branch
    )
</code>```

Body:
I won't comment on whether or not this is a good idea.
Suffice to say I was annoyed once leading me to create the following update hook to apply to the canonical repo (note however that Github does not allow custom update hooks so you're out of luck there):

#!/usr/bin/env python
import os
import re
import sys
from pathlib import Path
from subprocess import check_output

branch = sys.argv[1]
old_commit = sys.argv[2]
new_commit = sys.argv[3]
zero = "0000000000000000000000000000000000000000"
branch_pattern = 'feature/.+'

def get_author(commit):
    return str(check_output(['git', '--no-pager', 'show', '-s', "--format='%an'", commit]).strip(), 'utf-8')

def allow(message=None):
    if message:
        print(message)
    exit(0)

def deny(message=None):
    if message:
        print(message)
    exit(1)

# if this isn't a feature branch bail
if not re.match(branch_pattern, branch):
    allow()

# if the update is a delete bail
if new_commit == zero:
    allow("update: deleting branch '%s': OK" % branch)

# if this is the first commit on the branch bail
if old_commit == zero:
    allow("update: creating branch '%s': OK" % branch)

branch_log = Path('.git', 'logs', 'refs', 'heads').joinpath(*branch.split(os.path.sep))
with open(branch_log, 'r') as log:
    first_commit = log.readline(81).split(sep=' ', maxsplit=1)[1]

branch_author = get_author(first_commit)
new_commit_author = get_author(new_commit)

print("update: branch = '%s'; branch author = %s; commit author = %s" % (branch, branch_author, new_commit_author))

if new_commit_author == branch_author:
    allow("update: commit author == branch author: OK")
else:
    deny(
        "update: branch author != commit author: REJECTED\n"
        "update: create a branch for your changes from the tip of %s and request a pull instead"
        % branch
    )


问:
PHP Doctrine Query AND with either OR
A database has Products with many options, two of them are, say, Option 1 and Option 2. I need to make a query (I know how to build the whole thing, I'm just stuck with the following logic only) which will show only such products where:

If neither Option 1 nor Option 2 selected, show all products

If Options 1 selected, only show those products with this option

If Options 2 selected, only show those products with this option

If Options 1 and Option 2 selected, only show those products with these two options

I tried this:

```<code>function GetProducts(keywords) {
...
    ->andWhere($qb->expr()->orX(
        $qb->expr()->eq('option1', keywords['option1']),
        $qb->expr()->eq('option2', keywords['option2'])
    ))
...
}
</code>```

The keywords['option1'] and keywords['option2'] are values 0 or 1 from check boxes with such options.

But the result is the following:

If neither Option 1 nor Option 2 selected, all products are shown - OK

If Options 1 selected, products with Option 1 AND all those without any of these 2 options are shown - NOT what I need

If Options 2 selected, products with Option 1 AND all those without any of these 2 options are shown - NOT what I need

If Option 1 and Option 2 selected, all products are shown - NOT what I need

答:
```<code>public function getRandomSearch($keywords)
{
    $em = DatabaseORM::entityManager();
    $qb = $em->createQueryBuilder();
    $qb->select('c')
        ->from('Products\Product', 'c');

    if ($keywords['option1'] && !$keywords['option2']) {
        $qb->andWhere($qb->expr()->eq('c.option1', $keywords['option1']));
    }
    elseif (!$keywords['option1'] && $keywords['option2']) {
        $qb->andWhere($qb->expr()->eq('c.option2', $keywords['option2']));
    }
    elseif ($keywords['option1'] && $keywords['option2']) {
        $qb->andWhere($qb->expr()->orX(
            $qb->expr()->eq('c.option1', $keywords['option1']),
            $qb->expr()->eq('c.option2', $keywords['option2'])
        ));
    }

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

Title: PHP Doctrine Query AND with either OR

Body:
A database has Products with many options, two of them are, say, Option 1 and Option 2. I need to make a query (I know how to build the whole thing, I'm just stuck with the following logic only) which will show only such products where:

If neither Option 1 nor Option 2 selected, show all products

If Options 1 selected, only show those products with this option

If Options 2 selected, only show those products with this option

If Options 1 and Option 2 selected, only show those products with these two options

I tried this:

function GetProducts(keywords) {
...
    ->andWhere($qb->expr()->orX(
        $qb->expr()->eq('option1', keywords['option1']),
        $qb->expr()->eq('option2', keywords['option2'])
    ))
...
}

The keywords['option1'] and keywords['option2'] are values 0 or 1 from check boxes with such options.

But the result is the following:

If neither Option 1 nor Option 2 selected, all products are shown - OK

If Options 1 selected, products with Option 1 AND all those without any of these 2 options are shown - NOT what I need

If Options 2 selected, products with Option 1 AND all those without any of these 2 options are shown - NOT what I need

If Option 1 and Option 2 selected, all products are shown - NOT what I need


问:
Cannot call function from .kv file, interpreter claims class and method don't exist
When i run the file, the buttons show up. Everything looks fine, until i click button 1 for the method Main.c() to get called. the interpreter spits out an exception claiming i haven't defined it yet, when i have. I cannot find a solution anywhere.

the .py file:

```<code>import kivy
from kivy.app import App
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.lang.builder import Builder

kivy.require("1.11.1")

class Main:
    @staticmethod
    def c():
        print("c")

class Start(App):

    def setup(self):
        Builder.load_file('start.kv')

Start().run()
</code>```

the .kv file:

```<code>BoxLayout:
    Button:
        id: btn1
        text: "Button 1"
        on_press: Main.c()
    Button:
        text: "Button 2"
        on_press: print(8 * 8)
</code>```

答:
There are many problems with your code, but, one way to do what you ask for is to

Create an instance of your Main class in your App class: self.main = Main()

Call this instance from your kv code: on_press: app.main.c()

Body:
When i run the file, the buttons show up. Everything looks fine, until i click button 1 for the method Main.c() to get called. the interpreter spits out an exception claiming i haven't defined it yet, when i have. I cannot find a solution anywhere.

the .py file:

import kivy
from kivy.app import App
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.lang.builder import Builder

kivy.require("1.11.1")

class Main:
    @staticmethod
    def c():
        print("c")

class Start(App):

    def setup(self):
        Builder.load_file('start.kv')

Start().run()

the .kv file:

BoxLayout:
    Button:
        id: btn1
        text: "Button 1"
        on_press: Main.c()
    Button:
        text: "Button 2"
        on_press: print(8 * 8)


问:
SCNNode is not being anchored at real world coordinates
I have a simple SCNNode that I want to place in the real-world position, the node corresponds to a landmark with known coordinates. I want to keep the SCNNode still at its location, however it tends to move with the camera. I cannot use plane detection or a hit-test to place the node in the real-world, I can only use the real-world coordinates. My current solution creates an ARanchor using the SCNNodes world transform.

```<code>showNode(node: Node, location: convertedPoint)
let anchor = ARAnchor(transform: Node.simdWorldTransform)
self.sceneView.session.add(anchor: anchor)
</code>```

I thought this would be enough to anchor the node. Is there a solution to anchor the node without using plane detection or a hit-test?

Thanks

答:
First, even if you stabilize your node with an anchor, it's never going to be perfect, just better.

However, while an ARAnchor is being created at the coordinates you are telling it, but the node you want to be stabilized is not actually being placed within that anchor.

You need to implement the renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) function in your ARSCNViewDelegate and return the target node you want to be stabilized by the anchor (Alternatively, you can add your node as a childNode of the default created anchor node by implementing the renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) function).

If your nodeToBeStabilized object is available as property within the ViewController, then a very dumb implementation might be something like this:

```<code>extension WAViewController: ARSCNViewDelegate, ARSessionDelegate {
    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        return nodeToBeStabilized
    }
}
</code>```

Body:
I have a simple SCNNode that I want to place in the real-world position, the node corresponds to a landmark with known coordinates. I want to keep the SCNNode still at its location, however it tends to move with the camera. I cannot use plane detection or a hit-test to place the node in the real-world, I can only use the real-world coordinates. My current solution creates an ARanchor using the SCNNodes world transform.

showNode(node: Node, location: convertedPoint)
let anchor = ARAnchor(transform: Node.simdWorldTransform)
self.sceneView.session.add(anchor: anchor)

I thought this would be enough to anchor the node. Is there a solution to anchor the node without using plane detection or a hit-test?

Thanks

Body:
First, even if you stabilize your node with an anchor, it's never going to be perfect, just better.

However, while an ARAnchor is being created at the coordinates you are telling it, but the node you want to be stabilized is not actually being placed within that anchor.

You need to implement the renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) function in your ARSCNViewDelegate and return the target node you want to be stabilized by the anchor (Alternatively, you can add your node as a childNode of the default created anchor node by implementing the renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) function).

If your nodeToBeStabilized object is available as property within the ViewController, then a very dumb implementation might be something like this:

extension WAViewController: ARSCNViewDelegate, ARSessionDelegate {
    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        return nodeToBeStabilized
    }
}


问:
Passing value from dialog form to main form

Possible Duplicate:

  How do you pass an object from form1 to form2 and back to form1?

I'm used to passing variables between windows forms by simply passing them as a parameter.
Now I have a form that is already open (let's call it FormMain), and another form that should act like a dialog (FormTask). The user cannot interact with the main form until he has filled in the information on FormTask. FormTask simply contains a single textbox, and the value of this textbox should be returned to FormMain, and kept track of as a variable. FormTask requires a parameter exerciseType. When FormTask opens it checks the value of this parameter and sets the default value of the textbox accordingly. This already works, I'm just kind of clueless on how to return my string value to the already open MainForm.
These dialogs only seem to be able to return DialogResults, which isn't what I'm after. I'm not too experienced either, and I'd rather avoid fumbling around to make my own custom dialog.

FormMain:

```<code>FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoker.ShowDialog();
</code>```

FormTask:

```<code>private void button1_Click(object sender, EventArgs e)
{
    string opgave = textBoxOpgave.Text;
    // return string value to MainForm here
}
</code>```

答:
The simplest way to do this is to add a public property to your form class to return the string.

```<code>public string opgave
{
    get;
    private set;
}
</code>```

Assign to this property as your dialog closes and then read the property from the code that called ShowDialog():

```<code>private void button1_Click(object sender, EventArgs e)
{
    opgave = textBoxOpgave.Text;
}

...

FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoker.ShowDialog();
DoSomething(formTask.opgave);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  How do you pass an object from form1 to form2 and back to form1?

I'm used to passing variables between windows forms by simply passing them as a parameter.
Now I have a form that is already open (let's call it FormMain), and another form that should act like a dialog (FormTask). The user cannot interact with the main form until he has filled in the information on FormTask. FormTask simply contains a single textbox, and the value of this textbox should be returned to FormMain, and kept track of as a variable. FormTask requires a parameter exerciseType. When FormTask opens it checks the value of this parameter and sets the default value of the textbox accordingly. This already works, I'm just kind of clueless on how to return my string value to the already open MainForm.
These dialogs only seem to be able to return DialogResults, which isn't what I'm after. I'm not too experienced either, and I'd rather avoid fumbling around to make my own custom dialog.

FormMain:

FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoker.ShowDialog();

FormTask:

private void button1_Click(object sender, EventArgs e)
{
    string opgave = textBoxOpgave.Text;
    // return string value to MainForm here
}

Body:
The simplest way to do this is to add a public property to your form class to return the string.

public string opgave
{
    get;
    private set;
}

Assign to this property as your dialog closes and then read the property from the code that called ShowDialog():

private void button1_Click(object sender, EventArgs e)
{
    opgave = textBoxOpgave.Text;
}

...

FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoker.ShowDialog();
DoSomething(formTask.opgave);


问:
how to properly initialize firebase app that can be used more than once?
usually I initialize firebase in my activity just like this

```<code>class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // usually initializing firebase just like this
        FirebaseApp.initializeApp(this)

}
</code>```

but now I need that firebaseApp to be passed to get FirebaseStorage instance like this:

```<code>    // set firebase option
    val optionBuilder = FirebaseOptions.Builder()
    optionBuilder.setStorageBucket("newBucket")
    val firebaseOption = optionBuilder.build()

    // initialize firebase app
    val app = FirebaseApp.initializeApp(this,firebaseOption)

    // create reference, pass app to firebase storage
    val storageRef = FirebaseStorage.getInstance(app).reference.child("profilePicture")
</code>```

but the problem is.....

I need to create that firebase storage reference in more than one place. so how how to properly initialize firebase app so that I can use it in more than one place ?

do I need to initialize it in MainActivity AND recreate it again whenever I need to make storage reference ? it seems like a bad idea, but I don't know .... please help :)

答: Just initialize it once and store it in a place where they can all access it - a singleton.</p>

Body:
usually I initialize firebase in my activity just like this

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // usually initializing firebase just like this
        FirebaseApp.initializeApp(this)

}

but now I need that firebaseApp to be passed to get FirebaseStorage instance like this:

    // set firebase option
    val optionBuilder = FirebaseOptions.Builder()
    optionBuilder.setStorageBucket("newBucket")
    val firebaseOption = optionBuilder.build()

    // initialize firebase app
    val app = FirebaseApp.initializeApp(this,firebaseOption)

    // create reference, pass app to firebase storage
    val storageRef = FirebaseStorage.getInstance(app).reference.child("profilePicture")

but the problem is.....

I need to create that firebase storage reference in more than one place. so how how to properly initialize firebase app so that I can use it in more than one place ?

do I need to initialize it in MainActivity AND recreate it again whenever I need to make storage reference ? it seems like a bad idea, but I don't know .... please help :)


问:
Recursion function to count how many times a certain sequence appears
I am writing a recursive function that takes an integer as input and it will return the number of times 123 appears in the integer.

So for example:

print(onetwothree(123123999123))

Will print out 3 because the sequence 123 appears 3 times in the number I entered into the function.

Here is my code so far:

```<code>def onetwothree(x):
    count = 0
    while(x > 0):
        x = x//10
        count = count + 1
    if (count < 3):  #here i check if the digits is less than 3, it can't have the sequence 123 if it doesn't have 3 digits
        return 0
    if (x%10==1 and x//10%10 == 2 and x//10//10%10==3):
        counter += 1
    else:
        return(onetwothree(x//10))
</code>```

This keeps printing "0".

答:
If you want to count how many times '123' occurs in a number, why not convert your number from an integer to a string and use str.count?

Then your function would look like this:

```<code>def onetwothree(x):
    return str(x).count('123')
</code>```

But it would also not be recursive anymore.

You could also just use the line print(str(123123999123).count('123')) which is pretty much the same as using it with the onetwothree function.

I hope this answer helps :)

Body:
I am writing a recursive function that takes an integer as input and it will return the number of times 123 appears in the integer.

So for example:

print(onetwothree(123123999123))

Will print out 3 because the sequence 123 appears 3 times in the number I entered into the function.

Here is my code so far:

def onetwothree(x):
    count = 0
    while(x > 0):
        x = x//10
        count = count + 1
    if (count < 3):  #here i check if the digits is less than 3, it can't have the sequence 123 if it doesn't have 3 digits
        return 0
    if (x%10==1 and x//10%10 == 2 and x//10//10%10==3):
        counter += 1
    else:
        return(onetwothree(x//10))

This keeps printing "0".

Body:
If you want to count how many times '123' occurs in a number, why not convert your number from an integer to a string and use str.count?

Then your function would look like this:

def onetwothree(x):
    return str(x).count('123')

But it would also not be recursive anymore.

You could also just use the line print(str(123123999123).count('123')) which is pretty much the same as using it with the onetwothree function.

I hope this answer helps :)


问:
Can't open design view on Visual Studio 2019 C# Windows Form Application
I've seen this problem on google a few times and I've seen people solve it, but whatever solution I saw and tried didn't work. I saw things like

putting the "public partial class Form1 : Form" first, or pressing F7, or using the View tab to-go-to designer and etc, none has worked. I did manage to look at another file code Form1 Designer, but it was a code as well, different than the form's code but still code, and when I run it it shows a blank page meaning that code does work, I just can't visualize it. Can anyone help me, please?

Appreciate all the help :)

答:
To check the target framework of your project, you can follow Project -> Properties... Application. And then you can see the target in the page.

If the target is .Net Framework, you can follow the steps provided by Flydog57.

If it is a Windows Forms App(.Net Core), there is no Designer by default.

The .NET Core Windows Forms designer is available with the Visual Studio 16.5 Preview 1. So you can try to update Visual Studio to Visual Studio 16.5 Preview 1 or a later version.

For more details, you can refer to this blog.

Updates to .NET Core Windows Forms designer in Visual Studio 16.5 Preview 1


问:
Using async instead of Task.Run()
I have the following piece of code:

private void btnAction_Click(object sender, RoutedEventArgs e)
{

    /** Clear the results field */
    txtResult.Text = "";

    /** Disable the button and show waiting status */
    btnAction.IsEnabled = false;
    lblStatus.Text = "Wait...";

    /** Get input from the query field */
    string input = query.Text;

    /** Run a new task */
    Task.Run(() => {

        // calling a method that takes a long time (>3s) to finish and return
        var attempt = someLibrary.doSomethingWith(input);

        // return the result to the GUI thred
        this.Dispatcher.Invoke(() =>
        {

            if (attempt.ContainsKey("success"))
            {
                if (attempt["success"] == true)
                {
                    txtResult.Text = "Success! The door is: " + (attempt["is_open"] ? "open" : "closed");
                    lblStatus.Text = "";
                }
                else
                {
                    lblStatus.Text = "Error! The service says: " + attempt["errorMessage"];
                }
            }

            else
            {
                MessageBox.Show("There was a problem getting results from web service.");
                lblStatus.Text = "";
            }

            /** Re-enable the button */
            btnAction.IsEnabled = true;

        });
    });

}
```

Now, I would like to:

Write the same code in a way that uses a callback instead of using Dispatcher.Invoke().

Be able to cancel a running task that calls doSomething()

Be able to chain multiple calls, i.e. await doSomething() and after it finished, doAnotherThing() with the results from the previous call

Hence why I want to write this using the async model.

What do I do?

答:
You would mark your method as async,  await the Task.Run so the continuations run on the UI, also leaving only the long running (seemingly CPU bound) job within it

```<code>private async void btnAction_Click(object sender, RoutedEventArgs e)
{
   btnAction.IsEnabled = false;
   txtResult.Text = "";
   lblStatus.Text = "Wait...";

   string input = query.Text;

   // calling a method that takes a long time (>3s) to finish and return
   var attempt =  await Task.Run(() => someLibrary.doSomethingWith(input));

   if (attempt.ContainsKey("success"))
   {
      if (attempt["success"] == true)
      {
         txtResult.Text = "Success! The door is: " + (attempt["is_open"] ? "open" : "closed");
         lblStatus.Text = "";
      }
      else
      {
         lblStatus.Text = "Error! The service says: " + attempt["errorMessage"];
      }
   }
   else
   {
      MessageBox.Show("There was a problem getting results from web service.");
      lblStatus.Text = "";
   }

   btnAction.IsEnabled = true;

}
</code>```

Update

To cancel the task, you would use a CancellationToken from am instance of CancellationTokenSource and pass that into Task.Run and also your long running method to check for IsCancellationRequested (if you can). You cancel by calling CancellationTokenSource.Cancel

Note you would likely want to wrap this in a try catch finally and catch on OperationCanceledException and place your button enabling code in the finally

Title: Using async instead of Task.Run()

Body:
I have the following piece of code:

private void btnAction_Click(object sender, RoutedEventArgs e)
{

    /** Clear the results field */
    txtResult.Text = "";

    /** Disable the button and show waiting status */
    btnAction.IsEnabled = false;
    lblStatus.Text = "Wait...";

    /** Get input from the query field */
    string input = query.Text;

    /** Run a new task */
    Task.Run(() => {

        // calling a method that takes a long time (>3s) to finish and return
        var attempt = someLibrary.doSomethingWith(input);

        // return the result to the GUI thred
        this.Dispatcher.Invoke(() =>
        {

            if (attempt.ContainsKey("success"))
            {
                if (attempt["success"] == true)
                {
                    txtResult.Text = "Success! The door is: " + (attempt["is_open"] ? "open" : "closed");
                    lblStatus.Text = "";
                }
                else
                {
                    lblStatus.Text = "Error! The service says: " + attempt["errorMessage"];
                }
            }

            else
            {
                MessageBox.Show("There was a problem getting results from web service.");
                lblStatus.Text = "";
            }

            /** Re-enable the button */
            btnAction.IsEnabled = true;

        });
    });

}

Now, I would like to:

Write the same code in a way that uses a callback instead of using Dispatcher.Invoke().

Be able to cancel a running task that calls doSomething()

Be able to chain multiple calls, i.e. await doSomething() and after it finished, doAnotherThing() with the results from the previous call

Hence why I want to write this using the async model.

What do I do?

Body:
You would mark your method as async,  await the Task.Run so the continuations run on the UI, also leaving only the long running (seemingly CPU bound) job within it

private async void btnAction_Click(object sender, RoutedEventArgs e)
{
   btnAction.IsEnabled = false;
   txtResult.Text = "";
   lblStatus.Text = "Wait...";

   string input = query.Text;

   // calling a method that takes a long time (>3s) to finish and return
   var attempt =  await Task.Run(() => someLibrary.doSomethingWith(input));

   if (attempt.ContainsKey("success"))
   {
      if (attempt["success"] == true)
      {
         txtResult.Text = "Success! The door is: " + (attempt["is_open"] ? "open" : "closed");
         lblStatus.Text = "";
      }
      else
      {
         lblStatus.Text = "Error! The service says: " + attempt["errorMessage"];
      }
   }
   else
   {
      MessageBox.Show("There was a problem getting results from web service.");
      lblStatus.Text = "";
   }

   btnAction.IsEnabled = true;

}

Update

To cancel the task, you would use a CancellationToken from am instance of CancellationTokenSource and pass that into Task.Run and also your long running method to check for IsCancellationRequested (if you can). You cancel by calling CancellationTokenSource.Cancel

Note you would likely want to wrap this in a try catch finally and catch on OperationCanceledException and place your button enabling code in the finally


问:
CodeMirror - PHP Mode Not Working?
For some reason its not displaying the text to be highlighted or anything, not sure why.

Links:

```<code><link rel=stylesheet href="http://codemirror.net/mode/php/../../doc/docs.css">
<link rel="stylesheet" href="http://codemirror.net/mode/php/../../lib/codemirror.css">
<script src="http://codemirror.net/mode/php/../../lib/codemirror.js"></script>
<script src="http://codemirror.net/mode/php/../../addon/edit/matchbrackets.js"></script>
<script src="http://codemirror.net/mode/php/../htmlmixed/htmlmixed.js"></script>
<script src="http://codemirror.net/mode/php/../xml/xml.js"></script>
<script src="http://codemirror.net/mode/php/../javascript/javascript.js"></script>
<script src="http://codemirror.net/mode/php/../css/css.js"></script>
<script src="http://codemirror.net/mode/php/../clike/clike.js"></script>
<script src="http://codemirror.net/mode/php/php.js"></script>
</code>```

CSS:

```<code>  .CodeMirror { height: 400px; width: 500px; border-radius:6px; padding-top:3px; border: 1px solid #ddd; }
  .CodeMirror-scroll { max-height: 400px; width:500px; }
  .CodeMirror pre { display:inline-block; padding-left: 7px; line-height: 1.25; }
</code>```

Script:

```<code>  <script>
    var editor = CodeMirror.fromTextArea(document.getElementById("demotext"), {
        lineNumbers: true,
        matchBrackets: true,
        mode: "text/x-php",
        indentUnit: 4,
        indentWithTabs: true,
        enterMode: "keep",
        tabMode: "shift"
    });
  </script>
</code>```

Its displaying weirdly and not working D:

Need more information? Let me know!

答:
```<code>codemirror/mode/clike/clike.js
</code>```

make sure you include this js in order for the syntax highlighting to works

Title: CodeMirror - PHP Mode Not Working?

Body:
For some reason its not displaying the text to be highlighted or anything, not sure why.

Links:

<link rel=stylesheet href="http://codemirror.net/mode/php/../../doc/docs.css">
<link rel="stylesheet" href="http://codemirror.net/mode/php/../../lib/codemirror.css">

CSS:

  .CodeMirror { height: 400px; width: 500px; border-radius:6px; padding-top:3px; border: 1px solid #ddd; }
  .CodeMirror-scroll { max-height: 400px; width:500px; }
  .CodeMirror pre { display:inline-block; padding-left: 7px; line-height: 1.25; }

Script:

Its displaying weirdly and not working D:

Need more information? Let me know!

Body:
codemirror/mode/clike/clike.js

make sure you include this js in order for the syntax highlighting to works


问:
How do I delete object from object array if its field variable = the parameter of the method
I want to delete an object instance called Entry if its surname field variable = the method parameter surname. This is what I have so far:

```<code>public class ArrayDirectory implements Directory {

    public Entry[] records_array = new Entry[100];
    List<Entry> record_list = new ArrayList<Entry>(Arrays.asList(records_array));
    public static void main(String[] args){
        ArrayDirectory newArrayDirectory = new ArrayDirectory();
        Entry a = new Entry("Alexander" , "H.A", "53454");
        Entry b = new Entry("Hughes","H.H", "12234" );
        Entry c = new Entry("Brown" , "L.B", "47665");
        Entry d = new Entry("Jenkins", "A.J", "34456");
        Entry e = new Entry("Cole", "P.C","57811");

        newArrayDirectory.insertEntry(a);
        newArrayDirectory.insertEntry(b);
        newArrayDirectory.insertEntry(c);
        newArrayDirectory.insertEntry(d);
        newArrayDirectory.insertEntry(e);

        newArrayDirectory.deleteEntryUsingName("Alexander");

    }

    public void deleteEntryUsingName(String surname) {
        // turns records array into ArrayList
        Predicate<Entry> condition = Entry -> Entry.getSurname().contains(surname);
        record_list.removeIf(condition);
        records_array = record_list.toArray(records_array);// turns record_list back into an array
        System.out.print(Arrays.toString(records_array));
    }

}
</code>```

I keep getting a nullpointer exception in the main class where the method is called and I don't really know what that means, to be honest.

Here is the Directory class:

```<code>import java.util.List;

public interface Directory {

    /**
     * Insert a new entry into the directory.
     *
     * @param entry the new entry to add
     */
    public void insertEntry(Entry entry);

    /**
     * Remove an entry from the directory using their surname.
     *
     * @param surname the surname of the entry to remove
     */
    public void deleteEntryUsingName(String surname);

    /**
     * Remove an entry from the directory using their extension number.
     *
     * @param number the extension number of the entry to remove
     */
    public void deleteEntryUsingExtension(String number);

    /**
     * Update an entry's extension number using their surname.
     *
     * @param surname   surname of the entry to be updated
     * @param newNumber the new number
     */
    public void updateExtensionUsingName(String surname, String newNumber);

    /**
     * Get the extension number of an entry using their surname.
     *
     * @param surname the surname of the entry
     * @return the extension number of the entry
     */
    public String lookupExtension(String surname);

    /**
     * Return an array list of all entries in the directory.
     *
     * @return an array list of all entries
     */
   public List<Entry> toArrayList();

}
</code>```

答:
The reason is that while declaring the record_list variable on the class you are converting the "records_array" array to list. This "records_array" array contains 100 NULL values initially and as a result, there are null Entry objects populated in the record_list. Then in deleteEntry method "getSurname()" is called on a null object. Hence the null pointer exception. You could write as below to avoid exception in the delete method:</p>

```<code>Predicate<Entry> condition = entry -> Objects.nonNull(entry) && entry.getSurname().contains(surname);
</code>```

Body:
I want to delete an object instance called Entry if its surname field variable = the method parameter surname. This is what I have so far:

public class ArrayDirectory implements Directory {

    public Entry[] records_array = new Entry[100];
    List<Entry> record_list = new ArrayList<Entry>(Arrays.asList(records_array));
    public static void main(String[] args){
        ArrayDirectory newArrayDirectory = new ArrayDirectory();
        Entry a = new Entry("Alexander" , "H.A", "53454");
        Entry b = new Entry("Hughes","H.H", "12234" );
        Entry c = new Entry("Brown" , "L.B", "47665");
        Entry d = new Entry("Jenkins", "A.J", "34456");
        Entry e = new Entry("Cole", "P.C","57811");

        newArrayDirectory.insertEntry(a);
        newArrayDirectory.insertEntry(b);
        newArrayDirectory.insertEntry(c);
        newArrayDirectory.insertEntry(d);
        newArrayDirectory.insertEntry(e);

        newArrayDirectory.deleteEntryUsingName("Alexander");

    }

    public void deleteEntryUsingName(String surname) {
        // turns records array into ArrayList
        Predicate<Entry> condition = Entry -> Entry.getSurname().contains(surname);
        record_list.removeIf(condition);
        records_array = record_list.toArray(records_array);// turns record_list back into an array
        System.out.print(Arrays.toString(records_array));
    }

}

I keep getting a nullpointer exception in the main class where the method is called and I don't really know what that means, to be honest.

Here is the Directory class:

import java.util.List;

public interface Directory {

    /**
     * Insert a new entry into the directory.
     *
     * @param entry the new entry to add
     */
    public void insertEntry(Entry entry);

    /**
     * Remove an entry from the directory using their surname.
     *
     * @param surname the surname of the entry to remove
     */
    public void deleteEntryUsingName(String surname);

    /**
     * Remove an entry from the directory using their extension number.
     *
     * @param number the extension number of the entry to remove
     */
    public void deleteEntryUsingExtension(String number);

    /**
     * Update an entry's extension number using their surname.
     *
     * @param surname   surname of the entry to be updated
     * @param newNumber the new number
     */
    public void updateExtensionUsingName(String surname, String newNumber);

    /**
     * Get the extension number of an entry using their surname.
     *
     * @param surname the surname of the entry
     * @return the extension number of the entry
     */
    public String lookupExtension(String surname);

    /**
     * Return an array list of all entries in the directory.
     *
     * @return an array list of all entries
     */
   public List<Entry> toArrayList();

}

Body:
The reason is that while declaring the record_list variable on the class you are converting the "records_array" array to list. This "records_array" array contains 100 NULL values initially and as a result, there are null Entry objects populated in the record_list. Then in deleteEntry method "getSurname()" is called on a null object. Hence the null pointer exception. You could write as below to avoid exception in the delete method:

Predicate<Entry> condition = entry -> Objects.nonNull(entry) && entry.getSurname().contains(surname);


答:
The async modifier requires that the function return Task<T> (or void, in which case any await statements will be ignored). This means that using async and using Task.Run() are one and the same, the premise of your question doesn't make sense.

However, what I think you want to do is just use the async await syntax to avoid an explicit call to Task.Run().

Callbacks

Just create a function which returns a Task

```<code>async Task<T> Foo()
</code>```

And then assign a variable var bar=await Foo();

Cancel a running task

Just use CancellationToken

```<code>CancellationTokenSource tokenSource = new CancellationTokenSource();
</code>```

If you construct a task with two arguments, the second argument is a cancellation token:

```<code>var bar= new Task(action, tokenSource.Token)
</code>```

This lets you use
    tokenSource.Cancel();

Relevant link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=netframework-4.8

Chaining Calls

If you don't require a defined order of execution, you can use Task.WhenAll(), otherwise you can either execute the next task inside the previous one or in the awaiting code.

Task.WhenAll(): https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenall?view=netframework-4.8#System_Threading_Tasks_Task_WhenAll_System_Collections_Generic_IEnumerable_System_Threading_Tasks_Task__

Title: Using async instead of Task.Run()

Body:
The async modifier requires that the function return Task<T> (or void, in which case any await statements will be ignored). This means that using async and using Task.Run() are one and the same, the premise of your question doesn't make sense.

However, what I think you want to do is just use the async await syntax to avoid an explicit call to Task.Run().

Callbacks

Just create a function which returns a Task

async Task<T> Foo()

And then assign a variable var bar=await Foo();

Cancel a running task

Just use CancellationToken

CancellationTokenSource tokenSource = new CancellationTokenSource();

If you construct a task with two arguments, the second argument is a cancellation token:

var bar= new Task(action, tokenSource.Token)

This lets you use
    tokenSource.Cancel();

Relevant link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=netframework-4.8

Chaining Calls

If you don't require a defined order of execution, you can use Task.WhenAll(), otherwise you can either execute the next task inside the previous one or in the awaiting code.

Task.WhenAll(): https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenall?view=netframework-4.8#System_Threading_Tasks_Task_WhenAll_System_Collections_Generic_IEnumerable_System_Threading_Tasks_Task__


问:
How to save stdout.read() in a csv file?
Guys I am struggling to figure out how to save output of a command I ran to a csv file. Here is the code i have written so far to get the output from a linux host using paramiko modue.

```<code>ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip,port=22,username=user_name,password=passwd)
stdin, stdout, stderr = ssh_client.exec_command("some random command")
output = (stdout.read().decode(encoding='ascii'))
print(output)
</code>```

This is the output I get:

```<code>Lun VV_WWN                           VVName                   HostName
1 600525465446418gsdhgdfhahf14488454 HOST-California_westcos domain123
9 600525465446418gsdhgdfhahf14488454 HOST-Texas_westcos      domain123
4 600525465446418gsdhgdfhahf14488454 HOST-Kasnsas_westcos    domain123
4 600525465446418gsdhgdfhahf14488454 HOST-Ohio_westcos       domain123
7 600525465446418gsdhgdfhahf14488454 HOST-Nevada_westcos     domain123
---------------------------------------------------------------------------
5                                                  total
</code>```

I need to remove header and footer and save this file as CSV. Any suggestion on how can i achieve this.
I would really appreciate the help.

答:
You can use the csv builtin python package.

just add the following code:

```<code>import csv

lines = list(output.splitlines())
lines = lines[1:-2]

with open('my_csv.csv', 'w', newline='') as csvfile:
    my_writer = csv.writer(csvfile, delimiter=' ')
    for line in lines:
        my_writer.writerow(line[0].split())

</code>```

good luck and let me know if you need more help.
Some reference can be found here: CSV File Reading and Writing

Body:
Guys I am struggling to figure out how to save output of a command I ran to a csv file. Here is the code i have written so far to get the output from a linux host using paramiko modue.

ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip,port=22,username=user_name,password=passwd)
stdin, stdout, stderr = ssh_client.exec_command("some random command")
output = (stdout.read().decode(encoding='ascii'))
print(output)

This is the output I get:

Lun VV_WWN                           VVName                   HostName
1 600525465446418gsdhgdfhahf14488454 HOST-California_westcos domain123
9 600525465446418gsdhgdfhahf14488454 HOST-Texas_westcos      domain123
4 600525465446418gsdhgdfhahf14488454 HOST-Kasnsas_westcos    domain123
4 600525465446418gsdhgdfhahf14488454 HOST-Ohio_westcos       domain123
7 600525465446418gsdhgdfhahf14488454 HOST-Nevada_westcos     domain123
---------------------------------------------------------------------------
5                                                  total

I need to remove header and footer and save this file as CSV. Any suggestion on how can i achieve this.
I would really appreciate the help.

Body:
You can use the csv builtin python package.

just add the following code:

import csv

lines = list(output.splitlines())
lines = lines[1:-2]

with open('my_csv.csv', 'w', newline='') as csvfile:
    my_writer = csv.writer(csvfile, delimiter=' ')
    for line in lines:
        my_writer.writerow(line[0].split())

good luck and let me know if you need more help.
Some reference can be found here: CSV File Reading and Writing


问:
Using object when out of scope?
I'm working on a school assignment require to create a char LinkedList from user string input based on a menu of options:

Enter new string and store as linked list character of in an LinkedList class.

Get current length from the LinkedList.

Find index of character in this linked list.

Append another LinkedList to this LinkedList.

I have everything working fine, but now I'm stuck at the menu option part.
So let's say I choose option 1 to enter a string, and then I decide to use that object for case 2 and 3 to get the size and find index. That would not work because the object will be destroyed when out of scope. Is there any proper way that I can use to implement this ?

Simple Code Below

```<code>switch(option){
case 1:
 LinkedList ls1(getInput());
 ls1.printList();
 break;
}
case 2:
cout << "Size of LinkedList: " <<ls1.getSize() << endl; //wouldn't work because ls1 got destroyed when out of scope.
}
</code>```

答:
If you want to expand the scope of an object, you declare it at a higher scope. You probably have a while loop asking for input, and then switching on that input? If you want your LinkedList to survive successive iterations of the loop, you'll need to declare it before the loop starts.

```<code>LinkedList ls1; // required default constructor
int option = 3;
do
{
    std::cout << "Enter 1 to create new list. 2 to print current list. 3 to quit: ";
    std::cin >> option;
    switch(option)
    {
    case 1:
        ls1 = getInput(); // requires conversion from getInput()'s return type and copy (or preferably move) assignment operators
        ls1.printList();
        break;
    case 2:
        std::cout << "Size of LinkedList: " <<ls1.getSize() << std::endl;
        break;
    }
} while(option != 3);
</code>```

Title: Using object when out of scope?

Body:
I'm working on a school assignment require to create a char LinkedList from user string input based on a menu of options:

Enter new string and store as linked list character of in an LinkedList class.

Get current length from the LinkedList.

Find index of character in this linked list.

Append another LinkedList to this LinkedList.

I have everything working fine, but now I'm stuck at the menu option part.
So let's say I choose option 1 to enter a string, and then I decide to use that object for case 2 and 3 to get the size and find index. That would not work because the object will be destroyed when out of scope. Is there any proper way that I can use to implement this ?

Simple Code Below

switch(option){
case 1:
 LinkedList ls1(getInput());
 ls1.printList();
 break;
}
case 2:
cout << "Size of LinkedList: " <<ls1.getSize() << endl; //wouldn't work because ls1 got destroyed when out of scope.
}

Body:
If you want to expand the scope of an object, you declare it at a higher scope. You probably have a while loop asking for input, and then switching on that input? If you want your LinkedList to survive successive iterations of the loop, you'll need to declare it before the loop starts.

LinkedList ls1; // required default constructor
int option = 3;
do
{
    std::cout << "Enter 1 to create new list. 2 to print current list. 3 to quit: ";
    std::cin >> option;
    switch(option)
    {
    case 1:
        ls1 = getInput(); // requires conversion from getInput()'s return type and copy (or preferably move) assignment operators
        ls1.printList();
        break;
    case 2:
        std::cout << "Size of LinkedList: " <<ls1.getSize() << std::endl;
        break;
    }
} while(option != 3);


问:
Write a list of Complex Numbers as Binary Data
I'm trying to output some data from a python script to a binary file.

If I have a list of floats I've been using this

```<code>out_file = open("filename", "wb")
float_array.array("f", [])
float_array.fromlist(mylist)
float_array.tofile(out_file)
out_file.close()
</code>```

This seems to work fine, at least it's resulting in a file with the correct number of bytes.

How can I do the same thing but using a list of complex numbers?

Thanks

答:
You could create a flattened list of floats out of your complex array like

```<code>flattend = [f for sublist in ((c.real, c.imag) for c in complex_list) for f in sublist]
</code>```

and write this one to the file.

Body:
I'm trying to output some data from a python script to a binary file.

If I have a list of floats I've been using this

out_file = open("filename", "wb")
float_array.array("f", [])
float_array.fromlist(mylist)
float_array.tofile(out_file)
out_file.close()

This seems to work fine, at least it's resulting in a file with the correct number of bytes.

How can I do the same thing but using a list of complex numbers?

Thanks

Body:
You could create a flattened list of floats out of your complex array like

flattend = [f for sublist in ((c.real, c.imag) for c in complex_list) for f in sublist]

and write this one to the file.


问:
How to detect and visualize ceiling with RealityKit?
Since RealityKit is new to me, apparently the plane anchors now have classification (floor, wall, ceiling, ...), so does anyone of you know the procedure of detecting ceilings (or any class of a plane)with RealityKit and ARKit and visualizing them using specific color (for instance red). Any information regarding this would be welcome.</p>

答: ARKit/RealityKit can detect horizontal surfaces, so yes, it can definitely detect a ceiling. Of course, ARKit won't inherently know that it is a ceiling vs a floor or a table. You could compare the ARPlaneAnchor's y value to the phone's present y value and determine that it is likely a ceiling and add geometry/coloration based on that.


问:
Why doesn't react output anything to the console when input is submited?
This is the react code I'm currently using:

import React, { Component } from 'react'

export class AddProduct extends Component {
    doSomething(){
        console.log('Hello')
    }
    render() {
        return (

Product name

                <input type="text" id="product"></input>

Product price

                <input type="text" id="price"></input>
                <input type="submit" id="submit" value="Submit" onSubmit={(e) => {this.doSomething();}}></input>

        )
    }
}

export default AddProduct
```

I'm expecting a 'Hello' output to the terminal when the submit button is pressed however it does not show up. Could anyone help me out?

答:
<input> elements do not fire a submit event when clicked, even when inside a form:

document.querySelector('input').addEventListener('submit', () => {
  alert('submit event seen');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="submit">
</form></code>```

A click event would work, though. Change

```<code>onSubmit={(e) => {this.doSomething();}}
</code>```

to

```<code>onClick={(e) => {this.doSomething();}}
</code>```

If your <input> happens to be inside a form, you could attach a submit listener to the form instead.

Body:
This is the react code I'm currently using:

import React, { Component } from 'react'

export class AddProduct extends Component {
    doSomething(){
        console.log('Hello')
    }
    render() {
        return (

Product name

                <input type="text" id="product"></input>

Product price

                <input type="text" id="price"></input>
                <input type="submit" id="submit" value="Submit" onSubmit={(e) => {this.doSomething();}}></input>

        )
    }
}

export default AddProduct

I'm expecting a 'Hello' output to the terminal when the submit button is pressed however it does not show up. Could anyone help me out?

Body:
<input> elements do not fire a submit event when clicked, even when inside a form:

document.querySelector('input').addEventListener('submit', () => {
  alert('submit event seen');
});

<form>
  <input type="submit">
</form>

A click event would work, though. Change

onSubmit={(e) => {this.doSomething();}}

to

onClick={(e) => {this.doSomething();}}

If your <input> happens to be inside a form, you could attach a submit listener to the form instead.


问:
where to see xPath Extractor results in Jmeter
I am new to Jmeter, I want to see the Xpath Extractor generated results.

I have

```<code> Reference Name : pt_idx
 Xpath query : //patientList/patient/idnetifierList/identifier/text()
 Default Value : 0
</code>```

Please clarify my doubts, can i use Xpath query generated results in Http Request?

Is those result will store in pt_idx variable?

Finally, where can i see the results?

答:
Yes, you can use it in an Http Request, I have previously used several XPath Extractors and been able to use them as variables in subsequent http request using the placeholder notation ${varname} (for you it would be ${pt_idx})

To verify the value of the variable, I could do it via the report by looking at the HTTP Request (as I used the variable to fill a request parameter).

Hope it helps.

Body:
I am new to Jmeter, I want to see the Xpath Extractor generated results.

I have

 Reference Name : pt_idx
 Xpath query : //patientList/patient/idnetifierList/identifier/text()
 Default Value : 0

Please clarify my doubts, can i use Xpath query generated results in Http Request?

Is those result will store in pt_idx variable?

Finally, where can i see the results?


问:
multiply based on a condition on hardcoded values in pandas python
I have :

```<code>a = 2
b = 3
c = 4
</code>```

my table looks like :

```<code>ID   value
a    20
b    30
c    40
</code>```

Expected table :

```<code>ID   value   Expected_output
a    20      40
b    30      90
c    40      160
</code>```

I tried using np.where but getting the wrong output. How can I multiply hardcoded a,b,c with values

答:
Assuming your values a,b,c are stored in a dictionary, you can create another pandas series multiplier to perform the multiplication

Edit: added map() function thanks to @filbranden

```<code>import pandas as pd
mul_dict = {"a": 2, "b": 3, "c": 4}

id_col = ["a", "b", "c"]
val_col = [20, 30, 40]
df = pd.DataFrame(list(zip(id_col, val_col)), columns=["ID", "value"])

# multiplier is a pandas series
multiplier = df["ID"].map(mul_dict)

df["Expected_output"] = df["value"] * multiplier
print(df)
</code>```

Body:
I have :

a = 2
b = 3
c = 4

my table looks like :

ID   value
a    20
b    30
c    40

Expected table :

ID   value   Expected_output
a    20      40
b    30      90
c    40      160

I tried using np.where but getting the wrong output. How can I multiply hardcoded a,b,c with values

Body:
Assuming your values a,b,c are stored in a dictionary, you can create another pandas series multiplier to perform the multiplication

Edit: added map() function thanks to @filbranden

import pandas as pd
mul_dict = {"a": 2, "b": 3, "c": 4}

id_col = ["a", "b", "c"]
val_col = [20, 30, 40]
df = pd.DataFrame(list(zip(id_col, val_col)), columns=["ID", "value"])

# multiplier is a pandas series
multiplier = df["ID"].map(mul_dict)

df["Expected_output"] = df["value"] * multiplier
print(df)


问:
How do I use convertAndSendToUser() with an external broker such as RabbitMQ in Spring4?
I am trying to configure web socket support in Spring 4 using RabbitMQ as the external broker, but as soon as I switch to RabbitMQ, I get the following error on start-up in the client:

```<code>'/user/queue/changes' is not a valid destination.
Valid destination types are: /temp-queue, /exchange, /topic, /queue, /amq/queue, /reply-queue/.
</code>```

On the server I am using convertAndSendToUser and this works fine with the simple broker, but as soon as I switch to RabbitMQ, I get this error.  Note that RabbitMQ works fine for normal topic broadcasts - it's just the /user channel that falls over.

Do I need to do something special to get /user to work with RabbitMQ?

Edit to include Web Socket Config

My WebSocketConfig is pretty standard with a few customisations to integrate it with spring-session:

```<code>@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> {

@Override
public void configureStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/changes").withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    //config.enableSimpleBroker("/queue", "/topic");
    StompBrokerRelayRegistration r = config.enableStompBrokerRelay("/user", "/topic");

    try {
        String rabbitUrl = System.getenv("CLOUDAMQP_URL");
        if(rabbitUrl != null) {
            log.info("RABBIT URL detected: " + rabbitUrl);
            URI uri = new URI(rabbitUrl);
            String host = uri.getHost();
            String login = uri.getUserInfo().split(":",2)[0];
            String passCode = uri.getUserInfo().split(":",2)[1];
            String vhost = uri.getPath().substring(1);
            r.setRelayHost(host);
            r.setSystemLogin(login);
            r.setSystemPasscode(passCode);
            r.setClientLogin(login);
            r.setClientPasscode(passCode);
            r.setVirtualHost(vhost);
        }
    } catch(Exception e) {
        log.error("Error setting up RabbitMQ", e);
    }
    config.setApplicationDestinationPrefixes("/app");
  }
}
</code>```

答:
It is quite an old question, but I just met the same error so my solution might works for others. It's basicly what @Memo 313 MediaSA said(and why his answer is downvoted).
The two key points I have found are:

set only the prefix that message broker support(for rabbitmq, see:https://www.rabbitmq.com/stomp.html), and only use them in application.

*optional: call setUserDestinationPrefix and set a user destinations for MessageBrokerRegistry when over configureMessageBroker.(the default is "/user/" so if you just want to use "/user/" as user destinations this setting is not necessary)

After doing those, everything should work as what doc for setUserDestinationPrefix methord says:

For example when a user attempts to subscribe to "/user/queue/position-updates",
  the destination may be translated to "/queue/position-updatesi9oqdfzo" yielding a
  unique queue name that does not collide with any other user attempting to do the same.
  Subsequently when messages are sent to "/user/{username}/queue/position-updates",
  the destination is translated to "/queue/position-updatesi9oqdfzo".

Also, be sure that the {username} your application is using is the same with principal.

Body:
I am trying to configure web socket support in Spring 4 using RabbitMQ as the external broker, but as soon as I switch to RabbitMQ, I get the following error on start-up in the client:

'/user/queue/changes' is not a valid destination.
Valid destination types are: /temp-queue, /exchange, /topic, /queue, /amq/queue, /reply-queue/.

On the server I am using convertAndSendToUser and this works fine with the simple broker, but as soon as I switch to RabbitMQ, I get this error.  Note that RabbitMQ works fine for normal topic broadcasts - it's just the /user channel that falls over.

Do I need to do something special to get /user to work with RabbitMQ?

Edit to include Web Socket Config

My WebSocketConfig is pretty standard with a few customisations to integrate it with spring-session:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> {

@Override
public void configureStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/changes").withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    //config.enableSimpleBroker("/queue", "/topic");
    StompBrokerRelayRegistration r = config.enableStompBrokerRelay("/user", "/topic");

    try {
        String rabbitUrl = System.getenv("CLOUDAMQP_URL");
        if(rabbitUrl != null) {
            log.info("RABBIT URL detected: " + rabbitUrl);
            URI uri = new URI(rabbitUrl);
            String host = uri.getHost();
            String login = uri.getUserInfo().split(":",2)[0];
            String passCode = uri.getUserInfo().split(":",2)[1];
            String vhost = uri.getPath().substring(1);
            r.setRelayHost(host);
            r.setSystemLogin(login);
            r.setSystemPasscode(passCode);
            r.setClientLogin(login);
            r.setClientPasscode(passCode);
            r.setVirtualHost(vhost);
        }
    } catch(Exception e) {
        log.error("Error setting up RabbitMQ", e);
    }
    config.setApplicationDestinationPrefixes("/app");
  }
}


问:
CORS with Azure function from localhost (not CLI)
We are using axios in a vue.js app to access an Azure function.  Right now we are getting this error:

No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access.
```
<p>We are trying to set response headers in the function this way:</p>
<pre class="lang-js prettyprint-override"><code>context.res = {
  body: response.data,
  headers: {
    'Access-Control-Allow-Credentials': 'true',
    'Access-Control-Allow-Origin': 'http://localhost:8080',
    'Access-Control-Allow-Methods': 'GET',
    'Access-Control-Request-Headers': 'X-Custom-Header'
  }
}
</code>```

Has anyone run across this error?

答:
Had same problem. On root of backend project, there's a file local.settings.json.

Added "CORS": "*" and "CORSCredentials": false in that file (following is the example), did mvn clean package -DskipTests=true on root, and mvn azure-functions:run -DenableDebug on the azure function directory.

```<code>{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "<language worker>",
    "AzureWebJobsStorage": "<connection-string>",
    "AzureWebJobsDashboard": "<connection-string>",
    "MyBindingConnection": "<binding-connection-string>"
  },
  "Host": {
    "LocalHttpPort": 7071,
    "CORS": "*",
    "CORSCredentials": false
  },
  "ConnectionStrings": {
    "SQLConnectionString": "<sqlclient-connection-string>"
  }
}
</code>```

Reference:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=macos

Body:
We are using axios in a vue.js app to access an Azure function.  Right now we are getting this error:

No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access.

We are trying to set response headers in the function this way:

context.res = {
  body: response.data,
  headers: {
    'Access-Control-Allow-Credentials': 'true',
    'Access-Control-Allow-Origin': 'http://localhost:8080',
    'Access-Control-Allow-Methods': 'GET',
    'Access-Control-Request-Headers': 'X-Custom-Header'
  }
}

Has anyone run across this error?

Body:
Had same problem. On root of backend project, there's a file local.settings.json.

Added "CORS": "*" and "CORSCredentials": false in that file (following is the example), did mvn clean package -DskipTests=true on root, and mvn azure-functions:run -DenableDebug on the azure function directory.

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "<language worker>",
    "AzureWebJobsStorage": "<connection-string>",
    "AzureWebJobsDashboard": "<connection-string>",
    "MyBindingConnection": "<binding-connection-string>"
  },
  "Host": {
    "LocalHttpPort": 7071,
    "CORS": "*",
    "CORSCredentials": false
  },
  "ConnectionStrings": {
    "SQLConnectionString": "<sqlclient-connection-string>"
  }
}

Reference:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=macos


答:
Forms are just normal classes. This means, you can create properties in them.

So: Create a property and assign the value to it.

Title: Passing value from dialog form to main form

Body:
Possible Duplicate:

  How do you pass an object from form1 to form2 and back to form1?

I'm used to passing variables between windows forms by simply passing them as a parameter.
Now I have a form that is already open (let's call it FormMain), and another form that should act like a dialog (FormTask). The user cannot interact with the main form until he has filled in the information on FormTask. FormTask simply contains a single textbox, and the value of this textbox should be returned to FormMain, and kept track of as a variable. FormTask requires a parameter exerciseType. When FormTask opens it checks the value of this parameter and sets the default value of the textbox accordingly. This already works, I'm just kind of clueless on how to return my string value to the already open MainForm.
These dialogs only seem to be able to return DialogResults, which isn't what I'm after. I'm not too experienced either, and I'd rather avoid fumbling around to make my own custom dialog.

FormMain:

FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoker.ShowDialog();

FormTask:

private void button1_Click(object sender, EventArgs e)
{
    string opgave = textBoxOpgave.Text;
    // return string value to MainForm here
}


问:
Is there a way to version ~/.bashrc in-place by git, without copying to a different repo?
I'd like to version ~/.bashrc and ~/.bash_profile using git, best if in-place (at the actual location), rather than creating a new repo and copy the file over and do the versioning there.

Is there a way to do that? I think the difficulty is, if I create a repo at ~, it includes every folder in my home directory and is not desirable.

Is there some way to tell git: version only these files or folder, and disregard everything else and don't consider them to be submodules? If it can be like that, it might be a solution, except it seem like a super big repo to be at the home directory but at the same time ignoring almost everything.

答:
You can create a repo in another directory, and then use a symbolic link in your home directory (~) to point to the new file.

```<code>mkdir -p ~/path/to/repo
mv ~/.bashrc ~/path/to/repo/

cd ~
ln -s ~/path/to/repo/.bashrc .bashrc

cd ~/path/to/repo
# edit .bashrc
git init
git add .bashrc
git commit -m "Initial commit"
</code>```

This way, you have a plain repository that contains only the files you want to version control, and the rest of your system uses ~/.bashrc as before, transparently following the link to the version controlled file.  No .gitignore or shell aliases needed.

Body:
You can create a repo in another directory, and then use a symbolic link in your home directory (~) to point to the new file.

mkdir -p ~/path/to/repo
mv ~/.bashrc ~/path/to/repo/

cd ~
ln -s ~/path/to/repo/.bashrc .bashrc

cd ~/path/to/repo
# edit .bashrc
git init
git add .bashrc
git commit -m "Initial commit"

This way, you have a plain repository that contains only the files you want to version control, and the rest of your system uses ~/.bashrc as before, transparently following the link to the version controlled file.  No .gitignore or shell aliases needed.


问:
how to map and array inside of an object
So here I have an object that I am trying to map:

var bakery = {
        "items":
        {
            "item":[
                 {
                     "id": "0001",
                     "type": "donut",
                     "name": "Cake",
                     "ppu": 0.55,
                     "batters": {
                         "batter":[
                             { "id": "1001", "type": "Regular" },
                             { "id": "1002", "type": "Chocolate" },
                             { "id": "1003", "type": "Blueberry" },
                             { "id": "1004", "type": "Devil's Food" }
                         ]
                     },
                     "topping":[
                         { "id": "5001", "type": "None" },
                         { "id": "5002", "type": "Glazed" },
                         { "id": "5005", "type": "Sugar" },
                         { "id": "5007", "type": "Powdered Sugar" },
                         { "id": "5006", "type": "Chocolate with Sprinkles" },
                         { "id": "5003", "type": "Chocolate" },
                         { "id": "5004", "type": "Maple" }
                      ]
                 },
                 ...
                 ...
                 ...
            ]
        }
}
```

<p>This is the target outcome </p>

<pre class="lang-js prettyprint-override"><code>var target = [{
        "id": 1, //as an int
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters": "all of the batter types as a string",
        "ingredients": [],//a copy of all the toppings
        "countOfFillings": 0
}];
</code>```

And here is my mapping function

//  creates variable bakeryArray that contains the actual Array inside of Baker var
var bakeryArray = bakery.items.item

//  newCakes var invoked map function with the bakeryArray
var newCakes = bakeryArray.map(mapCakes)

function mapCakes(oldCakes) {
    let batter = oldCakes.batters.batter
    console.log(batter, "batter Logged")
    var newCakesObject = {
        type: oldCakes.type,
        name: oldCakes.name,
        ppu: oldCakes.ppu,
        batters: batter.type,
        ingredients: "ingridients",
        countOfFillings: "total number of ingrediensts"
    };
    return newCakesObject;
};
```

<p>I am running into problems in getting the <code>Batter</code>, <code>Ingredients</code>, and <code>countOfFillings</code> from the old object into the new one. </p>

<p>The only thing I can think of doing in order to get the batters in the <code>newCakesObject</code> is that I have to create another mapping function for the batter (I put my attempt at that below)? and then invoke that in the <code>mapCakes</code> function under batters? but every time I create another function for that I get an error saying that it's undefined once I call <code>newBatterArray</code> in the console  </p>

<pre class="lang-js prettyprint-override"><code>var newBatterArray = bakeryArray.map(mapBatters)
function mapBatters(oldarray) {
    let theBatters = oldarray.batters.batter
    console.log(theBatters.type, "we ran")
    var newBatters = {
        type: theBatters.type
    }
    return newBatters;
}
</code>```

答:
To have a much more clear interpretation of your bakery object I have tweaked it a bit

var bakery = {
    "items":[
        {
          "id": "0001",
          "type": "donut",
          "name": "Cake",
          "ppu": 0.55,
          "batters":[
            { "id": "1001", "type": "Regular" },
            { "id": "1002", "type": "Chocolate" },
            { "id": "1003", "type": "Blueberry" },
            { "id": "1004", "type": "Devil's Food" }
          ],
          "toppings":[
            { "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5007", "type": "Powdered Sugar" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" }
          ]
        },
        {
          "id": "0002",
          "type": "donut",
          "name": "Cake",
          "ppu": 0.65,
          "batters":[
            { "id": "1001", "type": "Regular1" },
            { "id": "1002", "type": "Chocolate1" },
            { "id": "1003", "type": "Blueberry1" },
            { "id": "1004", "type": "Devil's Food1" }
          ],
          "toppings":[
            { "id": "5001", "type": "None1" },
            { "id": "5002", "type": "Glazed1" },
            { "id": "5005", "type": "Sugar1" },
            { "id": "5007", "type": "Powdered Sugar1" },
            { "id": "5006", "type": "Chocolate with Sprinkles1" },
            { "id": "5003", "type": "Chocolate1" },
            { "id": "5004", "type": "Maple1" }
          ]
        },
        ...
        ...
        ...
        ...
    ]
}
```

<p>Now You can iterate through each item and build your <code>target</code> array as follows</p>

<pre class="lang-js prettyprint-override"><code>var target = [];

// define reducer function for each item in bakery.items
const reduceToTarget = item => {
    var obj = {};
    obj.id = item.id;
    obj.type = item.type;
    obj.name = item.name;
    obj.ppu = item.ppu;
    obj.batters = '';
    item.batters.forEach(b => obj.batters+=b.type+'|');
    obj.ingredients = item.toppings;
    target.push(obj);
}

// Now you can call the reduceToTarget function to get the desired target list/array
bakery.items.forEach(reduceToTarget);
</code>```

The output for this looks something like this

target = [
  {
    id: "0001"
    type: "donut"
    name: "Cake"
    ppu: 0.55
    batters: "Regular|Chocolate|Blueberry|Devil's Food|",
    ingredients : [/* list of ingredients*/]
  },
  {
    id: "0002"
    type: "donut"
    name: "Cake"
    ppu: 0.65
    batters: "Regular|Chocolate|Blueberry|Devil's Food|",
    ingredients : [/* list of ingredients*/]
  }
]
```

NOTE:

For getting the countOfFillings you can simply call length() function on your ingredients list for any element in target

Body:
So here I have an object that I am trying to map:

var bakery = {
        "items":
        {
            "item":[
                 {
                     "id": "0001",
                     "type": "donut",
                     "name": "Cake",
                     "ppu": 0.55,
                     "batters": {
                         "batter":[
                             { "id": "1001", "type": "Regular" },
                             { "id": "1002", "type": "Chocolate" },
                             { "id": "1003", "type": "Blueberry" },
                             { "id": "1004", "type": "Devil's Food" }
                         ]
                     },
                     "topping":[
                         { "id": "5001", "type": "None" },
                         { "id": "5002", "type": "Glazed" },
                         { "id": "5005", "type": "Sugar" },
                         { "id": "5007", "type": "Powdered Sugar" },
                         { "id": "5006", "type": "Chocolate with Sprinkles" },
                         { "id": "5003", "type": "Chocolate" },
                         { "id": "5004", "type": "Maple" }
                      ]
                 },
                 ...
                 ...
                 ...
            ]
        }
}

This is the target outcome

var target = [{
        "id": 1, //as an int
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters": "all of the batter types as a string",
        "ingredients": [],//a copy of all the toppings
        "countOfFillings": 0
}];

And here is my mapping function

//  creates variable bakeryArray that contains the actual Array inside of Baker var
var bakeryArray = bakery.items.item

//  newCakes var invoked map function with the bakeryArray
var newCakes = bakeryArray.map(mapCakes)

function mapCakes(oldCakes) {
    let batter = oldCakes.batters.batter
    console.log(batter, "batter Logged")
    var newCakesObject = {
        type: oldCakes.type,
        name: oldCakes.name,
        ppu: oldCakes.ppu,
        batters: batter.type,
        ingredients: "ingridients",
        countOfFillings: "total number of ingrediensts"
    };
    return newCakesObject;
};

I am running into problems in getting the Batter, Ingredients, and countOfFillings from the old object into the new one.

The only thing I can think of doing in order to get the batters in the newCakesObject is that I have to create another mapping function for the batter (I put my attempt at that below)? and then invoke that in the mapCakes function under batters? but every time I create another function for that I get an error saying that it's undefined once I call newBatterArray in the console

var newBatterArray = bakeryArray.map(mapBatters)
function mapBatters(oldarray) {
    let theBatters = oldarray.batters.batter
    console.log(theBatters.type, "we ran")
    var newBatters = {
        type: theBatters.type
    }
    return newBatters;
}

Body:
To have a much more clear interpretation of your bakery object I have tweaked it a bit

var bakery = {
    "items":[
        {
          "id": "0001",
          "type": "donut",
          "name": "Cake",
          "ppu": 0.55,
          "batters":[
            { "id": "1001", "type": "Regular" },
            { "id": "1002", "type": "Chocolate" },
            { "id": "1003", "type": "Blueberry" },
            { "id": "1004", "type": "Devil's Food" }
          ],
          "toppings":[
            { "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5007", "type": "Powdered Sugar" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" }
          ]
        },
        {
          "id": "0002",
          "type": "donut",
          "name": "Cake",
          "ppu": 0.65,
          "batters":[
            { "id": "1001", "type": "Regular1" },
            { "id": "1002", "type": "Chocolate1" },
            { "id": "1003", "type": "Blueberry1" },
            { "id": "1004", "type": "Devil's Food1" }
          ],
          "toppings":[
            { "id": "5001", "type": "None1" },
            { "id": "5002", "type": "Glazed1" },
            { "id": "5005", "type": "Sugar1" },
            { "id": "5007", "type": "Powdered Sugar1" },
            { "id": "5006", "type": "Chocolate with Sprinkles1" },
            { "id": "5003", "type": "Chocolate1" },
            { "id": "5004", "type": "Maple1" }
          ]
        },
        ...
        ...
        ...
        ...
    ]
}

Now You can iterate through each item and build your target array as follows

var target = [];

// define reducer function for each item in bakery.items
const reduceToTarget = item => {
    var obj = {};
    obj.id = item.id;
    obj.type = item.type;
    obj.name = item.name;
    obj.ppu = item.ppu;
    obj.batters = '';
    item.batters.forEach(b => obj.batters+=b.type+'|');
    obj.ingredients = item.toppings;
    target.push(obj);
}

// Now you can call the reduceToTarget function to get the desired target list/array
bakery.items.forEach(reduceToTarget);

The output for this looks something like this

target = [
  {
    id: "0001"
    type: "donut"
    name: "Cake"
    ppu: 0.55
    batters: "Regular|Chocolate|Blueberry|Devil's Food|",
    ingredients : [/* list of ingredients*/]
  },
  {
    id: "0002"
    type: "donut"
    name: "Cake"
    ppu: 0.65
    batters: "Regular|Chocolate|Blueberry|Devil's Food|",
    ingredients : [/* list of ingredients*/]
  }
]

NOTE:

For getting the countOfFillings you can simply call length() function on your ingredients list for any element in target