问:
How can i make the box expand?
this is my contact form and the footer with the logo. when an error pops up, the button hides under the footer, how can I make the contact form expand or the footer to go down?

This is my css for the contact form

```<code>element.style {
}
.vincent_reservation_full .vincent_reservation_block {
    background: transparent;
    padding: 100px 205px 105px 205px;
    position: relative;
}
.vincent_reservation_block {
    padding: 102px 100px 105px 100px;
    text-align: center;
    background-image: url(../img/back_1.jpg);
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    overflow: hidden;
}
* {
    margin: 0;
    padding: 0;
}
* {
    margin: 0;
    padding: 0;
    outline: 0;
    -webkit-overflow-scrolling: touch;
}
*, *:before, *:after {
    box-sizing: inherit;
}
user agent stylesheet
div {
    display: block;
}
body {
    width: 100%;
    overflow-x: hidden;
    font-family: "Open Sans";
    font-size: 16px;
    line-height: 28px;
    font-weight: 300;
    color: #dce4e8;
    background-color: #121618;
    -webkit-font-smoothing: antialiased;
}
body {
    font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
    color: #313439;
    background-color: transparent;
}
html, body {
    font-size: 16px;
    line-height: 24px;
}
user agent stylesheet
html {
    color: -internal-root-color;
}
*, *:before, *:after {
    box-sizing: inherit;
}
*, *:before, *:after {
    box-sizing: inherit;
}
</code>```

and this is my css for the footer

```<code>
element.style {
}
footer {
    border-top: 1px solid #1d2326;
    color: #ffffff;
    text-align: center;
}
.vincent_menu>li>a, footer, .vincent_infobox_content h5, .vincent_advantages_item_dark h4, .vincent_collapse_item_content a:hover, .vincent_slider_main_item_text, .vincent_slider_main_item_cont h1, .vincent_slider_main_item h1, .vincent_slider_main_item h2, .vincent_slider_main_item_text, .vincent_post_item .vincent_button_background:hover, .vincent_slider_price, .vincent_hom4_block2_button:hover, .vincent_404_content_wrapper h1, .vincent_404_text, .vincent_sharing a:hover {
    color: #ffffff;
}
* {
    margin: 0;
    padding: 0;
}
* {
    margin: 0;
    padding: 0;
    outline: 0;
    -webkit-overflow-scrolling: touch;
}
*, *:before, *:after {
    box-sizing: inherit;
}
user agent stylesheet
footer {
    display: block;
}
body {
    width: 100%;
    overflow-x: hidden;
    font-family: "Open Sans";
    font-size: 16px;
    line-height: 28px;
    font-weight: 300;
    color: #dce4e8;
    background-color: #121618;
    -webkit-font-smoothing: antialiased;
}
body {
    font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
    color: #313439;
    background-color: transparent;
}
html, body {
    font-size: 16px;
    line-height: 24px;
}
user agent stylesheet
html {
    color: -internal-root-color;
}
*, *:before, *:after {
    box-sizing: inherit;
}
*, *:before, *:after {
    box-sizing: inherit;
}
</code>```

how can i make the contact form expland and show the submit button?

答: you have this problem becouse errors create extra space. Make your contact form section (wrapper) height from 100% to min-height: 100% so when ever errors come out everyting can expand and fit </p>

Title: How can i make the box expand?

Body:
this is my contact form and the footer with the logo. when an error pops up, the button hides under the footer, how can I make the contact form expand or the footer to go down?

This is my css for the contact form

element.style {
}
.vincent_reservation_full .vincent_reservation_block {
    background: transparent;
    padding: 100px 205px 105px 205px;
    position: relative;
}
.vincent_reservation_block {
    padding: 102px 100px 105px 100px;
    text-align: center;
    background-image: url(../img/back_1.jpg);
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    overflow: hidden;
}
* {
    margin: 0;
    padding: 0;
}
* {
    margin: 0;
    padding: 0;
    outline: 0;
    -webkit-overflow-scrolling: touch;
}
*, *:before, *:after {
    box-sizing: inherit;
}
user agent stylesheet
div {
    display: block;
}
body {
    width: 100%;
    overflow-x: hidden;
    font-family: "Open Sans";
    font-size: 16px;
    line-height: 28px;
    font-weight: 300;
    color: #dce4e8;
    background-color: #121618;
    -webkit-font-smoothing: antialiased;
}
body {
    font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
    color: #313439;
    background-color: transparent;
}
html, body {
    font-size: 16px;
    line-height: 24px;
}
user agent stylesheet
html {
    color: -internal-root-color;
}
*, *:before, *:after {
    box-sizing: inherit;
}
*, *:before, *:after {
    box-sizing: inherit;
}

and this is my css for the footer

element.style {
}
footer {
    border-top: 1px solid #1d2326;
    color: #ffffff;
    text-align: center;
}
.vincent_menu>li>a, footer, .vincent_infobox_content h5, .vincent_advantages_item_dark h4, .vincent_collapse_item_content a:hover, .vincent_slider_main_item_text, .vincent_slider_main_item_cont h1, .vincent_slider_main_item h1, .vincent_slider_main_item h2, .vincent_slider_main_item_text, .vincent_post_item .vincent_button_background:hover, .vincent_slider_price, .vincent_hom4_block2_button:hover, .vincent_404_content_wrapper h1, .vincent_404_text, .vincent_sharing a:hover {
    color: #ffffff;
}
* {
    margin: 0;
    padding: 0;
}
* {
    margin: 0;
    padding: 0;
    outline: 0;
    -webkit-overflow-scrolling: touch;
}
*, *:before, *:after {
    box-sizing: inherit;
}
user agent stylesheet
footer {
    display: block;
}
body {
    width: 100%;
    overflow-x: hidden;
    font-family: "Open Sans";
    font-size: 16px;
    line-height: 28px;
    font-weight: 300;
    color: #dce4e8;
    background-color: #121618;
    -webkit-font-smoothing: antialiased;
}
body {
    font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
    color: #313439;
    background-color: transparent;
}
html, body {
    font-size: 16px;
    line-height: 24px;
}
user agent stylesheet
html {
    color: -internal-root-color;
}
*, *:before, *:after {
    box-sizing: inherit;
}
*, *:before, *:after {
    box-sizing: inherit;
}

how can i make the contact form expland and show the submit button?


来源: stackexchange

问:
Select randomly x files in subdirectories
I need to take exactly 10 files (images) in a dataset randomly, but this dataset is hierarchically structured.

So I need that for each subdirectory that contains images hold just 10 of them randomly. Is there an easy way to do that or I should do it manually?

```<code>def getListOfFiles(dirName):
    ### create a list of file and sub directories
    ### names in the given directory
    listOfFile = os.listdir(dirName)
    allFiles = list()
    ### Iterate over all the entries
    for entry in listOfFile:

        ### Create full path
        fullPath = os.path.join(dirName, entry)
        ### If entry is a directory then get the list of files in this directory
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(random.sample(fullPath, 10))
    return allFiles

dirName = 'C:/Users/bla/bla'

### Get the list of all files in directory tree at given path
listOfFiles = getListOfFiles(dirName)

with open("elements.txt", mode='x') as f:
    for elem in listOfFiles:
        f.write(elem + '\n')
</code>```

答:
Good approach to sample from unknown size directory listing is to use Reservoir Sampling. With this approach, you don't have to run upfront and list all files in the directory. Read it one-by-one and sample. It even works when you have to sample fixed number of files across multiple directories.

It would be good to use generator-based directory scanning code, which picks one file at a time, thus you don't use gobs of memory upfront to hold all file names.

Along the lines (NB! undested code!)

```<code>import numpy as np
import os

def ResSampleFiles(dirname, N):
    """pick N files from directory"""

    sampled_files = list()
    k = 0
    for item in scandir(dirname):
        if item.is_dir():
            continue
        full_path = os.path.join(dirname, item.name)
        if k < N:
            sampled_files.append(full_path)
        else:
            idx = np.random.randint(0, k+1)
            if (idx < N):
                sampled_files[idx] = full_path
        k += 1

    return sampled_files
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to take exactly 10 files (images) in a dataset randomly, but this dataset is hierarchically structured.

So I need that for each subdirectory that contains images hold just 10 of them randomly. Is there an easy way to do that or I should do it manually?

def getListOfFiles(dirName):
    ### create a list of file and sub directories
    ### names in the given directory
    listOfFile = os.listdir(dirName)
    allFiles = list()
    ### Iterate over all the entries
    for entry in listOfFile:

        ### Create full path
        fullPath = os.path.join(dirName, entry)
        ### If entry is a directory then get the list of files in this directory
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(random.sample(fullPath, 10))
    return allFiles

dirName = 'C:/Users/bla/bla'

### Get the list of all files in directory tree at given path
listOfFiles = getListOfFiles(dirName)

with open("elements.txt", mode='x') as f:
    for elem in listOfFiles:
        f.write(elem + '\n')

Body:
Good approach to sample from unknown size directory listing is to use Reservoir Sampling. With this approach, you don't have to run upfront and list all files in the directory. Read it one-by-one and sample. It even works when you have to sample fixed number of files across multiple directories.

It would be good to use generator-based directory scanning code, which picks one file at a time, thus you don't use gobs of memory upfront to hold all file names.

Along the lines (NB! undested code!)

import numpy as np
import os

def ResSampleFiles(dirname, N):
    """pick N files from directory"""

    sampled_files = list()
    k = 0
    for item in scandir(dirname):
        if item.is_dir():
            continue
        full_path = os.path.join(dirname, item.name)
        if k < N:
            sampled_files.append(full_path)
        else:
            idx = np.random.randint(0, k+1)
            if (idx < N):
                sampled_files[idx] = full_path
        k += 1

    return sampled_files


问:
Using Python to send email, sourcing the recipient list from a text file
I have been able to scrape together the below code, which I can now use to send an email via OSX10.6. What I wish to add to this script however is the ability to 'source' the recipient list directly from a text file within the same directory as the python file itself.

I also wish to hard code the 'sender' element because that will remain static. Help please.

```<code>#!/usr/bin/env python

"""Send the contents of a directory as a MIME message."""

