问:
How to handle specific route address in react.js
I have a specific route like:

```<code>http://localhost:3000/Transaction?Authority=A00000000000000000000000000111&Status=NOK
</code>```

But I don't know how to handle this url, here I used:

```<code>        <Route path="/Transaction/:Authority/:Status" element={<Cart />} />
</code>```

When I entered this URL, it won't redirect me to the Cart component.  Why and how can I fix it?

答:
For a URL path such as: "/Transaction?Authority=A00000000000000000000000000111&Status=NOK"

There is only a single path segment and two queryString params. An example Route may look as follows:

```<code><Route path="/Transaction" element={<Cart />} />
</code>```

The queryString params can be accessed within the Cart component via the useSearchParams hook

```<code>const { useSearchParams } from 'react-router-dom';

...

const [searchParams] = useSearchParams();

const authority = searchParams.get("Authority"); // "A00000000000000000000000000111"
const status = searchParams.get("Status");       // "NOK"
</code>```

If you instead are really wanting to use path="/Transaction/:Authority/:Status" then you should compose your link a little differently

```<code>`"/Transaction/A00000000000000000000000000111/NOK"`

const { useParams } from 'react-router-dom';

...

const { Authority, Status } = useParams();
</code>```

then use the useParams hook to access the route match params

Body:
I have a specific route like:

http://localhost:3000/Transaction?Authority=A00000000000000000000000000111&Status=NOK

But I don't know how to handle this url, here I used:

        <Route path="/Transaction/:Authority/:Status" element={<Cart />} />

When I entered this URL, it won't redirect me to the Cart component.  Why and how can I fix it?

Body:
For a URL path such as: "/Transaction?Authority=A00000000000000000000000000111&Status=NOK"

There is only a single path segment and two queryString params. An example Route may look as follows:

<Route path="/Transaction" element={<Cart />} />

The queryString params can be accessed within the Cart component via the useSearchParams hook

const { useSearchParams } from 'react-router-dom';

...

const [searchParams] = useSearchParams();

const authority = searchParams.get("Authority"); // "A00000000000000000000000000111"
const status = searchParams.get("Status");       // "NOK"

If you instead are really wanting to use path="/Transaction/:Authority/:Status" then you should compose your link a little differently

`"/Transaction/A00000000000000000000000000111/NOK"`

const { useParams } from 'react-router-dom';

...

const { Authority, Status } = useParams();

then use the useParams hook to access the route match params


来源: stackexchange

问:
How do I measure the length of an int array in C++?
My goal is to print all elements of an array of integers regardless of its length. I would like to print it in Python list format, but then I got this error.
Here is my code

```<code>int measure(int n[])
{
    int num=0;
    while (n[num]) { num++; }
    return num;
}

void show(int n[])
{
    int a = measure(n);
    for (int i=0; i<a; i++) {
        if (i==0) { printf("[%d,",n[i]); }
        else if (i==a-1) { printf(" %d]",n[i]); }
        else { printf(" %d,",n[i]); }
    }
}

int main(void)
{
    int arr[10] = {1,2,3,4,5,6,7,8,9,10};
    show(arr);

}
</code>```

It is supposed to print this: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
but I got this instead: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1935094528, -1664206169]

then I replace show() with this:

```<code>int i=0;
    while (n[i]) {
        if (i==0) { printf("[%d,",n[i]); i++; }
        else if (n[i+1] == NULL) { printf(" %d]",n[i]); break; }
        else { printf(" %d,",n[i]); i++; }
    }
</code>```

and then I got these:

```<code>main.cpp:23:28: warning: NULL used in arithmetic [-Wpointer-arith]
   23 |         else if (n[i+1] == NULL) { printf(" %d]",n[i]); break; }
      |                            ^~~~
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -680101376, -1228044632]
</code>```

Why does this happen?

答:
How do I measure the length of an int array in C++?

You can use std::size to get the size of an array with known size:

```<code>int arr[10] = {1,2,3,4,5,6,7,8,9,10};
std::cout << std::size(arr);
</code>```

Why does this happen?

Because the continue condition for your loop is "while the element is not 0". There are no elements with the value 0, so the loop doesn't end before exceeding the end of the array, at which point your overflow the array and the behaviour of the program becomes undefined.

The parameter n of the functions measure and show is not an array of known size. Since n isn't an array of known size, you cannot use std::size to get its size. In fact, although it looks like an array of unspecified size, n is adjusted to be a pointer to element of such array. There is no general way to measure the size of an array given a pointer to its element.

In cases where you want to pass array of any size into a function, and also need to know the size of the array within the function, a good solution is to use a span parameter:

```<code>void show(std::span<int> n)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My goal is to print all elements of an array of integers regardless of its length. I would like to print it in Python list format, but then I got this error.
Here is my code

int measure(int n[])
{
    int num=0;
    while (n[num]) { num++; }
    return num;
}

void show(int n[])
{
    int a = measure(n);
    for (int i=0; i<a; i++) {
        if (i==0) { printf("[%d,",n[i]); }
        else if (i==a-1) { printf(" %d]",n[i]); }
        else { printf(" %d,",n[i]); }
    }
}

int main(void)
{
    int arr[10] = {1,2,3,4,5,6,7,8,9,10};
    show(arr);

}

It is supposed to print this: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
but I got this instead: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1935094528, -1664206169]

then I replace show() with this:

int i=0;
    while (n[i]) {
        if (i==0) { printf("[%d,",n[i]); i++; }
        else if (n[i+1] == NULL) { printf(" %d]",n[i]); break; }
        else { printf(" %d,",n[i]); i++; }
    }

and then I got these:

main.cpp:23:28: warning: NULL used in arithmetic [-Wpointer-arith]
   23 |         else if (n[i+1] == NULL) { printf(" %d]",n[i]); break; }
      |                            ^~~~
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -680101376, -1228044632]

Why does this happen?

Body:
How do I measure the length of an int array in C++?

You can use std::size to get the size of an array with known size:

int arr[10] = {1,2,3,4,5,6,7,8,9,10};
std::cout << std::size(arr);

Why does this happen?

Because the continue condition for your loop is "while the element is not 0". There are no elements with the value 0, so the loop doesn't end before exceeding the end of the array, at which point your overflow the array and the behaviour of the program becomes undefined.

The parameter n of the functions measure and show is not an array of known size. Since n isn't an array of known size, you cannot use std::size to get its size. In fact, although it looks like an array of unspecified size, n is adjusted to be a pointer to element of such array. There is no general way to measure the size of an array given a pointer to its element.

In cases where you want to pass array of any size into a function, and also need to know the size of the array within the function, a good solution is to use a span parameter:

void show(std::span<int> n)


问:
Tox does not find the requirements file
I have a Python module in which the setup.py script starts as follows:

```<code>import setuptools, pathlib

HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
REQUIRES = (HERE / "requirements.txt").read_text().strip().split("\n")

setuptools.setup(
   install_requires=REQUIRES,
   long_description=README,
   ...
)
</code>```

When I run the setup from the command line, like this:

```<code>python setup.py sdist
</code>```

it runs fine. But when I run

```<code>tox
</code>```

I get an error on line 5 in file setup.py:

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt'
</code>```

even though both the requirements.txt file and the README.md file remain in the same folder as setup.py.

Here is my tox.ini file:

```<code>[tox]
envlist = py39

[testenv]
deps =
    pytest
    -r requirements.txt
commands =
    pytest
</code>```

How can I make tox find my requirements.txt file?

答:
As a complementary answer to the correct one by Erel.

Depending on configuration, tox builds the project, installs the build artifact and then tests against it. This is a good thing as only then you test what you ship, and not what is in the source tree.

In order to not forget to include files in the MANIFEST.in file, I usually use the check-manifest tool/linter, see https://pypi.org/project/check-manifest/

Two minor notes

python setup.py sdist is deprecated, see https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html - you should use https://pypa-build.readthedocs.io/en/stable/ instead

using a requirements.txt in a setup.py is not recommended, see this classic article https://caremad.io/posts/2013/07/setup-vs-requirement/ ; additionally, nowadays I would recommend to use pip-tools to pin dependencies

Title: Tox does not find the requirements file

Body:
I have a Python module in which the setup.py script starts as follows:

import setuptools, pathlib

HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
REQUIRES = (HERE / "requirements.txt").read_text().strip().split("\n")

setuptools.setup(
   install_requires=REQUIRES,
   long_description=README,
   ...
)

When I run the setup from the command line, like this:

python setup.py sdist

it runs fine. But when I run

tox

I get an error on line 5 in file setup.py:

FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt'

even though both the requirements.txt file and the README.md file remain in the same folder as setup.py.

Here is my tox.ini file:

[tox]
envlist = py39

[testenv]
deps =
    pytest
    -r requirements.txt
commands =
    pytest

How can I make tox find my requirements.txt file?


问:
Pagination in django
I wanted to implement pagination in my django based app. For that I am using django-pagination module. However the pagination generated by it is not pleasing. I wanted something like the one generated by django's admin view where the page numbers are clickable links rather than something like Page 1 of 4 next... Suggestions?. It should have been possible since django's admin view is generating it.</p>

答: Simply change the template. The one as an example here is not the default. You can do anything else with the paginator integrated attributes and functions.</p>

ContentLicense: CC BY-SA 3.0

Title: Pagination in django


问:
How can I delete node_modules? It will not let me under any circumstance due to snoretoast-x64.exe
I have tried deleting two Vue/Laravel projects with no success. Each time, everything but node_modules is removed. The only remaining file is snoretoast-x64.exe. I have tried all the following:

FileAssassin: Just states I do not have permission to delete the file.

'Del' key: States I need admin permissions. When given, says I need permission from myself.

