问:
Passing an additional parameter to a function called using beast::bind_front_handler
I have a boost::beast REST client. the .hpp and .cxx are given below.

```<code>#pragma once

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/strand.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;

// Performs an HTTP GET and prints the response
class RESTClient : public std::enable_shared_from_this<RESTClient> {

public:
    explicit RESTClient(net::io_context& ioc);

    virtual ~RESTClient();

    virtual void run(char const* host, char const* port, char const* target, int version);

    virtual void onResolve(beast::error_code ec, tcp::resolver::results_type results);

    virtual void onConnect(beast::error_code ec, tcp::resolver::results_type::endpoint_type);

    virtual void onWrite(beast::error_code ec, std::size_t bytes_transferred);

    virtual void onRead(beast::error_code ec, std::size_t bytes_transferred);

private:
    void createGetRequest(char const* host, char const* target, int version);

    void createPostRequest(char const* host, char const* target, int version, char const *body);

    std::string createBody();

    tcp::resolver m_resolver;
    beast::tcp_stream m_stream;
    beast::flat_buffer m_buffer; // (Must persist between reads)
    http::request<http::string_body> m_httpRequest;
    http::response<http::string_body> m_httpResponse;
};

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/strand.hpp>
#include <boost/lexical_cast.hpp>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include "RESTClient.hpp"

namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;

void fail(beast::error_code ec, char const* what) {
    std::cerr << what << ": " << ec.message() << "\n";
}

RESTClient::RESTClient(net::io_context& ioc)
    : m_resolver(net::make_strand(ioc)), m_stream(net::make_strand(ioc)) {

}

RESTClient::~RESTClient() = default;

void RESTClient::run(char const* host, char const* port, char const* target, int version) {

    createPostRequest(host, target, version, createBody().c_str());

    m_resolver.async_resolve(host, port, beast::bind_front_handler(
        &RESTClient::onResolve,
        shared_from_this()));
}

void RESTClient::onResolve(beast::error_code ec, tcp::resolver::results_type results) {
    if (ec) {
        return fail(ec, "resolve");
    }

    std::cout << "onResolve ******" << std::endl;
    m_stream.expires_after(std::chrono::seconds(30));

    m_stream.async_connect(results, beast::bind_front_handler(
        &RESTClient::onConnect,
        shared_from_this()));
}

void
RESTClient::onConnect(beast::error_code ec, tcp::resolver::results_type::endpoint_type) {
    if (ec) {
        return fail(ec, "connect");
    }

    std::cout << "onConnect ******" << std::endl;

    m_stream.expires_after(std::chrono::seconds(30));

    http::async_write(m_stream, m_httpRequest,
                      beast::bind_front_handler(
                          &RESTClient::onWrite,
                          shared_from_this()));
}

void
RESTClient::onWrite(beast::error_code ec, std::size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);

    if (ec) {
        return fail(ec, "write");
    }

    std::cout << "onWrite ******" << std::endl;

    http::async_read(m_stream, m_buffer, m_httpResponse, beast::bind_front_handler(
        &RESTClient::onRead,
        shared_from_this()));
}

void RESTClient::onRead(beast::error_code ec, std::size_t bytes_transferred) {

    boost::ignore_unused(bytes_transferred);

    if (ec) {
        return fail(ec, "read");
    }

    std::cout << "onRead ******" << std::endl;

    std::cout << m_httpResponse << std::endl;

    m_stream.socket().shutdown(tcp::socket::shutdown_both, ec);

    if (ec && ec != beast::errc::not_connected) {
        return fail(ec, "shutdown");
    }
}

void RESTClient::createGetRequest(char const* host, char const* target, int version) {
    m_httpRequest.version(version);
    m_httpRequest.method(http::verb::get);
    m_httpRequest.target(target);
    m_httpRequest.set(http::field::host, host);
    m_httpRequest.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
}

void RESTClient::createPostRequest(char const* host, char const* target, int version, char const* body) {
    m_httpRequest.version(version);
    m_httpRequest.method(http::verb::post);
    m_httpRequest.target(target);
    m_httpRequest.set(http::field::host, host);
    m_httpRequest.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
    m_httpRequest.set(http::field::content_length, boost::lexical_cast<std::string>(strlen(body)));
    m_httpRequest.set(http::field::body, body);
    m_httpRequest.prepare_payload();
}

std::string RESTClient::createBody() {
    boost::property_tree::ptree tree;
    boost::property_tree::read_json("test.json",tree);
    std::basic_stringstream<char> jsonStream;
    boost::property_tree::json_parser::write_json(jsonStream, tree, false);
    std::cout << "json stream :" << jsonStream.str() << std::endl;
    return jsonStream.str();
}

int main(int argc, char** argv) {
    // Check command line arguments.
    if (argc != 4 && argc != 5) {
        std::cerr <<
                  "Usage: http-client-async <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" <<
                  "Example:\n" <<
                  "    http-client-async www.example.com 80 /\n" <<
                  "    http-client-async www.example.com 80 / 1.0\n";
        return EXIT_FAILURE;
    }
    auto const host = argv[1];
    auto const port = argv[2];
    auto const target = argv[3];
    int version = argc == 5 && !std::strcmp("1.0", argv[4]) ? 10 : 11;

    // The io_context is required for all I/O
    net::io_context ioc;
    std::cout << "version: " << version << std::endl;

    // Launch the asynchronous operation
    std::make_shared<RESTClient>(ioc)->run(host, port, target, version);

    // Run the I/O service. The call will return when
    // the get operation is complete.
    ioc.run();

    return EXIT_SUCCESS;
}
</code>```

I want to pass an additional parameter of the type std::function<void(bool)> to onWrite in the line shown below.

```<code>http::async_write(m_stream, m_httpRequest,
                      beast::bind_front_handler(
                          &RESTClient::onWrite,
                          shared_from_this()));
</code>```

how do I do that?

答:
The declaration:

```<code>virtual void onWrite(std::function<void(bool)> f, beast::error_code ec, std::size_t bytes_transferred);
</code>```

The definition:

```<code>void
RESTClient::onWrite(std::function<void(bool)> f, beast::error_code ec, std::size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);

    if (ec) {
        return fail(ec, "write");
    }
    //...
</code>```

The invocation:

```<code>http::async_write(m_stream, m_httpRequest,
                  beast::bind_front_handler(
                      &RESTClient::onWrite,
                      shared_from_this(),
                      [](bool){ std::cout << "functor" << std::endl;}
                     ));
</code>```

Body:
I have a boost::beast REST client. the .hpp and .cxx are given below.

#pragma once

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/strand.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;

// Performs an HTTP GET and prints the response
class RESTClient : public std::enable_shared_from_this<RESTClient> {

public:
    explicit RESTClient(net::io_context& ioc);

    virtual ~RESTClient();

    virtual void run(char const* host, char const* port, char const* target, int version);

    virtual void onResolve(beast::error_code ec, tcp::resolver::results_type results);

    virtual void onConnect(beast::error_code ec, tcp::resolver::results_type::endpoint_type);

    virtual void onWrite(beast::error_code ec, std::size_t bytes_transferred);

    virtual void onRead(beast::error_code ec, std::size_t bytes_transferred);

private:
    void createGetRequest(char const* host, char const* target, int version);

    void createPostRequest(char const* host, char const* target, int version, char const *body);

    std::string createBody();

    tcp::resolver m_resolver;
    beast::tcp_stream m_stream;
    beast::flat_buffer m_buffer; // (Must persist between reads)
    http::request<http::string_body> m_httpRequest;
    http::response<http::string_body> m_httpResponse;
};

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/strand.hpp>
#include <boost/lexical_cast.hpp>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include "RESTClient.hpp"

namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;

void fail(beast::error_code ec, char const* what) {
    std::cerr << what << ": " << ec.message() << "\n";
}

RESTClient::RESTClient(net::io_context& ioc)
    : m_resolver(net::make_strand(ioc)), m_stream(net::make_strand(ioc)) {

}

RESTClient::~RESTClient() = default;

void RESTClient::run(char const* host, char const* port, char const* target, int version) {

    createPostRequest(host, target, version, createBody().c_str());

    m_resolver.async_resolve(host, port, beast::bind_front_handler(
        &RESTClient::onResolve,
        shared_from_this()));
}

void RESTClient::onResolve(beast::error_code ec, tcp::resolver::results_type results) {
    if (ec) {
        return fail(ec, "resolve");
    }

    std::cout << "onResolve ******" << std::endl;
    m_stream.expires_after(std::chrono::seconds(30));

    m_stream.async_connect(results, beast::bind_front_handler(
        &RESTClient::onConnect,
        shared_from_this()));
}

void
RESTClient::onConnect(beast::error_code ec, tcp::resolver::results_type::endpoint_type) {
    if (ec) {
        return fail(ec, "connect");
    }

    std::cout << "onConnect ******" << std::endl;

    m_stream.expires_after(std::chrono::seconds(30));

    http::async_write(m_stream, m_httpRequest,
                      beast::bind_front_handler(
                          &RESTClient::onWrite,
                          shared_from_this()));
}

void
RESTClient::onWrite(beast::error_code ec, std::size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);

    if (ec) {
        return fail(ec, "write");
    }

    std::cout << "onWrite ******" << std::endl;

    http::async_read(m_stream, m_buffer, m_httpResponse, beast::bind_front_handler(
        &RESTClient::onRead,
        shared_from_this()));
}

void RESTClient::onRead(beast::error_code ec, std::size_t bytes_transferred) {

    boost::ignore_unused(bytes_transferred);

    if (ec) {
        return fail(ec, "read");
    }

    std::cout << "onRead ******" << std::endl;

    std::cout << m_httpResponse << std::endl;

    m_stream.socket().shutdown(tcp::socket::shutdown_both, ec);

    if (ec && ec != beast::errc::not_connected) {
        return fail(ec, "shutdown");
    }
}

void RESTClient::createGetRequest(char const* host, char const* target, int version) {
    m_httpRequest.version(version);
    m_httpRequest.method(http::verb::get);
    m_httpRequest.target(target);
    m_httpRequest.set(http::field::host, host);
    m_httpRequest.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
}

void RESTClient::createPostRequest(char const* host, char const* target, int version, char const* body) {
    m_httpRequest.version(version);
    m_httpRequest.method(http::verb::post);
    m_httpRequest.target(target);
    m_httpRequest.set(http::field::host, host);
    m_httpRequest.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
    m_httpRequest.set(http::field::content_length, boost::lexical_cast<std::string>(strlen(body)));
    m_httpRequest.set(http::field::body, body);
    m_httpRequest.prepare_payload();
}