import os
import sys
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from optparse import OptionParser

from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

COMMASPACE = ', '

def main():
parser = OptionParser(usage="""\
Send the contents of a directory as a MIME message.

Usage: %prog [options]

Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process. Your local machine
must be running an SMTP server.
""")
parser.add_option('-d','--directory',
type='string', action='store')
parser.add_option('-o', '--output',
type='string', action='store', metavar='FILE',
help="""Print the composed message to FILE instead of
sending the message to the SMTP server.""")
parser.add_option('-s', '--sender',
type='string', action='store', metavar='SENDER',
help='The value of the From: header (required)')
parser.add_option('-r', '--recipients',
type='string', action='store', metavar='RECIPIENT',
default="recipient.txt", dest='recipients',
help='A file containing email addresses of recipients. One recipient per line')
opts, args = parser.parse_args()
if not opts.sender or not opts.recipients:
    parser.print_help()
    sys.exit(1)
directory = opts.directory
if not directory:
    directory = '.'
# Create the enclosing (outer) message
outer = MIMEMultipart()
outer['Subject'] = 'Malware submission'

# Variable to hold the recipients string
rec = ""
# Open recipients file
f = open(opts.recipients)
# Loop through each line of the file
for line in f:
    # Remove whitespace from line and add COMMASPACE
    rec += line.rstrip() + COMMASPACE
f.close()

outer['To'] = rec[:-2]; #Remove last COMMASPACE
outer['From'] = opts.sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

for filename in os.listdir(directory):
    path = os.path.join(directory, filename)
    if not os.path.isfile(path):
        continue
    # Guess the content type based on the file's extension. Encoding
    # will be ignored, although we should check for simple things like
    # gzip'd or compressed files.
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
    # No guess could be made, or the file is encoded (compressed), so
    # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
    if maintype == 'text':
        fp = open(path)
    # Note: we should handle calculating the charset
        msg = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'image':
        fp = open(path, 'rb')
        msg = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'audio':
        fp = open(path, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(path, 'rb')
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(fp.read())
        fp.close()
    # Encode the payload using Base64
    encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=filename)
outer.attach(msg)
# Now send or store the message
composed = outer.as_string()
if opts.output:
    fp = open(opts.output, 'w')
    fp.write(composed)
    fp.close()
else:
    s = smtplib.SMTP('localhost')
    s.sendmail(opts.sender, opts.recipients, composed)
    s.quit()

if __name__ == '__main__':
main()
</code>```

Many thanks.

答:
OK, so I have (or more accurately a colleague has) solved the issue. Code as follows and a BIG thank you to Paul Littlefair for the solution.

```<code>#!/usr/bin/env python

"""Send the contents of a directory as a MIME message."""

import os
import sys
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from optparse import OptionParser

from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

COMMASPACE = ', '

def main():
parser = OptionParser(usage="""\
Send the contents of a directory as a MIME message.

Usage: %prog [options]

Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process. Your local machine
must be running an SMTP server.
""")
parser.add_option('-d','--directory',
type='string', action='store')
parser.add_option('-o', '--output',
type='string', action='store', metavar='FILE',
help="""Print the composed message to FILE instead of
sending the message to the SMTP server.""")
parser.add_option('-s', '--sender',
type='string', action='store', metavar='SENDER',
help='The value of the From: header (required)')
parser.add_option('-r', '--recipient',
type='string', action='append', metavar='RECIPIENT',
default=[], dest='recipients'),
parser.add_option('-f', '--recipientfile',
type='string', action='store', metavar='RECIPIENT_FILE',
dest='recipient_file', default="",
help='A To: header value (a file containing this)')

opts, args = parser.parse_args()
if not opts.sender or not (opts.recipient_file or opts.recipients):
    parser.print_help()
    sys.exit(1)
directory = opts.directory
if not directory:
    directory = '.'
# Create the enclosing (outer) message

try:
    rec_file = open(opts.recipient_file)
    recipients = rec_file.read()
    rec_file.close()
except IOError:
    print "/!\ Bad file. Falling back to recipent option"
    recipients = COMMASPACE.join(opts.recipients)

outer = MIMEMultipart()
outer['Subject'] = 'Malware submission'
outer['To'] = recipients
outer['From'] = opts.sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

for filename in os.listdir(directory):
    path = os.path.join(directory, filename)
    if not os.path.isfile(path):
        continue
    # Guess the content type based on the file's extension. Encoding
    # will be ignored, although we should check for simple things like
    # gzip'd or compressed files.
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
    # No guess could be made, or the file is encoded (compressed), so
    # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
    if maintype == 'text':
        fp = open(path)
    # Note: we should handle calculating the charset
        msg = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'image':
        fp = open(path, 'rb')
        msg = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'audio':
        fp = open(path, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(path, 'rb')
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(fp.read())
        fp.close()
    # Encode the payload using Base64
    encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=filename)
outer.attach(msg)
# Now send or store the message
composed = outer.as_string()
if opts.output:
    fp = open(opts.output, 'w')
    fp.write(composed)
    fp.close()
else:
    s = smtplib.SMTP('localhost')
    s.sendmail(opts.sender, recipients, composed)
    s.quit()

if __name__ == '__main__':
main()
</code>```

Input format is -d [dir] -s [fromaddress] -f [recipientsourcefile]

ContentLicense: CC BY-SA 3.0

Body:
I have been able to scrape together the below code, which I can now use to send an email via OSX10.6. What I wish to add to this script however is the ability to 'source' the recipient list directly from a text file within the same directory as the python file itself.

I also wish to hard code the 'sender' element because that will remain static. Help please.

#!/usr/bin/env python

"""Send the contents of a directory as a MIME message."""

import os
import sys
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from optparse import OptionParser

from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

COMMASPACE = ', '

def main():
parser = OptionParser(usage="""\
Send the contents of a directory as a MIME message.

Usage: %prog [options]

Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process. Your local machine
must be running an SMTP server.
""")
parser.add_option('-d','--directory',
type='string', action='store')
parser.add_option('-o', '--output',
type='string', action='store', metavar='FILE',
help="""Print the composed message to FILE instead of
sending the message to the SMTP server.""")
parser.add_option('-s', '--sender',
type='string', action='store', metavar='SENDER',
help='The value of the From: header (required)')
parser.add_option('-r', '--recipients',
type='string', action='store', metavar='RECIPIENT',
default="recipient.txt", dest='recipients',
help='A file containing email addresses of recipients. One recipient per line')
opts, args = parser.parse_args()
if not opts.sender or not opts.recipients:
    parser.print_help()
    sys.exit(1)
directory = opts.directory
if not directory:
    directory = '.'
# Create the enclosing (outer) message
outer = MIMEMultipart()
outer['Subject'] = 'Malware submission'

# Variable to hold the recipients string
rec = ""
# Open recipients file
f = open(opts.recipients)
# Loop through each line of the file
for line in f:
    # Remove whitespace from line and add COMMASPACE
    rec += line.rstrip() + COMMASPACE
f.close()

outer['To'] = rec[:-2]; #Remove last COMMASPACE
outer['From'] = opts.sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

for filename in os.listdir(directory):
    path = os.path.join(directory, filename)
    if not os.path.isfile(path):
        continue
    # Guess the content type based on the file's extension. Encoding
    # will be ignored, although we should check for simple things like
    # gzip'd or compressed files.
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
    # No guess could be made, or the file is encoded (compressed), so
    # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
    if maintype == 'text':
        fp = open(path)
    # Note: we should handle calculating the charset
        msg = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'image':
        fp = open(path, 'rb')
        msg = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'audio':
        fp = open(path, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(path, 'rb')
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(fp.read())
        fp.close()
    # Encode the payload using Base64
    encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=filename)
outer.attach(msg)
# Now send or store the message
composed = outer.as_string()
if opts.output:
    fp = open(opts.output, 'w')
    fp.write(composed)
    fp.close()
else:
    s = smtplib.SMTP('localhost')
    s.sendmail(opts.sender, opts.recipients, composed)
    s.quit()

if __name__ == '__main__':
main()

Many thanks.

Body:
OK, so I have (or more accurately a colleague has) solved the issue. Code as follows and a BIG thank you to Paul Littlefair for the solution.

#!/usr/bin/env python

"""Send the contents of a directory as a MIME message."""

import os
import sys
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from optparse import OptionParser

from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

COMMASPACE = ', '

def main():
parser = OptionParser(usage="""\
Send the contents of a directory as a MIME message.

Usage: %prog [options]

Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process. Your local machine
must be running an SMTP server.
""")
parser.add_option('-d','--directory',
type='string', action='store')
parser.add_option('-o', '--output',
type='string', action='store', metavar='FILE',
help="""Print the composed message to FILE instead of
sending the message to the SMTP server.""")
parser.add_option('-s', '--sender',
type='string', action='store', metavar='SENDER',
help='The value of the From: header (required)')
parser.add_option('-r', '--recipient',
type='string', action='append', metavar='RECIPIENT',
default=[], dest='recipients'),
parser.add_option('-f', '--recipientfile',
type='string', action='store', metavar='RECIPIENT_FILE',
dest='recipient_file', default="",
help='A To: header value (a file containing this)')

opts, args = parser.parse_args()
if not opts.sender or not (opts.recipient_file or opts.recipients):
    parser.print_help()
    sys.exit(1)
directory = opts.directory
if not directory:
    directory = '.'
# Create the enclosing (outer) message

try:
    rec_file = open(opts.recipient_file)
    recipients = rec_file.read()
    rec_file.close()
except IOError:
    print "/!\ Bad file. Falling back to recipent option"
    recipients = COMMASPACE.join(opts.recipients)

outer = MIMEMultipart()
outer['Subject'] = 'Malware submission'
outer['To'] = recipients
outer['From'] = opts.sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

for filename in os.listdir(directory):
    path = os.path.join(directory, filename)
    if not os.path.isfile(path):
        continue
    # Guess the content type based on the file's extension. Encoding
    # will be ignored, although we should check for simple things like
    # gzip'd or compressed files.
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
    # No guess could be made, or the file is encoded (compressed), so
    # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
    if maintype == 'text':
        fp = open(path)
    # Note: we should handle calculating the charset
        msg = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'image':
        fp = open(path, 'rb')
        msg = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'audio':
        fp = open(path, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(path, 'rb')
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(fp.read())
        fp.close()
    # Encode the payload using Base64
    encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=filename)
outer.attach(msg)
# Now send or store the message
composed = outer.as_string()
if opts.output:
    fp = open(opts.output, 'w')
    fp.write(composed)
    fp.close()
else:
    s = smtplib.SMTP('localhost')
    s.sendmail(opts.sender, recipients, composed)
    s.quit()

if __name__ == '__main__':
main()

Input format is -d [dir] -s [fromaddress] -f [recipientsourcefile]


问:
POST Method Always Returns 405 Response
I have a .NET Core 3.1 API that has two endpoints I am using to test some error handling middleware that I am writing. I am using Swagger UI to test this API.

The issue I'm having is that if any kind of exception is thrown during the execution of my POST request, it will be returned back as a 405 response and not even trigger the error handling middleware I am writing. This happens for ALL POST request across my API, not just the test one I am showing.

I decided to try an equally simple GET method and to my surprise, when an exception was thrown within it, it would trigger my error handling middleware which would then write a 500 response back to the caller. Here is the whole controller code:

```<code>[Route("api/[controller]")]
[ApiController]

