问:
Enabling CGI in Apache on MacOS
I'm attempting to enable CGI in Apache on MacOS and so far have attempted a lot of steps listed on the website. Whenever I hit the "Submit" button on my page, it just displays the contents of the cgi (or python) file instead of executing it. Here're some of the details:

OS: MacOS Catalina

Apache Server: 2.4.41

CGI File has a PY extension, so httpd.conf located at /private/etc/apache2 and /usr/local/etc/httpd has been modified.

Also renamed the .py file to .cgi, not sure if it matters but I tried both ways to no avail. I would appreciate if someone can tell me if it is ok to change the extension from py to cgi.

The location of this sendmail.cgi file is in the same directory as the other html files, I didn't put it in the special cgi-bin folder yet as I'm not sure which one that would be. Do I use a preexisting cgi-bin or do I create a new one in my web project directory.

httpd.conf modifications:

uncommented: Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews

uncommented and edited:   AddHandler cgi-script .cgi .py

Python File Header:

import smtplib
import cgi, cgitb

form = cgi.FieldStorage()
```
<p><strong>HTML Form:</strong></p>
<pre class="lang-html prettyprint-override"><code><form action="sendmail.cgi" method="post" class="container">
    <label for="email"><b>Name: </b></label>
    <input type="text" name="name_dlx" required>
    <br>
    <br>
    <label for="email"><b>Company: </b></label>
    <input type="text" name="company_dlx" required>
    <br>
    <br>
    <center><button type="submit" class="btn">Submit</button></center>
  </form>
</code>```

======================================================================
Update
I was able to get the webpage run my python code after I made a series of changes. HOWEVER, now it does what it's supposed to do (send out an email using the HTML form data), then gives me a 500 Internal Server Error.

A summary of changes:

Httpd.conf at /usr/local/etc/httpd (just below are the actual file contents)

AddHandler cgi-script .cgi .py .pl

AddType text/html .shtml
AddOutputFilter INCLUDES .shtml

<Directory "/usr/local/var/www/cgi-bin">
    AllowOverride None
    Options ExecCGI
    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>
```

Actual httpd.conf contents:

#
# 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 8080

#
# 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 md_module lib/httpd/modules/mod_md.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.
#

</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 192.168.1.101

#
# 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 all
    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 "/usr/local/var/www"
<Directory "/usr/local/var/www">
    #
    # 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.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>

#
# 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 ExecCGI
    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 .py

    # 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><strong>Added the following at the top of my python code:</strong></p>
<pre class="lang-python prettyprint-override"><code>#!/usr/local/bin/python
import cgi, cgitb
cgitb.enable()
</code>```

