问:
Longest Increasing Subsequence Problem with Javascript
I generated this code for Longest Increasing Subsequence:

Input: nums = [10,9,2,5,3,7,101,18]

Output: 4

Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

var lengthOfLIS = function(nums) {
  if (nums.length === 0) return 0;
  let result = 1;
  const LISEndAt = new Array(nums.length).fill(1);

  for (let i = 1; i < nums.length; i++) {
    LISEndAt[i] = Math.max(1,
      ...LISEndAt.slice(0, i).map((item, j) => {
        return nums[i] > nums[j] ? item + 1 : 0
      }));

    result = Math.max(LISEndAt[i], result);
  }

  return result;
}

let nums = [7,7,7,7,7,7,7];

console.log(lengthOfLIS(nums));```
</div>
</div>
</p>
<p>Can some one help me to understand this line:</p>
```LISEndAt[i] = Math.max(1,...LISEndAt.slice(0, i).map((item, j)
```

What is significance of three dots and as we know map generates key value pairs, what is map doing along with slice?

答:
Clarification

Before I can explain what the line you're asking about does, there are a few things to clear up.

...

... is the spread syntax which expands the given iterable (array indices, object key-value pairs, etc). Here's an example where an existing array is used to create a new array with more elements:

const first = [1, 2, 3];
const second = [...first, 4, 5, 6];
console.log(second);
/* returns [1, 2, 3, 4, 5, 6] */```
</div>
</div>
</p>
<p>In your example, it is being used to provide multiple parameters to the <code>Math.max()</code> function. Here's an example of that:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const candidates = [1, 5, 6, 2, 4];
const largest = Math.max(...candidates);
console.log(largest);
/* returns 6 */</code>```

Array#map

Array#map doesn't create key/value pairs. Instead, it creates a new array by performing an action on each element in the original array. Here's an example where a new array is created by doubling each item in the original array:

const original = [1, 2, 3];
const doubled = original.map(i => i * 2);
console.log(doubled);
/* returns [2, 4, 6] */```
</div>
</div>
</p>
<p>You can also access the index of each item in the original array:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const alphabet = ['A', 'B', 'C'];
const positions = alphabet.map((letter, index) => index);
console.log(positions);
/* returns [0, 1, 2] */</code>```

Array#slice

Array#slice creates a new array that is a subset of the original array from the provided starting index until (but not including) the provided end index. Here's an example where a new array is created from the first three items of an existing array:

const superset = [1, 2, 3, 4, 5, 6];
const subset = superset.slice(0, 3);
console.log(subset);
/* returns [1, 2, 3] */```
</div>
</div>
</p>
<h1>Your question</h1>
<p>With all that in mind, let's take a look at the loop containing your line:</p>
```const nums = [10, 9, 2, 5, 3, 7, 101, 18];
const LISEndAt = new Array(nums.length).fill(1);
/* [1, 1, 1, 1, 1, 1, 1, 1] */

for (let i = 1; i < nums.length; i++) {
    LISEndAt[i] = Math.max(1,
        ...LISEndAt.slice(0, i).map((item, j) => {
            return nums[i] > nums[j] ? item + 1 : 0;
        }));
}
```
<p><code>LISEndAt</code> is being updated with each iteration of your for-loop. Each time, the next index is calculated as:</p>
<ul>
<li>The max of <code>1</code> and any element in:</li>
<li>The subset of <code>LISEndAt</code> from 0 to the current iteration of the for-loop as modified by:</li>
<li>Some comparison in <code>map</code> which returns either:</li>
<li>The item at the current index being modified plus one or:</li>
<li>Zero.</li>
</ul>
<p>If we add some logging to your loop, you can see this happen in sequence:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const nums = [10, 9, 2, 5, 3, 7, 101, 18];
const LISEndAt = new Array(nums.length).fill(1);
console.log(`original: ${JSON.stringify(LISEndAt)}`);

for (let i = 1; i < nums.length; i++) {
  const subset = LISEndAt.slice(0, i);
  console.log(`sliced: [${subset.join(', ')}]`);
  const someArray = subset.map((item, j) => {
    console.log(`comparing ${nums[i]} > ${nums[j]} ? ${item + 1} : 0`);
    return nums[i] > nums[j] ? item + 1 : 0;
  });
  console.log(`taking max of 1, ${JSON.stringify(...someArray)}`);
  LISEndAt[i] = Math.max(1, ...someArray);
  console.log(`iteration ${i}: ${JSON.stringify(LISEndAt)}`);
}</code>```

Body:
I generated this code for Longest Increasing Subsequence:

Input: nums = [10,9,2,5,3,7,101,18]

Output: 4

Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

var lengthOfLIS = function(nums) {
  if (nums.length === 0) return 0;
  let result = 1;
  const LISEndAt = new Array(nums.length).fill(1);

  for (let i = 1; i < nums.length; i++) {
    LISEndAt[i] = Math.max(1,
      ...LISEndAt.slice(0, i).map((item, j) => {
        return nums[i] > nums[j] ? item + 1 : 0
      }));

    result = Math.max(LISEndAt[i], result);
  }

  return result;
}

let nums = [7,7,7,7,7,7,7];

console.log(lengthOfLIS(nums));

Can some one help me to understand this line:

LISEndAt[i] = Math.max(1,...LISEndAt.slice(0, i).map((item, j)

What is significance of three dots and as we know map generates key value pairs, what is map doing along with slice?

Body:
Clarification

Before I can explain what the line you're asking about does, there are a few things to clear up.

...

... is the spread syntax which expands the given iterable (array indices, object key-value pairs, etc). Here's an example where an existing array is used to create a new array with more elements:

const first = [1, 2, 3];
const second = [...first, 4, 5, 6];
console.log(second);
/* returns [1, 2, 3, 4, 5, 6] */

In your example, it is being used to provide multiple parameters to the Math.max() function. Here's an example of that:

const candidates = [1, 5, 6, 2, 4];
const largest = Math.max(...candidates);
console.log(largest);
/* returns 6 */

Array#map

Array#map doesn't create key/value pairs. Instead, it creates a new array by performing an action on each element in the original array. Here's an example where a new array is created by doubling each item in the original array:

const original = [1, 2, 3];
const doubled = original.map(i => i * 2);
console.log(doubled);
/* returns [2, 4, 6] */

You can also access the index of each item in the original array:

const alphabet = ['A', 'B', 'C'];
const positions = alphabet.map((letter, index) => index);
console.log(positions);
/* returns [0, 1, 2] */

Array#slice

Array#slice creates a new array that is a subset of the original array from the provided starting index until (but not including) the provided end index. Here's an example where a new array is created from the first three items of an existing array:

const superset = [1, 2, 3, 4, 5, 6];
const subset = superset.slice(0, 3);
console.log(subset);
/* returns [1, 2, 3] */

Your question

With all that in mind, let's take a look at the loop containing your line:

const nums = [10, 9, 2, 5, 3, 7, 101, 18];
const LISEndAt = new Array(nums.length).fill(1);
/* [1, 1, 1, 1, 1, 1, 1, 1] */

for (let i = 1; i < nums.length; i++) {
    LISEndAt[i] = Math.max(1,
        ...LISEndAt.slice(0, i).map((item, j) => {
            return nums[i] > nums[j] ? item + 1 : 0;
        }));
}

LISEndAt is being updated with each iteration of your for-loop. Each time, the next index is calculated as:

The max of 1 and any element in:

The subset of LISEndAt from 0 to the current iteration of the for-loop as modified by:

Some comparison in map which returns either:

The item at the current index being modified plus one or:

Zero.

If we add some logging to your loop, you can see this happen in sequence:

const nums = [10, 9, 2, 5, 3, 7, 101, 18];
const LISEndAt = new Array(nums.length).fill(1);
console.log(`original: ${JSON.stringify(LISEndAt)}`);

for (let i = 1; i < nums.length; i++) {
  const subset = LISEndAt.slice(0, i);
  console.log(`sliced: [${subset.join(', ')}]`);
  const someArray = subset.map((item, j) => {
    console.log(`comparing ${nums[i]} > ${nums[j]} ? ${item + 1} : 0`);
    return nums[i] > nums[j] ? item + 1 : 0;
  });
  console.log(`taking max of 1, ${JSON.stringify(...someArray)}`);
  LISEndAt[i] = Math.max(1, ...someArray);
  console.log(`iteration ${i}: ${JSON.stringify(LISEndAt)}`);
}


来源: stackexchange

问:
iOS 15.3 has broken SwiftUI layout
I just upgraded my phone from 15.x (I think 15.2) to 15.3, and my SwiftUI layout is broken, seems to be a List border issue.

Here is the code, followed by a screen shot of normal behavior (13.x to 15.x) and then what I see in 15.3

```<code>struct SessionView: View {
    var title: String
    var panel: Int
    var index: Int
    var range: [Int] = [0,2,3,4]

    @EnvironmentObject var state: MainViewModel
    @EnvironmentObject var content: ContentViewModel

    @ViewBuilder
    var body: some View {
        VStack() {
            // -- Header
            HStack() {
                Text(" ")
                Image(self.state.panelIcon(panel: panel)).resizable().frame(width: 12.0, height: 12.0)
                Text(title)
                Spacer()
            }.padding(EdgeInsets(top: 8, leading: 0, bottom: 8, trailing: 0))
            .background(Color(red: 0.9, green: 0.9, blue: 0.9))
            .onTapGesture {
                showDetailDialog()
            }

            // -- Rows
            List {
                ForEach(0..<5) { i in
                    if i != 1 { // Skip IP address
                        HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: -4, content: {
                            Text("\(state.keyValues[i+index]!.key)").frame(minWidth: 120, maxHeight: 20, alignment: .leading)
                                .font(Font.system(size: 15, design: .default)).padding(0)
                            Text("\(state.keyValues[i+index]!.value)").frame(maxHeight: 20, alignment: .leading)
                                .font(Font.system(size: 15, design: .default)).padding(0)
                        }).frame(height: 10)
                    }
                }
            }.environment(\.defaultMinListRowHeight, 10)
            .frame(height: 4*20+20)
            .listStyle(DefaultListStyle()).environment(\.defaultMinListRowHeight, 8).onAppear {
                UITableView.appearance().isScrollEnabled = false
            }.layoutPriority(1)
        }.overlay(
            RoundedRectangle(cornerRadius: 10)
                .stroke(Color(red: 0.8, green: 0.8, blue: 0.8), lineWidth: 1.25)
        ).background(Color.white)

    }
    .
    .
    .
}
</code>```

答:
I had this problem too. However, it is not a border issue. When you updated your iPhone, the default list style for SwiftUI changed. The old default style is now called PlainListStyle(). Use that instead to get the old look back.

```<code>List {

}.listStyle(PlainListStyle())
</code>```

ContentLicense: CC BY-SA 4.0

Title: iOS 15.3 has broken SwiftUI layout

Body:
I just upgraded my phone from 15.x (I think 15.2) to 15.3, and my SwiftUI layout is broken, seems to be a List border issue.

Here is the code, followed by a screen shot of normal behavior (13.x to 15.x) and then what I see in 15.3

struct SessionView: View {
    var title: String
    var panel: Int
    var index: Int
    var range: [Int] = [0,2,3,4]

    @EnvironmentObject var state: MainViewModel
    @EnvironmentObject var content: ContentViewModel

    @ViewBuilder
    var body: some View {
        VStack() {
            // -- Header
            HStack() {
                Text(" ")
                Image(self.state.panelIcon(panel: panel)).resizable().frame(width: 12.0, height: 12.0)
                Text(title)
                Spacer()
            }.padding(EdgeInsets(top: 8, leading: 0, bottom: 8, trailing: 0))
            .background(Color(red: 0.9, green: 0.9, blue: 0.9))
            .onTapGesture {
                showDetailDialog()
            }

            // -- Rows
            List {
                ForEach(0..<5) { i in
                    if i != 1 { // Skip IP address
                        HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: -4, content: {
                            Text("\(state.keyValues[i+index]!.key)").frame(minWidth: 120, maxHeight: 20, alignment: .leading)
                                .font(Font.system(size: 15, design: .default)).padding(0)
                            Text("\(state.keyValues[i+index]!.value)").frame(maxHeight: 20, alignment: .leading)
                                .font(Font.system(size: 15, design: .default)).padding(0)
                        }).frame(height: 10)
                    }
                }
            }.environment(\.defaultMinListRowHeight, 10)
            .frame(height: 4*20+20)
            .listStyle(DefaultListStyle()).environment(\.defaultMinListRowHeight, 8).onAppear {
                UITableView.appearance().isScrollEnabled = false
            }.layoutPriority(1)
        }.overlay(
            RoundedRectangle(cornerRadius: 10)
                .stroke(Color(red: 0.8, green: 0.8, blue: 0.8), lineWidth: 1.25)
        ).background(Color.white)

    }
    .
    .
    .
}

Body:
I had this problem too. However, it is not a border issue. When you updated your iPhone, the default list style for SwiftUI changed. The old default style is now called PlainListStyle(). Use that instead to get the old look back.

List {

}.listStyle(PlainListStyle())


问:
Sql Query To get data
i have a table called DrTimings ,in which Doctors time for each day is this.

```<code>DrID(int identity)  StartTime(DateTime)             EndTime(DateTime)
    1                3/31/2009 8:00:00 AM   3/31/2009 10:30:00 AM
</code>```

I have another table called TimeList which contain 3 fields

```<code>SlotID   SlotStartTime(varchar)   SlotEndTime(varchar)
1         8:00AM                      8:15AM
2         8:15AM                      8:30AM
3         8:30AM                     8:45AM
</code>```

and goes on till 7:00PM

I have another table DrDutyDetails in which DrTiming is set for whole month like this.

```<code>DrID    StartTime             EndTime              DateOfAllocation
1       4/5/2009 8:00:00 AM   4/5/2009 9:30:00 AM   4/5/2009 12:00:00 AM
2       4/12/2009 8:00:00 AM  4/12/2009 9:30:00 AM  4/12/2009 12:00:00 AM
likewise
</code>```

I have another table called AppointmentSchedule which gets filled when patient requests appointment

```<code>AppointmentID    SlotID  AppointmentDate
1                1        4/5/2009
2                3        4/12/2009
</code>```

i have a appointment schedule form in which i selects DrID and Appointment date.Then slots corresponding to date that has not been in Appointmentschedule,but slots should be in between starttime and endtime that in DrTimings and in TimeSlots should get filled in a dropdownlist.I need a query to implement this.
for eg:If Patient enters '4/5/2009' Then slots other than 1 and 3 but biw DrTimings i want to get.

Similarly i want to search by time.Means if Patient enters any time b/w DrTimings for eg:8:30AM,Then available first date has to be displayed in textbox

答:
You are going to need to look at doing some Casting/COnverting of date values.  This MSDN article gives you a bit of information on what you need to work with.

There are a number of ways that you can do this, but ideally you can do something like CONVERT(VARCHAR(50), StartTime) to get the fully formatted time.  Then, since you know that the ending format of that is 08:00AM, you can do a RIGHT(CONVERT(VARCHAR(50), StartTime), 7), which will get you just the time value.

Now, with that you know how to manipulate the date into parts, you can from here, do the various things needed to query your items.

For comparison sake, I would be storing the "TimeList" data as DateTime values, that way you can use standard time comparisons to actually allow you to use functions such as "Between" and similar.  You could store them as 1/1/1900 08:00AM or similar.  But this would require a data model change.  If you want some helpful SQL for this type of thing, here is a great article on "Essential SQL Server Date, Time, and DateTime Functions".

ContentLicense: CC BY-SA 3.0

Title: Sql Query To get data

Body:
i have a table called DrTimings ,in which Doctors time for each day is this.

DrID(int identity)  StartTime(DateTime)             EndTime(DateTime)
    1                3/31/2009 8:00:00 AM   3/31/2009 10:30:00 AM

I have another table called TimeList which contain 3 fields

SlotID   SlotStartTime(varchar)   SlotEndTime(varchar)
1         8:00AM                      8:15AM
2         8:15AM                      8:30AM
3         8:30AM                     8:45AM

and goes on till 7:00PM

I have another table DrDutyDetails in which DrTiming is set for whole month like this.

DrID    StartTime             EndTime              DateOfAllocation
1       4/5/2009 8:00:00 AM   4/5/2009 9:30:00 AM   4/5/2009 12:00:00 AM
2       4/12/2009 8:00:00 AM  4/12/2009 9:30:00 AM  4/12/2009 12:00:00 AM
likewise

I have another table called AppointmentSchedule which gets filled when patient requests appointment

AppointmentID    SlotID  AppointmentDate
1                1        4/5/2009
2                3        4/12/2009

i have a appointment schedule form in which i selects DrID and Appointment date.Then slots corresponding to date that has not been in Appointmentschedule,but slots should be in between starttime and endtime that in DrTimings and in TimeSlots should get filled in a dropdownlist.I need a query to implement this.
for eg:If Patient enters '4/5/2009' Then slots other than 1 and 3 but biw DrTimings i want to get.

Similarly i want to search by time.Means if Patient enters any time b/w DrTimings for eg:8:30AM,Then available first date has to be displayed in textbox

OwnerDisplayName: Mitchel Sellers

ContentLicense: CC BY-SA 2.5


问:
Replace a set of html br elements with another in jQuery -- parsing HTML with jQuery
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

```<code><br><br clear=all><br>
</code>```

with

```<code><br />
</code>```

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

答:
You can play with selector attributes, not inside the onload but inside the jquery ready (http://api.jquery.com/ready/)

$('br[clear=all]').remove();

more details on selector attribute:http://api.jquery.com/attribute-equals-selector/

Body:
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

with

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!


问:
How to target parents from elements with a class?
So, .search-chat-search-btn > form { } targets the form "inside" the element with class .search-chat-search-btn, but can I make it go the other way? As in, target the form that is outside .search-chat-search-btn?

```<code><form>
    <button class="search-chat-search-btn"></button>
</form>
</code>```

Apparently this is suppose to work, but it doesn't. Target every form that has a button.

```<code>form:has(> button) {
    display: inline;
    border: red 1px solid;
}
</code>```

https://developer.mozilla.org/en-US/docs/Web/CSS/:has

(but then I just realised it's only supported in Safari, development version?)

答: You can't target a parent element in CSS. It's not possible (at least not yet). Also concerning :has, no major browser supports it yet.

Body:
So, .search-chat-search-btn > form { } targets the form "inside" the element with class .search-chat-search-btn, but can I make it go the other way? As in, target the form that is outside .search-chat-search-btn?

<form>
    <button class="search-chat-search-btn"></button>
</form>

Apparently this is suppose to work, but it doesn't. Target every form that has a button.

form:has(> button) {
    display: inline;
    border: red 1px solid;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/:has

(but then I just realised it's only supported in Safari, development version?)


问:
DNS_PROBE_FINISHED_NXDOMAIN – Set up a WordPress development environment using Homebrew on macOS
I have followed https://noisysocks.com/2021/11/12/set-up-a-wordpress-development-environment-using-homebrew-on-macos/ tutorial to setup WordPress development environment using Homebrew on mac os 12. Before I’ve been using only MAMP.

The problem is at the final

You should now be able to browse to http://wp-build.test/wp-admin and
log in. The username is admin and the password is password.

when I’m launching http://wp-build.test/wp-admin

```<code> This site can’t be reached
Check if there is a typo in wp-build.test.
    DNS_PROBE_FINISHED_NXDOMAIN
</code>```

httpd.conf:

```#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/access_log"
# with ServerRoot set to "/usr/local/apache2" will be interpreted by the
# server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log"
# will be interpreted as '/logs/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/usr/local/opt/httpd"

#
# Mutex: Allows you to set the mutex mechanism and mutex file directory
# for individual mutexes, or change the global defaults
#
# Uncomment and change the directory if mutexes are file-based and the default
# mutex file directory is not on a local disk or is not appropriate for some
# other reason.
#
# Mutex default:/usr/local/var/run/httpd

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 0.0.0.0:80
LoadModule php_module /usr/local/opt/php/lib/httpd/modules/libphp.so
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
#LoadModule mpm_event_module lib/httpd/modules/mod_mpm_event.so
LoadModule mpm_prefork_module lib/httpd/modules/mod_mpm_prefork.so
#LoadModule mpm_worker_module lib/httpd/modules/mod_mpm_worker.so
LoadModule authn_file_module lib/httpd/modules/mod_authn_file.so
#LoadModule authn_dbm_module lib/httpd/modules/mod_authn_dbm.so
#LoadModule authn_anon_module lib/httpd/modules/mod_authn_anon.so
#LoadModule authn_dbd_module lib/httpd/modules/mod_authn_dbd.so
#LoadModule authn_socache_module lib/httpd/modules/mod_authn_socache.so
LoadModule authn_core_module lib/httpd/modules/mod_authn_core.so
LoadModule authz_host_module lib/httpd/modules/mod_authz_host.so
LoadModule authz_groupfile_module lib/httpd/modules/mod_authz_groupfile.so
LoadModule authz_user_module lib/httpd/modules/mod_authz_user.so
#LoadModule authz_dbm_module lib/httpd/modules/mod_authz_dbm.so
#LoadModule authz_owner_module lib/httpd/modules/mod_authz_owner.so
#LoadModule authz_dbd_module lib/httpd/modules/mod_authz_dbd.so
LoadModule authz_core_module lib/httpd/modules/mod_authz_core.so
#LoadModule authnz_fcgi_module lib/httpd/modules/mod_authnz_fcgi.so
LoadModule access_compat_module lib/httpd/modules/mod_access_compat.so
LoadModule auth_basic_module lib/httpd/modules/mod_auth_basic.so
#LoadModule auth_form_module lib/httpd/modules/mod_auth_form.so
#LoadModule auth_digest_module lib/httpd/modules/mod_auth_digest.so
#LoadModule allowmethods_module lib/httpd/modules/mod_allowmethods.so
#LoadModule file_cache_module lib/httpd/modules/mod_file_cache.so
#LoadModule cache_module lib/httpd/modules/mod_cache.so
#LoadModule cache_disk_module lib/httpd/modules/mod_cache_disk.so
#LoadModule cache_socache_module lib/httpd/modules/mod_cache_socache.so
#LoadModule socache_shmcb_module lib/httpd/modules/mod_socache_shmcb.so
#LoadModule socache_dbm_module lib/httpd/modules/mod_socache_dbm.so
#LoadModule socache_memcache_module lib/httpd/modules/mod_socache_memcache.so
#LoadModule socache_redis_module lib/httpd/modules/mod_socache_redis.so
#LoadModule watchdog_module lib/httpd/modules/mod_watchdog.so
#LoadModule macro_module lib/httpd/modules/mod_macro.so
#LoadModule dbd_module lib/httpd/modules/mod_dbd.so
#LoadModule dumpio_module lib/httpd/modules/mod_dumpio.so
#LoadModule echo_module lib/httpd/modules/mod_echo.so
#LoadModule buffer_module lib/httpd/modules/mod_buffer.so
#LoadModule data_module lib/httpd/modules/mod_data.so
#LoadModule ratelimit_module lib/httpd/modules/mod_ratelimit.so
LoadModule reqtimeout_module lib/httpd/modules/mod_reqtimeout.so
#LoadModule ext_filter_module lib/httpd/modules/mod_ext_filter.so
#LoadModule request_module lib/httpd/modules/mod_request.so
#LoadModule include_module lib/httpd/modules/mod_include.so
LoadModule filter_module lib/httpd/modules/mod_filter.so
#LoadModule reflector_module lib/httpd/modules/mod_reflector.so
#LoadModule substitute_module lib/httpd/modules/mod_substitute.so
#LoadModule sed_module lib/httpd/modules/mod_sed.so
#LoadModule charset_lite_module lib/httpd/modules/mod_charset_lite.so
#LoadModule deflate_module lib/httpd/modules/mod_deflate.so
#LoadModule xml2enc_module lib/httpd/modules/mod_xml2enc.so
#LoadModule proxy_html_module lib/httpd/modules/mod_proxy_html.so
#LoadModule brotli_module lib/httpd/modules/mod_brotli.so
LoadModule mime_module lib/httpd/modules/mod_mime.so
LoadModule log_config_module lib/httpd/modules/mod_log_config.so
#LoadModule log_debug_module lib/httpd/modules/mod_log_debug.so
#LoadModule log_forensic_module lib/httpd/modules/mod_log_forensic.so
#LoadModule logio_module lib/httpd/modules/mod_logio.so
LoadModule env_module lib/httpd/modules/mod_env.so
#LoadModule mime_magic_module lib/httpd/modules/mod_mime_magic.so
#LoadModule expires_module lib/httpd/modules/mod_expires.so
LoadModule headers_module lib/httpd/modules/mod_headers.so
#LoadModule usertrack_module lib/httpd/modules/mod_usertrack.so
#LoadModule unique_id_module lib/httpd/modules/mod_unique_id.so
LoadModule setenvif_module lib/httpd/modules/mod_setenvif.so
LoadModule version_module lib/httpd/modules/mod_version.so
#LoadModule remoteip_module lib/httpd/modules/mod_remoteip.so
#LoadModule proxy_module lib/httpd/modules/mod_proxy.so
#LoadModule proxy_connect_module lib/httpd/modules/mod_proxy_connect.so
#LoadModule proxy_ftp_module lib/httpd/modules/mod_proxy_ftp.so
#LoadModule proxy_http_module lib/httpd/modules/mod_proxy_http.so
#LoadModule proxy_fcgi_module lib/httpd/modules/mod_proxy_fcgi.so
#LoadModule proxy_scgi_module lib/httpd/modules/mod_proxy_scgi.so
#LoadModule proxy_uwsgi_module lib/httpd/modules/mod_proxy_uwsgi.so
#LoadModule proxy_fdpass_module lib/httpd/modules/mod_proxy_fdpass.so
#LoadModule proxy_wstunnel_module lib/httpd/modules/mod_proxy_wstunnel.so
#LoadModule proxy_ajp_module lib/httpd/modules/mod_proxy_ajp.so
#LoadModule proxy_balancer_module lib/httpd/modules/mod_proxy_balancer.so
#LoadModule proxy_express_module lib/httpd/modules/mod_proxy_express.so
#LoadModule proxy_hcheck_module lib/httpd/modules/mod_proxy_hcheck.so
#LoadModule session_module lib/httpd/modules/mod_session.so
#LoadModule session_cookie_module lib/httpd/modules/mod_session_cookie.so
#LoadModule session_crypto_module lib/httpd/modules/mod_session_crypto.so
#LoadModule session_dbd_module lib/httpd/modules/mod_session_dbd.so
#LoadModule slotmem_shm_module lib/httpd/modules/mod_slotmem_shm.so
#LoadModule slotmem_plain_module lib/httpd/modules/mod_slotmem_plain.so
#LoadModule ssl_module lib/httpd/modules/mod_ssl.so
#LoadModule dialup_module lib/httpd/modules/mod_dialup.so
#LoadModule http2_module lib/httpd/modules/mod_http2.so
#LoadModule lbmethod_byrequests_module lib/httpd/modules/mod_lbmethod_byrequests.so
#LoadModule lbmethod_bytraffic_module lib/httpd/modules/mod_lbmethod_bytraffic.so
#LoadModule lbmethod_bybusyness_module lib/httpd/modules/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_heartbeat_module lib/httpd/modules/mod_lbmethod_heartbeat.so
LoadModule unixd_module lib/httpd/modules/mod_unixd.so
#LoadModule heartbeat_module lib/httpd/modules/mod_heartbeat.so
#LoadModule heartmonitor_module lib/httpd/modules/mod_heartmonitor.so
#LoadModule dav_module lib/httpd/modules/mod_dav.so
LoadModule status_module lib/httpd/modules/mod_status.so
LoadModule autoindex_module lib/httpd/modules/mod_autoindex.so
#LoadModule asis_module lib/httpd/modules/mod_asis.so
#LoadModule info_module lib/httpd/modules/mod_info.so
#LoadModule suexec_module lib/httpd/modules/mod_suexec.so
<IfModule !mpm_prefork_module>
    #LoadModule cgid_module lib/httpd/modules/mod_cgid.so
</IfModule>
<IfModule mpm_prefork_module>
    #LoadModule cgi_module lib/httpd/modules/mod_cgi.so
</IfModule>
#LoadModule dav_fs_module lib/httpd/modules/mod_dav_fs.so
#LoadModule dav_lock_module lib/httpd/modules/mod_dav_lock.so
#LoadModule vhost_alias_module lib/httpd/modules/mod_vhost_alias.so
#LoadModule negotiation_module lib/httpd/modules/mod_negotiation.so
LoadModule dir_module lib/httpd/modules/mod_dir.so
#LoadModule actions_module lib/httpd/modules/mod_actions.so
#LoadModule speling_module lib/httpd/modules/mod_speling.so
#LoadModule userdir_module lib/httpd/modules/mod_userdir.so
LoadModule alias_module lib/httpd/modules/mod_alias.so
LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so

<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User trzcinski
Group staff

</IfModule>

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
ServerAdmin you@example.com

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
ServerName localhost

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
    AllowOverride none
    Require all denied
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot /Users/trzcinski/Sites
<Directory "/Users/trzcinski/Sites">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.php index.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>
<FilesMatch \.php$>
    SetHandler application/x-httpd-php
</FilesMatch>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "/usr/local/var/log/httpd/error_log"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    CustomLog "/usr/local/var/log/httpd/access_log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    #CustomLog "/usr/local/var/log/httpd/access_log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to
    # exist in your server's namespace, but do not anymore. The client
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts.
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "/usr/local/var/www/cgi-bin/"

</IfModule>

<IfModule cgid_module>
    #
    # ScriptSock: On threaded servers, designate the path to the UNIX
    # socket used to communicate with the CGI daemon of mod_cgid.
    #
    #Scriptsock cgisock
</IfModule>

#
# "/usr/local/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/usr/local/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule headers_module>
    #
    # Avoid passing HTTP_PROXY environment to CGI's on this or any proxied
    # backend servers which have lingering "httpoxy" defects.
    # 'Proxy' request header is undefined by the IETF, not listed by IANA
    #
    RequestHeader unset Proxy early
</IfModule>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /usr/local/etc/httpd/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    #AddType text/html .shtml
    #AddOutputFilter INCLUDES .shtml
</IfModule>

#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type.  The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile /usr/local/etc/httpd/magic

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# MaxRanges: Maximum number of Ranges in a request before
# returning the entire resource, or one of the special
# values 'default', 'none' or 'unlimited'.
# Default setting is to accept 200 Ranges.
#MaxRanges unlimited

#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
#EnableSendfile on

# Supplemental configuration
#
# The configuration files in the /usr/local/etc/httpd/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.

# Server-pool management (MPM specific)
#Include /usr/local/etc/httpd/extra/httpd-mpm.conf

# Multi-language error messages
#Include /usr/local/etc/httpd/extra/httpd-multilang-errordoc.conf

# Fancy directory listings
#Include /usr/local/etc/httpd/extra/httpd-autoindex.conf

# Language settings
#Include /usr/local/etc/httpd/extra/httpd-languages.conf

# User home directories
#Include /usr/local/etc/httpd/extra/httpd-userdir.conf

# Real-time info on requests and configuration
#Include /usr/local/etc/httpd/extra/httpd-info.conf

# Virtual hosts
Include /usr/local/etc/httpd/extra/httpd-vhosts.conf

# Local access to the Apache HTTP Server Manual
#Include /usr/local/etc/httpd/extra/httpd-manual.conf

# Distributed authoring and versioning (WebDAV)
#Include /usr/local/etc/httpd/extra/httpd-dav.conf

# Various default settings
#Include /usr/local/etc/httpd/extra/httpd-default.conf

# Configure mod_proxy_html to understand HTML4/XHTML1
<IfModule proxy_html_module>
Include /usr/local/etc/httpd/extra/proxy-html.conf
</IfModule>

# Secure (SSL/TLS) connections
#Include /usr/local/etc/httpd/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
#       starting without SSL on platforms with no /dev/random equivalent
#       but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
```
<p>httpd-vhosts.conf:</p>
```# Virtual Hosts
#
# Required modules: mod_log_config

# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
Include /usr/local/etc/httpd/vhosts/*.conf
```
<p>wp-build.test.conf:</p>
```<Directory "/Users/trzcinski/Sites/wordpress-develop/build">
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

<VirtualHost *:80>
    ServerName wp-build.test
    DocumentRoot "/Users/trzcinski/Sites/wordpress-develop/build"
    ErrorLog "/usr/local/var/log/httpd/wp-build.test-error_log"
    CustomLog "/usr/local/var/log/httpd/wp-build.test-access_log" common
</VirtualHost>
```

In step 3 he didn't mention where should I install wp-cli and others. So I assumed it should be in the /Users/trzcinski/Sites/wordpress-develop/.

I’m curious if its good way to setup Wordpress environment locally or there is some better alternative. MAMP is causing some problems to me so I wanted to try different approach.

答:
Is apache running?

You must also spoof your DNS to point to your local ip, so your machine does not ask internet dns servers for an ip, which they would not be able to find.

I'm assuming you're on mac, so edit /etc/hosts and add:

```<code>127.0.0.1 wp-build.test
</code>```

UPDATE

You could look into Docker (Docker Desktop for mac) and docker-compose. It's a very simple way of setting up a complete environment with separated, but connected containers.

In it's simplest form, you could run a full apache with PHP8 environment with just this docker-compose.yml, where app-files is a directory with your php files that get's mounted to the dir that apache serves it's files from. The port mapping makes that you can access your application at http://localhost:8080. The PHP Docker image has many "tags" that determine your PHP version and environment.

```<code># docker-compose.yml

version: '3.1'
services:
  app:
    image: php:8.0-apache-buster
    ports:
      - "8080:80"
    volumes:
      - ./app-files:/var/www/html
</code>```

Ofcourse there's too many options to explain in a simple post, but this might get you started and enthousiastic about Docker. The beauty of it all? If you want to deploy to a production server, you can run the same script on a server with Docker and the whole enrironment will be the same. No more "it doesn't run when I deploy it to my live server" ;-)

There is also an official image for Wordpress, look into it.

P.S. If you would want to use that domain name, you'd still have to spoof it to 127.0.0.1 and then make sure that your webserver in the Docker enrironment has a vhost that listens to that domain, or listens to all.

Body:
I have followed https://noisysocks.com/2021/11/12/set-up-a-wordpress-development-environment-using-homebrew-on-macos/ tutorial to setup WordPress development environment using Homebrew on mac os 12. Before I’ve been using only MAMP.

The problem is at the final

You should now be able to browse to http://wp-build.test/wp-admin and
log in. The username is admin and the password is password.

when I’m launching http://wp-build.test/wp-admin

 This site can’t be reached
Check if there is a typo in wp-build.test.
    DNS_PROBE_FINISHED_NXDOMAIN

httpd.conf:

#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/access_log"
# with ServerRoot set to "/usr/local/apache2" will be interpreted by the
# server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log"
# will be interpreted as '/logs/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/usr/local/opt/httpd"

#
# Mutex: Allows you to set the mutex mechanism and mutex file directory
# for individual mutexes, or change the global defaults
#
# Uncomment and change the directory if mutexes are file-based and the default
# mutex file directory is not on a local disk or is not appropriate for some
# other reason.
#
# Mutex default:/usr/local/var/run/httpd

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 0.0.0.0:80
LoadModule php_module /usr/local/opt/php/lib/httpd/modules/libphp.so
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
#LoadModule mpm_event_module lib/httpd/modules/mod_mpm_event.so
LoadModule mpm_prefork_module lib/httpd/modules/mod_mpm_prefork.so
#LoadModule mpm_worker_module lib/httpd/modules/mod_mpm_worker.so
LoadModule authn_file_module lib/httpd/modules/mod_authn_file.so
#LoadModule authn_dbm_module lib/httpd/modules/mod_authn_dbm.so
#LoadModule authn_anon_module lib/httpd/modules/mod_authn_anon.so
#LoadModule authn_dbd_module lib/httpd/modules/mod_authn_dbd.so
#LoadModule authn_socache_module lib/httpd/modules/mod_authn_socache.so
LoadModule authn_core_module lib/httpd/modules/mod_authn_core.so
LoadModule authz_host_module lib/httpd/modules/mod_authz_host.so
LoadModule authz_groupfile_module lib/httpd/modules/mod_authz_groupfile.so
LoadModule authz_user_module lib/httpd/modules/mod_authz_user.so
#LoadModule authz_dbm_module lib/httpd/modules/mod_authz_dbm.so
#LoadModule authz_owner_module lib/httpd/modules/mod_authz_owner.so
#LoadModule authz_dbd_module lib/httpd/modules/mod_authz_dbd.so
LoadModule authz_core_module lib/httpd/modules/mod_authz_core.so
#LoadModule authnz_fcgi_module lib/httpd/modules/mod_authnz_fcgi.so
LoadModule access_compat_module lib/httpd/modules/mod_access_compat.so
LoadModule auth_basic_module lib/httpd/modules/mod_auth_basic.so
#LoadModule auth_form_module lib/httpd/modules/mod_auth_form.so
#LoadModule auth_digest_module lib/httpd/modules/mod_auth_digest.so
#LoadModule allowmethods_module lib/httpd/modules/mod_allowmethods.so
#LoadModule file_cache_module lib/httpd/modules/mod_file_cache.so
#LoadModule cache_module lib/httpd/modules/mod_cache.so
#LoadModule cache_disk_module lib/httpd/modules/mod_cache_disk.so
#LoadModule cache_socache_module lib/httpd/modules/mod_cache_socache.so
#LoadModule socache_shmcb_module lib/httpd/modules/mod_socache_shmcb.so
#LoadModule socache_dbm_module lib/httpd/modules/mod_socache_dbm.so
#LoadModule socache_memcache_module lib/httpd/modules/mod_socache_memcache.so
#LoadModule socache_redis_module lib/httpd/modules/mod_socache_redis.so
#LoadModule watchdog_module lib/httpd/modules/mod_watchdog.so
#LoadModule macro_module lib/httpd/modules/mod_macro.so
#LoadModule dbd_module lib/httpd/modules/mod_dbd.so
#LoadModule dumpio_module lib/httpd/modules/mod_dumpio.so
#LoadModule echo_module lib/httpd/modules/mod_echo.so
#LoadModule buffer_module lib/httpd/modules/mod_buffer.so
#LoadModule data_module lib/httpd/modules/mod_data.so
#LoadModule ratelimit_module lib/httpd/modules/mod_ratelimit.so
LoadModule reqtimeout_module lib/httpd/modules/mod_reqtimeout.so
#LoadModule ext_filter_module lib/httpd/modules/mod_ext_filter.so
#LoadModule request_module lib/httpd/modules/mod_request.so
#LoadModule include_module lib/httpd/modules/mod_include.so
LoadModule filter_module lib/httpd/modules/mod_filter.so
#LoadModule reflector_module lib/httpd/modules/mod_reflector.so
#LoadModule substitute_module lib/httpd/modules/mod_substitute.so
#LoadModule sed_module lib/httpd/modules/mod_sed.so
#LoadModule charset_lite_module lib/httpd/modules/mod_charset_lite.so
#LoadModule deflate_module lib/httpd/modules/mod_deflate.so
#LoadModule xml2enc_module lib/httpd/modules/mod_xml2enc.so
#LoadModule proxy_html_module lib/httpd/modules/mod_proxy_html.so
#LoadModule brotli_module lib/httpd/modules/mod_brotli.so
LoadModule mime_module lib/httpd/modules/mod_mime.so
LoadModule log_config_module lib/httpd/modules/mod_log_config.so
#LoadModule log_debug_module lib/httpd/modules/mod_log_debug.so
#LoadModule log_forensic_module lib/httpd/modules/mod_log_forensic.so
#LoadModule logio_module lib/httpd/modules/mod_logio.so
LoadModule env_module lib/httpd/modules/mod_env.so
#LoadModule mime_magic_module lib/httpd/modules/mod_mime_magic.so
#LoadModule expires_module lib/httpd/modules/mod_expires.so
LoadModule headers_module lib/httpd/modules/mod_headers.so
#LoadModule usertrack_module lib/httpd/modules/mod_usertrack.so
#LoadModule unique_id_module lib/httpd/modules/mod_unique_id.so
LoadModule setenvif_module lib/httpd/modules/mod_setenvif.so
LoadModule version_module lib/httpd/modules/mod_version.so
#LoadModule remoteip_module lib/httpd/modules/mod_remoteip.so
#LoadModule proxy_module lib/httpd/modules/mod_proxy.so
#LoadModule proxy_connect_module lib/httpd/modules/mod_proxy_connect.so
#LoadModule proxy_ftp_module lib/httpd/modules/mod_proxy_ftp.so
#LoadModule proxy_http_module lib/httpd/modules/mod_proxy_http.so
#LoadModule proxy_fcgi_module lib/httpd/modules/mod_proxy_fcgi.so
#LoadModule proxy_scgi_module lib/httpd/modules/mod_proxy_scgi.so
#LoadModule proxy_uwsgi_module lib/httpd/modules/mod_proxy_uwsgi.so
#LoadModule proxy_fdpass_module lib/httpd/modules/mod_proxy_fdpass.so
#LoadModule proxy_wstunnel_module lib/httpd/modules/mod_proxy_wstunnel.so
#LoadModule proxy_ajp_module lib/httpd/modules/mod_proxy_ajp.so
#LoadModule proxy_balancer_module lib/httpd/modules/mod_proxy_balancer.so
#LoadModule proxy_express_module lib/httpd/modules/mod_proxy_express.so
#LoadModule proxy_hcheck_module lib/httpd/modules/mod_proxy_hcheck.so
#LoadModule session_module lib/httpd/modules/mod_session.so
#LoadModule session_cookie_module lib/httpd/modules/mod_session_cookie.so
#LoadModule session_crypto_module lib/httpd/modules/mod_session_crypto.so
#LoadModule session_dbd_module lib/httpd/modules/mod_session_dbd.so
#LoadModule slotmem_shm_module lib/httpd/modules/mod_slotmem_shm.so
#LoadModule slotmem_plain_module lib/httpd/modules/mod_slotmem_plain.so
#LoadModule ssl_module lib/httpd/modules/mod_ssl.so
#LoadModule dialup_module lib/httpd/modules/mod_dialup.so
#LoadModule http2_module lib/httpd/modules/mod_http2.so
#LoadModule lbmethod_byrequests_module lib/httpd/modules/mod_lbmethod_byrequests.so
#LoadModule lbmethod_bytraffic_module lib/httpd/modules/mod_lbmethod_bytraffic.so
#LoadModule lbmethod_bybusyness_module lib/httpd/modules/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_heartbeat_module lib/httpd/modules/mod_lbmethod_heartbeat.so
LoadModule unixd_module lib/httpd/modules/mod_unixd.so
#LoadModule heartbeat_module lib/httpd/modules/mod_heartbeat.so
#LoadModule heartmonitor_module lib/httpd/modules/mod_heartmonitor.so
#LoadModule dav_module lib/httpd/modules/mod_dav.so
LoadModule status_module lib/httpd/modules/mod_status.so
LoadModule autoindex_module lib/httpd/modules/mod_autoindex.so
#LoadModule asis_module lib/httpd/modules/mod_asis.so
#LoadModule info_module lib/httpd/modules/mod_info.so
#LoadModule suexec_module lib/httpd/modules/mod_suexec.so
<IfModule !mpm_prefork_module>
    #LoadModule cgid_module lib/httpd/modules/mod_cgid.so
</IfModule>
<IfModule mpm_prefork_module>
    #LoadModule cgi_module lib/httpd/modules/mod_cgi.so
</IfModule>
#LoadModule dav_fs_module lib/httpd/modules/mod_dav_fs.so
#LoadModule dav_lock_module lib/httpd/modules/mod_dav_lock.so
#LoadModule vhost_alias_module lib/httpd/modules/mod_vhost_alias.so
#LoadModule negotiation_module lib/httpd/modules/mod_negotiation.so
LoadModule dir_module lib/httpd/modules/mod_dir.so
#LoadModule actions_module lib/httpd/modules/mod_actions.so
#LoadModule speling_module lib/httpd/modules/mod_speling.so
#LoadModule userdir_module lib/httpd/modules/mod_userdir.so
LoadModule alias_module lib/httpd/modules/mod_alias.so
LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so

<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User trzcinski
Group staff

</IfModule>

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
ServerAdmin you@example.com

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
ServerName localhost

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
    AllowOverride none
    Require all denied
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot /Users/trzcinski/Sites
<Directory "/Users/trzcinski/Sites">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.php index.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>
<FilesMatch \.php$>
    SetHandler application/x-httpd-php
</FilesMatch>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "/usr/local/var/log/httpd/error_log"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    CustomLog "/usr/local/var/log/httpd/access_log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    #CustomLog "/usr/local/var/log/httpd/access_log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to
    # exist in your server's namespace, but do not anymore. The client
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts.
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "/usr/local/var/www/cgi-bin/"

</IfModule>

<IfModule cgid_module>
    #
    # ScriptSock: On threaded servers, designate the path to the UNIX
    # socket used to communicate with the CGI daemon of mod_cgid.
    #
    #Scriptsock cgisock
</IfModule>

#
# "/usr/local/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/usr/local/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule headers_module>
    #
    # Avoid passing HTTP_PROXY environment to CGI's on this or any proxied
    # backend servers which have lingering "httpoxy" defects.
    # 'Proxy' request header is undefined by the IETF, not listed by IANA
    #
    RequestHeader unset Proxy early
</IfModule>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /usr/local/etc/httpd/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    #AddType text/html .shtml
    #AddOutputFilter INCLUDES .shtml
</IfModule>

#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type.  The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile /usr/local/etc/httpd/magic

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# MaxRanges: Maximum number of Ranges in a request before
# returning the entire resource, or one of the special
# values 'default', 'none' or 'unlimited'.
# Default setting is to accept 200 Ranges.
#MaxRanges unlimited

#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
#EnableSendfile on

# Supplemental configuration
#
# The configuration files in the /usr/local/etc/httpd/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.

# Server-pool management (MPM specific)
#Include /usr/local/etc/httpd/extra/httpd-mpm.conf

# Multi-language error messages
#Include /usr/local/etc/httpd/extra/httpd-multilang-errordoc.conf

# Fancy directory listings
#Include /usr/local/etc/httpd/extra/httpd-autoindex.conf

# Language settings
#Include /usr/local/etc/httpd/extra/httpd-languages.conf

# User home directories
#Include /usr/local/etc/httpd/extra/httpd-userdir.conf

# Real-time info on requests and configuration
#Include /usr/local/etc/httpd/extra/httpd-info.conf

# Virtual hosts
Include /usr/local/etc/httpd/extra/httpd-vhosts.conf

# Local access to the Apache HTTP Server Manual
#Include /usr/local/etc/httpd/extra/httpd-manual.conf

# Distributed authoring and versioning (WebDAV)
#Include /usr/local/etc/httpd/extra/httpd-dav.conf

# Various default settings
#Include /usr/local/etc/httpd/extra/httpd-default.conf

# Configure mod_proxy_html to understand HTML4/XHTML1
<IfModule proxy_html_module>
Include /usr/local/etc/httpd/extra/proxy-html.conf
</IfModule>

# Secure (SSL/TLS) connections
#Include /usr/local/etc/httpd/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
#       starting without SSL on platforms with no /dev/random equivalent
#       but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>

httpd-vhosts.conf:

# Virtual Hosts
#
# Required modules: mod_log_config

# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
Include /usr/local/etc/httpd/vhosts/*.conf

wp-build.test.conf:

<Directory "/Users/trzcinski/Sites/wordpress-develop/build">
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

<VirtualHost *:80>
    ServerName wp-build.test
    DocumentRoot "/Users/trzcinski/Sites/wordpress-develop/build"
    ErrorLog "/usr/local/var/log/httpd/wp-build.test-error_log"
    CustomLog "/usr/local/var/log/httpd/wp-build.test-access_log" common
</VirtualHost>

In step 3 he didn't mention where should I install wp-cli and others. So I assumed it should be in the /Users/trzcinski/Sites/wordpress-develop/.

I’m curious if its good way to setup Wordpress environment locally or there is some better alternative. MAMP is causing some problems to me so I wanted to try different approach.

Body:
Is apache running?

You must also spoof your DNS to point to your local ip, so your machine does not ask internet dns servers for an ip, which they would not be able to find.

I'm assuming you're on mac, so edit /etc/hosts and add:

127.0.0.1 wp-build.test

UPDATE

You could look into Docker (Docker Desktop for mac) and docker-compose. It's a very simple way of setting up a complete environment with separated, but connected containers.

In it's simplest form, you could run a full apache with PHP8 environment with just this docker-compose.yml, where app-files is a directory with your php files that get's mounted to the dir that apache serves it's files from. The port mapping makes that you can access your application at http://localhost:8080. The PHP Docker image has many "tags" that determine your PHP version and environment.

# docker-compose.yml

version: '3.1'
services:
  app:
    image: php:8.0-apache-buster
    ports:
      - "8080:80"
    volumes:
      - ./app-files:/var/www/html

Ofcourse there's too many options to explain in a simple post, but this might get you started and enthousiastic about Docker. The beauty of it all? If you want to deploy to a production server, you can run the same script on a server with Docker and the whole enrironment will be the same. No more "it doesn't run when I deploy it to my live server" ;-)

There is also an official image for Wordpress, look into it.

P.S. If you would want to use that domain name, you'd still have to spoof it to 127.0.0.1 and then make sure that your webserver in the Docker enrironment has a vhost that listens to that domain, or listens to all.


问:
Lunch Order Billing Menu
Alright so, i have got most of the things working except when i want to order something else like Pizza the Add-On items should change to Pepperoni, Sausage, Olives or Salad the Add-On items should change to  Croutons, Bacon bits, Bread stick but its not changing. Here is what i have got so far:

```<code>enter code here public partial class Form1 : Form
{
    decimal Subtotal;
    decimal Tax = 0.0775m;
    decimal OrderTotal;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        decimal add = 0m;
        if (chk1.Checked)
        {
            add++;
        }
        if (chk2.Checked)
        {
            add++;
        }
        if (chk3.Checked)
        {
            add++;
        }
        if (rdoHamburger.Checked)
        {
            decimal Hamburger = Convert.ToDecimal(rdoHamburger.Checked);
            Hamburger = 6.95m;

            Subtotal = Hamburger + (add * .75m);
            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoPizza.Checked)
        {

            decimal Pizza = Convert.ToDecimal(rdoPizza.Checked);
            Pizza = 5.95m;

            Subtotal = Pizza + (add * .50m);

            Tax = Subtotal * 0.00775m;

            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoSalad.Checked)
        {

            decimal salad = Convert.ToDecimal(rdoSalad.Checked);
            salad = 4.95m;

            Subtotal = salad + (add * .25m);

            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;
            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");
        }
    }

    private void groupBox1_Enter(object sender, EventArgs e)
    {
        if (rdoHamburger.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.75 each)";
            chk1.Text = "Lettuce, tomato and ketchup";
            chk2.Text = "Ketchup , mustard and mayo";
            chk3.Text = "French fries";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoPizza.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.50 each)";
            chk1.Text = "Pepperoni";
            chk2.Text = "Sausage";
            chk3.Text = "Olives";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoSalad.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.25 each)";
            chk1.Text = "Croutons";
            chk2.Text = "Bacon bits";
            chk3.Text = "Bread Sticks";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
        }
        textBox1.Clear();
        textBox2.Clear();
        textBox3.Clear();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string message = "Thank You for Using Our Service!\n Would You Like use our service again?";
        DialogResult button =
            MessageBox.Show(message, "Dear Customer",
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Information);

        if (button == DialogResult.No)
        {
            this.Close();
        }
        if (button == DialogResult.Yes)
        {
            MessageBox.Show("Thank You!! \n We Hope you will come Soon!", "Greeting      Message");
            this.Close();
        }

    }
}
</code>```

...

I would be grateful if anyone could help have 2 days left.

答:
you problem is that you are updating that menu using the Enter event. This is triggered if the user tabs into that control see https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.enter?view=windowsdesktop-6.0

This is not what you want , you want to run that update code based on the click events of the pizza / etc checkboxes

Title: Lunch Order Billing Menu

Body:
Alright so, i have got most of the things working except when i want to order something else like Pizza the Add-On items should change to Pepperoni, Sausage, Olives or Salad the Add-On items should change to  Croutons, Bacon bits, Bread stick but its not changing. Here is what i have got so far:

enter code here public partial class Form1 : Form
{
    decimal Subtotal;
    decimal Tax = 0.0775m;
    decimal OrderTotal;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        decimal add = 0m;
        if (chk1.Checked)
        {
            add++;
        }
        if (chk2.Checked)
        {
            add++;
        }
        if (chk3.Checked)
        {
            add++;
        }
        if (rdoHamburger.Checked)
        {
            decimal Hamburger = Convert.ToDecimal(rdoHamburger.Checked);
            Hamburger = 6.95m;

            Subtotal = Hamburger + (add * .75m);
            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoPizza.Checked)
        {

            decimal Pizza = Convert.ToDecimal(rdoPizza.Checked);
            Pizza = 5.95m;

            Subtotal = Pizza + (add * .50m);

            Tax = Subtotal * 0.00775m;

            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoSalad.Checked)
        {

            decimal salad = Convert.ToDecimal(rdoSalad.Checked);
            salad = 4.95m;

            Subtotal = salad + (add * .25m);

            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;
            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");
        }
    }

    private void groupBox1_Enter(object sender, EventArgs e)
    {
        if (rdoHamburger.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.75 each)";
            chk1.Text = "Lettuce, tomato and ketchup";
            chk2.Text = "Ketchup , mustard and mayo";
            chk3.Text = "French fries";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoPizza.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.50 each)";
            chk1.Text = "Pepperoni";
            chk2.Text = "Sausage";
            chk3.Text = "Olives";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoSalad.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.25 each)";
            chk1.Text = "Croutons";
            chk2.Text = "Bacon bits";
            chk3.Text = "Bread Sticks";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
        }
        textBox1.Clear();
        textBox2.Clear();
        textBox3.Clear();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string message = "Thank You for Using Our Service!\n Would You Like use our service again?";
        DialogResult button =
            MessageBox.Show(message, "Dear Customer",
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Information);

        if (button == DialogResult.No)
        {
            this.Close();
        }
        if (button == DialogResult.Yes)
        {
            MessageBox.Show("Thank You!! \n We Hope you will come Soon!", "Greeting      Message");
            this.Close();
        }

    }
}

...

I would be grateful if anyone could help have 2 days left.


问:
Why is list count not working as I expect with nested lists?
I can count simple list but can not count list of lists.

```<code>list1 = ['R', 'E', 'R', 'E']
print(list1[0])
print(list1.count(list1[0]))
</code>```

My logic thinks if above is true below should be true, but I was wrong.

```<code>list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
print(list1[0][1])
print(list1.count(list1[0][1]))
</code>```

Output

R
2
R
0
```

答:
If you're trying to count the total # of occurrences in your list of lists- you can add in a loop like this:

```<code>list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
check = list1[0][1]  # R
count = 0
for list in list1:
    count += list.count(check)
print(check)
print(count)
</code>```

Output:

```<code>R
2
</code>```

Body:
I can count simple list but can not count list of lists.

list1 = ['R', 'E', 'R', 'E']
print(list1[0])
print(list1.count(list1[0]))

My logic thinks if above is true below should be true, but I was wrong.

list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
print(list1[0][1])
print(list1.count(list1[0][1]))

Output

R
2
R
0

Body:
If you're trying to count the total # of occurrences in your list of lists- you can add in a loop like this:

list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
check = list1[0][1]  # R
count = 0
for list in list1:
    count += list.count(check)
print(check)
print(count)

Output:

R
2


问:
Nested functions in python: Polynomial exercise
Context: I'm trying to make make a function that will return the value of any given polynomial. So for polynomial(a), where a = [a0,a1,...,an] should return a function p so that p(x) is the polynomial a0x**n + a1x**(n-1)...+an.

This is what I have:

```<code>def polynomial(coefs):

    def p(x):
        res = 0
        i = len(coefs)
        for a in coefs[:-1]:
            i -=1
            res += a*x**i
        res += coefs[-1]
        return res
    return p(x)

# Tests:
xx = [0, 1, 2, 3]   # Valores de x a testar
r = polynomial([1, 2, 3])
print([r(x) for x in xx])   # should return [3, 6, 11, 18]
</code>```

But I keep getting name 'x' is not defined. If I'm saving the polynomial function as r, then if we pass an argument such as r(2) shouldn't it basically return p(2) which will in turn return the result?

Thank you in advance! Any help is welcome as I'm still learning python

Note: I'm aware the function isn't perfect yet for the example I'm trying to achieve, but I'd simply like to retrieve the desired output first and then I'll check the inner workings of the p(x) function again

答:
You actually can simplify this using lambda expression, and end up with something like this</p>
```<code>from typing import List, Callable

def polynomials(coefs: List[int]) -> Callable[[int], int]:
    return lambda x: sum([coefs[len(coefs) - i - 1] * (x ** i) for i in range(len(coefs) - 1, -1, -1)])

function = polynomials([1, 2, 3])  # x^2 + 2x + 3

print(function(1))  # 6
print(function(2))  # 11
</code>```

Body:
Context: I'm trying to make make a function that will return the value of any given polynomial. So for polynomial(a), where a = [a0,a1,...,an] should return a function p so that p(x) is the polynomial a0x**n + a1x**(n-1)...+an.

This is what I have:

def polynomial(coefs):

    def p(x):
        res = 0
        i = len(coefs)
        for a in coefs[:-1]:
            i -=1
            res += a*x**i
        res += coefs[-1]
        return res
    return p(x)

# Tests:
xx = [0, 1, 2, 3]   # Valores de x a testar
r = polynomial([1, 2, 3])
print([r(x) for x in xx])   # should return [3, 6, 11, 18]

But I keep getting name 'x' is not defined. If I'm saving the polynomial function as r, then if we pass an argument such as r(2) shouldn't it basically return p(2) which will in turn return the result?

Thank you in advance! Any help is welcome as I'm still learning python

Note: I'm aware the function isn't perfect yet for the example I'm trying to achieve, but I'd simply like to retrieve the desired output first and then I'll check the inner workings of the p(x) function again

Body:
You actually can simplify this using lambda expression, and end up with something like this

from typing import List, Callable

def polynomials(coefs: List[int]) -> Callable[[int], int]:
    return lambda x: sum([coefs[len(coefs) - i - 1] * (x ** i) for i in range(len(coefs) - 1, -1, -1)])

function = polynomials([1, 2, 3])  # x^2 + 2x + 3

print(function(1))  # 6
print(function(2))  # 11


问:
Send AWS API Gateway Key Name to Server
Let's say I have an AWS API Gateway.  I have a resource in said gateway that requires the use of a gateway API Key.  I would like my server to know which of my various keys are being used to authenticate (just for logging; there's no access control happening based on this).

How do I include the name of the gateway API Key in the request that is being sent to the server?

答:
API keys attached to an API gateway have to be unique. From the docs:

API key values must be unique. If you try to create two API keys with different names and the same value, API Gateway considers them to be the same API key.

The is no such header to specify the name of the key. You can create your own custom header where you would add this information, but nothing would guarantee that the correct name is sent with a given API key. You would probably want to implement a call using the AWS SDK from your server to retrieve the name of the API key.

In case you are using a Lambda authorizer function, you can fetch the name of the API key in this function and forward it as a header to the backend server.

Title: Send AWS API Gateway Key Name to Server


问:
C# Tic Tac Toe - Trying to iterate through list and set each element to X or O if value is 0 or 1
UI Image
I'm working on a Tic Tac Toe project that uses a two-dimensional int array to simulate the game board in memory. When the user clicks the New Game button, the application should step through the array, storing a random number in the range of 0 through 1 in each element.
The number 0 represents the letter O and the number 1 represents the letter X. The form should then be updated to display the game board. The application should display a message indicating whether player X or player O has won, or the game was a tie.

I created an array of the textboxes, and I'm trying to iterate through each element, and if A1 (value[0, 0]) has a value of 0, then A1.Text should be set equal to "O", and if A1 has a value of 1, A1.Text should be set equal to "X".

However, my loop isn't looping through each item, instead it's setting all of my elements in the textBox array to either X or O.

Here's my code:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Project_4
{
    public partial class TicTacToe : Form
    {
        public TicTacToe()
        {
            InitializeComponent();
        }

        // Initialize row and column count
        const int rowCount = 3;
        const int colCount = 3;

        // Generate random number
        Random random = new Random();

        // Create two-dimensional int array
        int[,] values = new int[rowCount, colCount];

        List<int> myList = new List<int>();

        private void newGame_Click(object sender, EventArgs e)
        {
            // Run functions
            randomize();
            updateView();
        }

        private void randomize()
        {
            // Loop through values[row, col]
            for (int row = 0; row < rowCount; row++)
            {
                for (int col = 0; col < colCount; col++)
                {
                    values[row, col] = random.Next(0, 2);
                    // Console.WriteLine(values[row, col]);
                }
            }
        }

        private void updateView()
        {
            TextBox[] textBoxes = { A1, A2, A3, B1, B2, B3, C1, C2, C3 };

            for (int row = 0; row < rowCount; row++)
            {
                for (int col = 0; col < colCount; col++)
                {
                    for (int i = 0; i < textBoxes.Length; i++)
                    {
                        if (values[row, col] == 0)
                        {
                            textBoxes[i].Text = "O";
                            Console.WriteLine(textBoxes[i]);
                        }
                        else
                        {
                            textBoxes[i].Text = "X";
                            Console.WriteLine(textBoxes[i]);
                        }
                    }
                }
            }
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
</code>```

Thank you!

答:
In your UpdateView method you're looping through rows, then columns then controls. For every combination of row and col you're iterating through all of the controls. The result is that your controls all get a final value based on the final cell (values[2,2]).

Remove the inner control loop and either calculate the array index each time or or use an index variable that is incremented after each column in the inner loop. For example:

```<code>private void UpdateView()
{
    TextBox[] textBoxes = { A1, A2, A3, B1, B2, B3, C1, C2, C3 };

    // Initialize the index here
    int index = 0;
    for (int row = 0; row < rowCount; row++)
    {
        // Increment index after each column
        for (int col = 0; col < colCount; col++, index++)
        {
            textBoxes[index].Text = values[row, col] == 0 ? "O" : "X";
            Console.WriteLine(textBoxes[i]);
        }
    }
}
</code>```

Alternatively, you could set up your textBoxes array to match the 2-dimensional layout of the values array and just use the row and col variables to index both. While we're at it, let's add a way to put an empty value in (anything not 0 or 1):

```<code>private void UpdateView()
{
    TextBox[,] textBoxes = { { A1, A2, A3 }, { B1, B2, B3 }, { C1, C2, C3 } };

    for (int row = 0; row < rowCount; row++)
    {
        for (int col = 0; col < colCount; col++)
        {
            textBoxes[row, col].Text = values[row, col] switch
            {
                0 => "O",
                1 => "X",
                _ => ""
            };
            Console.WriteLine(textBoxes[row, col]);
        }
    }
}
</code>```

Body:
UI Image
I'm working on a Tic Tac Toe project that uses a two-dimensional int array to simulate the game board in memory. When the user clicks the New Game button, the application should step through the array, storing a random number in the range of 0 through 1 in each element.
The number 0 represents the letter O and the number 1 represents the letter X. The form should then be updated to display the game board. The application should display a message indicating whether player X or player O has won, or the game was a tie.

I created an array of the textboxes, and I'm trying to iterate through each element, and if A1 (value[0, 0]) has a value of 0, then A1.Text should be set equal to "O", and if A1 has a value of 1, A1.Text should be set equal to "X".

However, my loop isn't looping through each item, instead it's setting all of my elements in the textBox array to either X or O.

Here's my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Project_4
{
    public partial class TicTacToe : Form
    {
        public TicTacToe()
        {
            InitializeComponent();
        }

        // Initialize row and column count
        const int rowCount = 3;
        const int colCount = 3;

        // Generate random number
        Random random = new Random();

        // Create two-dimensional int array
        int[,] values = new int[rowCount, colCount];

        List<int> myList = new List<int>();

        private void newGame_Click(object sender, EventArgs e)
        {
            // Run functions
            randomize();
            updateView();
        }

        private void randomize()
        {
            // Loop through values[row, col]
            for (int row = 0; row < rowCount; row++)
            {
                for (int col = 0; col < colCount; col++)
                {
                    values[row, col] = random.Next(0, 2);
                    // Console.WriteLine(values[row, col]);
                }
            }
        }

        private void updateView()
        {
            TextBox[] textBoxes = { A1, A2, A3, B1, B2, B3, C1, C2, C3 };

            for (int row = 0; row < rowCount; row++)
            {
                for (int col = 0; col < colCount; col++)
                {
                    for (int i = 0; i < textBoxes.Length; i++)
                    {
                        if (values[row, col] == 0)
                        {
                            textBoxes[i].Text = "O";
                            Console.WriteLine(textBoxes[i]);
                        }
                        else
                        {
                            textBoxes[i].Text = "X";
                            Console.WriteLine(textBoxes[i]);
                        }
                    }
                }
            }
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

Thank you!

Body:
In your UpdateView method you're looping through rows, then columns then controls. For every combination of row and col you're iterating through all of the controls. The result is that your controls all get a final value based on the final cell (values[2,2]).

Remove the inner control loop and either calculate the array index each time or or use an index variable that is incremented after each column in the inner loop. For example:

private void UpdateView()
{
    TextBox[] textBoxes = { A1, A2, A3, B1, B2, B3, C1, C2, C3 };

    // Initialize the index here
    int index = 0;
    for (int row = 0; row < rowCount; row++)
    {
        // Increment index after each column
        for (int col = 0; col < colCount; col++, index++)
        {
            textBoxes[index].Text = values[row, col] == 0 ? "O" : "X";
            Console.WriteLine(textBoxes[i]);
        }
    }
}

Alternatively, you could set up your textBoxes array to match the 2-dimensional layout of the values array and just use the row and col variables to index both. While we're at it, let's add a way to put an empty value in (anything not 0 or 1):

private void UpdateView()
{
    TextBox[,] textBoxes = { { A1, A2, A3 }, { B1, B2, B3 }, { C1, C2, C3 } };

    for (int row = 0; row < rowCount; row++)
    {
        for (int col = 0; col < colCount; col++)
        {
            textBoxes[row, col].Text = values[row, col] switch
            {
                0 => "O",
                1 => "X",
                _ => ""
            };
            Console.WriteLine(textBoxes[row, col]);
        }
    }
}