public class TestingController : ControllerBase
{
    [HttpPost]
    [Route("TestPost")]
    public IActionResult TestPost([FromBody] string test)
    {
        throw new Exception();
    }

    [HttpGet]
    [Route("TestGet/{test}")]
    public IActionResult TestGet(string test)
    {
        throw new Exception();
    }

}
</code>```

So why would a POST method be returning a 405 resposne when an exception occurs, but a GET method responds with a 500 response?

EDIT: Here is the example POST request I am making

Request URL: https://localhost:44387/api/Testing/TestPost

Request Body(JSON): "test"

Here are the response headers I receive from the POST:

allow: GET
 cache-control: no-cache
 date: Wed, 19 Feb 2020 17:58:22 GMT
 expires: -1
 pragma: no-cache
 server: Microsoft-IIS/10.0
 status: 405
 x-powered-by: ASP.NET

答:
So I eventually figured this out with some help from Rahul Sharma
. The issue did not have anything to do with the POST method, but rather the custom error handling controller that the POST request was trying to be routed to. The method in the error controller was defined as the following:

```<code>    [Route("/Error-descriptive")]
    [HttpGet]
    public IActionResult ErrorDescriptive()
    {
        if (!_env.IsNonProductionEnv())
            throw new InvalidOperationException("This endpoint cannot be invoked in a production environment.");

        IExceptionHandlerFeature exFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
        Exception ex = exFeature.Error;

        return Problem(detail: ex.StackTrace, title: ex.Message);
    }
</code>```

The issue was the [HttpGet] attribute used on this method, this was preventing my POST request from being routed to this controller when the exception occurred, which in turn produced a 405 response. Removing the attribute allows the error handler code to run, and produce a 500 response.

I apologize for not adding this code initially, however I was pretty confident that this code was not a cause of the issue because the code in the error controller wasn't being executed at all.

Title: POST Method Always Returns 405 Response

Body:
I have a .NET Core 3.1 API that has two endpoints I am using to test some error handling middleware that I am writing. I am using Swagger UI to test this API.

The issue I'm having is that if any kind of exception is thrown during the execution of my POST request, it will be returned back as a 405 response and not even trigger the error handling middleware I am writing. This happens for ALL POST request across my API, not just the test one I am showing.

I decided to try an equally simple GET method and to my surprise, when an exception was thrown within it, it would trigger my error handling middleware which would then write a 500 response back to the caller. Here is the whole controller code:

[Route("api/[controller]")]
[ApiController]

public class TestingController : ControllerBase
{
    [HttpPost]
    [Route("TestPost")]
    public IActionResult TestPost([FromBody] string test)
    {
        throw new Exception();
    }

    [HttpGet]
    [Route("TestGet/{test}")]
    public IActionResult TestGet(string test)
    {
        throw new Exception();
    }

}

So why would a POST method be returning a 405 resposne when an exception occurs, but a GET method responds with a 500 response?

EDIT: Here is the example POST request I am making

Request URL: https://localhost:44387/api/Testing/TestPost

Request Body(JSON): "test"

Here are the response headers I receive from the POST:

allow: GET
 cache-control: no-cache
 date: Wed, 19 Feb 2020 17:58:22 GMT
 expires: -1
 pragma: no-cache
 server: Microsoft-IIS/10.0
 status: 405
 x-powered-by: ASP.NET

Body:
So I eventually figured this out with some help from Rahul Sharma
. The issue did not have anything to do with the POST method, but rather the custom error handling controller that the POST request was trying to be routed to. The method in the error controller was defined as the following:

    [Route("/Error-descriptive")]
    [HttpGet]
    public IActionResult ErrorDescriptive()
    {
        if (!_env.IsNonProductionEnv())
            throw new InvalidOperationException("This endpoint cannot be invoked in a production environment.");

        IExceptionHandlerFeature exFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
        Exception ex = exFeature.Error;

        return Problem(detail: ex.StackTrace, title: ex.Message);
    }

The issue was the [HttpGet] attribute used on this method, this was preventing my POST request from being routed to this controller when the exception occurred, which in turn produced a 405 response. Removing the attribute allows the error handler code to run, and produce a 500 response.

I apologize for not adding this code initially, however I was pretty confident that this code was not a cause of the issue because the code in the error controller wasn't being executed at all.


问:
Xml angle brackets are changed to ampersand lt semicolon
I have following code and my message is in xml formatted and it is huge data. I am not getting my message in  and  . Xml angle brackets are now transformed. I would like to have angle brackets rather than ampersand lt semicolon.</p>

```<code><createOrderRequestType xmlns:ns2="http://xmlns.oracle.com/communications/ordermanagement">
    <msg><head></head>
</body>
</msg>
</createOrderRequestType>

<msg>
<head> </head>
<body> </body>
</msg>