std::string RESTClient::createBody() {
    boost::property_tree::ptree tree;
    boost::property_tree::read_json("test.json",tree);
    std::basic_stringstream<char> jsonStream;
    boost::property_tree::json_parser::write_json(jsonStream, tree, false);
    std::cout << "json stream :" << jsonStream.str() << std::endl;
    return jsonStream.str();
}

int main(int argc, char** argv) {
    // Check command line arguments.
    if (argc != 4 && argc != 5) {
        std::cerr <<
                  "Usage: http-client-async <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" <<
                  "Example:\n" <<
                  "    http-client-async www.example.com 80 /\n" <<
                  "    http-client-async www.example.com 80 / 1.0\n";
        return EXIT_FAILURE;
    }
    auto const host = argv[1];
    auto const port = argv[2];
    auto const target = argv[3];
    int version = argc == 5 && !std::strcmp("1.0", argv[4]) ? 10 : 11;

    // The io_context is required for all I/O
    net::io_context ioc;
    std::cout << "version: " << version << std::endl;

    // Launch the asynchronous operation
    std::make_shared<RESTClient>(ioc)->run(host, port, target, version);

    // Run the I/O service. The call will return when
    // the get operation is complete.
    ioc.run();

    return EXIT_SUCCESS;
}

I want to pass an additional parameter of the type std::function<void(bool)> to onWrite in the line shown below.

http::async_write(m_stream, m_httpRequest,
                      beast::bind_front_handler(
                          &RESTClient::onWrite,
                          shared_from_this()));

how do I do that?

Body:
The declaration:

virtual void onWrite(std::function<void(bool)> f, beast::error_code ec, std::size_t bytes_transferred);

The definition:

void
RESTClient::onWrite(std::function<void(bool)> f, beast::error_code ec, std::size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);

    if (ec) {
        return fail(ec, "write");
    }
    //...

The invocation:

http::async_write(m_stream, m_httpRequest,
                  beast::bind_front_handler(
                      &RESTClient::onWrite,
                      shared_from_this(),
                      [](bool){ std::cout << "functor" << std::endl;}
                     ));


来源: stackexchange

问:
CreateProcessWithLogonW() problems - Need to launch sub-processes with the same user
I have a Windows executable that is launched from within a service by calling CreateProcessWithLogonW() with a set of specfied user details.

This works fine and the process starts as expected. However, when this process tries to launch other processes itself, currently just using CreateProcess() these start then die straight away - they are executables that require desktop access.

After reading up on Microsoft's article on CreateProcess() - http://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx

I think can see why this is happening and it makes sense to an extent. CreateProcess() knows the calling process is impersonating a user so it uses it's parent process, which in this case is the Local System account. But of course anything run in the local system account doesn't have the access we need, so the launched process dies.

Oddly when I was previously using LogonUser() and CreateProcessAsUser() to launch the initial executable within the service, it worked fine. But I had to change this to CreateProcessWithLogonW() due to problems with not having the correct privileges.

Does anybody know of a solution to this? I've seen talk about this elsewhere on the web but not with any definite solution. It seems like I possibly need the token of the user i'm logging on with in CreateProcessWithLogonW() with so I can use it to launch the other processes later? But I have no way of getting hold of this token, can this be retreived for the current user in any way?

Any help would be greatly appreciated, thanks :)

答:
We solved the problem using some code that I found long-ago.  The "copyright" section of one of the source modules contains the following:

```<code>/////////////////////////////////////////////////////////////
// CreateProcessAsUser.cpp
//
// Written by Valery Pryamikov (1999)
//
// Command line utility that executes a command under specified user identity
// by temporarily installing itself as a service.
//
// Based on Keith Brown's AsLocalSystem utility (http://www.develop.com/kbrown)
// Uses some code from Mike Nelson's dcomperm sample utility
//   and from tlist sample (Microsoft Source Code Samples)
//
// Use:
//  CreateProcessAsUser.exe [-i[nteractive]]|[-s[ystem]]|
//       [-u"UserName" -d"DomainName" -p"Password"]|[-a"AppID"] command
//  Command must begin with the process (path to the exe file) to launch
//  -i        process will be launched under credentials of the
//            "Interactive User" (retrieved from winlogon\shell process)
//  -a        process will be launched under credentials of the user
//            specified in "RunAs" parameter of AppID.
//  -s        process will be launched as local system
//  -u -d -p  process will be launched on the result token of the
//            LogonUser(userName,domainName,password,LOGON32_LOGON_BATCH...)
//
// either (-s) or (-i) or (-a) or (-u -d -p) parameters must supplied
//
// Examples:
// CreateProcessAsUser -s cmd.exe
// CreateProcessAsUser -a"{731A63AF-2990-11D1-B12E-00C04FC2F56F}" winfile.exe
//
/////////////////////////////////////////////////////////////
</code>```

Perhaps this information will yield hits within your Google searches - I attempted a few quick attempts but came up empty-handed.
We decomposed the internals into a set of API that yielded the results we needed.

OwnerDisplayName: Adam Cobb

ContentLicense: CC BY-SA 2.5

Body:
We solved the problem using some code that I found long-ago.  The "copyright" section of one of the source modules contains the following:

/////////////////////////////////////////////////////////////
// CreateProcessAsUser.cpp
//
// Written by Valery Pryamikov (1999)
//
// Command line utility that executes a command under specified user identity
// by temporarily installing itself as a service.
//
// Based on Keith Brown's AsLocalSystem utility (http://www.develop.com/kbrown)
// Uses some code from Mike Nelson's dcomperm sample utility
//   and from tlist sample (Microsoft Source Code Samples)
//
// Use:
//  CreateProcessAsUser.exe [-i[nteractive]]|[-s[ystem]]|
//       [-u"UserName" -d"DomainName" -p"Password"]|[-a"AppID"] command
//  Command must begin with the process (path to the exe file) to launch
//  -i        process will be launched under credentials of the
//            "Interactive User" (retrieved from winlogon\shell process)
//  -a        process will be launched under credentials of the user
//            specified in "RunAs" parameter of AppID.
//  -s        process will be launched as local system
//  -u -d -p  process will be launched on the result token of the
//            LogonUser(userName,domainName,password,LOGON32_LOGON_BATCH...)
//
// either (-s) or (-i) or (-a) or (-u -d -p) parameters must supplied
//
// Examples:
// CreateProcessAsUser -s cmd.exe
// CreateProcessAsUser -a"{731A63AF-2990-11D1-B12E-00C04FC2F56F}" winfile.exe
//
/////////////////////////////////////////////////////////////

Perhaps this information will yield hits within your Google searches - I attempted a few quick attempts but came up empty-handed.
We decomposed the internals into a set of API that yielded the results we needed.

OwnerDisplayName: SAMills


问:
How can I get vsync callback on HTML5 canvas?
How can I vsync callback on HTML5 canvas?

答: There's no such thing. The browser should take care of doing the appropriate syncs, and you can help it by using requestAnimationFrame() - see, for example, http://paulirish.com/2011/requestanimationframe-for-smart-animating/ and https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Azure API retrieving SAS policy, error InvalidHostName
I am trying to create an Event Hub in Azure using the REST APi ( with Postman ) but I am getting an error in the process of generating the SAS token.

```<code>curl --location --request POST 'https://login.microsoftonline.com/0e3603bd-2f0b-43e2-b9b5-5d456791cf33/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id=myclientid' \
--data-urlencode 'client_secret=myclientsecret' \
--data-urlencode 'resource=https://management.azure.com/'
</code>```

I store the bearer token and use it to authentificate on the following requeste:
First create the Event Hub namespace :

'''
curl --location --request PUT 'https://management.azure.com/subscriptions/6fa11037-363b-4ff4-a5a2-f4e93efa527c/resourceGroups/easypeasybi/providers/Microsoft.EventHub/namespaces/easypeasybi?api-version=2017-04-01' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer mybearertoken' \
--data-raw '{"location":"francecentral"}'

'''
Now in order to create the Event Hub, I need to build a SAS token,therefore I need to retrieve the SAS policy first:
The creation of the Namespace generate a SAS policy named RootManageSharedAccessKey, I can list all the policy using this call :

```<code>curl --location --request GET 'https://management.azure.com/subscriptions/6fa11037-363b-4ff4-a5a2-f4e93efa527c/resourceGroups/easypeasybi/providers/Microsoft.EventHub/namespaces/easypeasybi/AuthorizationRules?api-version=2017-04-01' \
--header 'Authorization: Bearer mybearertoken'
</code>```

Lastly, I am trying to retrieve the RootManageSharedAccessKey policy but I am getting an error

```<code>{
    "error": {
        "code": "InvalidHostName",
        "message": "The provided host name 'easypeasybi.servicebus.windows.net' is not whitelisted. "
    }
}
</code>```

The code I am using is the following

```<code>curl --location --request POST 'https://management.azure.com/subscriptions/6fa11037-363b-4ff4-a5a2-f4e93efa527c/resourceGroups/easypeasybi/providers/Microsoft.EventHub/namespaces/easypeasybi/AuthorizationRules/RootManageSharedAccessKey/listKeys?api-version=2017-04-01' \
--header 'Content-Type: application/atom+xml;type=entry;charset=utf-8' \
--header 'Host: easypeasybi.servicebus.windows.net' \
--header 'Authorization: Bearer mybearertoken' \
--data-raw '<entry xmlns='\''http://www.w3.org/2005/Atom'\''>
  <content type='\''application/xml'\''>
    <EventHubDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
    </EventHubDescription>
  </content>
</entry>  '
</code>```

答:
In the header, the Host should be management.azure.com.

So in you command, change this line of code

--header 'Host: easypeasybi.servicebus.windows.net' \

to

```<code>--header 'Host: management.azure.com' \
</code>```

Body:
I am trying to create an Event Hub in Azure using the REST APi ( with Postman ) but I am getting an error in the process of generating the SAS token.

curl --location --request POST 'https://login.microsoftonline.com/0e3603bd-2f0b-43e2-b9b5-5d456791cf33/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id=myclientid' \
--data-urlencode 'client_secret=myclientsecret' \
--data-urlencode 'resource=https://management.azure.com/'

I store the bearer token and use it to authentificate on the following requeste:
First create the Event Hub namespace :