The python script just sends an email using smtp and ends (it does not return anything, maybe that's the problem?). The following is the end of the python script:

server=smtplib.SMTP('smtp.gmail.com')
server.starttls()
server.login(LOGIN,PASSWD)
server.sendmail(sendr,recvr,msgt)
server.quit
```

The CGI directory is /usr/local/var/www/cgi-bin
Changed Extension of the Python file from .py to .cgi.

Changed permissions of both the cgi-bin directory, and my python code file using sudo cmod 755 commands.

Also ensured that the line endings in all files are Unix and not Windows.

What would be solution to this problem now (Getting the 500 Internal Server Error after the script is executed successfully)

答:
I using the default CGI-executable folder with .py cgi is fine.</p>

```<code>#uncomment
<IfModule !mpm_prefork_module>
        LoadModule cgid_module libexec/apache2/mod_cgid.so
</IfModule>
<IfModule mpm_prefork_module>
        LoadModule cgi_module libexec/apache2/mod_cgi.so
</IfModule>

# And Edit
<Directory "/Library/WebServer/CGI-Executables">
    AllowOverride None
    Options ExecCGI
    Require all granted
    AddHandler cgi-script .cgi .py
</Directory>
</code>```

Title: Enabling CGI in Apache on MacOS

Body:
I'm attempting to enable CGI in Apache on MacOS and so far have attempted a lot of steps listed on the website. Whenever I hit the "Submit" button on my page, it just displays the contents of the cgi (or python) file instead of executing it. Here're some of the details:

OS: MacOS Catalina

Apache Server: 2.4.41

CGI File has a PY extension, so httpd.conf located at /private/etc/apache2 and /usr/local/etc/httpd has been modified.

Also renamed the .py file to .cgi, not sure if it matters but I tried both ways to no avail. I would appreciate if someone can tell me if it is ok to change the extension from py to cgi.

The location of this sendmail.cgi file is in the same directory as the other html files, I didn't put it in the special cgi-bin folder yet as I'm not sure which one that would be. Do I use a preexisting cgi-bin or do I create a new one in my web project directory.

httpd.conf modifications:

uncommented: Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews

uncommented and edited:   AddHandler cgi-script .cgi .py

Python File Header:

import smtplib
import cgi, cgitb

form = cgi.FieldStorage()

HTML Form:

<form action="sendmail.cgi" method="post" class="container">
    Name:
    <input type="text" name="name_dlx" required>

    Company:
    <input type="text" name="company_dlx" required>

    <button type="submit" class="btn">Submit</button>
  </form>

======================================================================
Update
I was able to get the webpage run my python code after I made a series of changes. HOWEVER, now it does what it's supposed to do (send out an email using the HTML form data), then gives me a 500 Internal Server Error.

A summary of changes:

Httpd.conf at /usr/local/etc/httpd (just below are the actual file contents)

AddHandler cgi-script .cgi .py .pl

AddType text/html .shtml
AddOutputFilter INCLUDES .shtml

<Directory "/usr/local/var/www/cgi-bin">
    AllowOverride None
    Options ExecCGI
    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

Actual httpd.conf contents:

#
# 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 8080

#
# 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 md_module lib/httpd/modules/mod_md.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.
#

</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 192.168.1.101

#
# 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 all
    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 "/usr/local/var/www"
<Directory "/usr/local/var/www">
    #
    # 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.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>

#
# 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 ExecCGI
    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 .py

    # 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>

Added the following at the top of my python code:

#!/usr/local/bin/python
import cgi, cgitb
cgitb.enable()

The python script just sends an email using smtp and ends (it does not return anything, maybe that's the problem?). The following is the end of the python script:

server=smtplib.SMTP('smtp.gmail.com')
server.starttls()
server.login(LOGIN,PASSWD)
server.sendmail(sendr,recvr,msgt)
server.quit

The CGI directory is /usr/local/var/www/cgi-bin
Changed Extension of the Python file from .py to .cgi.

Changed permissions of both the cgi-bin directory, and my python code file using sudo cmod 755 commands.

Also ensured that the line endings in all files are Unix and not Windows.

What would be solution to this problem now (Getting the 500 Internal Server Error after the script is executed successfully)

Body:
I using the default CGI-executable folder with .py cgi is fine.

#uncomment
<IfModule !mpm_prefork_module>
        LoadModule cgid_module libexec/apache2/mod_cgid.so
</IfModule>
<IfModule mpm_prefork_module>
        LoadModule cgi_module libexec/apache2/mod_cgi.so
</IfModule>

# And Edit
<Directory "/Library/WebServer/CGI-Executables">
    AllowOverride None
    Options ExecCGI
    Require all granted
    AddHandler cgi-script .cgi .py
</Directory>


来源: stackexchange

问:
Why is SDL_PollEvent so slow?
Ive been programming an emulator as a side project and am at a point now where I am tackling efficiency. Ive managed to get rid of all the slow things that I was doing like lots of SDL_RenderDrawPoint's, but now I'm stuck.

Ive managed to narrow it down to SDL_PollEvent. Ive simplified my main loop and event loop so that they look similar to a simple SDL tutorial.
When I comment out the event loop, the emulator runs super fast.
Ive also used the visual studio performance profiler to check, and sure enough, SDL_PollEvent is taking up ~94% of the cpu time.

The place where my emulator does all its stuff is in ppuNptr->cycle() which is taking up only 1.48% .

Unfortunately I can't replicate this in another project so I'm at a loss.

Is there something that I should be doing before polling for events?

How else could I debug this?

Currently im on windows 10 with visual studio 2019 and sdl 2.0.10 .

答:
I too ran across this when profiling my emulator. The answer for me was to downgrade the version of SDL2 to 2.0.8.

I was running SDL2 version 2.0.12 and I took keltar's suggestion in the comments, and downgraded to 2.0.8 and I was no longer having the issue with the SDL_PollEvent causing slow performance. This fixed the issue for me as I no longer having low FPS issues with my emulator.

I will see if this issue has been reported in the bug ticketing system and report it if not to the SDL2 as this issue starts occurring from version 2.0.9.

ContentLicense: CC BY-SA 4.0

Title: Why is SDL_PollEvent so slow?


问:
Dynamically create column and row in HTML
I have data structure like this. and
<param1> could be repeating . We can have multiple value for  param1

```<code><param>
  <param1>
    <name>
    <value>
  </param1>
  <param1>
    <name1>
    <value1>
    </param1>
</param>
I want to display in html dynamically like this(like column row ).  How can we do it ???

name     name1
value    value1

Can someone suggest how to do it . I am new to this area

</code>```

答:
The solution should be:

<!DOCTYPE html>

        <param-list>
            <my-name></my-name>
            <my-value></my-value>
        </param-list>
        <param-list>
            <my-name1></my-name1>
            <my-value1></my-value1>
        </param-list>

```

Live at custom-element

ref:

https://www.html5rocks.com/en/tutorials/webcomponents/customelements/

How to create custom tags for html

https://dev.to/jfbrennan/custom-html-tags-4788

https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements

Body:
I have data structure like this. and
<param1> could be repeating . We can have multiple value for  param1

<param>
  <param1>
    <name>
    <value>
  </param1>
  <param1>
    <name1>
    <value1>
    </param1>
</param>
I want to display in html dynamically like this(like column row ).  How can we do it ???

name     name1
value    value1

Can someone suggest how to do it . I am new to this area

Body:
The solution should be:

<!DOCTYPE html>
<html>
    <style>
        param-list {
        font-size : 20px;
        display:inline-block;
        border:1px solid gray;
        }
        param-list > *{
        font-size : 20px;
        display:block;
        }
    </style>
    <body>
        <param-list>
            <my-name></my-name>
            <my-value></my-value>
        </param-list>
        <param-list>
            <my-name1></my-name1>
            <my-value1></my-value1>
        </param-list>
        <script>
            class ParamList extends HTMLElement {
              connectedCallback() {
                 this.children;
              }
            }
            customElements.define('param-list', ParamList);

            class Name extends HTMLElement {
              connectedCallback() {
                this.innerHTML = `name`;
              }
            }
            customElements.define('my-name', Name);

            class Name1 extends HTMLElement {
              connectedCallback() {
                this.innerHTML = `name1`;
              }
            }
            customElements.define('my-name1', Name1);
            class Value extends HTMLElement {
              connectedCallback() {
                this.innerHTML = `value`;
              }
            }
            customElements.define('my-value', Value);

            class Value1 extends HTMLElement {
              connectedCallback() {
                this.innerHTML = `value1`;
              }
            }
            customElements.define('my-value1', Value1);

        </script>
    </body>
</html>

Live at custom-element

ref:

https://www.html5rocks.com/en/tutorials/webcomponents/customelements/

How to create custom tags for html

https://dev.to/jfbrennan/custom-html-tags-4788

https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements


问:
Change order of multiple optional substrings
That's a bit like this question, but I have multiple substrings that may or may not occur.

The substrings code for two different dimensions, in my example "test" and "eye". They can occur in any imaginable order.
The variables can be coded in different ways - in my example, "method|test" would be two ways to code for "test", as well as "r|re|l|le" different ways to code for eyes.

I found a convoluted solution, which is using a chain of seven (!) gsub calls, and I wondered if there is a more concise way.

x <- c("id", "r_test", "l_method", "test_re", "method_le", "test_r_old",
       "test_l_old", "re_test_new","new_le_method", "new_r_test")
x
#>  [1] "id"            "r_test"        "l_method"      "test_re"
#>  [5] "method_le"     "test_r_old"    "test_l_old"    "re_test_new"
#>  [9] "new_le_method" "new_r_test"
```

<p>Desired output</p>

```#>  [1] "id"         "r_test"     "l_test"     "r_test"     "l_test"
#>  [6] "r_test_old" "l_test_old" "r_test_new" "l_test_new" "r_test_new"
```

<p>How I got there (convoluted)</p>

```## Unify codes for variables, I use the underscores to make it more unique for future regex
clean_test<- gsub("(?<![a-z])(test|method)(?![a-z])", "_test_", tolower(x), perl = TRUE)
clean_r <- gsub("(?<![a-z])(r|re)(?![a-z])", "_r_", tolower(clean_test), perl = TRUE)
clean_l <- gsub("(?<![a-z])(l|le)(?![a-z])", "_l_", tolower(clean_r), perl = TRUE)

## Now sort, one after the other
sort_eye <- gsub("(.*)(_r_|_l_)(.*)", "\\2\\1\\3", clean_l, perl = TRUE)
sort_test <- gsub("(_r_|_l_)(.*)(_test_)(.*)", "\\1\\3\\2\\4", sort_eye, perl = TRUE)

## Remove underscores
clean_underscore_mult <- gsub("_{2,}", "_", sort_test)
clean_underscore_ends <- gsub("^_|_$", "", clean_underscore_mult)

clean_underscore_ends
#>  [1] "id"         "r_test"     "l_test"     "r_test"     "l_test"
#>  [6] "r_test_old" "l_test_old" "r_test_new" "l_test_new" "r_test_new"
```

I'd be already very very grateful for a suggestion how to better proceed from ## Now sort, one after the other downwards...

答:
Here's a one-liner with nested sub that transforms x without any intermediary steps:

```<code>sub("^(\\w+)_(r|re|l|le)", "\\2_\\1",
     sub("method", "test",
          sub("(l|r)e", "\\1",
               sub("(^new)_(\\w+_\\w+)$", "\\2_\\1", x))))

# [1] "id"  "r_test"  "l_test"  "r_test"  "l_test"  "r_test_old"
# [7] "l_test_old"  "r_test_new"  "l_test_new" "r_test_new"
</code>```

Data:

```<code>x <- c("id", "r_test", "l_method", "test_re", "method_le", "test_r_old",
       "test_l_old", "re_test_new","new_le_method", "new_r_test")
</code>```

Body:
That's a bit like this question, but I have multiple substrings that may or may not occur.

The substrings code for two different dimensions, in my example "test" and "eye". They can occur in any imaginable order.
The variables can be coded in different ways - in my example, "method|test" would be two ways to code for "test", as well as "r|re|l|le" different ways to code for eyes.

I found a convoluted solution, which is using a chain of seven (!) gsub calls, and I wondered if there is a more concise way.

x <- c("id", "r_test", "l_method", "test_re", "method_le", "test_r_old",
       "test_l_old", "re_test_new","new_le_method", "new_r_test")
x
#>  [1] "id"            "r_test"        "l_method"      "test_re"
#>  [5] "method_le"     "test_r_old"    "test_l_old"    "re_test_new"
#>  [9] "new_le_method" "new_r_test"

Desired output

#>  [1] "id"         "r_test"     "l_test"     "r_test"     "l_test"
#>  [6] "r_test_old" "l_test_old" "r_test_new" "l_test_new" "r_test_new"

How I got there (convoluted)

## Unify codes for variables, I use the underscores to make it more unique for future regex
clean_test<- gsub("(?<![a-z])(test|method)(?![a-z])", "_test_", tolower(x), perl = TRUE)
clean_r <- gsub("(?<![a-z])(r|re)(?![a-z])", "_r_", tolower(clean_test), perl = TRUE)
clean_l <- gsub("(?<![a-z])(l|le)(?![a-z])", "_l_", tolower(clean_r), perl = TRUE)

## Now sort, one after the other
sort_eye <- gsub("(.*)(_r_|_l_)(.*)", "\\2\\1\\3", clean_l, perl = TRUE)
sort_test <- gsub("(_r_|_l_)(.*)(_test_)(.*)", "\\1\\3\\2\\4", sort_eye, perl = TRUE)

## Remove underscores
clean_underscore_mult <- gsub("_{2,}", "_", sort_test)
clean_underscore_ends <- gsub("^_|_$", "", clean_underscore_mult)

clean_underscore_ends
#>  [1] "id"         "r_test"     "l_test"     "r_test"     "l_test"
#>  [6] "r_test_old" "l_test_old" "r_test_new" "l_test_new" "r_test_new"

I'd be already very very grateful for a suggestion how to better proceed from ## Now sort, one after the other downwards...

Body:
Here's a one-liner with nested sub that transforms x without any intermediary steps:

sub("^(\\w+)_(r|re|l|le)", "\\2_\\1",
     sub("method", "test",
          sub("(l|r)e", "\\1",
               sub("(^new)_(\\w+_\\w+)$", "\\2_\\1", x))))

# [1] "id"  "r_test"  "l_test"  "r_test"  "l_test"  "r_test_old"
# [7] "l_test_old"  "r_test_new"  "l_test_new" "r_test_new"

Data:

x <- c("id", "r_test", "l_method", "test_re", "method_le", "test_r_old",
       "test_l_old", "re_test_new","new_le_method", "new_r_test")


问:
Is it okay to use functions to stay organized in C?
I'm a relatively new C programmer, and I've noticed that many conventions from other higher-level OOP languages don't exactly hold true on C.

Is it okay to use short functions to have your coding stay organized (even though it will likely be called only once)? An example of this would be 10-15 lines in something like void init_file(void), then calling it first in main().

答:
It is indeed a good practice to refactor code into functions, irrespective of the language being used. Even if your code is short, it will make it more readable.
If your function is quite short, you can consider inlining it.

IBM Publib article on inlining

ContentLicense: CC BY-SA 3.0


问:
Can't access this.setState
I just implemented a working Apollo-client listener on a subscription. When a subscription is made, the code below can fetch and log it.

However, this.setState doesnt seem to work for some reason.. As when the subscription is fetched, the app throws TypeError: this.setState is not a function.

Can someone explain why?

    componentDidMount() {
        const SUBSCRIBE_POST = gql`
        subscription{
        postAdded{
            id
            message
            type
            created
            customers_ID
            customer{id,firstName}
        }
        }
        `;
        let response = null
        const {client} = this.props
        client.subscribe({query: SUBSCRIBE_POST})
            .subscribe({
                next(data) {
                    response = data.data.postAdded
                    console.log(response)
                    this.setState({list: response})
                },
                error(err) {console.error('err', err);},
            })
    }
```

答:
Before componentDidMount:

const that = this;

Then call later:

that.setState();

Read up on JavaScript “this” for an enlightened weekend. “You don’t know JavaScript yet” is an excellent read.

Also read up on react hooks.

Title: Can't access this.setState


问:
Eclipse -> Run Button -> Shortcut
Is there any shortcut key that I can use to run my program? Sick and tired of going to the top of the screen and clicking on the green run button. And yes, I've looked everywhere to find for a shortcut and trust me, I can't find it anywhere.

I'm currently working with Python 3.x and using a Mac.
And no, Ctrl+F11 does not work. It only increases my volume.

答: On Windows, it works for Ctrl + F11 key combination.</p>

Title: Eclipse -> Run Button -> Shortcut


问:
DAX function to check the amount of dates that is greater than another set of dates in 2 different columns
I'm currently doing an internship where I have been asked to make a few visuals in Power BI

I've searched around, tried a couple of things. But the truth is I am very much a beginner at coding and functions in general. Only had basic courses of different languages during my education and to be fair, it's a bit outside my scope of work.

So I have 2 columns I need to compare in order to find out how many dates in column 2 that is greater than the dates in column 1

So I'm imagining something like:

```<code>Measure = IF[(Investments(Expected closure)]<[(Investments(Actualclosure)]
</code>```

Basically I want an overview of how many investments have a later closure date than expected.

Next thing would possibly be to create a boxplot showing the distribution (by how far we are off).

I know this is very basic, and possibly not formulated in the best way possible, please let me know if you need any more information.

Thanks in advance

答:
You can use a calculated column as a flag to identify if actual date > expected date and then count the flag.

Flag = IF('Table'[Act] > 'Table'[Exp], 1, 0)

Hope this helps. Thanks.

enter image description here

Body:
I'm currently doing an internship where I have been asked to make a few visuals in Power BI

I've searched around, tried a couple of things. But the truth is I am very much a beginner at coding and functions in general. Only had basic courses of different languages during my education and to be fair, it's a bit outside my scope of work.

So I have 2 columns I need to compare in order to find out how many dates in column 2 that is greater than the dates in column 1

So I'm imagining something like:

Measure = IF[(Investments(Expected closure)]<[(Investments(Actualclosure)]

Basically I want an overview of how many investments have a later closure date than expected.

Next thing would possibly be to create a boxplot showing the distribution (by how far we are off).

I know this is very basic, and possibly not formulated in the best way possible, please let me know if you need any more information.

Thanks in advance


问:
Trying to perform a text change in my textview at a reoccurring time on daily basis in my android project

let say i will like to automatically change my textview text at 02:00pm everyday how do I implement this functionality.

```<code>val df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN).parse("2:00pm")
        val systemDat = Calendar.getInstance(Locale.JAPAN).after(df)
        if (systemDat) {
            binding.includeTokyoSession.text_one.text = "successful"
        } else {
            binding.includeTokyoSession.text_one.text = "failure"
        }
</code>```

答:
I suppose you want to change the text of your TextView after a particular time, but it seems that you're not aware of the date when comparing and you have a couple of mistakes in your code.

First, this line of code:

```<code>DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN).parse("2:00pm")
</code>```

will return a Date instance with this date and time in your local timezone 01-01-1970 02:00:00. However, you need to get a Date instance with today's date and the time 14:00:00.

Second, this line of code:

```<code>Calendar.getInstance(Locale.JAPAN).after(df)
</code>```

this is a wrong usage of the Calendar::after() function, and that's because you can only pass a Calendar object to the function in order to get the right comparison result, otherwise it will always return false.

In your case you're passing a Date object.

Following is the implementation of the Calendar::after() function.

```<code>public boolean after(Object when) {
    return when instanceof Calendar
        && compareTo((Calendar)when) > 0;
}
</code>```

If you want to proper compare the current time today with 14:00 (comparing only the time today), here is a modification to your code:

```<code>val calendarToCompare = Calendar.getInstance(Locale.JAPAN).apply {
    set(Calendar.HOUR_OF_DAY, 14)
    set(Calendar.MINUTE, 0)
    set(Calendar.SECOND, 0)
    set(Calendar.MILLISECOND, 0)
}

val systemDat = Calendar.getInstance().after(calendarToCompare)

if (systemDat) {
    textview.text = "successful"
} else {
    textview.text = "failure"
}
</code>```

If you want to perform a lifecycle-aware view update (ex. to set the text of your textview), you can check this gist.

Body:
let say i will like to automatically change my textview text at 02:00pm everyday how do I implement this functionality.

val df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN).parse("2:00pm")
        val systemDat = Calendar.getInstance(Locale.JAPAN).after(df)
        if (systemDat) {
            binding.includeTokyoSession.text_one.text = "successful"
        } else {
            binding.includeTokyoSession.text_one.text = "failure"
        }

Body:
I suppose you want to change the text of your TextView after a particular time, but it seems that you're not aware of the date when comparing and you have a couple of mistakes in your code.

First, this line of code:

DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN).parse("2:00pm")

will return a Date instance with this date and time in your local timezone 01-01-1970 02:00:00. However, you need to get a Date instance with today's date and the time 14:00:00.

Second, this line of code:

Calendar.getInstance(Locale.JAPAN).after(df)

this is a wrong usage of the Calendar::after() function, and that's because you can only pass a Calendar object to the function in order to get the right comparison result, otherwise it will always return false.

In your case you're passing a Date object.

Following is the implementation of the Calendar::after() function.

public boolean after(Object when) {
    return when instanceof Calendar
        && compareTo((Calendar)when) > 0;
}

If you want to proper compare the current time today with 14:00 (comparing only the time today), here is a modification to your code:

val calendarToCompare = Calendar.getInstance(Locale.JAPAN).apply {
    set(Calendar.HOUR_OF_DAY, 14)
    set(Calendar.MINUTE, 0)
    set(Calendar.SECOND, 0)
    set(Calendar.MILLISECOND, 0)
}

val systemDat = Calendar.getInstance().after(calendarToCompare)

if (systemDat) {
    textview.text = "successful"
} else {
    textview.text = "failure"
}

If you want to perform a lifecycle-aware view update (ex. to set the text of your textview), you can check this gist.


问:
cannot import name 'CenterCrop' from 'tensorflow.keras.layers.experimental.preprocessing'
I am using anaconda env.

Python 3.7
keras : 2.3.1
tensorflow: 2.1.0

when i want to use CenterCrop and Rescaling modules, pycharm gives me error.

```<code>from tensorflow.keras.layers.experimental.preprocessing import CenterCrop
from tensorflow.keras.layers.experimental.preprocessing import Rescaling
</code>```

error messages is:

```<code>D:\NewAnaconda\envs\Tensor_Turkcell\python.exe "C:/Users/Burak Ekincioğlu/Dekstop/TENSORFLOW/tensor_intro.py"
Traceback (most recent call last):
  File "C:/Users/Burak Ekincioğlu/Dekstop/TENSORFLOW/tensor_intro.py", line 5, in <module>
    from tensorflow.keras.layers.experimental.preprocessing import CenterCrop
ImportError: cannot import name 'CenterCrop' from 'tensorflow.keras.layers.experimental.preprocessing' (D:\NewAnaconda\envs\Tensor_Turkcell\lib\site-packages\tensorflow_core\python\keras\api\_v2\keras\layers\experimental\preprocessing\__init__.py)
</code>```

答:
I've tried the import with tensorflow 2.1.0 (keras 2.2.4 by default) and it gave me the same error you are encountering.

Using Tensorflow 2.2.0 with keras 2.3.0 works fine.

So you just need to upgrade tensorflow.

Body:
I am using anaconda env.

Python 3.7
keras : 2.3.1
tensorflow: 2.1.0

when i want to use CenterCrop and Rescaling modules, pycharm gives me error.

from tensorflow.keras.layers.experimental.preprocessing import CenterCrop
from tensorflow.keras.layers.experimental.preprocessing import Rescaling

error messages is:

D:\NewAnaconda\envs\Tensor_Turkcell\python.exe "C:/Users/Burak Ekincioğlu/Dekstop/TENSORFLOW/tensor_intro.py"
Traceback (most recent call last):
  File "C:/Users/Burak Ekincioğlu/Dekstop/TENSORFLOW/tensor_intro.py", line 5, in <module>
    from tensorflow.keras.layers.experimental.preprocessing import CenterCrop
ImportError: cannot import name 'CenterCrop' from 'tensorflow.keras.layers.experimental.preprocessing' (D:\NewAnaconda\envs\Tensor_Turkcell\lib\site-packages\tensorflow_core\python\keras\api\_v2\keras\layers\experimental\preprocessing\__init__.py)


问:
Problem with Login control of ASP.NET
I set up a website to use SqlMembershipProvider as written on this page.

I followed every step. I have the database, I modified the Web.config to use this provider, with the correct connection string, and the authentication mode is set to Forms. Created some users to test with.

I created a Login.aspx and put the Login control on it. Everything works fine until the point that a user can log in.

I call Default.aspx, it gets redirected to Login.aspx, I enter the user and the correct password. No error message, nothing seems to be wrong, but I see again the Login form, to enter the user's login information. However if I check the cookies in the browser, I can see that the cookie with the specified name exists.

I already tried to handle the events by myself and check, what is happening in them, but no success.

I'm using VS2008, Website in filesystem, SQL Express 2005 to store aspnetdb, no role management, tested with K-Meleon, IE7.0 and Chrome.

Any ideas?

Resolution: After some mailing with Rob we have the ideal solution, which is now the accepted answer.

答:
@Rob: You are right from your point of view.

From my point of view it is my test project to check some things. If it is working in any way, that fits to me. I haven't found any similair problem on the net, so it can be something else, absolutely not related to ASP.NET.

However I'm open, so that next time I also can say: aha, I know this!

I started over the project:

Default.aspx: added LoginStatus and LoginName controls

Login.aspx: added Login control and CreateUserWizard control

web.config: added

```<code><authentication mode="Forms">
    <forms name="SqlAuthCookie" timeout="10" loginUrl="Login.aspx"/>
</authentication>
<authorization>
    <deny users="?"/>
    <allow users="*"/>
</authorization>
<membership defaultProvider="MySqlMembershipProvider">
    <providers>
        <clear/>
        <add name="MySqlMembershipProvider" connectionStringName="MyLocalSQLServer" applicationName="MyAppName" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    </providers>
</membership>
</code>```

and

```<code><connectionStrings>
    <add name="MyLocalSQLServer" connectionString="Initial Catalog=aspnetdb;data source=iballanb\sqlexpress;uid=full;pwd=full;"/>
</connectionStrings>
</code>```

Create the database with aspnet_regsql -E -S iballanb\sqlexpress -A all, created an SQL user called full with password full.

Start the project, I got redirected to Login.aspx, create one user, it is created in database. Entering user data to login form, catching events: LoggingIn, Authenticate, LoggedIn, so I'm logged in ( I don't do anything in these events, I don't authenticate myself, I'm only interested in what is fired and in which order). RedirectURL is correctly pointing to Default.aspx, but has no effect.