public CreateOrderResponseType createAncillariesBySoloOrderId(String soloOrderId) {
        String message = findOrderBySoloOrderId(soloOrderId);

        final Pattern pattern = Pattern.compile("<msg xmlns=\"\">(.+?)</msg>", Pattern.DOTALL);
        final Matcher matcher = pattern.matcher(message);
        matcher.find();
        String msgStr =  matcher.group(1) ;
        log.info("message = " + msgStr );
CreateOrderRequestType createOrderRequestType = new CreateOrderRequestType() ;
        Document doc;
        try {
            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            Element msg = doc.createElement("msg");
            msg.setTextContent(msgStr);
            doc.appendChild(msg);
            createOrderRequestType.getAny().add((Element) doc.getFirstChild());

            StringWriter sw1 = new StringWriter();
            JAXB.marshal(createOrderRequestType, sw1);
            String xmlString = sw1.toString();
            log.info("xmlString = " + xmlString);

        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 return getOSMService(osmServiceUrl).createOrder(createOrderRequestType);
}

public class CreateOrderRequestType {

    @XmlAnyElement(lax = true)
    protected List<Object> any;

public List<Object> getAny() {
        if (any == null) {
            any = new ArrayList<Object>();
        }
        return this.any;
    }

}

</code>```

答:
It depends of XSD

But, i think it will be:

```<code>...
@XmlRootElement(name = "CreateOrderRequestType") // or probably (name = "CreateOrderRequest")
public class CreateOrderRequestType {
...
</code>```

and for response too

```<code>...
@XmlRootElement(name = "CreateOrderResponseType") // or probably (name = "CreateOrderResponse")
public class CreateOrderResponseType{
...
</code>```

Body:
I have following code and my message is in xml formatted and it is huge data. I am not getting my message in  and  . Xml angle brackets are now transformed. I would like to have angle brackets rather than ampersand lt semicolon.

<createOrderRequestType xmlns:ns2="http://xmlns.oracle.com/communications/ordermanagement">
    <msg>

</msg>
</createOrderRequestType>

<msg>

</msg>

public CreateOrderResponseType createAncillariesBySoloOrderId(String soloOrderId) {
        String message = findOrderBySoloOrderId(soloOrderId);

        final Pattern pattern = Pattern.compile("<msg xmlns=\"\">(.+?)</msg>", Pattern.DOTALL);
        final Matcher matcher = pattern.matcher(message);
        matcher.find();
        String msgStr =  matcher.group(1) ;
        log.info("message = " + msgStr );
CreateOrderRequestType createOrderRequestType = new CreateOrderRequestType() ;
        Document doc;
        try {
            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            Element msg = doc.createElement("msg");
            msg.setTextContent(msgStr);
            doc.appendChild(msg);
            createOrderRequestType.getAny().add((Element) doc.getFirstChild());

            StringWriter sw1 = new StringWriter();
            JAXB.marshal(createOrderRequestType, sw1);
            String xmlString = sw1.toString();
            log.info("xmlString = " + xmlString);

        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 return getOSMService(osmServiceUrl).createOrder(createOrderRequestType);
}

public class CreateOrderRequestType {

    @XmlAnyElement(lax = true)
    protected List<Object> any;

public List<Object> getAny() {
        if (any == null) {
            any = new ArrayList<Object>();
        }
        return this.any;
    }

}

Body:
It depends of XSD

But, i think it will be:

...
@XmlRootElement(name = "CreateOrderRequestType") // or probably (name = "CreateOrderRequest")
public class CreateOrderRequestType {
...

and for response too

...
@XmlRootElement(name = "CreateOrderResponseType") // or probably (name = "CreateOrderResponse")
public class CreateOrderResponseType{
...


问:
Datatype in converting dataframe from pandas to pyspark into foundry
For those of you working into Foundry's environnement, I'm trying to build a pipeline in "Code repositories" to process a raw dataset (from Excel file) into a clean one that I'll analyse in "Contour" later.
To that end I used python, except that pipeline seems to be using pyspark and at some point I must convert the dataset I've cleaned with pandas into a pyspark one and that's where i'm stuck.

I've looked at several post on stackover flow to convert Pandas DF to Pyspark DF but none of the solutions seems to be working so far.
When I try to run the transform, there's always a datatype failing to be converted evethough I forced a schema.

The Python code section has been tested succefully in Spyder (importing and exporting has an Excel file) and give the expected result. It's only when I need to convert to pyspark that it fails somehow.

```<code>@transform_pandas(
    Output("/MDM_OUT_OF_SERVICE_EVENTS_CLEAN"),
    OOS_raw=Input("/MDM_OUT_OF_SERVICE_EVENTS"),
)
def DA_transform(OOS_raw):

''' Code Section in Python '''

  mySchema=StructType([StructField(OOS_dup.columns[0], IntegerType(),
                   True),
                   StructField(OOS_dup.columns[1], StringType(), True),
                   ...])

  OOS_out=sqlContext.createDataFrame(OOS_dup,schema
    =mySchema,verifySchema=False)

return OOS_out
</code>```

I got this error message at some point :

```<code>AttributeError: 'unicode' object has no attribute 'toordinal'.
</code>```

According to this post : What is causing 'unicode' object has no attribute 'toordinal' in pyspark?

it's because pyspark fail to convert the Data into Datetype

but data is in Datetime64[ns] in pandas. I've tried converting this columns into string and integer and it fails as well.

Here is a picture of the output dataset from Python :

Here is the datatypes return by pandas once the data set has been cleaned :

```<code><class 'pandas.core.frame.DataFrame'>
RangeIndex: 4972 entries, 0 to 4971
Data columns (total 51 columns):
OOS_ID                       4972 non-null int64
OPERATOR_CODE                4972 non-null object
ATA_CAUSE                    4972 non-null int64
EVENT_CODE                   3122 non-null object
AC_MODEL                     4972 non-null object
AC_SN                        4972 non-null int64
OOS_DATE                     4972 non-null datetime64[ns]
AIRPORT_CODE                 4915 non-null object
RTS_DATE                     4972 non-null datetime64[ns]
EVENT_TYPE                   4972 non-null object
CORRECTIVE_ACTION            417 non-null object
DD_HOURS_OOS                 4972 non-null float64
EVENT_DESCRIPTION            4972 non-null object
EVENT_CATEGORY               4972 non-null object
ATA_REPORTED                 324 non-null float64
TOTAL_CAUSES                 4875 non-null float64
EVENT_NUMBER                 3117 non-null float64
RTS_TIME                     4972 non-null object
OOS_TIME                     4972 non-null object
PREV_REPORTED                4972 non-null object
FERRY_IND                    4972 non-null object
REPAIR_STN_CODE              355 non-null object
MAINT_DOWN_TIME              4972 non-null float64
LOGBOOK_RECORD_IDENTIFIER    343 non-null object
RTS_IND                      4972 non-null object
READY_FOR_USE                924 non-null object
DQ_COMMENTS                  2 non-null object
REVIEWED                     5 non-null object
DOES_NOT_MEET_SPECS          4 non-null object
CORRECTED                    12 non-null object
EDITED_BY                    4972 non-null object
EDIT_DATE                    4972 non-null datetime64[ns]
OUTSTATION_INDICATOR         3801 non-null object
COMMENT_TEXT                 11 non-null object
ATA_CAUSE_CHAPTER            4972 non-null int64
ATA_CAUSE_SECTION            4972 non-null int64
ATA_CAUSE_COMPONENT          770 non-null float64
PROCESSOR_COMMENTS           83 non-null object
PARTS_AVAIL_AT_STATION       4972 non-null object
PARTS_SHIPPED_AT_STATION     4972 non-null object
ENGINEER_AT_STATION          4972 non-null object
ENGINEER_SENT_AT_STATION     4972 non-null object
SOURCE_FILE                  4972 non-null object
OOS_Month                    4972 non-null float64
OOS_Hour                     4972 non-null float64
OOS_Min                      4972 non-null float64
RTS_Month                    4972 non-null float64
RTS_Hour                     4972 non-null float64
RTS_Min                      4972 non-null float64
OOS_Timestamp                4972 non-null datetime64[ns]
RTS_Timestamp                4972 non-null datetime64[ns]
dtypes: datetime64[ns](5), float64(12), int64(5), object(29)
</code>```

答:
In case it might help some of you I found this in the offical Foundry documentation on how to properly transition between pandas and pyspark DF.

OOS_dup is my Pandas dataframe I want to convert back to Spark.

```<code># Extract the name of each columns with its data type in pandas
    col = OOS_dup.columns
    col_type = list()

    for c in col:
        t = OOS_dup[c].dtype.name
        col_type.append(t)

    df_schema = pd.DataFrame({"field": col, "data_type": col_type})

    # Define a function to replace missing (NaN sky coverage cells with Null
    def replace_missing(df, col_names):
        for col in col_names:
            df = df.withColumn("{}".format(col),
                               F.when(df["{}".format(col)] == "NaN", None).otherwise(df["{}".format(col)]))
        return df

    # Replace missing values
    OOS_dup = replace_missing(OOS_dup, col)

    # Define a function to change column types to the proper type in spark
    def change_type(df, col_names, dtypes):
        for col in col_names:
            df = df.withColumn("{}".format(col), F.when(dtypes == "float64", (df["{}".format(col)]).cast("double")).when(dtypes == "int64", (df["{}".format(col)]).cast("int")).when(dtypes == "datetime64[ns]", (df["{}".format(col)]).cast("date")).otherwise((df["{}".format(col)]).cast("string")))
        return df

    # Cast each columns to the proper data type
    OOS_dup = change_type(OOS_dup, df_schema["field"], df_schema["data_type"])

    OOS_dup = sqlContext.createDataFrame(OOS_dup)
</code>```

Body:
For those of you working into Foundry's environnement, I'm trying to build a pipeline in "Code repositories" to process a raw dataset (from Excel file) into a clean one that I'll analyse in "Contour" later.
To that end I used python, except that pipeline seems to be using pyspark and at some point I must convert the dataset I've cleaned with pandas into a pyspark one and that's where i'm stuck.

I've looked at several post on stackover flow to convert Pandas DF to Pyspark DF but none of the solutions seems to be working so far.
When I try to run the transform, there's always a datatype failing to be converted evethough I forced a schema.

The Python code section has been tested succefully in Spyder (importing and exporting has an Excel file) and give the expected result. It's only when I need to convert to pyspark that it fails somehow.

@transform_pandas(
    Output("/MDM_OUT_OF_SERVICE_EVENTS_CLEAN"),
    OOS_raw=Input("/MDM_OUT_OF_SERVICE_EVENTS"),
)
def DA_transform(OOS_raw):

''' Code Section in Python '''

  mySchema=StructType([StructField(OOS_dup.columns[0], IntegerType(),
                   True),
                   StructField(OOS_dup.columns[1], StringType(), True),
                   ...])

  OOS_out=sqlContext.createDataFrame(OOS_dup,schema
    =mySchema,verifySchema=False)

return OOS_out

I got this error message at some point :

AttributeError: 'unicode' object has no attribute 'toordinal'.

According to this post : What is causing 'unicode' object has no attribute 'toordinal' in pyspark?

it's because pyspark fail to convert the Data into Datetype

but data is in Datetime64[ns] in pandas. I've tried converting this columns into string and integer and it fails as well.

Here is a picture of the output dataset from Python :

Here is the datatypes return by pandas once the data set has been cleaned :

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4972 entries, 0 to 4971
Data columns (total 51 columns):
OOS_ID                       4972 non-null int64
OPERATOR_CODE                4972 non-null object
ATA_CAUSE                    4972 non-null int64
EVENT_CODE                   3122 non-null object
AC_MODEL                     4972 non-null object
AC_SN                        4972 non-null int64
OOS_DATE                     4972 non-null datetime64[ns]
AIRPORT_CODE                 4915 non-null object
RTS_DATE                     4972 non-null datetime64[ns]
EVENT_TYPE                   4972 non-null object
CORRECTIVE_ACTION            417 non-null object
DD_HOURS_OOS                 4972 non-null float64
EVENT_DESCRIPTION            4972 non-null object
EVENT_CATEGORY               4972 non-null object
ATA_REPORTED                 324 non-null float64
TOTAL_CAUSES                 4875 non-null float64
EVENT_NUMBER                 3117 non-null float64
RTS_TIME                     4972 non-null object
OOS_TIME                     4972 non-null object
PREV_REPORTED                4972 non-null object
FERRY_IND                    4972 non-null object
REPAIR_STN_CODE              355 non-null object
MAINT_DOWN_TIME              4972 non-null float64
LOGBOOK_RECORD_IDENTIFIER    343 non-null object
RTS_IND                      4972 non-null object
READY_FOR_USE                924 non-null object
DQ_COMMENTS                  2 non-null object
REVIEWED                     5 non-null object
DOES_NOT_MEET_SPECS          4 non-null object
CORRECTED                    12 non-null object
EDITED_BY                    4972 non-null object
EDIT_DATE                    4972 non-null datetime64[ns]
OUTSTATION_INDICATOR         3801 non-null object
COMMENT_TEXT                 11 non-null object
ATA_CAUSE_CHAPTER            4972 non-null int64
ATA_CAUSE_SECTION            4972 non-null int64
ATA_CAUSE_COMPONENT          770 non-null float64
PROCESSOR_COMMENTS           83 non-null object
PARTS_AVAIL_AT_STATION       4972 non-null object
PARTS_SHIPPED_AT_STATION     4972 non-null object
ENGINEER_AT_STATION          4972 non-null object
ENGINEER_SENT_AT_STATION     4972 non-null object
SOURCE_FILE                  4972 non-null object
OOS_Month                    4972 non-null float64
OOS_Hour                     4972 non-null float64
OOS_Min                      4972 non-null float64
RTS_Month                    4972 non-null float64
RTS_Hour                     4972 non-null float64
RTS_Min                      4972 non-null float64
OOS_Timestamp                4972 non-null datetime64[ns]
RTS_Timestamp                4972 non-null datetime64[ns]
dtypes: datetime64[ns](5), float64(12), int64(5), object(29)

Body:
In case it might help some of you I found this in the offical Foundry documentation on how to properly transition between pandas and pyspark DF.

OOS_dup is my Pandas dataframe I want to convert back to Spark.

# Extract the name of each columns with its data type in pandas
    col = OOS_dup.columns
    col_type = list()

    for c in col:
        t = OOS_dup[c].dtype.name
        col_type.append(t)

    df_schema = pd.DataFrame({"field": col, "data_type": col_type})

    # Define a function to replace missing (NaN sky coverage cells with Null
    def replace_missing(df, col_names):
        for col in col_names:
            df = df.withColumn("{}".format(col),
                               F.when(df["{}".format(col)] == "NaN", None).otherwise(df["{}".format(col)]))
        return df

    # Replace missing values
    OOS_dup = replace_missing(OOS_dup, col)

    # Define a function to change column types to the proper type in spark
    def change_type(df, col_names, dtypes):
        for col in col_names:
            df = df.withColumn("{}".format(col), F.when(dtypes == "float64", (df["{}".format(col)]).cast("double")).when(dtypes == "int64", (df["{}".format(col)]).cast("int")).when(dtypes == "datetime64[ns]", (df["{}".format(col)]).cast("date")).otherwise((df["{}".format(col)]).cast("string")))
        return df

    # Cast each columns to the proper data type
    OOS_dup = change_type(OOS_dup, df_schema["field"], df_schema["data_type"])

    OOS_dup = sqlContext.createDataFrame(OOS_dup)


问:
Bootstrap modal only showing backdrop
EDIT: I've found the issue.  Turns out the person who originally made this page missed a closing
 tag on modal s/he had created, so the content of my modal was hidden inside the original.

My bootstrap modal is not showing the dialog box, instead only showing the darkened backdrop. I have the following Modal set up in the footer of my page.

```<code><div id="timePopup" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" style='border-radius:0px;width:430px;margin-left:-215px'>
    <div class="modal-body">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true" style="position: absolute; top: 3px; right: 7px; z-index: 9999;">×</button>
        <div class="modal-body" style='border: black solid 2px;margin: 5px;'>
            <?php echo $popup_content; ?>
        </div>
    </div>
</div>
</code>```

$popup_content just contains the simple string 'Test test test test'.  It is triggered by an onclick attribute in a  which call this function

```<code>function forcePopUp(){
    jQuery('#timePopup').modal('show');
}
</code>```

The exact same code worked on our development server, but since moving it to the testserver this has started happening, or not happening i suppose.

From another post on SO I tried removing the .hide class from the modal, and have ensured this modal has a unique id. Any other ideas why would be appreciated.

答: If you have a namespace collision between your modal and another element (identical id attributes, or however your modal selects its content), and the conflicting element is higher in the DOM, triggering the modal will make the modal backdrop appear but your modal won't be selected to be shown. Instead, JS will find the first matching element, which in this case is the conflicting element. The solution is of course to rename one of your elements.

Title: Bootstrap modal only showing backdrop

Body:
EDIT: I've found the issue.  Turns out the person who originally made this page missed a closing
 tag on modal s/he had created, so the content of my modal was hidden inside the original.

My bootstrap modal is not showing the dialog box, instead only showing the darkened backdrop. I have the following Modal set up in the footer of my page.

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true" style="position: absolute; top: 3px; right: 7px; z-index: 9999;">×</button>

            <?php echo $popup_content; ?>

$popup_content just contains the simple string 'Test test test test'.  It is triggered by an onclick attribute in a  which call this function

function forcePopUp(){
    jQuery('#timePopup').modal('show');
}

The exact same code worked on our development server, but since moving it to the testserver this has started happening, or not happening i suppose.

From another post on SO I tried removing the .hide class from the modal, and have ensured this modal has a unique id. Any other ideas why would be appreciated.


问:
Options for sharing dashboards with sensitive information with PowerBI
I have a dashboard I've built using Power BI, that contains sensitive information.  I want to share this dashboard with external users outside of my organization, that do not and will not have PowerBI.

From everything I've read, it appears I have a few options:

The external recipient of the dashboard would need to download Power BI Pro (from my understanding, they won't be able to view my dashboard with anything other than Power BI Pro?)

I somehow embed my dashboard in a Sharepoint which the external recipients have access to - but from what I've read, this seems likely to fail since they don't have Power BI.

I publish dashboard to the web, and have no way to password protect or restrict access.

Are these my only options?  Am I correct in that anyone I wish to share the dashboard with needs Power BI Pro to view, or I need to publish it to the open web and let it be publicly available?

If this is the case.. this is just one more reason I am disenchanted by Power BI.

答:
To add to Andrey's answer, depending on the number of users you can use Azure AD B2B so you can have guest users access your Power Bi Reports and allocated work-spaces. However it depends on the number.

For example, if you need to add 100 users, and you pay for the Power BI Pro licenses then it would be cheaper to design a basic portal and use the Power BI Embedded option and build you own basic web portal to embedded the reports in (The app owns data scenario). The basic A SKU's start around the same price as about 73 Pro licenses, or £570 per month. There will be extra cost in development of the portal and the running costs on top of the Embedded price.

If your external end user is going to pay for the Pro license, then Azure AD B2B could work for you.


问:
Forward function calls to underlying data in a wrapper template
I'm writing a template wrapper, something like this

```<code>template<class T>
class Wrapper{
public:
    Wrapper(T data);
    ~Wrapper();

    void doSomeWrapperWork();

private:
    T data;
};
</code>```

If I want to access the wrapped data, I can obviously add a getter function that returns a reference to the data. I was wondering however if there is anyway, with some template magic, to call directly on the wrapper functions of the underlying wrapped data. In other words, if I have a class TestObject with a public function void foo(), I would like to be able to call it in this way:

```<code>Wrapper<TestObject> myWrapper;
myWrapper.foo();
</code>```

instead of:

```<code>myWrapper.getData().foo();
</code>```

without knowing a priori that such a function exists. Is this possible?

答:
Not quite, until C++ gets reflection we can't easily write wrapper classes without a lot of boilerplate macros

but

You can add an implicit conversion of your wrapper class to T:

```<code>template<class T>
class Wrapper{
public:
    Wrapper(T data_) : data(data_) {}

    operator const T&() const
    {
        return data;
    }

private:
    T data;
};
</code>```

And now your class is convertible to T, so we can call a method on T, with a little work:

usage:

```<code>struct Foo
{
    constexpr int bar() const
    {
        return 42;
    }
};

int main()
{
    constexpr Foo f;
    Wrapper<Foo> my_wrapper(f);
    static_assert(static_cast<const Foo&>(my_wrapper).bar() == 42);
}
</code>```

Demo

If you want to avoid the casting yourself, you can write a free function that will call your function, so that implicit conversion may take over:

```<code>int call_bar(const Foo& f)
{
    return f.bar();
}
</code>```

Usage:

```<code>Foo f;
Wrapper<Foo> my_wrapper(f);
std::cout << call_bar(my_wrapper); // 42
</code>```

Demo2

I kind of like this approach as all it requires is that we add a free function for each wrapped function we want instead of having to manually do a bunch of casting.

Body:
I'm writing a template wrapper, something like this

template<class T>
class Wrapper{
public:
    Wrapper(T data);
    ~Wrapper();

    void doSomeWrapperWork();

private:
    T data;
};

If I want to access the wrapped data, I can obviously add a getter function that returns a reference to the data. I was wondering however if there is anyway, with some template magic, to call directly on the wrapper functions of the underlying wrapped data. In other words, if I have a class TestObject with a public function void foo(), I would like to be able to call it in this way:

Wrapper<TestObject> myWrapper;
myWrapper.foo();

instead of:

myWrapper.getData().foo();

without knowing a priori that such a function exists. Is this possible?

Body:
Not quite, until C++ gets reflection we can't easily write wrapper classes without a lot of boilerplate macros

but

You can add an implicit conversion of your wrapper class to T:

template<class T>
class Wrapper{
public:
    Wrapper(T data_) : data(data_) {}

    operator const T&() const
    {
        return data;
    }

private:
    T data;
};

And now your class is convertible to T, so we can call a method on T, with a little work:

usage:

struct Foo
{
    constexpr int bar() const
    {
        return 42;
    }
};

int main()
{
    constexpr Foo f;
    Wrapper<Foo> my_wrapper(f);
    static_assert(static_cast<const Foo&>(my_wrapper).bar() == 42);
}

Demo

If you want to avoid the casting yourself, you can write a free function that will call your function, so that implicit conversion may take over:

int call_bar(const Foo& f)
{
    return f.bar();
}

Usage:

Foo f;
Wrapper<Foo> my_wrapper(f);
std::cout << call_bar(my_wrapper); // 42

Demo2

I kind of like this approach as all it requires is that we add a free function for each wrapped function we want instead of having to manually do a bunch of casting.


问:
Java 8 - How to get single values out of Map of Lists?
I have the following Map Map<List<String>, String> with the following example values:

```<code>List["Los Angeles", "New York", "Chicago"] -> "USA",
List["Toronto", "Vancover", "Montréal"] -> "Canada"
</code>```

Is it possible to get a Map Map<String, String> and map every element of the value list to it's key? Example:

```<code>"Los Angeles" -> "USA",
"New York" -> "USA",
"Chicago" -> "USA",
"Toronto" -> "Canada",
...
</code>```

I need it in a stream, that afterwords I can sort.

答:
Of course it is possible:

```<code> Map<List<String>, String> map = new HashMap<>();
    map.put(List.of("Los Angeles", "New York", "Chicago"), "USA");
    map.put(List.of("Toronto", "Vancover", "Montréal"), "Canada");

    Map<String, String> newMap = map.entrySet().stream().flatMap(entry -> entry.getKey().stream().map(city -> Map.entry(city, entry.getValue()))).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
</code>```

An example output:

{New York=USA, MontrÃ©al=Canada, Chicago=USA, Vancover=Canada, Los Angeles=USA, Toronto=Canada}

First, you have to flatMap on the entrySet's Stream where you can map the keys to a new Stream of entries for example.

As you mentioned you need it as a Stream, so probably you want to stop before collect:

```<code>map.entrySet().stream()
  .flatMap(entry -> entry.getKey().stream()
    .map(city -> Map.entry(city, entry.getValue())))
</code>```

(Those entries you can collect to a new Map.)

Body:
I have the following Map Map<List<String>, String> with the following example values:

List["Los Angeles", "New York", "Chicago"] -> "USA",
List["Toronto", "Vancover", "Montréal"] -> "Canada"

Is it possible to get a Map Map<String, String> and map every element of the value list to it's key? Example:

"Los Angeles" -> "USA",
"New York" -> "USA",
"Chicago" -> "USA",
"Toronto" -> "Canada",
...

I need it in a stream, that afterwords I can sort.

Body:
Of course it is possible:

 Map<List<String>, String> map = new HashMap<>();
    map.put(List.of("Los Angeles", "New York", "Chicago"), "USA");
    map.put(List.of("Toronto", "Vancover", "Montréal"), "Canada");

    Map<String, String> newMap = map.entrySet().stream().flatMap(entry -> entry.getKey().stream().map(city -> Map.entry(city, entry.getValue()))).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));

An example output:

{New York=USA, MontrÃ©al=Canada, Chicago=USA, Vancover=Canada, Los Angeles=USA, Toronto=Canada}

First, you have to flatMap on the entrySet's Stream where you can map the keys to a new Stream of entries for example.

As you mentioned you need it as a Stream, so probably you want to stop before collect:

map.entrySet().stream()
  .flatMap(entry -> entry.getKey().stream()
    .map(city -> Map.entry(city, entry.getValue())))

(Those entries you can collect to a new Map.)


问:
How to calc distance between two postcodes without API - PHP preferred
I've been making search functionality that takes in two fields, Start Postcode and End Postcode. The search is supposed to query the database and collect any records that fall into the radius for both postcodes. I can retrieve the records but after, I need to get the distance between the postcodes. I know how to use the GMaps API to do this but I need to do it locally with PHP for performance reasons (Looping over multiple records etc). It would be very bad for performance to do this with an API. Any suggestions?

Just to be clear: I need a code solution to calculate distance between two postcodes without API use. Is this possible and if so how?

PHP is preferred but even just the logical idea represented in any language is okay for me.

答:
I know this is a bit late, but it may help other people in future.
First, you can get Postcode -> Lat/long databases for free.
Here's a useful site which has plenty of geo mapping data like that:
https://www.freemaptools.com/download-uk-postcode-lat-lng.htm

Before you use such calculations though, you should think about what you want - straight-line 'As the crow flies' distances or driving distances. They are not the same!

To make a point, have a look at the Google Map: https://www.google.co.uk/maps/@51.4226247,-3.8874075,8.88z

The straight-line distance (calculated using Lat/Long) between, for example, Ilfracombe and Swansea is going to bear not relationship to the driving distance where you hav eto go up to the Severn bridge.

Calculating straight line distances - cheap and quick but inaccurate.

Calculating driving distances - accurate but very difficult to do yourself - an API, and its costs are necessary if you need this


问:
how to convert mysql TIMESTAMPDIFF to oraclesql query
TIMESTAMPDIFF(HOUR, pk.consprtydate, rs.consprtydate)

wanted the difference of hours from two dates and extract the hours in oracle sql

答:
It depends on the datatype. IF they are of Oracle type TIMESTAMP, then follow the methods already answered here

If they are of type date, then - as said by Tejash- simple subtraction gives the difference in days that you would then need to round to hours. (integer portion will be days = 24 hours, and the decimal portion will be in fractions of a day)

e.g.) to round down to the integer number of hours without a fractional part:

(days * 24 hours, plus the fraction of a day * 86400 seconds in a day / 3600 seconds in an hour)

```<code>SELECT   trunc(date1 - date2) * 24    +  trunc((mod (date1-date2,1) * 86400) / 3600)
FROM DUAL
</code>```

Body:
It depends on the datatype. IF they are of Oracle type TIMESTAMP, then follow the methods already answered here

If they are of type date, then - as said by Tejash- simple subtraction gives the difference in days that you would then need to round to hours. (integer portion will be days = 24 hours, and the decimal portion will be in fractions of a day)

e.g.) to round down to the integer number of hours without a fractional part:

(days * 24 hours, plus the fraction of a day * 86400 seconds in a day / 3600 seconds in an hour)

SELECT   trunc(date1 - date2) * 24    +  trunc((mod (date1-date2,1) * 86400) / 3600)
FROM DUAL


问:
How to reuse the same style rule with multiple selectors
I want this using jss styling.

```<code>.a{
height: 20px;
}
.b{
height: 40px;
}
.a,.b{
width: 100px;
}
</code>```

Try 1

Make a rule c and add the class to both a and b

```<code>c: {
width: '100px'
}
</code>```

Try 2

Make a object common and merge them to both a and b rule

```<code>const common = {
   width: '100px',
};

a: {
height: '20px',
...common
}
b: {
height: '40px',
...common
}
</code>```

Is there any better way possible ?

答:
A simpler alternative that I feel is easier to parse would be to set the key to be a String by wrapping in quotes:

'.a, .b': {
   width: 100px;
}
```

Body:
I want this using jss styling.

.a{
height: 20px;
}
.b{
height: 40px;
}
.a,.b{
width: 100px;
}

Try 1

Make a rule c and add the class to both a and b

c: {
width: '100px'
}

Try 2

Make a object common and merge them to both a and b rule

const common = {
   width: '100px',
};

a: {
height: '20px',
...common
}
b: {
height: '40px',
...common
}

Is there any better way possible ?


问:
Function as parameter (DART)
I'm trying to understand how dart uses a function as parameter. I wrote this code...

```<code>typedef Future<String> myFunction();

void main() {
  A a = A();
  a.f1(a._f1);
}

class A {
  f1(myFunction func) async {
    String x = await _f1;
    print(x);
  }

  Future<String> _f1() {
    Future.delayed(Duration(seconds: 3)).then((f) {
      return "test";
    });
  }
}
</code>```

I need the function f1 returns "test", but I have this error : A value of type 'Future Function()' can't be assigned to a variable of type 'String'

If I change  String x = await _f1 by Future x = await _f1 I have another error.. I tried a lot of
combinations, all of them fail.

Can someone fix my code? Thank you.

答:
The problem is this line:

```<code>String x = await _f1;
</code>```

The parameter for the method is func, so you are referencing the _f1 method directly here rather than the parameter. Furthermore, rather than calling the method you are just referencing the method directly. In essence, you are trying to assign a Function to a variable that expects a String, which is what the error message is trying to tell you.

You need to reference the parameter and then you need to call it.

```<code>String x = await func();
</code>```

As an aside, your _f1 method is currently returning null. This is because you are returning a value from the method within the then but you aren't returning anything to _f1 itself, which makes Dart default to returning null. You have to either return the future itself:

Future<String> _f1() {
  return Future.delayed(Duration(seconds: 3)).then((f) {
    return "test";
  });
}

```

<p>or you need to switch to <code>async/await</code> syntax (my personal recommendation):</p>

<pre class="lang-dart prettyprint-override"><code>Future<String> _f1() async {
  await Future.delayed(Duration(seconds: 3));
  return 'test';
}
</code>```

Title: Function as parameter (DART)

Body:
I'm trying to understand how dart uses a function as parameter. I wrote this code...

typedef Future<String> myFunction();

void main() {
  A a = A();
  a.f1(a._f1);
}

class A {
  f1(myFunction func) async {
    String x = await _f1;
    print(x);
  }

  Future<String> _f1() {
    Future.delayed(Duration(seconds: 3)).then((f) {
      return "test";
    });
  }
}

I need the function f1 returns "test", but I have this error : A value of type 'Future Function()' can't be assigned to a variable of type 'String'

If I change  String x = await _f1 by Future x = await _f1 I have another error.. I tried a lot of
combinations, all of them fail.

Can someone fix my code? Thank you.

Body:
The problem is this line:

String x = await _f1;

The parameter for the method is func, so you are referencing the _f1 method directly here rather than the parameter. Furthermore, rather than calling the method you are just referencing the method directly. In essence, you are trying to assign a Function to a variable that expects a String, which is what the error message is trying to tell you.

You need to reference the parameter and then you need to call it.

String x = await func();

As an aside, your _f1 method is currently returning null. This is because you are returning a value from the method within the then but you aren't returning anything to _f1 itself, which makes Dart default to returning null. You have to either return the future itself:

Future<String> _f1() {
  return Future.delayed(Duration(seconds: 3)).then((f) {
    return "test";
  });
}

or you need to switch to async/await syntax (my personal recommendation):

Future<String> _f1() async {
  await Future.delayed(Duration(seconds: 3));
  return 'test';
}


问:
Create table using text file bulk insert
I'm trying to create a table in SQL Server from a text file using bulk insert but I keep getting bulk load data conversion error(truncation). Is there something I'm doing wrong? The top part is how the data is in the text and below is the code. </p>

```<code>'01','INPATIENT FACILITY','010','ACUTE CARE HOSPITAL'
'01','INPATIENT FACILITY','011','PRIVATE PSYCHIATRIC HOSPITAL'
'01','INPATIENT FACILITY','012','INPATIENT MEDICAL REHAB HOSPITAL'

CREATE TABLE [dbo].[PROVIDER_TYPE]
(
    [PROVIDER_TYPE_ID] [VARCHAR](2) NULL,
    [PROVIDER_TYPE] [VARCHAR](50) NULL,
    [PROVIDER_SPECIALITY_ID] [VARCHAR](3) NULL,
    [PROVIDER_SPECIALITY] [VARCHAR](50) NULL
) ON [PRIMARY]

BULK INSERT DBO.PROVIDER_TYPE FROM 'C:\SQL\t2.txt'
WITH (
    datafiletype = 'char'
    ,fieldterminator = ','
    ,ROWTERMINATOR = '\n'
)
</code>```

答:
The first value isn't 2 characters long, it's 4. The value is '01'; that's inclusive of the single quotes ('). This is why you're getting a truncation error, as '01' ('''01''' if you were to want to represent the string in T-SQL) doesn't fit in a varchar(2).

If you're on SQL Server 2017+ you can use the FORMAT and FIELDQUOTE options. Note that I also use \r\n for ROWTERMINATOR, as I had both when I created the file, if yours only contains a line break (and no carriage return), then just use \n:

```<code>BULK INSERT dbo.PROVIDER_TYPE FROM '/mnt/WDBlue/t2.txt' --This was my test file
WITH (DATAFILETYPE = 'char',
      FIELDTERMINATOR = ',',
      ROWTERMINATOR = '\r\n',
      FORMAT = 'CSV',
      FIELDQUOTE = '''');
</code>```

If you aren't using SQL Server 2017+, then it simply does not support quoted fields, and I suggest using a different tool.

Body:
I'm trying to create a table in SQL Server from a text file using bulk insert but I keep getting bulk load data conversion error(truncation). Is there something I'm doing wrong? The top part is how the data is in the text and below is the code.

'01','INPATIENT FACILITY','010','ACUTE CARE HOSPITAL'
'01','INPATIENT FACILITY','011','PRIVATE PSYCHIATRIC HOSPITAL'
'01','INPATIENT FACILITY','012','INPATIENT MEDICAL REHAB HOSPITAL'

CREATE TABLE [dbo].[PROVIDER_TYPE]
(
    [PROVIDER_TYPE_ID] [VARCHAR](2) NULL,
    [PROVIDER_TYPE] [VARCHAR](50) NULL,
    [PROVIDER_SPECIALITY_ID] [VARCHAR](3) NULL,
    [PROVIDER_SPECIALITY] [VARCHAR](50) NULL
) ON [PRIMARY]

BULK INSERT DBO.PROVIDER_TYPE FROM 'C:\SQL\t2.txt'
WITH (
    datafiletype = 'char'
    ,fieldterminator = ','
    ,ROWTERMINATOR = '\n'
)

Body:
The first value isn't 2 characters long, it's 4. The value is '01'; that's inclusive of the single quotes ('). This is why you're getting a truncation error, as '01' ('''01''' if you were to want to represent the string in T-SQL) doesn't fit in a varchar(2).

If you're on SQL Server 2017+ you can use the FORMAT and FIELDQUOTE options. Note that I also use \r\n for ROWTERMINATOR, as I had both when I created the file, if yours only contains a line break (and no carriage return), then just use \n:

BULK INSERT dbo.PROVIDER_TYPE FROM '/mnt/WDBlue/t2.txt' --This was my test file
WITH (DATAFILETYPE = 'char',
      FIELDTERMINATOR = ',',
      ROWTERMINATOR = '\r\n',
      FORMAT = 'CSV',
      FIELDQUOTE = '''');

If you aren't using SQL Server 2017+, then it simply does not support quoted fields, and I suggest using a different tool.


问:
Calculating the speed of routines?
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

```<code>// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process
</code>```

I look forward to hearing some suggestions.

Thanks.

Craig.

答:
From my knowledge, the most accurate method is by using QueryPerformanceFrequency:

code:

```<code>var
  Freq, StartCount, StopCount: Int64;
  TimingSeconds: real;
begin
  QueryPerformanceFrequency(Freq);
  QueryPerformanceCounter(StartCount);
  // Execute process that you want to time: ...
  QueryPerformanceCounter(StopCount);
  TimingSeconds := (StopCount - StartCount) / Freq;
  // Display timing: ...
end;
</code>```

Title: Calculating the speed of routines?

Body:
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process

I look forward to hearing some suggestions.

Thanks.

Craig.

Body:
From my knowledge, the most accurate method is by using QueryPerformanceFrequency:

code:

var
  Freq, StartCount, StopCount: Int64;
  TimingSeconds: real;
begin
  QueryPerformanceFrequency(Freq);
  QueryPerformanceCounter(StartCount);
  // Execute process that you want to time: ...
  QueryPerformanceCounter(StopCount);
  TimingSeconds := (StopCount - StartCount) / Freq;
  // Display timing: ...
end;


问:
Javascript click function only selects the first element or all elements at once
I made a simple unordered list with checkboxes and want a class with strikethrough text to be applied to the li that the checkbox belongs to. The methods I've tried either only work on the first element or get applied to all of them at once.

The HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
  <h1>Todo List</h1>
  <ul>
    <li>
      <input type="checkbox">
      List Item 1
    </li>
    <li>
      <input type="checkbox">
      List Item 2
    </li>
    <li>
      <input type="checkbox">
      List Item 3
    </li>
  </ul>
</body>
</html>
</code>```

The Javascript (only selects the first one):

```<code>document.querySelector("input").addEventListener("click", addStrike);

function addStrike() {
  document.querySelector("li").classList.toggle("completed");
}
</code>```

(selects all at once, when using this code I had the jquery CDN in my html)

```<code>$("li").on("click", addStrike);

function addStrike() {
  $("li").toggleClass("completed")
}
</code>```

答:
Add an Id to the UL and then use the below javascript

```<code>document.getElementById('ele').addEventListener('click',function(e){
    event.target.parentElement.classList.toggle('completed');
});
</code>```

document.querySelector always returns the first element that matches the given selector

Body:
I made a simple unordered list with checkboxes and want a class with strikethrough text to be applied to the li that the checkbox belongs to. The methods I've tried either only work on the first element or get applied to all of them at once.

The HTML:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>

Todo List

      <input type="checkbox">
      List Item 1

      <input type="checkbox">
      List Item 2

      <input type="checkbox">
      List Item 3

The Javascript (only selects the first one):

document.querySelector("input").addEventListener("click", addStrike);

function addStrike() {
  document.querySelector("li").classList.toggle("completed");
}

(selects all at once, when using this code I had the jquery CDN in my html)

$("li").on("click", addStrike);

function addStrike() {
  $("li").toggleClass("completed")
}

Body:
Add an Id to the UL and then use the below javascript

document.getElementById('ele').addEventListener('click',function(e){
    event.target.parentElement.classList.toggle('completed');
});

document.querySelector always returns the first element that matches the given selector


问:
how to check if my graphql server is down
How to check if my Graphql server is down. Currently I make a query on the server using QueryResult and if I get an error I record it. I want to make sure that graphql is up and running before making a query. Is there any way of checking the same in react js. Thank you.</p>

答: It looks like there is no solution to know if the grapphql server is down without hitting a query. We should though not the server with multiple queries, but make the first query and according to the response we get we should hit our other queries in the application. We can use network and graphql error to handle error scenarios. </p>


问:
Qt5, CMake, AUTOMOC and precompiled headers
How to specify a precompiled header to the output of CMake (2.8.12.1) AUTOMOC ?

So far, in the CMakeLists.txt I've tried these two separately:

```<code> set(AUTOMOC_MOC_OPTIONS "-bstdafx.h")
 set(AUTOMOC_MOC_OPTIONS "-fstdafx.h")
</code>```

The generated AUTOMOC output when building the project (project_automoc.cpp) only contains the moc_xxx.cpp files:

```<code>/* This file is autogenerated, do not edit*/
/// <- stdafx.h should be here ?!?!
#include "moc_widget_fps.cpp"
#include "moc_widget_sysevents.cpp"
</code>```

答:
A perhaps more elegant way is to disable precompiled headers for the mocs_... file. This allows you to keep AUTOMOC:

```<code>append_to_source_file_property(
  ${CMAKE_CURRENT_BINARY_DIR}/<PROJECT_NAME_HERE>_autogen/mocs_compilation.cpp
  COMPILE_FLAGS " /Y- ")
</code>```

Alternatively if you can/are willing to change the name and contents of the precompiled header file, you can add this to it:

```<code>#ifdef HACK_FOR_TRICKING_MOC_INTO_INCLUDING_ME_IN_THE_MOCS_FILE_DO_NOT_DEFINE
Q_OBJECT
#endif
</code>```

This will trick cmake into including it in the mocs_... file. You then need it to be at the top which requires a name change, files are sorted numbers first, then uppercase, then lowercase, so e.g. 1_precompiled.h should do the trick.

Body:
How to specify a precompiled header to the output of CMake (2.8.12.1) AUTOMOC ?

So far, in the CMakeLists.txt I've tried these two separately:

 set(AUTOMOC_MOC_OPTIONS "-bstdafx.h")
 set(AUTOMOC_MOC_OPTIONS "-fstdafx.h")

The generated AUTOMOC output when building the project (project_automoc.cpp) only contains the moc_xxx.cpp files:

/* This file is autogenerated, do not edit*/
/// <- stdafx.h should be here ?!?!
#include "moc_widget_fps.cpp"
#include "moc_widget_sysevents.cpp"

Body:
A perhaps more elegant way is to disable precompiled headers for the mocs_... file. This allows you to keep AUTOMOC:

append_to_source_file_property(
  ${CMAKE_CURRENT_BINARY_DIR}/<PROJECT_NAME_HERE>_autogen/mocs_compilation.cpp
  COMPILE_FLAGS " /Y- ")

Alternatively if you can/are willing to change the name and contents of the precompiled header file, you can add this to it:

#ifdef HACK_FOR_TRICKING_MOC_INTO_INCLUDING_ME_IN_THE_MOCS_FILE_DO_NOT_DEFINE
Q_OBJECT
#endif

This will trick cmake into including it in the mocs_... file. You then need it to be at the top which requires a name change, files are sorted numbers first, then uppercase, then lowercase, so e.g. 1_precompiled.h should do the trick.


问:
How to get a list of all topics containing specific values known to MQTT broker?

I'm looking for a way to get a list of all topics known to a broker. There are some quite similar question's, but they didn't help me to figure it out for my use case.

I've got 3 Raspberry Pi's with multiple sensors (temperature, humidity) which are connected over an MQTT network. Every Pi has it's own database containing time series of measurements and other system variables(like CPU).

Now I'm looking for a way for the following szenario:

I want to monitor my system and detect anomalies. For that I want to get all sensor-time series in the last x seconds and process them in a python script. My system to do the monitoring calculations can be every Pi.

Example: I'm on RPI2 and want to monitor the whole distributed network. There's no given knowledge about the sensors attached to the Pi's. Now from my python script running on RP2 I would initalise a MQTT client and subscribe every sensor data on the broker.
 I know about the wildcard # but I'm not sure how to use it in that case. My magic command would look like the following pseudo code:

```<code>1) client subscribe to all sensor data - #/sensor/#
2) get list with all topics
3) client subscribe to all topics from given list list/#
4) analyse data for anomalies every x seconds
</code>```

答:
First, your wildcard topic patterns are not valid. Topic patterns can only contain a single '#' character and it can only appear at the end of a topic e.g. foo/bar/# is valid, #/foo is not. You can use the + character which is a single level wildcard character.

This means a topic pattern of +/sensor/# will match each of the following:

rpi1/sensor/foo

rpi1/sensor/bar/temp

but not

rpi1/foo/sensor/bar

Next brokers do not have a list of topics that exist. Topics only really exist at the instant that a message is published to one, the broker then checks the patterns that subscribing clients have requested and checks that topic against the list and delivers it to the clients that match.

Thirdly when bridging brokers in loops like that you have to be very careful with the  bridge filters to make sure that messages don' end up a constant loop.

The solution is probably to designate a "master" broker and bridge all the others one way to that broker and then have the client subscribe to either '#' to get everything or something more like '+/sensor/#' to just see the sensor readings.

Body:
I'm looking for a way to get a list of all topics known to a broker. There are some quite similar question's, but they didn't help me to figure it out for my use case.

I've got 3 Raspberry Pi's with multiple sensors (temperature, humidity) which are connected over an MQTT network. Every Pi has it's own database containing time series of measurements and other system variables(like CPU).

Now I'm looking for a way for the following szenario:

I want to monitor my system and detect anomalies. For that I want to get all sensor-time series in the last x seconds and process them in a python script. My system to do the monitoring calculations can be every Pi.

Example: I'm on RPI2 and want to monitor the whole distributed network. There's no given knowledge about the sensors attached to the Pi's. Now from my python script running on RP2 I would initalise a MQTT client and subscribe every sensor data on the broker.
 I know about the wildcard # but I'm not sure how to use it in that case. My magic command would look like the following pseudo code:

1) client subscribe to all sensor data - #/sensor/#
2) get list with all topics
3) client subscribe to all topics from given list list/#
4) analyse data for anomalies every x seconds