'''
curl --location --request PUT 'https://management.azure.com/subscriptions/6fa11037-363b-4ff4-a5a2-f4e93efa527c/resourceGroups/easypeasybi/providers/Microsoft.EventHub/namespaces/easypeasybi?api-version=2017-04-01' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer mybearertoken' \
--data-raw '{"location":"francecentral"}'

'''
Now in order to create the Event Hub, I need to build a SAS token,therefore I need to retrieve the SAS policy first:
The creation of the Namespace generate a SAS policy named RootManageSharedAccessKey, I can list all the policy using this call :

curl --location --request GET 'https://management.azure.com/subscriptions/6fa11037-363b-4ff4-a5a2-f4e93efa527c/resourceGroups/easypeasybi/providers/Microsoft.EventHub/namespaces/easypeasybi/AuthorizationRules?api-version=2017-04-01' \
--header 'Authorization: Bearer mybearertoken'

Lastly, I am trying to retrieve the RootManageSharedAccessKey policy but I am getting an error

{
    "error": {
        "code": "InvalidHostName",
        "message": "The provided host name 'easypeasybi.servicebus.windows.net' is not whitelisted. "
    }
}

The code I am using is the following

curl --location --request POST 'https://management.azure.com/subscriptions/6fa11037-363b-4ff4-a5a2-f4e93efa527c/resourceGroups/easypeasybi/providers/Microsoft.EventHub/namespaces/easypeasybi/AuthorizationRules/RootManageSharedAccessKey/listKeys?api-version=2017-04-01' \
--header 'Content-Type: application/atom+xml;type=entry;charset=utf-8' \
--header 'Host: easypeasybi.servicebus.windows.net' \
--header 'Authorization: Bearer mybearertoken' \
--data-raw '<entry xmlns='\''http://www.w3.org/2005/Atom'\''>
  <content type='\''application/xml'\''>
    <EventHubDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
    </EventHubDescription>
  </content>
</entry>  '

Body:
In the header, the Host should be management.azure.com.

So in you command, change this line of code

--header 'Host: easypeasybi.servicebus.windows.net' \

to

--header 'Host: management.azure.com' \


问:
How to find and replace multiple words from paragraph with identified next word in python?
I want to replace and tag multiple words from a paragraph with their next word.

```<code>paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female"
</code>```

I want to replace the keys [YES] and [NO] with their next word like below.

```<code>paragraph = "Python is the most powerful language [YES]yes[/YES]. my sex is [NO]male[/NO] [YES]female[/YES]"
</code>```

答:
```<code>paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female"

def find_replace(paragraph):
    par = paragraph.split(" ")
    for i, p in enumerate(par):
        if p == "[NO]":
            par[i] = "[NO]" + par[i+1] + "[/NO]"
            del par[i+1]

    # the same for [YES]

    return " ".join(par)
</code>```

Body:
I want to replace and tag multiple words from a paragraph with their next word.

paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female"

I want to replace the keys [YES] and [NO] with their next word like below.

paragraph = "Python is the most powerful language [YES]yes[/YES]. my sex is [NO]male[/NO] [YES]female[/YES]"


问:
Array of JavaScript arrow functions
I'm implementing the card game Hearts in JavaScript, and one of the core elements of the game is that you can pass your cards to other players. My game has strictly 4 players, no more, no less.

The passing order goes left, right, straight ahead, then no passing. Therefore, P1 would pass to P2, P4, P3, and then pass to nobody. The cycle loops until the game is over.

I am trying to implement this logic via arrow functions, however, it is not working. What I am trying to do is print out the player, and the player that they should pass to, based on a given index.

Here is my code, I hope it is clear what I am trying to do.

const players = [1, 2, 3, 4];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + "passes to " + passCards[passingOrder](index))
})```

答:
1, 2, 3, 4 are not good numbers to work with when you have to do MOD, which produces something from 0 and up, and you use it to indicate which user.

Use 0, 1, 2, 3 instead:

const players = [0, 1, 2, 3];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + "passes to " + passCards[passingOrder](index))
})```
</div>
</div>
</p>

<p>Or if you want to keep it 1, 2, 3, 4, or even use names, you need to use the index generated to find the player using <code>players[generatedIndex]</code>, where <code>generatedIndex</code> is <code>passCards[passingOrder](index)</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const players = [1, 2, 3, 4];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + "passes to " + players[passCards[passingOrder](index)])
})</code>```

And you can use names if you want:

const players = ["Peter", "Paul", "Mary", "Susan"];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + " passes to " + players[passCards[passingOrder](index)])
})```
</div>
</div>
</p>

<p>And all passing methods:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const players = ["Peter", "Paul", "Mary", "Susan"];
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

passCards.forEach((passMethod, iPassMethod) => {
  console.log(`Game ${iPassMethod + 1}`);
  players.forEach((player, index) => {
    console.log(player + " passes to " + players[passMethod(index)])
  })
  console.log("\n");
})</code>```

Title: Array of JavaScript arrow functions

Body:
1, 2, 3, 4 are not good numbers to work with when you have to do MOD, which produces something from 0 and up, and you use it to indicate which user.

Use 0, 1, 2, 3 instead:

const players = [0, 1, 2, 3];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + "passes to " + passCards[passingOrder](index))
})

Or if you want to keep it 1, 2, 3, 4, or even use names, you need to use the index generated to find the player using players[generatedIndex], where generatedIndex is passCards[passingOrder](index):

const players = [1, 2, 3, 4];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + "passes to " + players[passCards[passingOrder](index)])
})

And you can use names if you want:

const players = ["Peter", "Paul", "Mary", "Susan"];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + " passes to " + players[passCards[passingOrder](index)])
})

And all passing methods:

const players = ["Peter", "Paul", "Mary", "Susan"];
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

passCards.forEach((passMethod, iPassMethod) => {
  console.log(`Game ${iPassMethod + 1}`);
  players.forEach((player, index) => {
    console.log(player + " passes to " + players[passMethod(index)])
  })
  console.log("\n");
})


问:
App freezes on launch screen when installed from xcode 10.1 to iOS 12+
When I install the applications from Xcode 10.1 to iPad(iOS 12.1), apps freeze on the launch screen. Applications work fine with the iPads which have iOS version lower than 12.
I am facing this issue since i updated Xcode to 10.

Does anyone know how to fix this issue?

答:
I am answering this question to help others who are experiencing this issue.

If you use a distribution certificate to install the app on the device with Ad-hoc provisioning profile or in-house provisioning profile app freezes on the launch screen. Even if app launches you will not get the logs in Xcode.

Following are the steps to handle this issue:

Create a new scheme

Edit this scheme and on left side select "Run"

For executable select "Ask on Launch"

Use this scheme to install the app on the device. It will ask to select the executable file to launch. Select the executable file name of your app and it will launch the app on the device. You also see the logs in the Xcode.


问:
Get a point that's 25% of the screen size in Android
I use an android Studio Library that requires me to use a pointF when using a position. For the Y value I just use max screen size. For the x value I would like it to be 25% of the screen size, how do I do this?
This is what I have right now:</p>

```<code>Display display = getActivity().getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    new ShowCaseStepDisplayer.Builder(getActivity())
    .addStep(new ShowCaseStep(new Position(new PointF(510, size.y)), "Based upon the information you've provided, we've selected certain articles for you"))
</code>```

答: you can simply calculate value, like getResources().getDisplayMetrics().widthPixels * 0.25

Body:
I use an android Studio Library that requires me to use a pointF when using a position. For the Y value I just use max screen size. For the x value I would like it to be 25% of the screen size, how do I do this?
This is what I have right now:

Display display = getActivity().getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    new ShowCaseStepDisplayer.Builder(getActivity())
    .addStep(new ShowCaseStep(new Position(new PointF(510, size.y)), "Based upon the information you've provided, we've selected certain articles for you"))


问:
How to upload a multer file as a blob in MySQL?
I'm trying to store a file uploaded into a nodejs server into a mysql database. The file is uploaded and processed using a Multer middleware, thus storing all the file information in req.files. I believe, correct me if I am mistaken, that this data/parameters must be somehow converted to a blob format yet I do not know how to do so effectively. How could this be done in order to upload it into a MySQL database?

I am using the latest version of XAMPP with a MySQL InnoDB tables. The file parameters/data generated by Multer are shown in the code snippet. I've attempted converting the entire file, that is req.files[0], into a blob yet the blobs stored in the MySQL database are identical in size despite using different files.

```<code>[ { fieldname: 'files',
    originalname: 'Event Information 2018-1_2084.pdf',
    encoding: '7bit',
    mimetype: 'application/pdf',
    destination:
     '/home/millana/Desktop/Brandink/Code/server/middleware/../designs/',
    filename: 'Event Information 2018-1_2084_1559843587360.pdf',
    path:
     '/home/millana/Desktop/Brandink/Code/server/designs/Event Information 2018-1_2084_1559843587360.pdf',
    size: 1125992 } ]