'Shift'+'Del' keys: Deletes the .exe, which then immediately regenerates.

CMD, PowerShell, Git Bash, PuTTy, RimRaf(npm & npx) (All in Administrator Mode): State I do not have permission to delete the file.

Altering security settings under file properties: States I do not have permission to view permissions.

I've tried looking anywhere I could. This is everything I can remember trying. I'm at a complete loss.

答:
I had the exact same issue. Could not delete under any circumstance, even force delete from bash didn't work.

Shift delete, would result in the file reappearing if the window was reloaded. But Shift delete , and immediately restart, and then I was able to remove the node_modules folder , and re-run npm install

Thanks!


问:
Trouble establishing proxy connection from React frontend to Express backend
I am having trouble sending a JSON object using POST method from React frontend to Express Backend.
I get the following error when I submit the form:
Access to XMLHttpRequest at 'http://localhost:8080/create' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Any help will be much appreciated. I do not want to enables CORS due to security implications, and setting proxy parameter in package.json of the React project is not working.

Here is some of my code:

```<code>const handleSubmit = e => {
    e.preventDefault();

   if(entry !== "" && dueDate > Date.now()){
       console.log({entryDate: entryDate, entry: entry, dueDate: dueDate});
    axios({
        method: 'post',
        url: 'http://localhost:8080/create',
        data: {
          entryDate: entryDate,
          entry: entry,
          dueDate: dueDate
        }
      })
        .then(response => response.json)
        .then(data => {
            console.log(`Success:: ${data}`)
        })
        .catch(e => {
            console.log(`error: ${e}`)
        })
        toggle();

   } else {
       console.log("error")
   }

}
    <div>
        <Modal toggle={toggle} isOpen={modal} >
            <ModalHeader>Create Item</ModalHeader>
            <ModalBody>
                <Form>
                    <FormGroup>
                        <Label for="date">Date</Label>
                            <DatePicker id="entryDate" name="entryDate" onChange={onEntryDateChange} selected={entryDate}/>
                    </FormGroup>
                    <FormGroup>
                        <Label for="TODO">TODO</Label>
                        <Input type="textarea"
                            id="entry"
                            name="entry"
                            placeholder="Enter TODO here"
                            onChange={onEntryChange}/>
                    </FormGroup>
                    <FormGroup>
                    <Label for="dueDate">Due date</Label>
                            <DatePicker id="dueDate" name="dueDate"onChange={onDueDateChange} selected={dueDate}/>
                    </FormGroup>
                </Form>
            </ModalBody>
            <ModalFooter>
                <Button color="success" block type="submit" onClick={handleSubmit}>Create <FontAwesomeIcon icon={faPlus} size="sm"/></Button>
            </ModalFooter>
        </Modal>
    </div>
)
</code>```

}

// package.json - I have set the proxy to localhost:8080:
...

```<code> "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:8080",'
</code>```

...

答:
SOLVED

I ended up using axios.post function with url string not including excluding localhost:8080. It seems like since its already specified proxy url in package.json file, I don't have to do it again when making a post call with axios.

Here's the updated code:

axios
  .post('/create', data)
  .then((response) => response.json)
  .then((data) => {
    console.log(`Success:: ${data}`);
  })
  .catch((e) => {
    console.log(`error: ${e}`);
  });
```

Thanks anyways!

Body:
I am having trouble sending a JSON object using POST method from React frontend to Express Backend.
I get the following error when I submit the form:
Access to XMLHttpRequest at 'http://localhost:8080/create' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Any help will be much appreciated. I do not want to enables CORS due to security implications, and setting proxy parameter in package.json of the React project is not working.

Here is some of my code:

const handleSubmit = e => {
    e.preventDefault();

   if(entry !== "" && dueDate > Date.now()){
       console.log({entryDate: entryDate, entry: entry, dueDate: dueDate});
    axios({
        method: 'post',
        url: 'http://localhost:8080/create',
        data: {
          entryDate: entryDate,
          entry: entry,
          dueDate: dueDate
        }
      })
        .then(response => response.json)
        .then(data => {
            console.log(`Success:: ${data}`)
        })
        .catch(e => {
            console.log(`error: ${e}`)
        })
        toggle();

   } else {
       console.log("error")
   }

}

        <Modal toggle={toggle} isOpen={modal} >
            <ModalHeader>Create Item</ModalHeader>
            <ModalBody>
                <Form>
                    <FormGroup>
                        Date
                            <DatePicker id="entryDate" name="entryDate" onChange={onEntryDateChange} selected={entryDate}/>
                    </FormGroup>
                    <FormGroup>
                        TODO
                        <Input type="textarea"
                            id="entry"
                            name="entry"
                            placeholder="Enter TODO here"
                            onChange={onEntryChange}/>
                    </FormGroup>
                    <FormGroup>
                    Due date
                            <DatePicker id="dueDate" name="dueDate"onChange={onDueDateChange} selected={dueDate}/>
                    </FormGroup>
                </Form>
            </ModalBody>
            <ModalFooter>
                <Button color="success" block type="submit" onClick={handleSubmit}>Create <FontAwesomeIcon icon={faPlus} size="sm"/></Button>
            </ModalFooter>
        </Modal>

)

}

// package.json - I have set the proxy to localhost:8080:
...

 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:8080",'

...

Body:
SOLVED

I ended up using axios.post function with url string not including excluding localhost:8080. It seems like since its already specified proxy url in package.json file, I don't have to do it again when making a post call with axios.

Here's the updated code:

axios
  .post('/create', data)
  .then((response) => response.json)
  .then((data) => {
    console.log(`Success:: ${data}`);
  })
  .catch((e) => {
    console.log(`error: ${e}`);
  });

Thanks anyways!


问:
Optimizing nested activerecord query
Activerecord question.. How to optimize this query..

```<code>Prefectures (have many) Cities (have many) Shops (have many) Sales (have many) Brands
</code>```

I'd like to get a list of one sale per prefecture, which is yet to end.. and then list the brands available at the sale.

The nesting is making this kind of tricky for me!

Here is what I came up with, though it's pretty ugly & I think it can be optimized at the query level rather than getting all unfinished sales..

```<code>#Get all sales which are yet to finish, ordered by finish date
upcoming_sales = Sale.includes([{:shop => {:city => :prefecture}}, :brands])
  .where("finish > ?", Date.today)
  .order('start ASC, finish ASC')
  .select(['shop.city.prefecture.name', 'brands.name'])

#filter down to a single sale per prefecture
 @sales = upcoming_sales.each_with_object({}){ |s,o|
    o[s.shop.city.prefecture.name] = o[s.shop.city.prefecture.name] ||= s
  }
</code>```

答:
I'm going to try this using Arel

```<code>class Sale < ActiveRecord::Base

  belongs_to :shop

  class << self
    # Returns only Sale objects with obj.finish > today
    # add on other ActiveRecord queries:
    # Sale.unfinished.all
    # Sale.unfinished.all :limit => 10
    def unfinished
      where(Sale.arel_table[:finish].gt(Date.today))
    end

    # should select only one set of unfinished sales,
    # and where the prefecture name is distinct
    def distinct_prefecture
      Sale.unfinished.joins({:shop => {:city => :prefecture}}).where(Prefecture.arel_table[:name].distinct)
    end
  end
end
</code>```

Then, where you want it:

```<code>@sales = Sale.distinct_prefecture \
  .includes(:brands]) \     # should already include the other stuff with joins
  .order('start ASC, finish ASC')
@brand_list = @sales.collect{|s| s.brands}
</code>```

If you want a limited result, this should be ok:

```<code>@sales = Sale.distinct_prefecture  \
  .limit(10)  \
  .includes(:brands]) \
  .order('start ASC, finish ASC')
</code>```

Title: Optimizing nested activerecord query

Body:
Activerecord question.. How to optimize this query..

Prefectures (have many) Cities (have many) Shops (have many) Sales (have many) Brands

I'd like to get a list of one sale per prefecture, which is yet to end.. and then list the brands available at the sale.

The nesting is making this kind of tricky for me!

Here is what I came up with, though it's pretty ugly & I think it can be optimized at the query level rather than getting all unfinished sales..

#Get all sales which are yet to finish, ordered by finish date
upcoming_sales = Sale.includes([{:shop => {:city => :prefecture}}, :brands])
  .where("finish > ?", Date.today)
  .order('start ASC, finish ASC')
  .select(['shop.city.prefecture.name', 'brands.name'])

#filter down to a single sale per prefecture
 @sales = upcoming_sales.each_with_object({}){ |s,o|
    o[s.shop.city.prefecture.name] = o[s.shop.city.prefecture.name] ||= s
  }

Body:
I'm going to try this using Arel

class Sale < ActiveRecord::Base

  belongs_to :shop

  class << self
    # Returns only Sale objects with obj.finish > today
    # add on other ActiveRecord queries:
    # Sale.unfinished.all
    # Sale.unfinished.all :limit => 10
    def unfinished
      where(Sale.arel_table[:finish].gt(Date.today))
    end

    # should select only one set of unfinished sales,
    # and where the prefecture name is distinct
    def distinct_prefecture
      Sale.unfinished.joins({:shop => {:city => :prefecture}}).where(Prefecture.arel_table[:name].distinct)
    end
  end
end

Then, where you want it:

@sales = Sale.distinct_prefecture \
  .includes(:brands]) \     # should already include the other stuff with joins
  .order('start ASC, finish ASC')
@brand_list = @sales.collect{|s| s.brands}

If you want a limited result, this should be ok:

@sales = Sale.distinct_prefecture  \
  .limit(10)  \
  .includes(:brands]) \
  .order('start ASC, finish ASC')


问:
Comparing two arrays - removing element from array based on object keys
I have two objects.

const arrayOne = [
  {
label: "Categories",
to: "/categories",
id: "product_type",
  },
  {
label: "Colors",
to: "/colors",
id: "color",
  },
  {
label: "Materials",
to: "/materials",
id: "material",
  },
  {
label: "Sizes",
to: "/sizes",
id: "sizes",
  },
  {
label: "Designers",
to: "/designers",
id: "designer_slug",
  },
  {
label: "Stores",
to: "/stores",
id: "retailer_slug",
  },
];

const arrayTwo = [
{
  id: "gender",
  label: "Gender",
  lazy_loaded: false,
},
{
  id: "product_type",
  label: "Category",
  lazy_loaded: false,
},
{
  id: "quick_filters",
  label: "Quick filters",
  lazy_loaded: false,
},
{
  id: "final_price",
  label: "Price",
  lazy_loaded: false,
},
{
  id: "color",
  label: "Color",
  lazy_loaded: false,
},
{
  id: "material",
  label: "Material",
  lazy_loaded: false,
},
{
  id: "designer_slug",
  label: "Brand",
  lazy_loaded: true,
},
{
  id: "retailer_slug",
  label: "Store",
  lazy_loaded: true,
},
  ];```