问:
Flutter method was called on null?
When i call the method from the same class then it works perfectly but when I made the method in separate class it gives me an error.

The method 'add' was called on null.
Receiver: null

```<code>import 'package:flutter/material.dart';
import 'package:logic_conversion/custom_widgets/custom_appbar.dart';
import 'package:logic_conversion/image_to_text/img-to-text.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int a = 10, b = 20;
  Method m;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Custom_Appbar('Sample Page'),
      body: Column(
      children: <Widget>[
        RaisedButton(onPressed: ()=>m.add(a, b),child: Text('Add'))
      ]
    ),);
  }
}
</code>```

Where "m" is the object of Method class and I call method as

```<code>m.add(a, b)
</code>```

Method Class is given as:

```<code>    class Method{
       int add(int a, int b){
       int c;
       c = a+b;
       print(c);
     }
   }
</code>```

答: You haven’t instantiated the Method class, ie Method m = Method(). Therefore your m variable is null.</p>

Title: Flutter method was called on null?

Body:
When i call the method from the same class then it works perfectly but when I made the method in separate class it gives me an error.

The method 'add' was called on null.
Receiver: null

import 'package:flutter/material.dart';
import 'package:logic_conversion/custom_widgets/custom_appbar.dart';
import 'package:logic_conversion/image_to_text/img-to-text.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int a = 10, b = 20;
  Method m;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Custom_Appbar('Sample Page'),
      body: Column(
      children: <Widget>[
        RaisedButton(onPressed: ()=>m.add(a, b),child: Text('Add'))
      ]
    ),);
  }
}