This is it so far.

OwnerDisplayName: Biri

ContentLicense: CC BY-SA 2.5

Title: Problem with Login control of ASP.NET

LastEditorDisplayName: Biri

Body:
@Rob: You are right from your point of view.

From my point of view it is my test project to check some things. If it is working in any way, that fits to me. I haven't found any similair problem on the net, so it can be something else, absolutely not related to ASP.NET.

However I'm open, so that next time I also can say: aha, I know this!

I started over the project:

Default.aspx: added LoginStatus and LoginName controls

Login.aspx: added Login control and CreateUserWizard control

web.config: added

<authentication mode="Forms">
    <forms name="SqlAuthCookie" timeout="10" loginUrl="Login.aspx"/>
</authentication>
<authorization>
    <deny users="?"/>
    <allow users="*"/>
</authorization>
<membership defaultProvider="MySqlMembershipProvider">
    <providers>
        <clear/>
        <add name="MySqlMembershipProvider" connectionStringName="MyLocalSQLServer" applicationName="MyAppName" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    </providers>
</membership>

and

<connectionStrings>
    <add name="MyLocalSQLServer" connectionString="Initial Catalog=aspnetdb;data source=iballanb\sqlexpress;uid=full;pwd=full;"/>
</connectionStrings>

Create the database with aspnet_regsql -E -S iballanb\sqlexpress -A all, created an SQL user called full with password full.