As you can see they both have the key 'id'. If the IDs in arrayOne aren't in arrayTwo, I would like them to be removed from arrayOne (the whole object). So in this case, only the object with "sizes" should be removed from arrayOne. How would I go about doing this? Thanks in advance!

答:
you could utilize filter:

const newArrayOne = arrayOne.filter(x => arrayTwo.find(y => y.id === x.id))
```

Body:
I have two objects.

const arrayOne = [
  {
label: "Categories",
to: "/categories",
id: "product_type",
  },
  {
label: "Colors",
to: "/colors",
id: "color",
  },
  {
label: "Materials",
to: "/materials",
id: "material",
  },
  {
label: "Sizes",
to: "/sizes",
id: "sizes",
  },
  {
label: "Designers",
to: "/designers",
id: "designer_slug",
  },
  {
label: "Stores",
to: "/stores",
id: "retailer_slug",
  },
];

const arrayTwo = [
{
  id: "gender",
  label: "Gender",
  lazy_loaded: false,
},
{
  id: "product_type",
  label: "Category",
  lazy_loaded: false,
},
{
  id: "quick_filters",
  label: "Quick filters",
  lazy_loaded: false,
},
{
  id: "final_price",
  label: "Price",
  lazy_loaded: false,
},
{
  id: "color",
  label: "Color",
  lazy_loaded: false,
},
{
  id: "material",
  label: "Material",
  lazy_loaded: false,
},
{
  id: "designer_slug",
  label: "Brand",
  lazy_loaded: true,
},
{
  id: "retailer_slug",
  label: "Store",
  lazy_loaded: true,
},
  ];

As you can see they both have the key 'id'. If the IDs in arrayOne aren't in arrayTwo, I would like them to be removed from arrayOne (the whole object). So in this case, only the object with "sizes" should be removed from arrayOne. How would I go about doing this? Thanks in advance!


问:
hackerrank doesn't accept my code but it prints the right result
The code below is accepted by hackerrank

```<code>function staircase($n) {
    $d = 1;

    for($col=$n;$col>0;$col--){
        for($row = 1;$row <$col ;$row++ ){
            echo" ";
        }

        for($a = 0; $a <$d;$a++){
            echo"#";
        }

        $d++;
        echo"\n";
    }
}
</code>```

This is my own code two code provide the same result but hackerrank don't accept my code. I want to know this reason

```<code>function staircase($n) {
    $x=1;
    $y=$n-1;

    while($x<=$n){
        while($y<$n){
            echo "#";
            $y++;
        }

        echo"\n";
        $x++;
        $y=$y-$x;
    }
}
</code>```

答:
When you run your code in the HackerRank environment, you'll get this output:

But this is the output that the description of the task gives:

Notice the difference? The task description stresses this point:

The staircase is right-aligned, composed of # symbols and spaces, and has a height and width of n = 6.

Your code does not print any spaces to align the hash symbols to the right.

Body:
The code below is accepted by hackerrank

function staircase($n) {
    $d = 1;

    for($col=$n;$col>0;$col--){
        for($row = 1;$row <$col ;$row++ ){
            echo" ";
        }

        for($a = 0; $a <$d;$a++){
            echo"#";
        }

        $d++;
        echo"\n";
    }
}

This is my own code two code provide the same result but hackerrank don't accept my code. I want to know this reason

function staircase($n) {
    $x=1;
    $y=$n-1;

    while($x<=$n){
        while($y<$n){
            echo "#";
            $y++;
        }

        echo"\n";
        $x++;
        $y=$y-$x;
    }
}


问:
Getting The Invalid Hook Call error while using biz charts library
While using the dependency of the Biz chart i have got this error message.
"Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons"

```<code>import React from 'react'
import {
    Chart,
    Interval,
    Axis,
    Tooltip,
    Coordinate,
    Label,
    Legend,
    View,
    Guide,
    Shape,
    Facet,
    Util
  } from "bizcharts";
  import DataSet from "@antv/data-set";

function Biz() {
    const data = [
        {
          State: "WY",
          "小于5岁": 25635,
          "5至13岁": 1890,
          "14至17岁": 9314
        },
        {
          State: "DC",
          "小于5岁": 30352,
          "5至13岁": 20439,
          "14至17岁": 10225
        },
        {
          State: "VT",
          小于5岁: 38253,
          "5至13岁": 42538,
          "14至17岁": 15757
        },
        {
          State: "ND",
          "小于5岁": 51896,
          "5至13岁": 67358,
          "14至17岁": 18794
        },
        {
          State: "AK",
          "小于5岁": 72083,
          "5至13岁": 85640,
          "14至17岁": 22153
        }
      ];
      const ds = new DataSet();
      const dv = ds.createView().source(data);
      dv.transform({
        type: "fold",
        fields: ["小于5岁", "5至13岁", "14至17岁"],
        // 展开字段集
        key: "年龄段",
        // key字段
        value: "人口数量",
        // value字段
        retains: ["State"] // 保留字段集，默认为除fields以外的所有字段
      });

    return (
        <div>
            <Chart height={400} data={dv.rows} autoFit>
        <Coordinate transposed/>
                <Tooltip shared />
        <Axis
          name="State"
          label={{
            offset: 12
          }}
        />
        <Interval
          adjust={[{ type: 'stack' }]}
          position="State*人口数量"
          color={"年龄段"}
                    style={{
                        fillOpacity:0.75
                    }}
          label={['人口数量', { position: 'middle', offset: 0, style: { fill: '#fff' }, layout: { type: 'limit-in-shape' } }]}
        />
      </Chart>

        </div>
    )
}