Where "m" is the object of Method class and I call method as

m.add(a, b)

Method Class is given as:

    class Method{
       int add(int a, int b){
       int c;
       c = a+b;
       print(c);
     }
   }


问:
has_one and belong_to associations with the same table
I wonder is it ok to have like 2 associations with the same table. For example:

```<code>class CreateTeams < ActiveRecord::Migration[6.0]
  def change
    create_table :teams do |t|
      t.string :name, null: false
      t.references :manager, foreign_key: { to_table: 'users' }
    end
  end
end

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :name, null: false
      t.references :team
    end
  end
end

class Team < ApplicationRecord
  has_many :users
  belongs_to :manager, class_name: 'User', foreign_key: 'manager_id'
end

class User < ApplicationRecord
  belongs_to :team
  has_one :child_team, class_name: 'Team' # bad name, but just for example
end
</code>```

Or it would be better to create a join table with team_id, user_id, and member_type?

Ruby/Rails versions do not matter but let's assume Ruby is 2.7.0 and Rails is 6.0.0

答:
From a technical point of view - that's perfectly fine, but be careful with possible foreign key loop in the future.

This is more a question of architecture and your predictions of how system will evolve. A many-to-many relation with a explicit join model is more flexible. For example:

does manager always belong to the team? with a join table it's easier to fetch "all users from the team, no matter the role" or "all the teams a person has relation to, also no matter the role"