Start the project, I got redirected to Login.aspx, create one user, it is created in database. Entering user data to login form, catching events: LoggingIn, Authenticate, LoggedIn, so I'm logged in ( I don't do anything in these events, I don't authenticate myself, I'm only interested in what is fired and in which order). RedirectURL is correctly pointing to Default.aspx, but has no effect.

This is it so far.


问:
How do I programmatically update OCX references in vb6 projects?
I periodically break binary compatibility and need to recompile an entire vb6 application composed of several dozen ActiveX DLLs and OCXs in total. I've written a script to automate this process, but I have encountered a problem.

When an OCX is recompiled with project compatibility its version is incremented, and projects referencing the OCX will not recompile until their reference is updated to the new version. This is checked automatically when the project is opened normally, and the user is prompted to update the reference, but I need to do it in a script.

How do I do it?

答:
Self-answer: I have written some vb6 code to do the upgrade programmatically. It is not extensively tested, there are probably a few bugs here and there for corner cases, but I did use it successfully.</p>

```<code>Option Explicit

Const HKEY_LOCAL_MACHINE As Long = &H80000002
Const KEY_ENUMERATE_SUB_KEYS As Long = 8
Private Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long
Private Declare Function RegEnumKeyEx Lib "advapi32.dll" Alias "RegEnumKeyExA" (ByVal hKey As Long, ByVal dwIndex As Long, ByVal lpName As String, lpcbName As Long, lpReserved As Long, ByVal lpClass As String, lpcbClass As Long, lpftLastWriteTime As Any) As Long
Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long

'''Returns the expected major version of a GUID if it exists, and otherwise returns the highest registered major version.
Public Function GetOcxMajorVersion(ByVal guid As String, Optional ByVal expected_version As Long) As Long
    Const BUFFER_SIZE As Long = 255
    Dim reg_key As Long
    Dim ret As Long
    Dim enum_index As Long
    Dim max_version As Long: max_version = -1

    ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\Classes\TypeLib\{" & guid & "}", 0, KEY_ENUMERATE_SUB_KEYS, reg_key)
    If ret <> 0 Then Err.Raise ret, , "Failed to open registry key."
    Do
        'Store next subkey name in buffer
        Dim buffer As String: buffer = Space(BUFFER_SIZE)
        Dim cur_buffer_size As Long: cur_buffer_size = BUFFER_SIZE
        ret = RegEnumKeyEx(reg_key, enum_index, buffer, cur_buffer_size, ByVal 0&, vbNullString, ByVal 0&, ByVal 0&)
        If ret <> 0 Then Exit Do
        buffer = Left(buffer, cur_buffer_size)

        'Keep most likely version
        buffer = Split(buffer, ".")(0)
        If Not buffer Like "*[!0-9A-B]*" And Len(buffer) < 4 Then
            Dim v As Long: v = CLng("&H" & buffer) 'convert from hex
            If v = expected_version Then
                max_version = v
                Exit Do
            ElseIf max_version < v Then
                max_version = v
            End If
        End If

        enum_index = enum_index + 1
    Loop
    RegCloseKey reg_key

    If max_version = -1 Then Err.Raise -1, , "Failed to enumerate any viable subkeys."
    GetOcxMajorVersion = max_version
End Function

Public Function RemoveFilename(ByVal path As String) As String
    Dim folders() As String: folders = Split(Replace(path, "/", "\"), "\")
    RemoveFilename = Left(path, Len(path) - Len(folders(UBound(folders))))
End Function

'''Changes any invalid OCX references to newer registered version
Public Sub UpdateFileOCXReferences(ByVal path As String)
    Dim file_data As String
    Dim changes_made As Boolean

    'Read
    Dim fn As Long: fn = FreeFile
    Open path For Input As fn
        While Not EOF(fn)
            Dim line As String
            Line Input #fn, line

            'check for ocx reference line
            If LCase(line) Like "object*=*{*-*-*-*-*}[#]*#.#*[#]#*;*.ocx*" Then
                'get guid
                Dim guid_start As Long: guid_start = InStr(line, "{") + 1
                Dim guid_end As Long: guid_end = InStr(line, "}")
                Dim guid As String: guid = Mid(line, guid_start, guid_end - guid_start)

                'get reference major version
                Dim version_start As Long: version_start = InStr(line, "#") + 1
                Dim version_end As Long: version_end = InStr(version_start + 1, line, ".")
                Dim version_text As String: version_text = Mid(line, version_start, version_end - version_start)

                'play it safe
                If Len(guid) <> 32 + 4 Then Err.Raise -1, , "GUID has unexpected length."
                If Len(version_text) > 4 Then Err.Raise -1, , "Major version is larger than expected."
                If guid Like "*[!0-9A-F-]*" Then Err.Raise -1, , "GUID has unexpected characters."
                If version_text Like "*[!0-9]*" Then Err.Raise -1, , "Major version isn't an integer."

                'get registry major version
                Dim ref_version As Long: ref_version = CLng(version_text)
                Dim reg_version As Long: reg_version = GetOcxMajorVersion(guid, ref_version)

                'change line if necessary
                If reg_version < ref_version Then
                    Err.Raise -1, , "Registered version precedes referenced version."
                ElseIf reg_version > ref_version Then
                    line = Left(line, version_start - 1) & CStr(reg_version) & Mid(line, version_end)
                    changes_made = True
                End If
            End If

            file_data = file_data & line & vbNewLine
        Wend
    Close fn

    'Write
    If changes_made Then
        Kill path
        Open path For Binary As fn
            Put fn, , file_data
        Close fn
    End If
End Sub

'''Changes any invalid in included files to newer registered version
Public Sub UpdateSubFileOCXReferences(ByVal path As String)
    Dim folder As String: folder = RemoveFilename(path)
    Dim fn As Long: fn = FreeFile
    Open path For Input As fn
        While Not EOF(fn)
            Dim line As String
            Line Input #fn, line

            If LCase(line) Like "form=*.frm" _
                            Or LCase(line) Like "usercontrol=*.ctl" Then
                Dim file As String: file = folder & Mid(line, InStr(line, "=") + 1)
                If Dir(file) <> "" Then
                    UpdateFileOCXReferences file
                End If
            End If
        Wend
    Close fn
End Sub
</code>```