</code>```

Below is shown the restAPI called to execute the query on an already existing table Designs and database.

```<code>router.post('/order', upload.array('files'), (req, res) => {
    console.log(req.files[0].buffer);

    const order_id = 1;
    const position = 'front';

    const sql = `INSERT INTO Designs VALUES ('${order_id}', '${position}', '${req.files[0].filename}', '${req.files[0].mimetype}', '${req.files[0].buffer}')`;

    db.query(sql, (err, result) => {
        if(err) res.status(400).send(err);
        res.status(200).send(result);
    });

});
</code>```

The middleware function includes:

```<code>const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null,  __dirname + '/../designs/');
    },
    filename: function (req, file, cb) {
        let format = '';

        if      ( file.mimetype === 'image/jpeg' )      format = '.jpg';
        else if ( file.mimetype === 'image/png' )       format = '.png';
        else if ( file.mimetype === 'application/pdf' ) format = '.pdf';

        let fileName = _.split(file.originalname, '.')[0] + '_' + Date.now() + format;
        cb(null, fileName);
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: MAX_SIZE
    },
});
</code>```

I expect the blob size to vary from one file to another proportionally with their file size. However, the size for all files uploaded is of 9 bytes while the buffers are identical, indicating that the same object/file is being stored. How can I store each different file accordingly?

答:
How about using fileFilter? You can manage the quality of file, or size etc.
https://github.com/expressjs/multer

As you see in links or your knowledge, multer has some options like fileFilter or limits.
fileFilter, is similar to your function, to select file type.
limits,

fileSize : {
    5 * 1024 * 1024
}

And I've heard that storing files like image is to convert a binary file in a buffer.

if you console.log(img file), you can see the output such as
Binary {
        _bsontype: 'Binary',
        sub_type: 0,
        position: 260547,
        buffer:  } }

then change array Buffer to base64, string.
the result is,

data : image/jpeg;base64, v9emlk3SGF45fg...

It is different from 'filename or originalName',

so it could be saved as a different one.

Body:
I'm trying to store a file uploaded into a nodejs server into a mysql database. The file is uploaded and processed using a Multer middleware, thus storing all the file information in req.files. I believe, correct me if I am mistaken, that this data/parameters must be somehow converted to a blob format yet I do not know how to do so effectively. How could this be done in order to upload it into a MySQL database?

I am using the latest version of XAMPP with a MySQL InnoDB tables. The file parameters/data generated by Multer are shown in the code snippet. I've attempted converting the entire file, that is req.files[0], into a blob yet the blobs stored in the MySQL database are identical in size despite using different files.

[ { fieldname: 'files',
    originalname: 'Event Information 2018-1_2084.pdf',
    encoding: '7bit',
    mimetype: 'application/pdf',
    destination:
     '/home/millana/Desktop/Brandink/Code/server/middleware/../designs/',
    filename: 'Event Information 2018-1_2084_1559843587360.pdf',
    path:
     '/home/millana/Desktop/Brandink/Code/server/designs/Event Information 2018-1_2084_1559843587360.pdf',
    size: 1125992 } ]

Below is shown the restAPI called to execute the query on an already existing table Designs and database.

router.post('/order', upload.array('files'), (req, res) => {
    console.log(req.files[0].buffer);

    const order_id = 1;
    const position = 'front';

    const sql = `INSERT INTO Designs VALUES ('${order_id}', '${position}', '${req.files[0].filename}', '${req.files[0].mimetype}', '${req.files[0].buffer}')`;

    db.query(sql, (err, result) => {
        if(err) res.status(400).send(err);
        res.status(200).send(result);
    });

});

The middleware function includes:

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null,  __dirname + '/../designs/');
    },
    filename: function (req, file, cb) {
        let format = '';

        if      ( file.mimetype === 'image/jpeg' )      format = '.jpg';
        else if ( file.mimetype === 'image/png' )       format = '.png';
        else if ( file.mimetype === 'application/pdf' ) format = '.pdf';

        let fileName = _.split(file.originalname, '.')[0] + '_' + Date.now() + format;
        cb(null, fileName);
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: MAX_SIZE
    },
});

I expect the blob size to vary from one file to another proportionally with their file size. However, the size for all files uploaded is of 9 bytes while the buffers are identical, indicating that the same object/file is being stored. How can I store each different file accordingly?


问:
invalid resource in a windows cuda project
I've ported a cuda project from linux to windows (basically just added few defines and typedefs in the header file). I'm using visual studio 2008, and the cuda runtime api custom build rules from the SDK. The code is c, not c++ (and I'm compiling /TC not /TP)

I'm having scope issues that I didn't have in linux. Global variables in my header file aren't shared between the .c files and .cu files.

I've created a simplified project, and here is all of the code:

main.h:

```<code>#ifndef MAIN_H
#define MAIN_H

#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>

cudaEvent_t cudaEventStart;

#if defined __cplusplus
extern "C" void func(void);
#else
extern void func(void);
#endif

#endif
</code>```

main.c:

```<code>#include "main.h"

int main(void)
{
    int iDevice = 0;

    cudaSetDevice(iDevice);
    cudaFree(0);
    cudaGetDevice(&iDevice);
    printf("device: %d\n", iDevice);

    cudaEventCreate(&cudaEventStart);
    printf("create event: %d\n", (int) cudaEventStart);

    func();

    cudaEventDestroy(cudaEventStart);
    printf("destroy event: %d\n", (int) cudaEventStart);

    return cudaThreadExit();
}
</code>```

kernel.cu:

```<code>#include "main.h"

void func()
{
    printf("event in cu: %d\n", (int) cudaEventStart);
}
</code>```

output:

```<code>device: 0
create event: 44199920
event in cu: 0
event destroy: 441999920
</code>```

Any ideas about what I am doing wrong here? How do I need to change my setup so that it works in visual studio? Ideally, I'd like a setup that works multi-platform.

CUDA 3.2, GTX 480, 64-bit Win7, 263.06 general

答:
What you are trying to do

Would not work even without CUDA -- try renaming kernel.cu to kernel.c and recompile.  You will get a linker error because cudaEventStart will be multiply defined -- in each compilation unit (.c file) that includes it.  You would need to make the variable static, and initialize it in only one compilation unit.

Compiles in CUDA because CUDA does not have a linker, and therefore code in compilation units compiled by nvcc (.cu files) cannot reference symbols in other compilation units.  CUDA doesn't support static global variables currently.  In the future CUDA will have a linker, but currently it does not.

What is happening is each compilation unit is getting its own, non-conflicting instance of cudaEventStart.

What you can do is get rid of the global variable (make it a local variable in main()), add cudaEvent_t parameters to the functions that need to use the event, and then pass the event variable around.

BTW, in your second post, you have circular #includes...

Body:
I've ported a cuda project from linux to windows (basically just added few defines and typedefs in the header file). I'm using visual studio 2008, and the cuda runtime api custom build rules from the SDK. The code is c, not c++ (and I'm compiling /TC not /TP)

I'm having scope issues that I didn't have in linux. Global variables in my header file aren't shared between the .c files and .cu files.

I've created a simplified project, and here is all of the code:

main.h:

#ifndef MAIN_H
#define MAIN_H

#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>

cudaEvent_t cudaEventStart;

#if defined __cplusplus
extern "C" void func(void);
#else
extern void func(void);
#endif

#endif

main.c:

#include "main.h"

int main(void)
{
    int iDevice = 0;

    cudaSetDevice(iDevice);
    cudaFree(0);
    cudaGetDevice(&iDevice);
    printf("device: %d\n", iDevice);

    cudaEventCreate(&cudaEventStart);
    printf("create event: %d\n", (int) cudaEventStart);

    func();

    cudaEventDestroy(cudaEventStart);
    printf("destroy event: %d\n", (int) cudaEventStart);

    return cudaThreadExit();
}

kernel.cu:

#include "main.h"

void func()
{
    printf("event in cu: %d\n", (int) cudaEventStart);
}

output:

device: 0
create event: 44199920
event in cu: 0
event destroy: 441999920

Any ideas about what I am doing wrong here? How do I need to change my setup so that it works in visual studio? Ideally, I'd like a setup that works multi-platform.

CUDA 3.2, GTX 480, 64-bit Win7, 263.06 general


问:
Cannot find element using xpath (Python and selenium)
I try to make some automations using Python+selenium (new to this). Unfortunatelly, inspecting elements of a specific webpage is more than hard. There is no id to use and I try xpath.
I want to select a drop down list , i inspect this element and I copy the xpath which is
//*[@id="frmMain:criteria:purchase_criteria_tab"]/div[13]/div[1]/div/button

my code is:

```<code>    NEXT_BUTTON_XPATH = "//*[@id='frmMain:criteria:purchase_criteria_tab']/div[13]/div[1]/div/button"
wait = WebDriverWait(driver, 10)
condition = expected_conditions.presence_of_element_located(
    (By.XPATH, NEXT_BUTTON_XPATH))