if there will be other roles or multiple people at same position - join table will also come handy

Body:
I wonder is it ok to have like 2 associations with the same table. For example:

class CreateTeams < ActiveRecord::Migration[6.0]
  def change
    create_table :teams do |t|
      t.string :name, null: false
      t.references :manager, foreign_key: { to_table: 'users' }
    end
  end
end

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :name, null: false
      t.references :team
    end
  end
end

class Team < ApplicationRecord
  has_many :users
  belongs_to :manager, class_name: 'User', foreign_key: 'manager_id'
end

class User < ApplicationRecord
  belongs_to :team
  has_one :child_team, class_name: 'Team' # bad name, but just for example
end

Or it would be better to create a join table with team_id, user_id, and member_type?

Ruby/Rails versions do not matter but let's assume Ruby is 2.7.0 and Rails is 6.0.0


问:
Do something after all asynchronous, nested, $.each database calls are completed
I'm trying to run a function after 1) all loops are completed and 2) all database calls within those loops are completed.

My database call functions (segmentDatabaseCall and stepDatabaseCall) all take some arguments, resolve a Promise and send the data once the call is complete. This is a (very) simplified version of my code:

```<code>let localData = {}

segmentDatabaseCall(argument) // Call the database
.then(segmentResult => { // Returns trip segments (array of objects)

  $.each(segmentResult, (segmentIndex, segmentValue) => { // For each trip segment...

    localData['something'] = segmentValue.something // Add some data to local data

    stepDatabaseCall(segmentValue.segment_id) // Call the database once per trip segment...
    .then(stepResult => { // Returns trip steps (array of objects)

      $.each(stepResult, (stepIndex, stepValue) => { // For each trip step...

        localData['something'][i]['something_else'] = stepValue.something_else // Add some data to local data

        // THIS DOESN'T WORK
        const segsDone = segmentIndex >= segmentResult.length - 1;
        const stepsDone = stepIndex >= stepResult.length - 1;
        if (segsDone && stepsDone) {
          // This if statement runs before all calls are finished 1 out of 3 times roughly
        }
      })
    })
  })
})
</code>```