OwnerDisplayName: Strilanc

Body:
Self-answer: I have written some vb6 code to do the upgrade programmatically. It is not extensively tested, there are probably a few bugs here and there for corner cases, but I did use it successfully.

Option Explicit

Const HKEY_LOCAL_MACHINE As Long = &H80000002
Const KEY_ENUMERATE_SUB_KEYS As Long = 8
Private Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long
Private Declare Function RegEnumKeyEx Lib "advapi32.dll" Alias "RegEnumKeyExA" (ByVal hKey As Long, ByVal dwIndex As Long, ByVal lpName As String, lpcbName As Long, lpReserved As Long, ByVal lpClass As String, lpcbClass As Long, lpftLastWriteTime As Any) As Long
Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long

'''Returns the expected major version of a GUID if it exists, and otherwise returns the highest registered major version.
Public Function GetOcxMajorVersion(ByVal guid As String, Optional ByVal expected_version As Long) As Long
    Const BUFFER_SIZE As Long = 255
    Dim reg_key As Long
    Dim ret As Long
    Dim enum_index As Long
    Dim max_version As Long: max_version = -1

    ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\Classes\TypeLib\{" & guid & "}", 0, KEY_ENUMERATE_SUB_KEYS, reg_key)
    If ret <> 0 Then Err.Raise ret, , "Failed to open registry key."
    Do
        'Store next subkey name in buffer
        Dim buffer As String: buffer = Space(BUFFER_SIZE)
        Dim cur_buffer_size As Long: cur_buffer_size = BUFFER_SIZE
        ret = RegEnumKeyEx(reg_key, enum_index, buffer, cur_buffer_size, ByVal 0&, vbNullString, ByVal 0&, ByVal 0&)
        If ret <> 0 Then Exit Do
        buffer = Left(buffer, cur_buffer_size)

        'Keep most likely version
        buffer = Split(buffer, ".")(0)
        If Not buffer Like "*[!0-9A-B]*" And Len(buffer) < 4 Then
            Dim v As Long: v = CLng("&H" & buffer) 'convert from hex
            If v = expected_version Then
                max_version = v
                Exit Do
            ElseIf max_version < v Then
                max_version = v
            End If
        End If

        enum_index = enum_index + 1
    Loop
    RegCloseKey reg_key

    If max_version = -1 Then Err.Raise -1, , "Failed to enumerate any viable subkeys."
    GetOcxMajorVersion = max_version
End Function

Public Function RemoveFilename(ByVal path As String) As String
    Dim folders() As String: folders = Split(Replace(path, "/", "\"), "\")
    RemoveFilename = Left(path, Len(path) - Len(folders(UBound(folders))))
End Function

'''Changes any invalid OCX references to newer registered version
Public Sub UpdateFileOCXReferences(ByVal path As String)
    Dim file_data As String
    Dim changes_made As Boolean

    'Read
    Dim fn As Long: fn = FreeFile
    Open path For Input As fn
        While Not EOF(fn)
            Dim line As String
            Line Input #fn, line

            'check for ocx reference line
            If LCase(line) Like "object*=*{*-*-*-*-*}[#]*#.#*[#]#*;*.ocx*" Then
                'get guid
                Dim guid_start As Long: guid_start = InStr(line, "{") + 1
                Dim guid_end As Long: guid_end = InStr(line, "}")
                Dim guid As String: guid = Mid(line, guid_start, guid_end - guid_start)

                'get reference major version
                Dim version_start As Long: version_start = InStr(line, "#") + 1
                Dim version_end As Long: version_end = InStr(version_start + 1, line, ".")
                Dim version_text As String: version_text = Mid(line, version_start, version_end - version_start)

                'play it safe
                If Len(guid) <> 32 + 4 Then Err.Raise -1, , "GUID has unexpected length."
                If Len(version_text) > 4 Then Err.Raise -1, , "Major version is larger than expected."
                If guid Like "*[!0-9A-F-]*" Then Err.Raise -1, , "GUID has unexpected characters."
                If version_text Like "*[!0-9]*" Then Err.Raise -1, , "Major version isn't an integer."

                'get registry major version
                Dim ref_version As Long: ref_version = CLng(version_text)
                Dim reg_version As Long: reg_version = GetOcxMajorVersion(guid, ref_version)

                'change line if necessary
                If reg_version < ref_version Then
                    Err.Raise -1, , "Registered version precedes referenced version."
                ElseIf reg_version > ref_version Then
                    line = Left(line, version_start - 1) & CStr(reg_version) & Mid(line, version_end)
                    changes_made = True
                End If
            End If

            file_data = file_data & line & vbNewLine
        Wend
    Close fn

    'Write
    If changes_made Then
        Kill path
        Open path For Binary As fn
            Put fn, , file_data
        Close fn
    End If