export default Biz
</code>```

Here are the dependencies

```<code>{
  "name": "Biz",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@antv/data-set": "^0.11.8",
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "bizcharts": "^4.1.14",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
</code>```

While I am running my program I have got the above error.

答:
The invalid hook call is currently an issue with bizcharts (see open issue on Github).

The problem may have to do with how different react version dependencies are handled with npm, and apparently yarn does a better job (here's a discussion). What worked for me and a few others is to uninstall with npm and re-install with yarn:

```<code>$ npm uninstall bizcharts
$ yarn add bizcharts
</code>```

Body:
While using the dependency of the Biz chart i have got this error message.
"Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons"

import React from 'react'
import {
    Chart,
    Interval,
    Axis,
    Tooltip,
    Coordinate,
    Label,
    Legend,
    View,
    Guide,
    Shape,
    Facet,
    Util
  } from "bizcharts";
  import DataSet from "@antv/data-set";

function Biz() {
    const data = [
        {
          State: "WY",
          "小于5岁": 25635,
          "5至13岁": 1890,
          "14至17岁": 9314
        },
        {
          State: "DC",
          "小于5岁": 30352,
          "5至13岁": 20439,
          "14至17岁": 10225
        },
        {
          State: "VT",
          小于5岁: 38253,
          "5至13岁": 42538,
          "14至17岁": 15757
        },
        {
          State: "ND",
          "小于5岁": 51896,
          "5至13岁": 67358,
          "14至17岁": 18794
        },
        {
          State: "AK",
          "小于5岁": 72083,
          "5至13岁": 85640,
          "14至17岁": 22153
        }
      ];
      const ds = new DataSet();
      const dv = ds.createView().source(data);
      dv.transform({
        type: "fold",
        fields: ["小于5岁", "5至13岁", "14至17岁"],
        // 展开字段集
        key: "年龄段",
        // key字段
        value: "人口数量",
        // value字段
        retains: ["State"] // 保留字段集，默认为除fields以外的所有字段
      });

    return (

            <Chart height={400} data={dv.rows} autoFit>
        <Coordinate transposed/>
                <Tooltip shared />
        <Axis
          name="State"
          label={{
            offset: 12
          }}
        />
        <Interval
          adjust={[{ type: 'stack' }]}
          position="State*人口数量"
          color={"年龄段"}
                    style={{
                        fillOpacity:0.75
                    }}
          label={['人口数量', { position: 'middle', offset: 0, style: { fill: '#fff' }, layout: { type: 'limit-in-shape' } }]}
        />
      </Chart>

    )
}

export default Biz

Here are the dependencies

{
  "name": "Biz",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@antv/data-set": "^0.11.8",
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "bizcharts": "^4.1.14",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },

While I am running my program I have got the above error.

Body:
The invalid hook call is currently an issue with bizcharts (see open issue on Github).

The problem may have to do with how different react version dependencies are handled with npm, and apparently yarn does a better job (here's a discussion). What worked for me and a few others is to uninstall with npm and re-install with yarn:

$ npm uninstall bizcharts
$ yarn add bizcharts


问:
How to map only changed properties using Automapper and Entity Framework
I know that this question had been asked already, but those answers didn't work for me. So, I beg not to close this question!

The goal is simple:

Get entity from database using Entity Framework.

Pass this entity to MVC view.

Edit entity on the page.

Save entity.

What I have:

Entities

• Client relates to table in database.

• ClientDto is the same as Client, but without Comment property (to emulate situation when user must not see this field).

public class Client
{
  public string TaskNumber { get; set; }
  public DateTime CrmRegDate { get; set; }
  public string Comment { get; set; }
}

public class ClientDto
{
  public string TaskNumber { get; set; }
  public DateTime CrmRegDate { get; set; }
}
```
<h2>Database table</h2>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE dbo.client
(
  task_number  varchar(50)   NOT NULL,
  crm_reg_date date          NOT NULL,
  comment      varchar(3000)     NULL
);

-- Seeding
INSERT INTO dbo.client VALUES
('1001246', '2010-09-14', 'comment 1'),
('1001364', '2010-09-14', 'comment 2'),
('1002489', '2010-09-22', 'comment 3');
</code>```

MVC controller

public class ClientsController : Controller
{
  private readonly ILogger logger;
  private readonly TestContext db;
  private IMapper mapper;

  public ClientsController(TestContext db, IMapper mapper, ILogger<ClientsController> logger)
  {
    this.db = db;
    this.logger = logger;
    this.mapper = mapper;
  }

  public IActionResult Index()
  {
    var clients = db.Clients;
    var clientsDto = mapper.ProjectTo<ClientDto>(clients);
    return View(model: clientsDto);
  }

  public async Task<IActionResult> Edit(string taskNumber)
  {
    var client = await db.Clients.FindAsync(taskNumber);
    return View(model: client);
  }

  [HttpPost]
  public async Task<IActionResult> Edit(ClientDto clientDto)
  {
    // For now it's empty - it'll be used for saving entity
  }
}
```
<h2>Mappings:</h2>
<pre class="lang-cs prettyprint-override"><code>builder.Services
  .AddAutoMapper(config =>
  {
    config.CreateMap<Client, ClientDto>();
    config.CreateMap<ClientDto, Client>();
  }
</code>```

Helper (outputs entity entry as JSON)

internal static class EntititesExtensions
{
  internal static string ToJson<TEntity>(this EntityEntry<TEntity> entry) where TEntity: class
  {
    var states = from member in entry.Members
                 select new
                 {
                   State = Enum.GetName(member.EntityEntry.State),
                   Name = member.Metadata.Name,
                   Value = member.CurrentValue
                 };
    var json = JsonSerializer.SerializeToNode(states);
    return json.ToJsonString(new JsonSerializerOptions { WriteIndented = true });
  }
}
```
<h1>THE PROBLEM</h1>
<p>I need to map only changed properties from <code>ClientDto</code> to <code>Client</code> in <code>Edit(ClientDto clientDto)</code>.</p>
<h2>Which solutions were used</h2>
<h3>Solution 1</h3>
<p>Just map <code>ClientDto</code> to <code>Client</code>:</p>
<pre class="lang-cs prettyprint-override"><code>[HttpPost]
public async Task<IActionResult> Edit(ClientDto clientDto)
{
  var client = mapper.Map<Client>(clientDto);
  logger.LogInformation(db.Entry(client).ToJson());
  db.Update(client);
  await db.SaveChangesAsync();
  return View(viewName: "Success");
}
</code>```

The problem with this code is that absolutely new Client entity gets created which properties will be filled by ClientDto. This means that Comment property will be NULL and it will make NULL the column comment in database. In general case, all hidden properties (i.e. absent in DTO) will have their default values. Not good.

Output:

[
  {
    "State": "Detached",
    "Name": "TaskNumber",
    "Value": "1001246"
  },
  {
    "State": "Detached",
    "Name": "Comment",
    "Value": null
  },
  {
    "State": "Detached",
    "Name": "CrmRegDate",
    "Value": "2010-09-15T00:00:00"
  }
]
```
<h3>Solution 2</h3>
<p>I tried to use the solution from the answer I mentioned above:</p>
<pre class="lang-cs prettyprint-override"><code>public static IMappingExpression<TSource, TDestination> MapOnlyIfChanged<TSource, TDestination>(this IMappingExpression<TSource, TDestination> map)
{
  map.ForAllMembers(source =>
  {
    source.Condition((sourceObject, destObject, sourceProperty, destProperty) =>
    {
      if (sourceProperty == null)
        return !(destProperty == null);
      return !sourceProperty.Equals(destProperty);
    });
  });
  return map;
}
</code>```

In configuration:

builder.Services
  .AddAutoMapper(config =>
  {
    config.CreateMap<Client, ClientDto>();
    config.CreateMap<ClientDto, Client>().MapOnlyIfChanged();
  });
```
<p>Running same code as in solution 1, we get the same output (<code>Comment</code> is <code>null</code>):</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "State": "Detached",
    "Name": "TaskNumber",
    "Value": "1001246"
  },
  {
    "State": "Detached",
    "Name": "Comment",
    "Value": null
  },
  {
    "State": "Detached",
    "Name": "CrmRegDate",
    "Value": "2010-09-15T00:00:00"
  }
]
</code>```

Not good.

Solution 3

Let's take another route:

Obtain entity from database.

Use non-generic Map in order to overwrite the values from ClientDto to Client from database.

Tune mapping configuration in order to skip properties which values are equal.

builder.Services
  .AddAutoMapper(config =>
  {
    config.CreateMap<Client, ClientDto>();
    config.CreateMap<ClientDto, Client>()
      .ForMember(
        dest => dest.TaskNumber,
        opt => opt.Condition((src, dest) => src.TaskNumber != dest.TaskNumber))
      .ForMember(
        dest => dest.TaskNumber,
        opt => opt.Condition((src, dest) => src.CrmRegDate != dest.CrmRegDate));
  });
```
<pre class="lang-cs prettyprint-override"><code>[HttpPost]
public async Task<IActionResult> Edit(ClientDto clientDto)
{
  var dbClient = await db.Clients.FindAsync(clientDto.TaskNumber);
  logger.LogInformation(db.Entry(dbClient).ToJson());
  mapper.Map(
    source: clientDto,
    destination: dbClient,
    sourceType: typeof(ClientDto),
    destinationType: typeof(Client)
  );
  logger.LogInformation(db.Entry(dbClient).ToJson());
  db.Update(dbClient);
  await db.SaveChangesAsync();
  return View(viewName: "Success");
}
</code>```

This finally works, but it has problem - it still modifies all properties. Here's the output:

[
  {
    "State": "Modified",
    "Name": "TaskNumber",
    "Value": "1001246"
  },
  {
    "State": "Modified",
    "Name": "Comment",
    "Value": "comment 1"
  },
  {
    "State": "Modified",
    "Name": "CrmRegDate",
    "Value": "2010-09-15T00:00:00"
  }
]
```

So, how to make Automapper update only modified properties?

答:
You do not need to call context.Update() explicitly.

When loading entity, EF remember every original values for every mapped property.

Then when you change property, EF will compare current properties with original and create appropriate update SQL only for changed properties.

For further reading: Change Tracking in EF Core

Body:
I know that this question had been asked already, but those answers didn't work for me. So, I beg not to close this question!

The goal is simple:

Get entity from database using Entity Framework.

Pass this entity to MVC view.

Edit entity on the page.

Save entity.

What I have:

Entities

• Client relates to table in database.

• ClientDto is the same as Client, but without Comment property (to emulate situation when user must not see this field).

public class Client
{
  public string TaskNumber { get; set; }
  public DateTime CrmRegDate { get; set; }
  public string Comment { get; set; }
}

public class ClientDto
{
  public string TaskNumber { get; set; }
  public DateTime CrmRegDate { get; set; }
}

Database table

CREATE TABLE dbo.client
(
  task_number  varchar(50)   NOT NULL,
  crm_reg_date date          NOT NULL,
  comment      varchar(3000)     NULL
);

-- Seeding
INSERT INTO dbo.client VALUES
('1001246', '2010-09-14', 'comment 1'),
('1001364', '2010-09-14', 'comment 2'),
('1002489', '2010-09-22', 'comment 3');

MVC controller

public class ClientsController : Controller
{
  private readonly ILogger logger;
  private readonly TestContext db;
  private IMapper mapper;

  public ClientsController(TestContext db, IMapper mapper, ILogger<ClientsController> logger)
  {
    this.db = db;
    this.logger = logger;
    this.mapper = mapper;
  }

  public IActionResult Index()
  {
    var clients = db.Clients;
    var clientsDto = mapper.ProjectTo<ClientDto>(clients);
    return View(model: clientsDto);
  }

  public async Task<IActionResult> Edit(string taskNumber)
  {
    var client = await db.Clients.FindAsync(taskNumber);
    return View(model: client);
  }

  [HttpPost]
  public async Task<IActionResult> Edit(ClientDto clientDto)
  {
    // For now it's empty - it'll be used for saving entity
  }
}

Mappings:

builder.Services
  .AddAutoMapper(config =>
  {
    config.CreateMap<Client, ClientDto>();
    config.CreateMap<ClientDto, Client>();
  }

Helper (outputs entity entry as JSON)

internal static class EntititesExtensions
{
  internal static string ToJson<TEntity>(this EntityEntry<TEntity> entry) where TEntity: class
  {
    var states = from member in entry.Members
                 select new
                 {
                   State = Enum.GetName(member.EntityEntry.State),
                   Name = member.Metadata.Name,
                   Value = member.CurrentValue
                 };
    var json = JsonSerializer.SerializeToNode(states);
    return json.ToJsonString(new JsonSerializerOptions { WriteIndented = true });
  }
}

THE PROBLEM

I need to map only changed properties from ClientDto to Client in Edit(ClientDto clientDto).

Which solutions were used

Solution 1

Just map ClientDto to Client:

[HttpPost]
public async Task<IActionResult> Edit(ClientDto clientDto)
{
  var client = mapper.Map<Client>(clientDto);
  logger.LogInformation(db.Entry(client).ToJson());
  db.Update(client);
  await db.SaveChangesAsync();
  return View(viewName: "Success");
}

The problem with this code is that absolutely new Client entity gets created which properties will be filled by ClientDto. This means that Comment property will be NULL and it will make NULL the column comment in database. In general case, all hidden properties (i.e. absent in DTO) will have their default values. Not good.

Output:

[
  {
    "State": "Detached",
    "Name": "TaskNumber",
    "Value": "1001246"
  },
  {
    "State": "Detached",
    "Name": "Comment",
    "Value": null
  },
  {
    "State": "Detached",
    "Name": "CrmRegDate",
    "Value": "2010-09-15T00:00:00"
  }
]

Solution 2

I tried to use the solution from the answer I mentioned above:

public static IMappingExpression<TSource, TDestination> MapOnlyIfChanged<TSource, TDestination>(this IMappingExpression<TSource, TDestination> map)
{
  map.ForAllMembers(source =>
  {
    source.Condition((sourceObject, destObject, sourceProperty, destProperty) =>
    {
      if (sourceProperty == null)
        return !(destProperty == null);
      return !sourceProperty.Equals(destProperty);
    });
  });
  return map;
}

In configuration:

builder.Services
  .AddAutoMapper(config =>
  {
    config.CreateMap<Client, ClientDto>();
    config.CreateMap<ClientDto, Client>().MapOnlyIfChanged();
  });

Running same code as in solution 1, we get the same output (Comment is null):

[
  {
    "State": "Detached",
    "Name": "TaskNumber",
    "Value": "1001246"
  },
  {
    "State": "Detached",
    "Name": "Comment",
    "Value": null
  },
  {
    "State": "Detached",
    "Name": "CrmRegDate",
    "Value": "2010-09-15T00:00:00"
  }
]

Not good.

Solution 3

Let's take another route:

Obtain entity from database.

Use non-generic Map in order to overwrite the values from ClientDto to Client from database.

Tune mapping configuration in order to skip properties which values are equal.

builder.Services
  .AddAutoMapper(config =>
  {
    config.CreateMap<Client, ClientDto>();
    config.CreateMap<ClientDto, Client>()
      .ForMember(
        dest => dest.TaskNumber,
        opt => opt.Condition((src, dest) => src.TaskNumber != dest.TaskNumber))
      .ForMember(
        dest => dest.TaskNumber,
        opt => opt.Condition((src, dest) => src.CrmRegDate != dest.CrmRegDate));
  });

[HttpPost]
public async Task<IActionResult> Edit(ClientDto clientDto)
{
  var dbClient = await db.Clients.FindAsync(clientDto.TaskNumber);
  logger.LogInformation(db.Entry(dbClient).ToJson());
  mapper.Map(
    source: clientDto,
    destination: dbClient,
    sourceType: typeof(ClientDto),
    destinationType: typeof(Client)
  );
  logger.LogInformation(db.Entry(dbClient).ToJson());
  db.Update(dbClient);
  await db.SaveChangesAsync();
  return View(viewName: "Success");
}

This finally works, but it has problem - it still modifies all properties. Here's the output:

[
  {
    "State": "Modified",
    "Name": "TaskNumber",
    "Value": "1001246"
  },
  {
    "State": "Modified",
    "Name": "Comment",
    "Value": "comment 1"
  },
  {
    "State": "Modified",
    "Name": "CrmRegDate",
    "Value": "2010-09-15T00:00:00"
  }
]

So, how to make Automapper update only modified properties?


答:
You could use a Set with id and filter the other array.

const
    arrayOne = [{ label: "Categories", to: "/categories", id: "product_type" }, { label: "Colors", to: "/colors", id: "color" }, { label: "Materials", to: "/materials", id: "material" }, { label: "Sizes", to: "/sizes", id: "sizes" }, { label: "Designers", to: "/designers", id: "designer_slug" }, { label: "Stores", to: "/stores", id: "retailer_slug" }],
    arrayTwo = [{ id: "gender", label: "Gender", lazy_loaded: false }, { id: "product_type", label: "Category", lazy_loaded: false }, { id: "quick_filters", label: "Quick filters", lazy_loaded: false }, { id: "final_price", label: "Price", lazy_loaded: false }, { id: "color", label: "Color", lazy_loaded: false }, { id: "material", label: "Material", lazy_loaded: false }, { id: "designer_slug", label: "Brand", lazy_loaded: true }, { id: "retailer_slug", label: "Store", lazy_loaded: true }],
    two = new Set(arrayTwo.map(({ id }) => id)),
    result = arrayOne.filter(({ id }) => two.has(id));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Comparing two arrays - removing element from array based on object keys

Body:
You could use a Set with id and filter the other array.

const
    arrayOne = [{ label: "Categories", to: "/categories", id: "product_type" }, { label: "Colors", to: "/colors", id: "color" }, { label: "Materials", to: "/materials", id: "material" }, { label: "Sizes", to: "/sizes", id: "sizes" }, { label: "Designers", to: "/designers", id: "designer_slug" }, { label: "Stores", to: "/stores", id: "retailer_slug" }],
    arrayTwo = [{ id: "gender", label: "Gender", lazy_loaded: false }, { id: "product_type", label: "Category", lazy_loaded: false }, { id: "quick_filters", label: "Quick filters", lazy_loaded: false }, { id: "final_price", label: "Price", lazy_loaded: false }, { id: "color", label: "Color", lazy_loaded: false }, { id: "material", label: "Material", lazy_loaded: false }, { id: "designer_slug", label: "Brand", lazy_loaded: true }, { id: "retailer_slug", label: "Store", lazy_loaded: true }],
    two = new Set(arrayTwo.map(({ id }) => id)),
    result = arrayOne.filter(({ id }) => two.has(id));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


答:
There simply is no "measuring" the length of arrays in C++. You have to know up front, and pass that info to any functions or methods you pass the array to. You can also use a specific "tag" value (as you have implicitly done here) but if you do that, you have to set the tag yourself, and that means you have to know the array length to set the tag. And you must be very sure that the tag does not equal any valid data value in your array.

A different approach would be to use std::vector instead of an array. That data type gives you all the functionality of an array but also provides variable length arrays and the ability to inquire the current length.

Title: How do I measure the length of an int array in C++?


问:
Good Practices to Serve Optimization System as Web App

What I am Doing

I am developing optimization system with genetic algorithm; just finished PoC on JupyterNotebook and going to serve it as web application with Python3.
This optimization process needs a lot of computational resource to evaluate each candidate chromosome, so I am planning to adopt parallel distributed processing.

How It Will Work

Below shows how this system will work (now planning).

Users upload file with parameters from browser and reserve optimization

System queues the optimization job

System shows reserved job list and optimization result on browser

My Plan and Question

Here shows what I am planning (I am not familiar with web application).

Request to upload API and save parameters in DB and pickle

Check if there are any reserved optimization jobs every n minutes with cron

Execute optimization if need and save result in DB and update job status (waiting -> finished)

I think this will work but I am not sure this is good.
Do you know good architecture practice to do this?

答: I think having a cron job would complicate the order flow and be inefficient. Try using a message broker (eg. rabbit-mq) and celery to schedule and run the jobs.</p>


问:
Can not log into mssql-server on Fedora 35 after install
I have followed these instructions to install mssql-server on Fedora 35. But I cannot log in!

Status:

```<code>mssql-server.service - Microsoft SQL Server Database Engine
     Loaded: loaded (/usr/lib/systemd/system/mssql-server.service; enabled; vendor preset: disabled)
    Drop-In: /etc/systemd/system/mssql-server.service.d
             └─override.conf
     Active: active (running) since Mon 2022-02-07 10:30:34 EST; 9min ago
</code>```

I have tried to find a password that is accepted by mssql-server and bash friendly.
Special character just enable a new line in bash. I have tried escaping the special character with '' with no success.

I am still getting the Error: 18456, Severity: 14, State: 8. Sometimes it is the State 7 error.

What is the fix? Does anyone have a suggested password that works with mssql-server and bash?

答:
Success!
By changing the special character to '%' works.
At the bash promt:

```<code>>echo Password%4398
>Password%4398
</code>```

Then used:

```<code>sudo /opt/mssql/bin/mssql-conf set-sa-password
</code>```

Now the password is accepted by mssql-server.

Body:
I have followed these instructions to install mssql-server on Fedora 35. But I cannot log in!

Status:

mssql-server.service - Microsoft SQL Server Database Engine
     Loaded: loaded (/usr/lib/systemd/system/mssql-server.service; enabled; vendor preset: disabled)
    Drop-In: /etc/systemd/system/mssql-server.service.d
             └─override.conf
     Active: active (running) since Mon 2022-02-07 10:30:34 EST; 9min ago

I have tried to find a password that is accepted by mssql-server and bash friendly.
Special character just enable a new line in bash. I have tried escaping the special character with '' with no success.

I am still getting the Error: 18456, Severity: 14, State: 8. Sometimes it is the State 7 error.

What is the fix? Does anyone have a suggested password that works with mssql-server and bash?

Body:
Success!
By changing the special character to '%' works.
At the bash promt:

>echo Password%4398
>Password%4398

Then used:

sudo /opt/mssql/bin/mssql-conf set-sa-password

Now the password is accepted by mssql-server.


问:
Insert at start function in linked list is not working properly
In the following code, I am creating a linked list but in the function, insert_at_start is only adding 5 only even after calling function again it only printing 5.</p>
```<code>    from pip import main
    class Node:
        def __init__(self, data = None, next = None):
              self.data = data
              self.next = next

    class linkedlist:
        def __init__(self):
              self.head = None
        def insert_at_start(self, data):
              node = Node(data, self.head)
              self.head = node
        def print(self):
              if self.head is None:
                  print("Linked List is empaty.")
                  return
              itr = self.head
              llst=" "
              while itr:
                  llst = str(itr.data) + "--->"
                  itr = itr.next
              print(llst)

    if __name__ == "__main__":
         ll = linkedlist()
         ll.insert_at_start(5)
         ll.insert_at_start(10)
         ll.insert_at_start(12)
         ll.insert_at_start(70)
         ll.print()

</code>```

答: If you want print to be called for each node, it has to be inside the loop.

Body:
In the following code, I am creating a linked list but in the function, insert_at_start is only adding 5 only even after calling function again it only printing 5.

    from pip import main
    class Node:
        def __init__(self, data = None, next = None):
              self.data = data
              self.next = next

    class linkedlist:
        def __init__(self):
              self.head = None
        def insert_at_start(self, data):
              node = Node(data, self.head)
              self.head = node
        def print(self):
              if self.head is None:
                  print("Linked List is empaty.")
                  return
              itr = self.head
              llst=" "
              while itr:
                  llst = str(itr.data) + "--->"
                  itr = itr.next
              print(llst)

    if __name__ == "__main__":
         ll = linkedlist()
         ll.insert_at_start(5)
         ll.insert_at_start(10)
         ll.insert_at_start(12)
         ll.insert_at_start(70)
         ll.print()


问:
Very basic JSON question
I have this JSON data:

```<code>var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];
</code>```

How can I loop through all the objects inside people and output their names along with their ages like so:

```<code>John 25
Jame 49
followed by the rest...
</code>```

答:
Here you go

Working demo

Markup

```<code><div id="people"></div>
</code>```

JS

```<code>var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];

$(function(){
    var $people = $("#people");
    $.each(people, function(){
       $people.append("<div>").append("<span>"+this.name+"</span>"+this.age+"<br />");
    });
});
</code>```

Css

```<code>#people
{
    width:70px;
    text-align:right;
}

#people span
{
    float:left;
}
</code>```

Title: Very basic JSON question

Body:
I have this JSON data:

var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];