Database call:

```<code>function databaseCall (argument) {
    return new Promise((resolve, reject) => {
        $.ajax({
          url: $phpUrl,
          type: 'post',
            data: {
              'argument': argument
            }
        })
        .done (function (data) {
            var resultJson = JSON.parse(data)
            resolve(resultJson)
        })
        .fail (function (error) {
            reject(error)
        })
    })
}
</code>```

I've tried using the answer here, but it runs before all calls are finished 1 in 3 times. I must be missing some counter there?

I also think there's a way to do this using Promise maps, but I can't get my head around it.

答:
There something called forkJoin in Rxjs. As I understand your question you can use that for your implementation.

```<code>forkJoin(
      this._myService.makeRequest('Request One', 2000),
      this._myService.makeRequest('Request Two', 1000),
      this._myService.makeRequest('Request Three', 3000)
    )
    .subscribe(([res1, res2, res3]) => {
      this.propOne = res1;
      this.propTwo = res2;
      this.propThree = res3;
    });
</code>```

read more from here.

Body:
I'm trying to run a function after 1) all loops are completed and 2) all database calls within those loops are completed.

My database call functions (segmentDatabaseCall and stepDatabaseCall) all take some arguments, resolve a Promise and send the data once the call is complete. This is a (very) simplified version of my code:

let localData = {}

segmentDatabaseCall(argument) // Call the database
.then(segmentResult => { // Returns trip segments (array of objects)

  $.each(segmentResult, (segmentIndex, segmentValue) => { // For each trip segment...

    localData['something'] = segmentValue.something // Add some data to local data

    stepDatabaseCall(segmentValue.segment_id) // Call the database once per trip segment...
    .then(stepResult => { // Returns trip steps (array of objects)

      $.each(stepResult, (stepIndex, stepValue) => { // For each trip step...

        localData['something'][i]['something_else'] = stepValue.something_else // Add some data to local data

        // THIS DOESN'T WORK
        const segsDone = segmentIndex >= segmentResult.length - 1;
        const stepsDone = stepIndex >= stepResult.length - 1;
        if (segsDone && stepsDone) {
          // This if statement runs before all calls are finished 1 out of 3 times roughly
        }
      })
    })
  })
})

Database call:

function databaseCall (argument) {
    return new Promise((resolve, reject) => {
        $.ajax({
          url: $phpUrl,
          type: 'post',
            data: {
              'argument': argument
            }
        })
        .done (function (data) {
            var resultJson = JSON.parse(data)
            resolve(resultJson)
        })
        .fail (function (error) {
            reject(error)
        })
    })
}

I've tried using the answer here, but it runs before all calls are finished 1 in 3 times. I must be missing some counter there?

I also think there's a way to do this using Promise maps, but I can't get my head around it.

Body:
There something called forkJoin in Rxjs. As I understand your question you can use that for your implementation.

forkJoin(
      this._myService.makeRequest('Request One', 2000),
      this._myService.makeRequest('Request Two', 1000),
      this._myService.makeRequest('Request Three', 3000)
    )
    .subscribe(([res1, res2, res3]) => {
      this.propOne = res1;
      this.propTwo = res2;
      this.propThree = res3;
    });

read more from here.