End Sub

'''Changes any invalid in included files to newer registered version
Public Sub UpdateSubFileOCXReferences(ByVal path As String)
    Dim folder As String: folder = RemoveFilename(path)
    Dim fn As Long: fn = FreeFile
    Open path For Input As fn
        While Not EOF(fn)
            Dim line As String
            Line Input #fn, line

            If LCase(line) Like "form=*.frm" _
                            Or LCase(line) Like "usercontrol=*.ctl" Then
                Dim file As String: file = folder & Mid(line, InStr(line, "=") + 1)
                If Dir(file) <> "" Then
                    UpdateFileOCXReferences file
                End If
            End If
        Wend
    Close fn
End Sub


问:
how convert string to path in opemnmt-py
I use opennmt-py for MT and in the code any time I want to set a path I have to write all directory and it's not good looking when I have long directory. is there any way to set a string as the main directory and just add the file name to the end.
I use google colab to train the model
The code is like:

```<code>!onmt_preprocess  \\
-train_src //content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//train.en \\
-train_tgt //content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//train.fa \\
-valid_src //content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//dev.en \\
-valid_tgt  //content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//dev.fa \\
-save_data //content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//demo//
</code>```

and the code I want to be like:

```<code>path ='//content//dri`ve//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//'

!onmt_preprocess  \\
-train_src path+'train.en' \\
-train_tgt path+'train.fa' \\
-valid_src path+'dev.en' \\
-valid_tgt  path++'dev.fa' \\
-save_data path+'demo//'
</code>```

or maybe just can write all path in a variable and use it like:

```<code>path_train ='//content//dri`ve//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//'

!onmt_preprocess  \\
-train_src path_train \\
</code>```

答:
You may use a mere concatenation:

```<code>path='//content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//'
!onmt_preprocess  \\
  -train_src $path'train.en' \\
  -train_tgt $path'train.fa' \\
  -valid_src $path'dev.en' \\
  -valid_tgt $path'dev.fa' \\
  -save_data $path'demo//'
</code>```

Notes:

The variable path must be followed with =, not a space. There must be no spaces around =. The path = 'text' is wrong, path ='text' is wrong, path= 'text' is also wrong.

When you use a variable, prepend it with $: !echo $path'train.en' will print //content//drive//My Drive//Colab Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//train.en

Concatenation means just glueing string literals to variables no need using +, &, etc.

Body:
I use opennmt-py for MT and in the code any time I want to set a path I have to write all directory and it's not good looking when I have long directory. is there any way to set a string as the main directory and just add the file name to the end.
I use google colab to train the model
The code is like:

!onmt_preprocess  \\
-train_src //content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//train.en \\
-train_tgt //content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//train.fa \\
-valid_src //content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//dev.en \\
-valid_tgt  //content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//dev.fa \\
-save_data //content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//demo//

and the code I want to be like:

path ='//content//dri`ve//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//'

!onmt_preprocess  \\
-train_src path+'train.en' \\
-train_tgt path+'train.fa' \\
-valid_src path+'dev.en' \\
-valid_tgt  path++'dev.fa' \\
-save_data path+'demo//'

or maybe just can write all path in a variable and use it like:

path_train ='//content//dri`ve//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//'

!onmt_preprocess  \\
-train_src path_train \\

Body:
You may use a mere concatenation:

path='//content//drive//My\ Drive//Colab\ Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//'
!onmt_preprocess  \\
  -train_src $path'train.en' \\
  -train_tgt $path'train.fa' \\
  -valid_src $path'dev.en' \\
  -valid_tgt $path'dev.fa' \\
  -save_data $path'demo//'

Notes:

The variable path must be followed with =, not a space. There must be no spaces around =. The path = 'text' is wrong, path ='text' is wrong, path= 'text' is also wrong.

When you use a variable, prepend it with $: !echo $path'train.en' will print //content//drive//My Drive//Colab Notebooks//NLP//spring99//CA6//Corpora//En2Fa-Translation//train.en

Concatenation means just glueing string literals to variables no need using +, &, etc.


问:
How to access a classes attribute variable in other method
I am learning python3 and I want to know that how I can

```<code>class testit:
    def assigna():
        a = "Hi"

    def geta(self):
        print(self.a)

test = testit
print(test.geta())
</code>```

How can I access a inside of geta as suggested in comments I tried to use self.a and it gives me an error.

Here is my Updated Code

```<code>class testit:
    def assigna(self):
        self.a = "Hi"

    def geta(self):
        print(self.a)

test = testit
print(test.geta())
</code>```

and here is the error.

```<code>Traceback (most recent call last):
  File "test.py", line 44, in <module>
    print(test.geta())
TypeError: geta() missing 1 required positional argument: 'self'

</code>```

答:
You can access the instance based variable through self but you have to assign to it in the constructor,  Here is a little code for you:

```<code>class Test:
  def __init__(self):
      self.a = ""
  def assign_a(self):
      self.a = "Hi"
  def get_a(self):
     print(self.a)
</code>```

So you can access it like :

```<code>test = Test()
test.assign_a()
test.get_a()
</code>```

Here look at the __init__ function carefully it is called the constructor and inside it we are declaring variable a through self. Now this variable will be accessible throughout the class.

Enjoy learning !!

Body:
I am learning python3 and I want to know that how I can

class testit:
    def assigna():
        a = "Hi"

    def geta(self):
        print(self.a)

test = testit
print(test.geta())

How can I access a inside of geta as suggested in comments I tried to use self.a and it gives me an error.

Here is my Updated Code

class testit:
    def assigna(self):
        self.a = "Hi"

    def geta(self):
        print(self.a)

test = testit
print(test.geta())

and here is the error.

Traceback (most recent call last):
  File "test.py", line 44, in <module>
    print(test.geta())
TypeError: geta() missing 1 required positional argument: 'self'

Body:
You can access the instance based variable through self but you have to assign to it in the constructor,  Here is a little code for you:

class Test:
  def __init__(self):
      self.a = ""
  def assign_a(self):
      self.a = "Hi"
  def get_a(self):
     print(self.a)

So you can access it like :

test = Test()
test.assign_a()
test.get_a()

Here look at the __init__ function carefully it is called the constructor and inside it we are declaring variable a through self. Now this variable will be accessible throughout the class.

Enjoy learning !!