button = wait.until(condition)
button.click()
</code>```

and I cannot get the element
Any ideas? Thank you in advance.

答:
You can click on the element using the syntax:

```<code>WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//*[@id='frmMain:criteria:purchase_criteria_tab']/div[13]/div[1]/div/button"))).click()
</code>```

Note: You have to add the following imports:

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
I try to make some automations using Python+selenium (new to this). Unfortunatelly, inspecting elements of a specific webpage is more than hard. There is no id to use and I try xpath.
I want to select a drop down list , i inspect this element and I copy the xpath which is
//*[@id="frmMain:criteria:purchase_criteria_tab"]/div[13]/div[1]/div/button

my code is:

    NEXT_BUTTON_XPATH = "//*[@id='frmMain:criteria:purchase_criteria_tab']/div[13]/div[1]/div/button"
wait = WebDriverWait(driver, 10)
condition = expected_conditions.presence_of_element_located(
    (By.XPATH, NEXT_BUTTON_XPATH))
button = wait.until(condition)
button.click()

and I cannot get the element
Any ideas? Thank you in advance.

Body:
You can click on the element using the syntax:

WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//*[@id='frmMain:criteria:purchase_criteria_tab']/div[13]/div[1]/div/button"))).click()

Note: You have to add the following imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


答:
Your players a 1 based while the index is 0 based.

Try

```<code>console.log(player + "passes to " + (passCards[passingOrder](index) + 1))
</code>```

Or make your players const players = [0, 1, 2, 3];.

Title: Array of JavaScript arrow functions

Body:
I'm implementing the card game Hearts in JavaScript, and one of the core elements of the game is that you can pass your cards to other players. My game has strictly 4 players, no more, no less.

The passing order goes left, right, straight ahead, then no passing. Therefore, P1 would pass to P2, P4, P3, and then pass to nobody. The cycle loops until the game is over.

I am trying to implement this logic via arrow functions, however, it is not working. What I am trying to do is print out the player, and the player that they should pass to, based on a given index.

Here is my code, I hope it is clear what I am trying to do.

const players = [1, 2, 3, 4];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + "passes to " + passCards[passingOrder](index))
})

Body:
Your players a 1 based while the index is 0 based.

Try

console.log(player + "passes to " + (passCards[passingOrder](index) + 1))

Or make your players const players = [0, 1, 2, 3];.


问:
Login-AzureRmAccount : The term 'Login-AzureRmAccount' is not recognized as the name of a cmdlet, function, script
I'm having an issue with Azure PS modules. I have installed via PS gallery with the following:

```<code>Install-Module AzureRM
Install-Module Azure
</code>```

(And restarted)

However, when I run Login-AzureRmAccount I get the following error:

Login-AzureRmAccount : The term 'Login-AzureRmAccount' is not
  recognized as the name of a cmdlet, function, script file, or operable
  program. Check the spelling of the name, or if a path was included,
  verify that the path is correct and try again. At line:1 char:1
  + Login-AzureRmAccount
  + ~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : ObjectNotFound: (Login-AzureRmAccount:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException

I seem to have all of the Azure Modules installed. I.e. if I run Get-Module -List I get following.

```<code>Script     3.7.0      Azure                               {Get-AzureAutomationCertificate, Get-AzureAutomationConnec...
Script     0.1.0      Azure.AnalysisServices              {Add-AzureAnalysisServicesAccount, Restart-AzureAnalysisSe...
Script     2.7.0      Azure.Storage                       {Get-AzureStorageTable, New-AzureStorageTableSASToken, New...
Script     3.7.0      AzureRM                             {Update-AzureRM, Import-AzureRM, Uninstall-AzureRM, Instal...
Script     0.1.0      AzureRM.AnalysisServices            {Resume-AzureRmAnalysisServicesServer, Suspend-AzureRmAnal...
Script     3.5.0      AzureRM.ApiManagement               {Add-AzureRmApiManagementRegion, Get-AzureRmApiManagementS...
Script     2.7.0      AzureRM.Automation                  {Get-AzureRMAutomationHybridWorkerGroup, Get-AzureRmAutoma...
Script     2.7.0      AzureRM.Backup                      {Backup-AzureRmBackupItem, Enable-AzureRmBackupContainerRe...
Script     2.7.0      AzureRM.Batch                       {Remove-AzureRmBatchAccount, Get-AzureRmBatchAccount, Get-...
Script     2.7.0      AzureRM.Cdn                         {Get-AzureRmCdnProfile, Get-AzureRmCdnProfileSsoUrl, New-A...
Script     0.5.0      AzureRM.CognitiveServices           {Get-AzureRmCognitiveServicesAccount, Get-AzureRmCognitive...
Script     2.8.0      AzureRM.Compute                     {Remove-AzureRmAvailabilitySet, Get-AzureRmAvailabilitySet...
Script     2.7.0      AzureRM.DataFactories               {Remove-AzureRmDataFactory, Get-AzureRmDataFactoryRun, Get...
Script     2.7.0      AzureRM.DataLakeAnalytics           {Get-AzureRmDataLakeAnalyticsDataSource, New-AzureRmDataLa...
Script     3.5.0      AzureRM.DataLakeStore               {Get-AzureRmDataLakeStoreTrustedIdProvider, Remove-AzureRm...
Script     2.7.0      AzureRM.DevTestLabs                 {Get-AzureRmDtlAllowedVMSizesPolicy, Get-AzureRmDtlAutoShu...
Script     2.7.0      AzureRM.Dns                         {Get-AzureRmDnsRecordSet, New-AzureRmDnsRecordConfig, Remo...
Script     0.1.0      AzureRM.EventHub                    {New-AzureRmEventHubKey, Get-AzureRmEventHubNamespace, Get...
Script     2.7.0      AzureRM.HDInsight                   {Get-AzureRmHDInsightJob, New-AzureRmHDInsightSqoopJobDefi...
Script     2.7.0      AzureRM.Insights                    {Get-AzureRmUsage, Get-AzureRmMetricDefinition, Get-AzureR...
Script     1.3.0      AzureRM.IotHub                      {Add-AzureRmIotHubKey, Get-AzureRmIotHubEventHubConsumerGr...
Script     2.7.0      AzureRM.KeyVault                    {Add-AzureKeyVaultCertificate, Set-AzureKeyVaultCertificat...
Script     2.7.0      AzureRM.LogicApp                    {Get-AzureRmIntegrationAccountAgreement, Get-AzureRmIntegr...
Script     0.12.0     AzureRM.MachineLearning             {Move-AzureRmMlCommitmentAssociation, Get-AzureRmMlCommitm...
Script     0.4.0      AzureRM.Media                       {Sync-AzureRmMediaServiceStorageKeys, Set-AzureRmMediaServ...
Script     3.6.0      AzureRM.Network                     {Add-AzureRmApplicationGatewayAuthenticationCertificate, G...
Script     2.7.0      AzureRM.NotificationHubs            {Get-AzureRmNotificationHub, Get-AzureRmNotificationHubAut...
Script     2.7.0      AzureRM.OperationalInsights         {New-AzureRmOperationalInsightsAzureActivityLogDataSource,...
Script     2.7.0      AzureRM.PowerBIEmbedded             {Remove-AzureRmPowerBIWorkspaceCollection, Get-AzureRmPowe...
Script     2.7.0      AzureRM.profile                     {Disable-AzureRmDataCollection, Enable-AzureRmDataCollecti...
...
</code>```

Hope someone is able to help? Running on Windows Server 2012 R2 with Powershell 4

Regards

答:
I faced a similar problem after I installed the Az module in Powershell.
In a particular session, PowerShell can run either Rm commands or Az commands.

To Run RM commands:

Open a new Powershell window.

Re-install AzureRM module using the command:

Install-Module "AzureRM"

Run the Rm command as usual.

Hope this solves your problem.

Body:
I'm having an issue with Azure PS modules. I have installed via PS gallery with the following:

Install-Module AzureRM
Install-Module Azure

(And restarted)

However, when I run Login-AzureRmAccount I get the following error:

Login-AzureRmAccount : The term 'Login-AzureRmAccount' is not
  recognized as the name of a cmdlet, function, script file, or operable
  program. Check the spelling of the name, or if a path was included,
  verify that the path is correct and try again. At line:1 char:1
  + Login-AzureRmAccount
  + ~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : ObjectNotFound: (Login-AzureRmAccount:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException

I seem to have all of the Azure Modules installed. I.e. if I run Get-Module -List I get following.

Script     3.7.0      Azure                               {Get-AzureAutomationCertificate, Get-AzureAutomationConnec...
Script     0.1.0      Azure.AnalysisServices              {Add-AzureAnalysisServicesAccount, Restart-AzureAnalysisSe...
Script     2.7.0      Azure.Storage                       {Get-AzureStorageTable, New-AzureStorageTableSASToken, New...
Script     3.7.0      AzureRM                             {Update-AzureRM, Import-AzureRM, Uninstall-AzureRM, Instal...
Script     0.1.0      AzureRM.AnalysisServices            {Resume-AzureRmAnalysisServicesServer, Suspend-AzureRmAnal...
Script     3.5.0      AzureRM.ApiManagement               {Add-AzureRmApiManagementRegion, Get-AzureRmApiManagementS...
Script     2.7.0      AzureRM.Automation                  {Get-AzureRMAutomationHybridWorkerGroup, Get-AzureRmAutoma...
Script     2.7.0      AzureRM.Backup                      {Backup-AzureRmBackupItem, Enable-AzureRmBackupContainerRe...
Script     2.7.0      AzureRM.Batch                       {Remove-AzureRmBatchAccount, Get-AzureRmBatchAccount, Get-...
Script     2.7.0      AzureRM.Cdn                         {Get-AzureRmCdnProfile, Get-AzureRmCdnProfileSsoUrl, New-A...
Script     0.5.0      AzureRM.CognitiveServices           {Get-AzureRmCognitiveServicesAccount, Get-AzureRmCognitive...
Script     2.8.0      AzureRM.Compute                     {Remove-AzureRmAvailabilitySet, Get-AzureRmAvailabilitySet...
Script     2.7.0      AzureRM.DataFactories               {Remove-AzureRmDataFactory, Get-AzureRmDataFactoryRun, Get...
Script     2.7.0      AzureRM.DataLakeAnalytics           {Get-AzureRmDataLakeAnalyticsDataSource, New-AzureRmDataLa...
Script     3.5.0      AzureRM.DataLakeStore               {Get-AzureRmDataLakeStoreTrustedIdProvider, Remove-AzureRm...
Script     2.7.0      AzureRM.DevTestLabs                 {Get-AzureRmDtlAllowedVMSizesPolicy, Get-AzureRmDtlAutoShu...
Script     2.7.0      AzureRM.Dns                         {Get-AzureRmDnsRecordSet, New-AzureRmDnsRecordConfig, Remo...
Script     0.1.0      AzureRM.EventHub                    {New-AzureRmEventHubKey, Get-AzureRmEventHubNamespace, Get...
Script     2.7.0      AzureRM.HDInsight                   {Get-AzureRmHDInsightJob, New-AzureRmHDInsightSqoopJobDefi...
Script     2.7.0      AzureRM.Insights                    {Get-AzureRmUsage, Get-AzureRmMetricDefinition, Get-AzureR...
Script     1.3.0      AzureRM.IotHub                      {Add-AzureRmIotHubKey, Get-AzureRmIotHubEventHubConsumerGr...
Script     2.7.0      AzureRM.KeyVault                    {Add-AzureKeyVaultCertificate, Set-AzureKeyVaultCertificat...
Script     2.7.0      AzureRM.LogicApp                    {Get-AzureRmIntegrationAccountAgreement, Get-AzureRmIntegr...
Script     0.12.0     AzureRM.MachineLearning             {Move-AzureRmMlCommitmentAssociation, Get-AzureRmMlCommitm...
Script     0.4.0      AzureRM.Media                       {Sync-AzureRmMediaServiceStorageKeys, Set-AzureRmMediaServ...
Script     3.6.0      AzureRM.Network                     {Add-AzureRmApplicationGatewayAuthenticationCertificate, G...
Script     2.7.0      AzureRM.NotificationHubs            {Get-AzureRmNotificationHub, Get-AzureRmNotificationHubAut...
Script     2.7.0      AzureRM.OperationalInsights         {New-AzureRmOperationalInsightsAzureActivityLogDataSource,...
Script     2.7.0      AzureRM.PowerBIEmbedded             {Remove-AzureRmPowerBIWorkspaceCollection, Get-AzureRmPowe...
Script     2.7.0      AzureRM.profile                     {Disable-AzureRmDataCollection, Enable-AzureRmDataCollecti...
...

Hope someone is able to help? Running on Windows Server 2012 R2 with Powershell 4

Regards


问:
Background image responsive without getting cropped
I've already made the background image to full size in my page, but when I inspect and try to display it in phone mode, my background image get cropped, how can I resist this thing so it can't get cropped but always cover particular part of the page </p>

```<code><div class="inner-banner has-base-color-overlay text-center" style="background: url(header.jpg); background-size: cover; position: center;">
    <div class="container">
        <div class="box">
            <h3>About Us</h3>
        </div>
    </div>
</div>
</code>```

答:
```<code>    <style>
    .header-img {
    max-width:100%;
    margin:0 auto;
    display:block;
    }
    @media all and (max-width:600px){
    .header-img {
    height:300px;
    object-fit:cover;
    }
    </style>
    <div class="inner-banner has-base-color-overlay text-center">
        <div class="container">
            <div class="box">
                <img src="images/header.jpg" class="header-img" alt="">
                <h3>About Us</h3>
            </div>
</div>
</code>```

Body:
I've already made the background image to full size in my page, but when I inspect and try to display it in phone mode, my background image get cropped, how can I resist this thing so it can't get cropped but always cover particular part of the page

About Us


问:
Avoiding repetitive sub-class definitions in C++
I am new to C++ classes, and I have a question about defining multiple sub-classes of an abstract type/interface which would have identical definitions.

Take the following example which might appear in a header file with 3 sub-classes:

```<code>class Animal {
private:
    int a;
    int b;
public:
    explicit Animal(int a) {}
    virtual Animal* getFriend() = 0;
    virtual bool walk() = 0;
    virtual bool talk() = 0;
    virtual bool someFunction() = 0;
    virtual bool someOtherFunction() = 0;
    // ... many more functions
}

class Zebra: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Cow: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Salmon: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

// ... many more animals
</code>```

Declaring the sub-classes like this seems repetitive and potentially error prone. Because the class definitions are identical except for the name of the class, is there a more efficient way to declare the animal sub-classes in bulk?

In the context I am working in each animal would have a completely independent implementation in separate .cpp files.

Please let me know if i'm approaching this completely wrong. Any help would be greatly appreciated.

答:
Short of using a macro to define the classes (which is even worse!), there probably isn't a great deal you can do. Occasionally stuff like this might work, but I'd wager that at some point, you'd want to specialise one of the animals, leading to you ditching the macro again. It's for that reason I'd avoid that particular technique.

#define DECLARE_ANIMAL(ANIMAL_TYPE) \
class ANIMAL_TYPE: public Animal { \
    Animal* getFriend() override; \
    bool walk() override; \
    bool someFunction() override; \
    bool someOtherFunction() override; \
};
DECLARE_ANIMAL(Zebra);
DECLARE_ANIMAL(Cow);
DECLARE_ANIMAL(Salmon);
```

Generally speaking, try to move as much of the duplicated class methods & data into the base class to minimise the amount of code duplication. This may require a slight change in the way you think about the problem though....

For example, walk(). In the case of a Cow/Zebra/Horse/Cat/Dog, the act of walking is pretty much identical. The only real differences can be measured with data (e.g. the walk speed, how many legs are used, what is the gait of the walk, how large is each stride?). If you can define the behaviour in a data-driven fashion, you would just need to set those parameters in the Derived class constructor, and avoid the need for
customised methods. Approaching the class design this way has a few other benefits, for example you'd have a single 'Dog' class, but it would be able to represent a 4 legged dog, and a 3 legged dog, without needing to create a new class.

That's usually the approach I'd recommend anyway...

Body:
I am new to C++ classes, and I have a question about defining multiple sub-classes of an abstract type/interface which would have identical definitions.

Take the following example which might appear in a header file with 3 sub-classes:

class Animal {
private:
    int a;
    int b;
public:
    explicit Animal(int a) {}
    virtual Animal* getFriend() = 0;
    virtual bool walk() = 0;
    virtual bool talk() = 0;
    virtual bool someFunction() = 0;
    virtual bool someOtherFunction() = 0;
    // ... many more functions
}

class Zebra: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Cow: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Salmon: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

// ... many more animals

Declaring the sub-classes like this seems repetitive and potentially error prone. Because the class definitions are identical except for the name of the class, is there a more efficient way to declare the animal sub-classes in bulk?

In the context I am working in each animal would have a completely independent implementation in separate .cpp files.

Please let me know if i'm approaching this completely wrong. Any help would be greatly appreciated.

Body:
Short of using a macro to define the classes (which is even worse!), there probably isn't a great deal you can do. Occasionally stuff like this might work, but I'd wager that at some point, you'd want to specialise one of the animals, leading to you ditching the macro again. It's for that reason I'd avoid that particular technique.

#define DECLARE_ANIMAL(ANIMAL_TYPE) \
class ANIMAL_TYPE: public Animal { \
    Animal* getFriend() override; \
    bool walk() override; \
    bool someFunction() override; \
    bool someOtherFunction() override; \
};
DECLARE_ANIMAL(Zebra);
DECLARE_ANIMAL(Cow);
DECLARE_ANIMAL(Salmon);

Generally speaking, try to move as much of the duplicated class methods & data into the base class to minimise the amount of code duplication. This may require a slight change in the way you think about the problem though....

For example, walk(). In the case of a Cow/Zebra/Horse/Cat/Dog, the act of walking is pretty much identical. The only real differences can be measured with data (e.g. the walk speed, how many legs are used, what is the gait of the walk, how large is each stride?). If you can define the behaviour in a data-driven fashion, you would just need to set those parameters in the Derived class constructor, and avoid the need for
customised methods. Approaching the class design this way has a few other benefits, for example you'd have a single 'Dog' class, but it would be able to represent a 4 legged dog, and a 3 legged dog, without needing to create a new class.

That's usually the approach I'd recommend anyway...


问:
Python -- Speed Up Imports?
I have 10000s custom (compiled to '.so') modules that I'd like to use in python. The usage of the modules will be consequential (modules are used one after the other; not at the same time).

Normally, the code would look something like this:

```<code># list with all the paths to all modules
listPathsToModules = [.....]
# loop through the list of all modules
for i in xrange(listPathsToModules):
    # get the path to the currently processed module
    pathToModule = listPathsToModules[i]
    # import the module
    import pathToModule
    # run a function in 'pathToModule' and get the results
    pathToModule.MyFunction( arg1, arg2, arg3 )
</code>```

Running this, here is what I find:

the avg. time it takes to import one module: 0.0024625 [sec]

the avg. time it takes to run the module's function: 1.63727e-05 [sec]

meaning, it takes x100 more time to import the module than to run a function that is in it!

Is there anything that can be done to speed-up the time it takes to load a module in python? What steps would you take to optimize this situation given the need to load and run many (assume 10,000s) of modules?

答:
I would first question whether import is really the technique you want to be using to access thousands of code fragments - the full import process is quite expensive, and loading (non-shared) dynamic modules at all isn't particularly cheap, either.

Second, the code as you have written it clearly isn't what you're actually doing. The import statement doesn't accept strings at runtime, you would have to be using importlib.import_module() or calling __import__() directly.

Finally, the first step in optimising this would be to ensure that the first directory on sys.path is the one that contains all these files. You may also want to run Python with the -vv flag to dial up the verbosity on the import attempts. Be warned that this is going to get very noisy if you're doing that many imports.

Title: Python -- Speed Up Imports?

Body:
I have 10000s custom (compiled to '.so') modules that I'd like to use in python. The usage of the modules will be consequential (modules are used one after the other; not at the same time).

Normally, the code would look something like this:

# list with all the paths to all modules
listPathsToModules = [.....]
# loop through the list of all modules
for i in xrange(listPathsToModules):
    # get the path to the currently processed module
    pathToModule = listPathsToModules[i]
    # import the module
    import pathToModule
    # run a function in 'pathToModule' and get the results
    pathToModule.MyFunction( arg1, arg2, arg3 )

Running this, here is what I find:

the avg. time it takes to import one module: 0.0024625 [sec]

the avg. time it takes to run the module's function: 1.63727e-05 [sec]

meaning, it takes x100 more time to import the module than to run a function that is in it!

Is there anything that can be done to speed-up the time it takes to load a module in python? What steps would you take to optimize this situation given the need to load and run many (assume 10,000s) of modules?


问:
Excel covert date from DDD MMM DD HH:MM:ss YYYY to YYYY-MM-DD HH:MM:ss
I am trying to convert this datetime format in MS Excel:

```<code>Sat Feb 09 09:58:15 PKT 2019
</code>```

Into mysql date time format:

```<code>YYYY-MM-DD HH:MM:ss
</code>```

So far custom date formating isn't working, any input would be appreciated.

Example test data:

答:
Use the formula below to convert your time strings (here in A1) to Date/Time values in a helper column. Then set the cell format to match your requirements and replace the original column with the reformatted copy.

```<code>=DATEVALUE(MID(A1, 5, 6) & ", " & RIGHT(A1, 4)) + TIMEVALUE(MID(A1,12,8))
</code>```

Use Copy/Paste Special > Values to replace the formulas with real values.

Body:
I am trying to convert this datetime format in MS Excel:

Sat Feb 09 09:58:15 PKT 2019

Into mysql date time format:

YYYY-MM-DD HH:MM:ss

So far custom date formating isn't working, any input would be appreciated.

Example test data:

Body:
Use the formula below to convert your time strings (here in A1) to Date/Time values in a helper column. Then set the cell format to match your requirements and replace the original column with the reformatted copy.

=DATEVALUE(MID(A1, 5, 6) & ", " & RIGHT(A1, 4)) + TIMEVALUE(MID(A1,12,8))

Use Copy/Paste Special > Values to replace the formulas with real values.


问:
Flash CS5: AS3: Weird XML errors?
I was working with one of the pre made templates in CS5, the "advanced slideshow presentation" one, all of the sudden I went to get a publish preview and it spit out a whole bunch of xml errors, which I am unfamiliar with.

```<code>SlidesMovieClip_2, Line 14  1104: invalid xml name
SlidesMovieClip_2, Line 253 1084: Syntax error: expecting xmltagendend before end of program.
SlidesMovieClip_2, Line 253 1100: Syntax error: XML does not have matching begin and end tags.
SlidesMovieClip_2, Line 253 1100: Syntax error: XML does not have matching begin and end tags.
SlidesMovieClip_2, Line 253 1100: Syntax error: XML does not have matching begin and end tags.
SlidesMovieClip_2, Line 253 1084: Syntax error: expecting rightparen before end of program.
SlidesMovieClip_2, Line 253 1084: Syntax error: expecting rightbrace before end of program.
SlidesMovieClip_2, Line 253 1073: Syntax error: expecting a catch or a finally clause.
</code>```

As far as I know, a "SlideshowMovieClip_2" doesn't even exist?  I'm not sure what is going on but I will leave the code and hopefully you guys can figure something!

code:

```<code>import fl.transitions.*;

// USER CONFIG SETTINGS
var buttonsOn:Boolean = true; // true, false
var pageNumberOn:Boolean = true; // true, false
var transitionOn:Boolean = true; // true, false
var transitionType:String = "Fade"; // Blinds, Fade, Fly, Iris, Photo, PixelDissolve, Rotate, Squeeze, Wipe, Zoom, Random
// END USER CONFIG SETTINGS

// EVENTS
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_changeSlideKeyboard);
prev_btn.addEventListener(MouseEvent.CLICK, fl_prevSlideButton);
next_btn.addEventListener(MouseEvent.CLICK, fl_nextSlideButton);
function fl_changeSlideKeyboard(evt:KeyboardEvent):void
{
    if(evt.keyCode == 37) // LEFT
    {
        fl_prevSlide();
    }
    else if (evt.keyCode == 39 || evt.keyCode == 32) // RIGHT OR SPACE
    {
        fl_nextSlide();
    }
}
function fl_prevSlideButton(evt:MouseEvent):void
{
    fl_prevSlide();
}
function fl_nextSlideButton(evt:MouseEvent):void
{
    fl_nextSlide();
}
// END EVENTS

// FUNCTIONS AND LOGIC
function fl_prevSlide():void
{
    if(slides_mc.currentFrame > 1)
    {
        slides_mc.gotoAndStop(slides_mc.currentFrame-1);
        if(transitionOn == true)
        {
            fl_doTransition();
        }
        if(pageNumberOn == false)
        {
            slideNumber_txt.text = "";
        } else {
            slideNumber_txt.text = String(slides_mc.currentFrame + "/" + slides_mc.totalFrames);
        }
    }
}
function fl_nextSlide():void
{
    if(slides_mc.currentFrame < slides_mc.totalFrames)
    {
        slides_mc.gotoAndStop(slides_mc.currentFrame+1);
        if(transitionOn == true)
        {
            fl_doTransition();
        }
        if(pageNumberOn == false)
        {
            slideNumber_txt.text = "";
        } else {
            slideNumber_txt.text = String(slides_mc.currentFrame + "/" + slides_mc.totalFrames);
        }
    }
}
function fl_doTransition():void
{
    if(transitionType == "Blinds")
    {
        TransitionManager.start(slides_mc, {type:Blinds, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Fade")
    {
        TransitionManager.start(slides_mc, {type:Fade, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Fly")
    {
        TransitionManager.start(slides_mc, {type:Fly, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Iris")
    {
        TransitionManager.start(slides_mc, {type:Iris, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Photo")
    {
        TransitionManager.start(slides_mc, {type:Photo, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "PixelDissolve")
    {
        TransitionManager.start(slides_mc, {type:PixelDissolve, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Rotate")
    {
        TransitionManager.start(slides_mc, {type:Rotate, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Squeeze")
    {
        TransitionManager.start(slides_mc, {type:Squeeze, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Wipe")
    {
        TransitionManager.start(slides_mc, {type:Wipe, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Zoom")
    {
        TransitionManager.start(slides_mc, {type:Zoom, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Random")
    {
        var randomNumber:Number = Math.round(Math.random()*9) + 1;
        switch (randomNumber) {
            case 1:
                TransitionManager.start(slides_mc, {type:Blinds, direction:Transition.IN, duration:0.25});
                break;
            case 2:
                TransitionManager.start(slides_mc, {type:Fade, direction:Transition.IN, duration:0.25});
                break;
            case 3:
                TransitionManager.start(slides_mc, {type:Fly, direction:Transition.IN, duration:0.25});
                break;
            case 4:
                TransitionManager.start(slides_mc, {type:Iris, direction:Transition.IN, duration:0.25});
                break;
            case 5:
                TransitionManager.start(slides_mc, {type:Photo, direction:Transition.IN, duration:0.25});
                break;
            case 6:
                TransitionManager.start(slides_mc, {type:PixelDissolve, direction:Transition.IN, duration:0.25});
                break;
            case 7:
                TransitionManager.start(slides_mc, {type:Rotate, direction:Transition.IN, duration:0.25});
                break;
            case 8:
                TransitionManager.start(slides_mc, {type:Squeeze, direction:Transition.IN, duration:0.25});
                break;
            case 9:
                TransitionManager.start(slides_mc, {type:Wipe, direction:Transition.IN, duration:0.25});
                break;
            case 10:
                TransitionManager.start(slides_mc, {type:Zoom, direction:Transition.IN, duration:0.25});
                break;
        }
    } else
    {
        trace("error - transitionType not recognized");
    }
}

if(buttonsOn == false)
{
    prev_btn.visible = false;
    next_btn.visible = false;
}
slides_mc.gotoAndStop(1);
stage.scaleMode = StageScaleMode.SHOW_ALL;
// END FUNCTIONS AND LOGIC

stop();
</code>```

答:
Sorry, but there is missing information here. The code you posted does not look like it relates to your errors.

I see an 'invalid xml name' error - did you rename any xml variables, move files, or otherwise alter an xml file? If so, retrace your steps and undo whatever you did.

As for the second set if errors, it looks like you erased a bracket by mistake. You're going to have to dig in and find whatever code is driving 'slidesMovieClip_2' and find the missing brace.

hope that steers you in the right direction ---

Title: Flash CS5: AS3: Weird XML errors?

Body:
I was working with one of the pre made templates in CS5, the "advanced slideshow presentation" one, all of the sudden I went to get a publish preview and it spit out a whole bunch of xml errors, which I am unfamiliar with.

SlidesMovieClip_2, Line 14  1104: invalid xml name
SlidesMovieClip_2, Line 253 1084: Syntax error: expecting xmltagendend before end of program.
SlidesMovieClip_2, Line 253 1100: Syntax error: XML does not have matching begin and end tags.
SlidesMovieClip_2, Line 253 1100: Syntax error: XML does not have matching begin and end tags.
SlidesMovieClip_2, Line 253 1100: Syntax error: XML does not have matching begin and end tags.
SlidesMovieClip_2, Line 253 1084: Syntax error: expecting rightparen before end of program.
SlidesMovieClip_2, Line 253 1084: Syntax error: expecting rightbrace before end of program.
SlidesMovieClip_2, Line 253 1073: Syntax error: expecting a catch or a finally clause.

As far as I know, a "SlideshowMovieClip_2" doesn't even exist?  I'm not sure what is going on but I will leave the code and hopefully you guys can figure something!

code:

import fl.transitions.*;

// USER CONFIG SETTINGS
var buttonsOn:Boolean = true; // true, false
var pageNumberOn:Boolean = true; // true, false
var transitionOn:Boolean = true; // true, false
var transitionType:String = "Fade"; // Blinds, Fade, Fly, Iris, Photo, PixelDissolve, Rotate, Squeeze, Wipe, Zoom, Random
// END USER CONFIG SETTINGS

// EVENTS
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_changeSlideKeyboard);
prev_btn.addEventListener(MouseEvent.CLICK, fl_prevSlideButton);
next_btn.addEventListener(MouseEvent.CLICK, fl_nextSlideButton);
function fl_changeSlideKeyboard(evt:KeyboardEvent):void
{
    if(evt.keyCode == 37) // LEFT
    {
        fl_prevSlide();
    }
    else if (evt.keyCode == 39 || evt.keyCode == 32) // RIGHT OR SPACE
    {
        fl_nextSlide();
    }
}
function fl_prevSlideButton(evt:MouseEvent):void
{
    fl_prevSlide();
}
function fl_nextSlideButton(evt:MouseEvent):void
{
    fl_nextSlide();
}
// END EVENTS

// FUNCTIONS AND LOGIC
function fl_prevSlide():void
{
    if(slides_mc.currentFrame > 1)
    {
        slides_mc.gotoAndStop(slides_mc.currentFrame-1);
        if(transitionOn == true)
        {
            fl_doTransition();
        }
        if(pageNumberOn == false)
        {
            slideNumber_txt.text = "";
        } else {
            slideNumber_txt.text = String(slides_mc.currentFrame + "/" + slides_mc.totalFrames);
        }
    }
}
function fl_nextSlide():void
{
    if(slides_mc.currentFrame < slides_mc.totalFrames)
    {
        slides_mc.gotoAndStop(slides_mc.currentFrame+1);
        if(transitionOn == true)
        {
            fl_doTransition();
        }
        if(pageNumberOn == false)
        {
            slideNumber_txt.text = "";
        } else {
            slideNumber_txt.text = String(slides_mc.currentFrame + "/" + slides_mc.totalFrames);
        }
    }
}
function fl_doTransition():void
{
    if(transitionType == "Blinds")
    {
        TransitionManager.start(slides_mc, {type:Blinds, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Fade")
    {
        TransitionManager.start(slides_mc, {type:Fade, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Fly")
    {
        TransitionManager.start(slides_mc, {type:Fly, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Iris")
    {
        TransitionManager.start(slides_mc, {type:Iris, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Photo")
    {
        TransitionManager.start(slides_mc, {type:Photo, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "PixelDissolve")
    {
        TransitionManager.start(slides_mc, {type:PixelDissolve, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Rotate")
    {
        TransitionManager.start(slides_mc, {type:Rotate, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Squeeze")
    {
        TransitionManager.start(slides_mc, {type:Squeeze, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Wipe")
    {
        TransitionManager.start(slides_mc, {type:Wipe, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Zoom")
    {
        TransitionManager.start(slides_mc, {type:Zoom, direction:Transition.IN, duration:0.25});
    } else if (transitionType == "Random")
    {
        var randomNumber:Number = Math.round(Math.random()*9) + 1;
        switch (randomNumber) {
            case 1:
                TransitionManager.start(slides_mc, {type:Blinds, direction:Transition.IN, duration:0.25});
                break;
            case 2:
                TransitionManager.start(slides_mc, {type:Fade, direction:Transition.IN, duration:0.25});
                break;
            case 3:
                TransitionManager.start(slides_mc, {type:Fly, direction:Transition.IN, duration:0.25});
                break;
            case 4:
                TransitionManager.start(slides_mc, {type:Iris, direction:Transition.IN, duration:0.25});
                break;
            case 5:
                TransitionManager.start(slides_mc, {type:Photo, direction:Transition.IN, duration:0.25});
                break;
            case 6:
                TransitionManager.start(slides_mc, {type:PixelDissolve, direction:Transition.IN, duration:0.25});
                break;
            case 7:
                TransitionManager.start(slides_mc, {type:Rotate, direction:Transition.IN, duration:0.25});
                break;
            case 8:
                TransitionManager.start(slides_mc, {type:Squeeze, direction:Transition.IN, duration:0.25});
                break;
            case 9:
                TransitionManager.start(slides_mc, {type:Wipe, direction:Transition.IN, duration:0.25});
                break;
            case 10:
                TransitionManager.start(slides_mc, {type:Zoom, direction:Transition.IN, duration:0.25});
                break;
        }
    } else
    {
        trace("error - transitionType not recognized");
    }
}

if(buttonsOn == false)
{
    prev_btn.visible = false;
    next_btn.visible = false;
}
slides_mc.gotoAndStop(1);
stage.scaleMode = StageScaleMode.SHOW_ALL;
// END FUNCTIONS AND LOGIC

stop();


问:
Why do i need to left shift before summing the result?
Here is a code snippet that works as intended, it correctly reverses the bits of an integer and returns the new int. My question is why does the line result <<= 1 have to occur before I sum result with the operation n&1?

In the first iteration, it does not affect results because the result is instantiated as 0. If I put the result <<= 1 line at the END of the for loop, I would still be left shifting result before I sum result with n&1.
My code, with the left shifting result at the end, isn't working and I can't seem to understand this final step.

```<code>public int reverseBits(int n) {
    int result = 0;
    for(int i=0; i<32; i++){
        result <<= 1;
        result += n&1;
        n >>= 1;
    }
    return result;
}
</code>```

答:
This is a one-off problem:

you need to copy 32 bits, so you're doing 32 result += n&1;operations (0..31)

to move the rightmost bit (position 0) to the leftmost position (position 31) you only need to do 31 left-shift operations.

Therefore, putting the result <<= 1; at the beginning is fine, as it actually does nothing, as there is nothing yet in result, so you're doing only 31 left-shifts.
Only when you move it after the result += n&1; you're doing 32 left-shift operations, loosing one bit.
The same holds for the n >>= 1;, where you do 32 right-shift operations as well, but the final right-shift doesn't matter, as it is never added to the result (and zero anyway).

Body:
Here is a code snippet that works as intended, it correctly reverses the bits of an integer and returns the new int. My question is why does the line result <<= 1 have to occur before I sum result with the operation n&1?

In the first iteration, it does not affect results because the result is instantiated as 0. If I put the result <<= 1 line at the END of the for loop, I would still be left shifting result before I sum result with n&1.
My code, with the left shifting result at the end, isn't working and I can't seem to understand this final step.

public int reverseBits(int n) {
    int result = 0;
    for(int i=0; i<32; i++){
        result <<= 1;
        result += n&1;
        n >>= 1;
    }
    return result;
}


问:
Upload multi part file to S3
I am using spring boot and I have a multipart file from request that I need to upload to S3,but S3 only supports file(not multipart file) to upload to S3.
How to upload multipart file to s3</p>

答:
You can do as follows :</p>

```<code>public class S3Utility{
    public static String upload(String bucket, String fileName, InputStream inputStream, String contentType, AmazonS3 s3Client, boolean isPublic) {
    if (inputStream != null) {
      try {
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(inputStream.available());
        meta.setContentType(contentType);

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, inputStream, meta);

        if (isPublic) {
          putObjectRequest = putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead);
        }

        PutObjectResult result = S3Util.getAmazonS3Client(s3Client).putObject(putObjectRequest);
        if (result != null) {
          return fileName;
        }

      } catch (Exception e) {
        log.error("Error uploading file on S3: ", e);
      }
    } else {
      log.warn("Content InputStream is null. Not Uploading on S3");
    }
    return null;
  }
}

@RestController
 public class TestController{

   @PostMapping(path = "upload/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> uploadStampPageImage( @RequestPart(value = "file") MultipartFile imageFile) {

        if(Objets.nonNull(file)){
          String uploadedFilePath = S3Utility.upload("myBucket","myFile.jpg",file.getInputStream(),file.getContentType(), amazonS3Client, true);
          return new ResponseEntity.ok(uploadedFilePath);
        }
        return new ResponseEntity.failure("Not uploaded");

    }

}

 }
</code>```

Title: Upload multi part file to S3

Body:
You can do as follows :

public class S3Utility{
    public static String upload(String bucket, String fileName, InputStream inputStream, String contentType, AmazonS3 s3Client, boolean isPublic) {
    if (inputStream != null) {
      try {
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(inputStream.available());
        meta.setContentType(contentType);

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, inputStream, meta);

        if (isPublic) {
          putObjectRequest = putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead);
        }

        PutObjectResult result = S3Util.getAmazonS3Client(s3Client).putObject(putObjectRequest);
        if (result != null) {
          return fileName;
        }

      } catch (Exception e) {
        log.error("Error uploading file on S3: ", e);
      }
    } else {
      log.warn("Content InputStream is null. Not Uploading on S3");
    }
    return null;
  }
}

@RestController
 public class TestController{

   @PostMapping(path = "upload/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> uploadStampPageImage( @RequestPart(value = "file") MultipartFile imageFile) {

        if(Objets.nonNull(file)){
          String uploadedFilePath = S3Utility.upload("myBucket","myFile.jpg",file.getInputStream(),file.getContentType(), amazonS3Client, true);
          return new ResponseEntity.ok(uploadedFilePath);
        }
        return new ResponseEntity.failure("Not uploaded");

    }

}

 }


问:
Swift 'if let' statement equivalent in Kotlin
In Kotlin is there an equivalent to the Swift code below?</p>
```<code>if let a = b.val {

} else {

}
</code>```

答:
I'm adding this answer to clarify the accepted answer because it's too big for a comment.

The general pattern here is that you can use any combination of the Scope Functions available in Kotlin separated by the Elvis Operator like this:

```<code><nullable>?.<scope function> {
    // code if not null
} :? <scope function> {
    // code if null
}
</code>```

For example:

```<code>val gradedStudent = student?.apply {
    grade = newGrade
} :? with(newGrade) {
    Student().apply { grade = newGrade }
}
</code>```

Body:
In Kotlin is there an equivalent to the Swift code below?

if let a = b.val {

} else {

}

Body:
I'm adding this answer to clarify the accepted answer because it's too big for a comment.

The general pattern here is that you can use any combination of the Scope Functions available in Kotlin separated by the Elvis Operator like this:

<nullable>?.<scope function> {
    // code if not null
} :? <scope function> {
    // code if null
}

For example:

val gradedStudent = student?.apply {
    grade = newGrade
} :? with(newGrade) {
    Student().apply { grade = newGrade }
}


问:
Promise is not resolving even after calling resolve()
My question here may sound little repetitive. But I haven't found any answer on stackoverflow which can solve my problem.

I am returning a promise from one of my function. The promise will be resolved after getting some data from database. And will be rejected if there is no data in the db table. Also I have to do some processing on the fetched data before resolving the promise, that's why I am using callbacks.

My Code Snippet

```<code>return new Promise((resolve, reject) => {

            ResourceModel.getById(resource_ID).then((data) => {
                if (data.length > 0) {
                    console.log(data);
                    resolve(data);
                    console.log("Resolve Function Called");
                } else {
                    console.log("No data available");
                    reject(new Error("No data available"));
                }
            });
        });
</code>```

ResourceModel.getById()

```<code>static getById(id) {
        const _transaction = cds.transaction();

        return _transaction.run(SELECT.from(Resource).where({ ID: id }));
    }
</code>```

cds.transaction() is one of cds framework provided method by SAP.

What I expect it to do is after successfully fetching all the records it should call the provided callback where I have my processing logic written and call resolve() after the processing is done.

I am receiving the data in the callback, able to print Data available and the received data object end even the Promise Resolved on the console. But surprisingly the promise is not getting resolved

I can say the "promise is not getting resolved" because this returned promise will be collected in a Promise.all() by the framework (as stated in the official docs - https://cap.cloud.sap/docs/node.js/api#service-before) and return a response after resolving. But I am not getting any response (neither success nor failure). Postman stays in loading... state forever.

The above example works fine with setTimeout() example.

where am I going wrong?

答:
first of all, add .catch() to get rejected value.

```<code>function asyncOpr = () => {
    return new Promise((resolve, reject) => {
        ResourceModel.getById(resource_ID).then((data) => {
                    if (data.length > 0) {
                        console.log(data);
                        resolve(data);
                        console.log("Resolve Function Called");
                    } else {
                        console.log("No data available");
                        reject(new Error("No data available"));
                    }
            }).catch(err => { /* handle error */ })
        });
  }
</code>```

The reason why you may not be getting the resolved value would be how you are using this function.
Correct implementation would be:

```<code>function foo() {
  asyncOpr().then( val => console.log(val))
            .catch( err => console.log(err))
}
</code>```

Also, see using async/await.

Body:
My question here may sound little repetitive. But I haven't found any answer on stackoverflow which can solve my problem.

I am returning a promise from one of my function. The promise will be resolved after getting some data from database. And will be rejected if there is no data in the db table. Also I have to do some processing on the fetched data before resolving the promise, that's why I am using callbacks.

My Code Snippet

return new Promise((resolve, reject) => {

            ResourceModel.getById(resource_ID).then((data) => {
                if (data.length > 0) {
                    console.log(data);
                    resolve(data);
                    console.log("Resolve Function Called");
                } else {
                    console.log("No data available");
                    reject(new Error("No data available"));
                }
            });
        });

ResourceModel.getById()

static getById(id) {
        const _transaction = cds.transaction();

        return _transaction.run(SELECT.from(Resource).where({ ID: id }));
    }

cds.transaction() is one of cds framework provided method by SAP.

What I expect it to do is after successfully fetching all the records it should call the provided callback where I have my processing logic written and call resolve() after the processing is done.

I am receiving the data in the callback, able to print Data available and the received data object end even the Promise Resolved on the console. But surprisingly the promise is not getting resolved

I can say the "promise is not getting resolved" because this returned promise will be collected in a Promise.all() by the framework (as stated in the official docs - https://cap.cloud.sap/docs/node.js/api#service-before) and return a response after resolving. But I am not getting any response (neither success nor failure). Postman stays in loading... state forever.

The above example works fine with setTimeout() example.

where am I going wrong?

Body:
first of all, add .catch() to get rejected value.

function asyncOpr = () => {
    return new Promise((resolve, reject) => {
        ResourceModel.getById(resource_ID).then((data) => {
                    if (data.length > 0) {
                        console.log(data);
                        resolve(data);
                        console.log("Resolve Function Called");
                    } else {
                        console.log("No data available");
                        reject(new Error("No data available"));
                    }
            }).catch(err => { /* handle error */ })
        });
  }

The reason why you may not be getting the resolved value would be how you are using this function.
Correct implementation would be:

function foo() {
  asyncOpr().then( val => console.log(val))
            .catch( err => console.log(err))
}

Also, see using async/await.