How can I loop through all the objects inside people and output their names along with their ages like so:

John 25
Jame 49
followed by the rest...

Body:
Here you go

Working demo

Markup

<div id="people"></div>

JS

var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];

$(function(){
    var $people = $("#people");
    $.each(people, function(){
       $people.append("<div>").append("<span>"+this.name+"</span>"+this.age+"<br />");
    });
});

Css

#people
{
    width:70px;
    text-align:right;
}

#people span
{
    float:left;
}


问:
Voluptuous : give error line in yaml file
I am using voluptuous a lot to validate yaml description files. Often the errors are cumbersome to decipher, especially for regular users.

I am looking for a way to make the error a bit more readable. One way is to identify which line in the YAML file is incrimined.

```<code>from voluptuous import Schema
import yaml
from io import StringIO

Validate = Schema({
    'name': str,
    'age': int,
})

data = """
name: John
age: oops
"""

data = Validate(yaml.load(StringIO(data)))
</code>```

In the above example, I get this error:

```<code>MultipleInvalid: expected int for dictionary value @ data['age']
</code>```

I would rather prefer an error like:

```<code>Error: validation failed on line 2, data.age should be an integer.
</code>```

Is there an elegant way to achieve this?

答:
With the help of flyx I found ruamel.yaml which provide the line and col of a parsed YAML file. So one can manage to get the wanted error with:

```<code>from voluptuous import Schema
from ruamel.yaml import load, RoundTripLoader
from io import StringIO

Validate = Schema({
    'name': {
        'firstname': str,
        'lastname': str
    },
    'age': int,
})

data = """
name:
    firstname: John
    lastname: 12.0
age: 42
"""

class Validate:
    def __init__(self, stream):
        self._yaml = load(stream, Loader=RoundTripLoader)
        return self.validate()

    def validate(self):
        try:
            self.data = Criteria(self._yaml)
        except Invalid as e:
            node = self._yaml
            for key in e.path:
                if (hasattr(node[key], '_yaml_line_col')):
                    node = node[key]
                else:
                    break
            path = '/'.join(e.path)
            print(f"Error: validation failed on line {node._yaml_line_col.line}:{node._yaml_line_col.col} (/{path}): {e.error_message}")
        else:
            return self.data

data = Validate(StringIO(data))
</code>```

With this I get this error message:

```<code>Error: validation failed on line 2:4 (/name): extra keys not allowed
</code>```

Body:
I am using voluptuous a lot to validate yaml description files. Often the errors are cumbersome to decipher, especially for regular users.

I am looking for a way to make the error a bit more readable. One way is to identify which line in the YAML file is incrimined.

from voluptuous import Schema
import yaml
from io import StringIO

Validate = Schema({
    'name': str,
    'age': int,
})

data = """
name: John
age: oops
"""

data = Validate(yaml.load(StringIO(data)))

In the above example, I get this error:

MultipleInvalid: expected int for dictionary value @ data['age']

I would rather prefer an error like:

Error: validation failed on line 2, data.age should be an integer.

Is there an elegant way to achieve this?

Body:
With the help of flyx I found ruamel.yaml which provide the line and col of a parsed YAML file. So one can manage to get the wanted error with:

from voluptuous import Schema
from ruamel.yaml import load, RoundTripLoader
from io import StringIO

Validate = Schema({
    'name': {
        'firstname': str,
        'lastname': str
    },
    'age': int,
})

data = """
name:
    firstname: John
    lastname: 12.0
age: 42
"""

class Validate:
    def __init__(self, stream):
        self._yaml = load(stream, Loader=RoundTripLoader)
        return self.validate()

    def validate(self):
        try:
            self.data = Criteria(self._yaml)
        except Invalid as e:
            node = self._yaml
            for key in e.path:
                if (hasattr(node[key], '_yaml_line_col')):
                    node = node[key]
                else:
                    break
            path = '/'.join(e.path)
            print(f"Error: validation failed on line {node._yaml_line_col.line}:{node._yaml_line_col.col} (/{path}): {e.error_message}")
        else:
            return self.data

data = Validate(StringIO(data))

With this I get this error message:

Error: validation failed on line 2:4 (/name): extra keys not allowed


问:
How to solve the problem with tf.keras.optimizers.Adam(lr=0.001) command not working?
I'm working on Google Colab and when I type

model.compile(optimizer=tf.keras.optimizers.Adam(lr=1e-6), loss=tf.keras.losses.BinaryCrossentropy())

it doesn't work and I get the following error message

Could not interpret optimizer identifier: <keras.optimizer_v2.adam.Adam object at 0x7f21a9b34d50>

答:
Actually I am using

```<code>keras===2.7.0
tensorflow==2.8.0
</code>```

and it worked for me when I used :

```<code>from keras.optimizers import adam_v2
</code>```

Then

```<code>optimizer = adam_v2.Adam(lr=learning_rate)
model.compile(loss="binary_crossentropy", optimizer=optimizer)
</code>```

Instead of using tf.keras.optimizers.Adam

Body:
Actually I am using

keras===2.7.0
tensorflow==2.8.0

and it worked for me when I used :

from keras.optimizers import adam_v2

Then

optimizer = adam_v2.Adam(lr=learning_rate)
model.compile(loss="binary_crossentropy", optimizer=optimizer)

Instead of using tf.keras.optimizers.Adam


问:
Compiler insists rename() function is of type void
I'm trying to write a program capable of renaming files, but I'm encountering a weird issue.
When I write this:

```<code>string oldname, newname;
rename(oldname, newname);
</code>```

Everything works fine. The file is renamed and there are no problems.
But then when I go ahead and try this:

```<code>int result;
result = rename(oldname, newname);
if(result)
//stuff
else
//other stuff
</code>```

The "=" gets a fresh new red underline and I get an error "a value of type "void" cannot be assigned to an entity of type "int"".
I also tried

```<code>if(rename(oldname, newname))
//stuff
</code>```

Then I just get "expression must have bool type (or be convertible to bool)"

Microsoft's documentation says that the rename function returns 0 if successful and nonzero if not successful. After a lot of googling I found countless examples of code that use the second or third snippet without issue, and none of it has helped me understand what might be different in my situation. The language standard is C++17. I can't think of any other relevant details, but just in case, here is a snippet of the actual code with all the "includes":

```<code>#include <windows.h>
#include <stdlib.h>
#include <tchar.h>
#include <vector>
#include <string>
#include <filesystem>
#include <fstream>
#include <time.h>
#include <iostream>
#include <codecvt>
#include <locale>
#include <sstream>
#include <windowsx.h>
#include <Shlobj.h>

using namespace std;
using namespace std::filesystem;
</code>```

```<code>tmp_wstr = oldname + L"\n\nwill be renamed to:\n\n" + newname + L"\n\nWould you like to proceed?";
                        msgboxID = MessageBox(NULL, tmp_wstr.c_str(), L"Renaming...", MB_YESNO | MB_SYSTEMMODAL);
                        switch (msgboxID)
                        {
                        case IDYES:
                            result = rename(oldname, newname);
                            if (result)
                            {
                                error = true;
                                msgboxID = MessageBox(NULL, L"Unable to rename", NULL, MB_OK | MB_SYSTEMMODAL);
                            }
                            else
                                error = false;
                            break;
                        case IDNO:
                            error = true;
                            break;
                        }
</code>```

Here oldname and newname are wstring instead of string, but I have tried using string and the error persists.

答:
You are expecting to call the C standard library function rename() with signature:

```<code>int rename(const char*, const char*);
</code>```

But that function would not be a viable overload for rename(oldname, newname) if oldname and newname are of type std::(w)string, since std::(w)string is not implicitly convertible to const char*.

So, you must be calling a different function named rename(). Since you used:

```<code>using namespace std::filesystem;
</code>```

you are, in fact, calling the following overload of the C++ standard library function std::filesystem::rename() with signature:

```<code>void rename(const std::filesystem::path&, const std::filesystem::path&);
</code>```

which is viable with your arguments, since std::filesystem::path is constructible from std::(w)string.

This function has a void return type, explaining the error messages. As explained in the link, it doesn't return a status code, but instead throws an exception if there is an error.

Body:
I'm trying to write a program capable of renaming files, but I'm encountering a weird issue.
When I write this:

string oldname, newname;
rename(oldname, newname);

Everything works fine. The file is renamed and there are no problems.
But then when I go ahead and try this:

int result;
result = rename(oldname, newname);
if(result)
//stuff
else
//other stuff

The "=" gets a fresh new red underline and I get an error "a value of type "void" cannot be assigned to an entity of type "int"".
I also tried

if(rename(oldname, newname))
//stuff

Then I just get "expression must have bool type (or be convertible to bool)"

Microsoft's documentation says that the rename function returns 0 if successful and nonzero if not successful. After a lot of googling I found countless examples of code that use the second or third snippet without issue, and none of it has helped me understand what might be different in my situation. The language standard is C++17. I can't think of any other relevant details, but just in case, here is a snippet of the actual code with all the "includes":

#include <windows.h>
#include <stdlib.h>
#include <tchar.h>
#include <vector>
#include <string>
#include <filesystem>
#include <fstream>
#include <time.h>
#include <iostream>
#include <codecvt>
#include <locale>
#include <sstream>
#include <windowsx.h>
#include <Shlobj.h>

using namespace std;
using namespace std::filesystem;

tmp_wstr = oldname + L"\n\nwill be renamed to:\n\n" + newname + L"\n\nWould you like to proceed?";
                        msgboxID = MessageBox(NULL, tmp_wstr.c_str(), L"Renaming...", MB_YESNO | MB_SYSTEMMODAL);
                        switch (msgboxID)
                        {
                        case IDYES:
                            result = rename(oldname, newname);
                            if (result)
                            {
                                error = true;
                                msgboxID = MessageBox(NULL, L"Unable to rename", NULL, MB_OK | MB_SYSTEMMODAL);
                            }
                            else
                                error = false;
                            break;
                        case IDNO:
                            error = true;
                            break;
                        }

Here oldname and newname are wstring instead of string, but I have tried using string and the error persists.

Body:
You are expecting to call the C standard library function rename() with signature:

int rename(const char*, const char*);

But that function would not be a viable overload for rename(oldname, newname) if oldname and newname are of type std::(w)string, since std::(w)string is not implicitly convertible to const char*.

So, you must be calling a different function named rename(). Since you used:

using namespace std::filesystem;

you are, in fact, calling the following overload of the C++ standard library function std::filesystem::rename() with signature:

void rename(const std::filesystem::path&, const std::filesystem::path&);

which is viable with your arguments, since std::filesystem::path is constructible from std::(w)string.

This function has a void return type, explaining the error messages. As explained in the link, it doesn't return a status code, but instead throws an exception if there is an error.


问:
Build Gradle Error Could not get unknown property 'compile'
i have react native porject when run android this error showed

Build file 'C:\dev\icnet_final\android\app\build.gradle' line: 213

A problem occurred evaluating project ':app'.

Could not get unknown property 'compile' for configuration container of type org.gradle.api.internal.artifacts.configurations.DefaultConfigurationContainer.

答:
RN 0.64.1
For the dependence, I use

```<code>    classpath('com.android.tools.build:gradle:7.0.0')
</code>```

and for the wrapper

```<code>    distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
</code>```

Body:
RN 0.64.1
For the dependence, I use

    classpath('com.android.tools.build:gradle:7.0.0')

and for the wrapper

    distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip


问:
Get first list index containing sub-string?
For lists, the method list.index(x) returns the index in the list of the first item whose value is x. But if I want to look inside the list items, and not just at the whole items, how do I make the most Pythoninc method for this?

For example, with

```<code>l = ['the cat ate the mouse',
     'the tiger ate the chicken',
     'the horse ate the straw']
</code>```

this function would return 1 provided with the argument tiger.

答:
@kennytm offers a great answer that helped me; to build from theirs a function that allows regex, I wrote:

```<code>def substringindex(inputlist, inputsubstring):
    s = [x for x in inputlist if re.search(inputsubstring, x)]

    if s != []:
        return (inputlist.index(s[0]), s[0])
    return -1
</code>```

This function works exactly like theirs, but supports regex.

Body:
For lists, the method list.index(x) returns the index in the list of the first item whose value is x. But if I want to look inside the list items, and not just at the whole items, how do I make the most Pythoninc method for this?

For example, with

l = ['the cat ate the mouse',
     'the tiger ate the chicken',
     'the horse ate the straw']

this function would return 1 provided with the argument tiger.

Body:
@kennytm offers a great answer that helped me; to build from theirs a function that allows regex, I wrote:

def substringindex(inputlist, inputsubstring):
    s = [x for x in inputlist if re.search(inputsubstring, x)]

    if s != []:
        return (inputlist.index(s[0]), s[0])
    return -1

This function works exactly like theirs, but supports regex.


问:
Ajax code sending form data to PHP server for validation
I'm having a difficult time implementing this AJAX code into my form so that the page doesn't need to reload but will still perform server-side validation. I'm new to AJAX and PHP, so I'm working off a couple form templates, but I have been working on this for hours and I can't figure out why it's not working. Any help would be appreciated.

Here's a portion of the HTML code:

```<code><div id="popupContact">
 <form id="formElem" name="formElem" action="" method="post">
     <fieldset class="step">
          <legend>Personal Details</legend>
          <p>
              <label for="firstname">First Name</label><em>*</em>
              <input id="firstname" name="firstname" />
          </p>
          <p>
              <label for="lastname">Last Name</label><em>*</em>
              <input id="lastname" name="lastname" />
          </p>
          <p>* fields are required</p>
      </fieldset>
      <fieldset class="step">
          <legend>Confirm</legend>
      <p>Before you submit your information, please ensure that each step
    below has this <img src="../img/global/checked.png" alt="Complete" >
    above them. If there is a step that has this
    <img src="../img/global/error.png" alt="Error" >, please click on that tab
    and review the information to ensure it is correct and complete. Thank you.</p>
    <p>
                <label for="human">Please Type: "Something"</label><em>*</em>
                <input id="human" name="human" />
            </p>
            <p class="submit">
                <button id="registerButton" type="submit">Submit</button>
            </p>
        </fieldset>
   </form>
</div>
</code>```

Here's the JAVAScript code:

```<code>$(function() {
var form = $("#formElem");
var fname = $("#firstname");
var lname = $("#lastname");
var address = $("#streetaddress");
var city = $("#city");
var state = $("#state");
var phone = $('#phone');
var email = $('#email');
var insurance = $('#insurance');
var license = $('#license');
var human = $('#human');
$('#registerButton').bind('click',function(){
    if($('#formElem').data('errors')){
        alert('Please correct the errors in the Form');
        return false;
    }
    else {
        var dataString = 'fname='+$('#firstname').val()+'&lname='+$('#lastname').val()+'&address='+$('#streetaddress'.val())+'&city='+$('#city')+'&state='+$('#state').val()+'&phone='+$('#phone').val()+'&email='+$('#email').val()+'&insurance='+$('#insurance').val()+'&license='+$('#license').val()+'&human='+$('#human').val();
        $.ajax({
        type: "POST",
        url: "js/validation.php",
        data: dataString,
        async: false,
        success: function() {
                $('#popupContact').html("<div id='message'></div>");
                $('#message').html("<h2>Inquiry Submitted!</h2>")
                .append("<p>We will be in touch soon.</p>")
                .hide()
                .fadeIn(1500, function() {
                $('#message').append("<img id='checkmark' src='..img/global/check.png' />");
                });
        }
    });
    return false;
    }
 });
</code>```

And here's the PHP code:

```<code><?php
if(isset($_POST['email'])) {
$email_to = "somebody@somewhere.com";
$email_subject = "Inquiry";
function died($error) {
    // your error code can go here
    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.<br /><br />";
    echo $error."<br /><br />";
    echo "Please go back and fix these errors.<br /><br />";
    die();
}

// validation expected data exists
if(!isset($_POST['firstname']) ||
    !isset($_POST['lastname']) ||
    !isset($_POST['email']) ||
    !isset($_POST['phone']) ||
    !isset($_POST['streetaddress']) ||
    !isset($_POST['city']) ||
    !isset($_POST['state']) ||
    !isset($_POST['insurance']) ||
    !isset($_POST['license']) ||
    !isset($_POST['human'])){
    died('We are sorry, but there appears to be a problem with the form you submitted.');
}

$firstname = $_POST['firstname']; // required
$lastname = $_POST['lastname']; // required
$emailfrom = $_POST['email']; // required
$phone = $_POST['phone']; // required
$address = $_POST['streetaddress']; //required
$city = $_POST['city']; //required
$state = $_POST['state']; //required
$insurance = $_POST['insurance']; //required
$license = $_POST['license']; //required
$human = $_POST['human']; //required

$error_message = "";
$email_exp = '/^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/';
if(!preg_match($email_exp,$emailfrom)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}

$email_message = "Form details below.\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($firstname)."\n";
$email_message .= "Last Name: ".clean_string($lastname)."\n";
$email_message .= "Email: ".clean_string($emailfrom)."\n";
$email_message .= "Telephone: ".clean_string($phone)."\n";
$email_message .= "Address: \n".clean_string($address)."\n";
$email_message .= "".clean_string($city).", ";
$email_message .= "".clean_string($state)."\n";
$email_message .= "Have Insurance: ".clean_string($insurance)."\n";
$email_message .= "Have License: ".clean_string($license)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

<!-- include your own success html here -->

Thank you for contacting us. We will be in touch with you very soon.

<?php
}
?>
</code>```

I left out most of the actual validation code part of it, so I know that what you see isn't complete. What I don't understand is that without the AJAX part of this, the form validation works just fine-client and server-side, but when I add the AJAX, something's not connecting. Thanks for your help in advance.

EDIT
Does anyone have a suggestion as to where my code is going wrong?

EDIT
Okay, so if I put js/validation.php in the action="" tag for the form and disable the AJAX part of the code, then validation works just fine, but I'm forwarded to a page that is just blank with the confirmation code. Does this shed any light on the issue? Really, any help is appreciated. I've tried using the tips given in the comments, but for some reason nothing happens. It looks like my page is refreshed, but no confirmation message, or anything. I am totally and completely lost.

答:
You're not far off, but I think I'd attack this in a slightly less aggressive manner.

Starting with the form, I'd just make it a form with an id, and park the submit button outside the form tags.  Why?  Because a button inside a form can have some undesirable effects (like submitting to a magical black hole)  Less code = happy developer.

I'd catch the click on the button with a click handler.  So:

$('#registerButton').click(function(){
    Do your ajax here
});

I'd catch errors initially with front-end validation, because it saves server hits and is more pleasant from a UI standpoint.  It's also faster....and no, it can't be entirely relied on because any competent person can override it, but it's a good first step. My personal favorite is here

In the click action, I'd use the ajax (like you have in your
    example) to submit the form to your script for validation.
    Serialize your form to send it in:

```<code>    $.ajax({
            type: "POST",
            url: "js/validation.php",
            data: $('#formElem').serialize(),
            ...
</code>```

I'd have the script return a json string with a result case
(true/false) and data to support that case (such as an id for
success, and an array of the error cases for false)  So, you're
doing exactly right with your ajax call above, but return the
data
type for my example as json (not dataString) and add a var in
the
parens after success (let's use returndata as an example)  Then, within your
success callback, the returned data would be available as
returndata.field (change field to equal the variable name in the
json string)  If it doesn't work, check the output on
jsonlint.com

In the success of the ajax call from step 4, setup two cases (if/else).  If your result case is true, let them proceed and indicate success as your UI dictates.  If the result case is false, then iterate through the array of error cases to notify the user on each respective question.

You're almost there.  If this is your first experience with jQuery AJAX, I'm really impressed!

Body:
I'm having a difficult time implementing this AJAX code into my form so that the page doesn't need to reload but will still perform server-side validation. I'm new to AJAX and PHP, so I'm working off a couple form templates, but I have been working on this for hours and I can't figure out why it's not working. Any help would be appreciated.

Here's a portion of the HTML code:

 <form id="formElem" name="formElem" action="" method="post">
     <fieldset class="step">
          <legend>Personal Details</legend>

              First Name*
              <input id="firstname" name="firstname" />

              Last Name*
              <input id="lastname" name="lastname" />

* fields are required

      </fieldset>
      <fieldset class="step">
          <legend>Confirm</legend>

Before you submit your information, please ensure that each step
    below has this
    above them. If there is a step that has this
    , please click on that tab
    and review the information to ensure it is correct and complete. Thank you.

                Please Type: "Something"*
                <input id="human" name="human" />

                <button id="registerButton" type="submit">Submit</button>

        </fieldset>
   </form>

Here's the JAVAScript code:

$(function() {
var form = $("#formElem");
var fname = $("#firstname");
var lname = $("#lastname");
var address = $("#streetaddress");
var city = $("#city");
var state = $("#state");
var phone = $('#phone');
var email = $('#email');
var insurance = $('#insurance');
var license = $('#license');
var human = $('#human');
$('#registerButton').bind('click',function(){
    if($('#formElem').data('errors')){
        alert('Please correct the errors in the Form');
        return false;
    }
    else {
        var dataString = 'fname='+$('#firstname').val()+'&lname='+$('#lastname').val()+'&address='+$('#streetaddress'.val())+'&city='+$('#city')+'&state='+$('#state').val()+'&phone='+$('#phone').val()+'&email='+$('#email').val()+'&insurance='+$('#insurance').val()+'&license='+$('#license').val()+'&human='+$('#human').val();
        $.ajax({
        type: "POST",
        url: "js/validation.php",
        data: dataString,
        async: false,
        success: function() {
                $('#popupContact').html("

");
                $('#message').html("
Inquiry Submitted!
")
                .append("
We will be in touch soon.
")
                .hide()
                .fadeIn(1500, function() {
                $('#message').append("");
                });
        }
    });
    return false;
    }
 });

And here's the PHP code:

<?php
if(isset($_POST['email'])) {
$email_to = "somebody@somewhere.com";
$email_subject = "Inquiry";
function died($error) {
    // your error code can go here
    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.

";
    echo $error."

";
    echo "Please go back and fix these errors.

";
    die();
}

// validation expected data exists
if(!isset($_POST['firstname']) ||
    !isset($_POST['lastname']) ||
    !isset($_POST['email']) ||
    !isset($_POST['phone']) ||
    !isset($_POST['streetaddress']) ||
    !isset($_POST['city']) ||
    !isset($_POST['state']) ||
    !isset($_POST['insurance']) ||
    !isset($_POST['license']) ||
    !isset($_POST['human'])){
    died('We are sorry, but there appears to be a problem with the form you submitted.');
}

$firstname = $_POST['firstname']; // required
$lastname = $_POST['lastname']; // required
$emailfrom = $_POST['email']; // required
$phone = $_POST['phone']; // required
$address = $_POST['streetaddress']; //required
$city = $_POST['city']; //required
$state = $_POST['state']; //required
$insurance = $_POST['insurance']; //required
$license = $_POST['license']; //required
$human = $_POST['human']; //required

$error_message = "";
$email_exp = '/^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/';
if(!preg_match($email_exp,$emailfrom)) {
$error_message .= 'The Email Address you entered does not appear to be valid.
';
}

$email_message = "Form details below.\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($firstname)."\n";
$email_message .= "Last Name: ".clean_string($lastname)."\n";
$email_message .= "Email: ".clean_string($emailfrom)."\n";
$email_message .= "Telephone: ".clean_string($phone)."\n";
$email_message .= "Address: \n".clean_string($address)."\n";
$email_message .= "".clean_string($city).", ";
$email_message .= "".clean_string($state)."\n";
$email_message .= "Have Insurance: ".clean_string($insurance)."\n";
$email_message .= "Have License: ".clean_string($license)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

Thank you for contacting us. We will be in touch with you very soon.

<?php
}
?>

I left out most of the actual validation code part of it, so I know that what you see isn't complete. What I don't understand is that without the AJAX part of this, the form validation works just fine-client and server-side, but when I add the AJAX, something's not connecting. Thanks for your help in advance.

EDIT
Does anyone have a suggestion as to where my code is going wrong?

EDIT
Okay, so if I put js/validation.php in the action="" tag for the form and disable the AJAX part of the code, then validation works just fine, but I'm forwarded to a page that is just blank with the confirmation code. Does this shed any light on the issue? Really, any help is appreciated. I've tried using the tips given in the comments, but for some reason nothing happens. It looks like my page is refreshed, but no confirmation message, or anything. I am totally and completely lost.

Body:
You're not far off, but I think I'd attack this in a slightly less aggressive manner.

Starting with the form, I'd just make it a form with an id, and park the submit button outside the form tags.  Why?  Because a button inside a form can have some undesirable effects (like submitting to a magical black hole)  Less code = happy developer.

I'd catch the click on the button with a click handler.  So:

$('#registerButton').click(function(){
    Do your ajax here
});

I'd catch errors initially with front-end validation, because it saves server hits and is more pleasant from a UI standpoint.  It's also faster....and no, it can't be entirely relied on because any competent person can override it, but it's a good first step. My personal favorite is here

In the click action, I'd use the ajax (like you have in your
    example) to submit the form to your script for validation.
    Serialize your form to send it in:

    $.ajax({
            type: "POST",
            url: "js/validation.php",
            data: $('#formElem').serialize(),
            ...

I'd have the script return a json string with a result case
(true/false) and data to support that case (such as an id for
success, and an array of the error cases for false)  So, you're
doing exactly right with your ajax call above, but return the
data
type for my example as json (not dataString) and add a var in
the
parens after success (let's use returndata as an example)  Then, within your
success callback, the returned data would be available as
returndata.field (change field to equal the variable name in the
json string)  If it doesn't work, check the output on
jsonlint.com

In the success of the ajax call from step 4, setup two cases (if/else).  If your result case is true, let them proceed and indicate success as your UI dictates.  If the result case is false, then iterate through the array of error cases to notify the user on each respective question.

You're almost there.  If this is your first experience with jQuery AJAX, I'm really impressed!