问:
How to create directory if it doesn't exist?
If I want to write a file to C:/output/results.csv what's a simple way to make the directory if it doesn't exist? I want to do this because CSV.write(path,data) errors if C:/output/ doesn't exist.

mkdir errors if the directory already exists. I am currently doing the following, but is there a safer/cleaner way to do this?

```<code>try
    mkdir("C:/output")
catch
    # if errors, likely already exists
end
</code>```

Edit:
As one of the commenters pointed out, mkpath will create a directory if it doesn't exist, and in either case will return the directory name.

My question was confounding the usage of mkdir (which errors if directory exists) and mkpath which does not error in that case.

答: mkpath(oath) will create a directory if it does not exist and return the path after doing so. If it already exists, the path is returned.

Body:
If I want to write a file to C:/output/results.csv what's a simple way to make the directory if it doesn't exist? I want to do this because CSV.write(path,data) errors if C:/output/ doesn't exist.

mkdir errors if the directory already exists. I am currently doing the following, but is there a safer/cleaner way to do this?

try
    mkdir("C:/output")
catch
    # if errors, likely already exists
end

Edit:
As one of the commenters pointed out, mkpath will create a directory if it doesn't exist, and in either case will return the directory name.

My question was confounding the usage of mkdir (which errors if directory exists) and mkpath which does not error in that case.


来源: stackexchange

问:
Oracle XE installation aborts with no error explanation
I have downloaded Oracle XE 18c for Windows 64 bit, and tried to install it on a Windows 10 machine.  I checked the SHA-256 checksum and it's correct.

The installation starts fine, but when it's copying new files it suddenly says "Rolling back installation", then ends and there's no error log to look at. Any ideas?

(1) "Copying files" screen

(2) "Rolling back" screen

(3) "Finished with errors" screen

答: I run "setup.exe" as administrator instead of "Oracle Database 18c Express Edition.msi" and it worked perfectly.</p>

ContentLicense: CC BY-SA 4.0


问:
Telebot InlineKeyboardMarkup callback
I want to send data via InlineKeyboardMarkup in function:

```<code>def choosing_room(message):
    keyboard = telebot.types.InlineKeyboardMarkup()
    for room_id in imagi_room.get_room_ids():
        room = imagi_room.get_room_by_id(room_id)
        keyboard.add(telebot.types.InlineKeyboardButton(text=room['master_name'], callback_data='room_' + str(room_id)))
    bot.send_message(message.chat.id, text='Choose', reply_markup=keyboard)

@bot.callback_query_handler(func=lambda c: 'room_' in c.data)
def call_back_room(c):
    ...
    bot.register_next_step_handler(selected, get_select) # Not working
</code>```

or

```<code>@bot.callback_query_handler(func=lambda c: 'room_' in c.data)
def call_back_room(c):
    ...
    foo(c.message)

def foo(message):
    photo_mess = bot.send_message(message.chat.id, text='Send a photo')
    photo_id = photo_mess.photo[-1].file_id #Error NonType...
</code>```

Why does register_next_step_handler or the second variant does not work in the callback function?
How else can I send data like id?

答:
Here is what I, "Hoping I'm answering your question", applied to my bot:</p>

```<code>#Start_command/s for your bot
@bot.message_handler(commands=['start', 'help', 'hi', ... ]) #...Anycommand_text_etc..._you_want])
def cmd_start(message):
    chat_id = message.chat.id
    bot.send_message(
            chat_id,\
            '''X Bot At Your Sevice''', parse_mode='HTML')
# Some bot functionality of your choice
@bot.message_handler(func=lambda message: True) #...[You can also do content type here]
def do_do_sth(message):
    bot.send_message(
            chat_id,\
            '''X Bot At Your Sevice''', parse_mode='HTML', reply_markup=x_keyboard())

    # or ... Do your thing.

# Callback_Handler
@bot.callback_query_handler(func=lambda call: True)
def callback_handler(call):
    if call.data == 'do_sth':
        do_do_sth(call.message)

# Your inline keyboard
def x_keyboard():
    markup = types.InlineKeyboardMarkup()
    btn = types.InlineKeyboardButton(\
    'xxx', callback_data='do_sth')
    markup.row(btn, btn1)
    return markup

Run your bot.
</code>```

Title: Telebot InlineKeyboardMarkup callback

Body:
I want to send data via InlineKeyboardMarkup in function:

def choosing_room(message):
    keyboard = telebot.types.InlineKeyboardMarkup()
    for room_id in imagi_room.get_room_ids():
        room = imagi_room.get_room_by_id(room_id)
        keyboard.add(telebot.types.InlineKeyboardButton(text=room['master_name'], callback_data='room_' + str(room_id)))
    bot.send_message(message.chat.id, text='Choose', reply_markup=keyboard)

@bot.callback_query_handler(func=lambda c: 'room_' in c.data)
def call_back_room(c):
    ...
    bot.register_next_step_handler(selected, get_select) # Not working

or

@bot.callback_query_handler(func=lambda c: 'room_' in c.data)
def call_back_room(c):
    ...
    foo(c.message)

def foo(message):
    photo_mess = bot.send_message(message.chat.id, text='Send a photo')
    photo_id = photo_mess.photo[-1].file_id #Error NonType...

Why does register_next_step_handler or the second variant does not work in the callback function?
How else can I send data like id?

Body:
Here is what I, "Hoping I'm answering your question", applied to my bot:

#Start_command/s for your bot
@bot.message_handler(commands=['start', 'help', 'hi', ... ]) #...Anycommand_text_etc..._you_want])
def cmd_start(message):
    chat_id = message.chat.id
    bot.send_message(
            chat_id,\
            '''X Bot At Your Sevice''', parse_mode='HTML')
# Some bot functionality of your choice
@bot.message_handler(func=lambda message: True) #...[You can also do content type here]
def do_do_sth(message):
    bot.send_message(
            chat_id,\
            '''X Bot At Your Sevice''', parse_mode='HTML', reply_markup=x_keyboard())

    # or ... Do your thing.

# Callback_Handler
@bot.callback_query_handler(func=lambda call: True)
def callback_handler(call):
    if call.data == 'do_sth':
        do_do_sth(call.message)

# Your inline keyboard
def x_keyboard():
    markup = types.InlineKeyboardMarkup()
    btn = types.InlineKeyboardButton(\
    'xxx', callback_data='do_sth')
    markup.row(btn, btn1)
    return markup

Run your bot.


问:
How to filter FileUpload Control?
How to add filter to the fileupload control in asp.net? I want a filter for Oasis File (.000).?

Please advice me... thank you very much!

答:
There's no property on the control. I think the simplest way is to validate the chosen file via javascript. For example

JS Function:

```<code>function checkFileExtension(elem) {
        var filePath = elem.value;

        if(filePath.indexOf('.') == -1)
            return false;

        var validExtensions = new Array();
        var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();

        validExtensions[0] = 'jpg';
        validExtensions[1] = 'jpeg';
        validExtensions[2] = 'bmp';
        validExtensions[3] = 'png';
        validExtensions[4] = 'gif';
        validExtensions[5] = 'tif';
        validExtensions[6] = 'tiff';
        validExtensions[7] = 'txt';
        validExtensions[8] = 'doc';
        validExtensions[9] = 'xls';
        validExtensions[10] = 'pdf';

        for(var i = 0; i < validExtensions.length; i++) {
            if(ext == validExtensions[i])
                return true;
        }

        alert('The file extension ' + ext.toUpperCase() + ' is not allowed!');
        return false;
    }
</code>```

Wire it up in page_load:

```<code>FileUpload1.Attributes.Add("onchange", "return checkFileExtension(this);")
</code>```

NOTE: This code was reproduced verbatim from here: http://forums.asp.net/t/1156963.aspx/1?How+to+filter+files+in+file+upload+HTML+control. I didn't write it and I haven't tested it!

ContentLicense: CC BY-SA 3.0

Title: How to filter FileUpload Control?

Body:
There's no property on the control. I think the simplest way is to validate the chosen file via javascript. For example

JS Function:

function checkFileExtension(elem) {
        var filePath = elem.value;

        if(filePath.indexOf('.') == -1)
            return false;

        var validExtensions = new Array();
        var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();

        validExtensions[0] = 'jpg';
        validExtensions[1] = 'jpeg';
        validExtensions[2] = 'bmp';
        validExtensions[3] = 'png';
        validExtensions[4] = 'gif';
        validExtensions[5] = 'tif';
        validExtensions[6] = 'tiff';
        validExtensions[7] = 'txt';
        validExtensions[8] = 'doc';
        validExtensions[9] = 'xls';
        validExtensions[10] = 'pdf';

        for(var i = 0; i < validExtensions.length; i++) {
            if(ext == validExtensions[i])
                return true;
        }

        alert('The file extension ' + ext.toUpperCase() + ' is not allowed!');
        return false;
    }

Wire it up in page_load:

FileUpload1.Attributes.Add("onchange", "return checkFileExtension(this);")

NOTE: This code was reproduced verbatim from here: http://forums.asp.net/t/1156963.aspx/1?How+to+filter+files+in+file+upload+HTML+control. I didn't write it and I haven't tested it!


问:
Determine if first & last characters in a string are vowels and return true if they match
This function is continually returning false. Anything i'm missing here?</p>

```<code>function regexVar() {
    var re = ""

    var last = re.length - 1
    var first = re[0]

    var match = (first === last) ? "true" : "false"

    if(match && (first == "a" ||
                first == 'e' ||
                first == 'i' ||
                first == 'o' ||
                first ==  'u')){
                console.log(true)
            } else {
                console.log(false)
            }
}
</code>```

答:
The last = re.length - 1 equals -1 cause re.length equals 0

and first = re[0] is undefined because of empty string re

So your match is always false just like all the conditions below:

```<code>(first == "a" || first == 'e' || first == 'i' || first == 'o' || first ==  'u')
</code>```

Body:
This function is continually returning false. Anything i'm missing here?

function regexVar() {
    var re = ""

    var last = re.length - 1
    var first = re[0]

    var match = (first === last) ? "true" : "false"

    if(match && (first == "a" ||
                first == 'e' ||
                first == 'i' ||
                first == 'o' ||
                first ==  'u')){
                console.log(true)
            } else {
                console.log(false)
            }
}

Body:
The last = re.length - 1 equals -1 cause re.length equals 0

and first = re[0] is undefined because of empty string re

So your match is always false just like all the conditions below:

(first == "a" || first == 'e' || first == 'i' || first == 'o' || first ==  'u')


问:
Relative performance of std::atomic and std::mutex
I am considering options for implementation of a queue for a project, a requirement of which is that the producer, at least, must be as low latency as possibe. To this end, I have been investigating "lock free" queues using std::atomic to control access to the data structure by the producer and consumer threads.  It was my hope that this would avoid overheads in std::mutex, and specifically std::unique_lock, which the code currently uses.

To this end, I have written a simple test program to assess the relative performance of std::mutex (coupled with std::unique_lock) and std::atomic.  The program also does a check to ensure the atomic object is lock free, which it is.

```<code>#include <mutex>
#include <atomic>
#include <thread>
#include <chrono>
#include <iostream>

#define CYCLES 100000000

void testAtomic()
{
   bool var(true);
   std::atomic_bool _value(true);

   std::cout << "atomic bool is ";

   if(!_value.is_lock_free())
      std::cout << "not ";
   std::cout << "lock free" << std::endl;
   const auto _start_time = std::chrono::high_resolution_clock::now();

   for(size_t counter = 0; counter < CYCLES; counter++)
   {
      var = _value.load();
      var = !var;
      _value.store(var);
   }

   const auto _end_time = std::chrono::high_resolution_clock::now();

   std::cout << 1e-6 * std::chrono::duration_cast<std::chrono::microseconds>
      (_end_time - _start_time).count() << " s" << std::endl;
}

void testMutex()
{
   bool var(true);
   std::mutex _mutex;
   std::chrono::high_resolution_clock _clock;

   const auto _start_time = std::chrono::high_resolution_clock::now();

   for(size_t counter = 0; counter < CYCLES; counter++)
   {
      std::unique_lock<std::mutex> lock(_mutex);
      var = !var;
   }

   const auto _end_time = std::chrono::high_resolution_clock::now();

   std::cout << 1e-6 * std::chrono::duration_cast<std::chrono::microseconds>
      (_end_time - _start_time).count() << " s" << std::endl;
}

int main()
{
   std::thread t1(testAtomic);
   t1.join();
   std::thread t2(testMutex);
   t2.join();
   return 0;
}
</code>```

When running this program, I get the following output:

```<code>atomic bool is lock free
3.49434 s
2.31755 s
</code>```

This would indicate to me that std::mutex (and std::unique_lock) is significantly faster, which is the opposite of what I've come to expect from reading up about atomics vs mutexes. Are my findings correct? Is there a problem with my test program? Is my understanding about the differences between the two incorrect?

The code was compiled with GCC 4.8.5 on CentOS7

答:
What hardware are you testing on?

Since you're using GCC, the std::atomic seq_cst store will be using a mov + slow mfence instead of a somewhat less slow xchg-with-mem (which is also a full barrier, like all other x86 atomic RMW operations).

Taking a mutex costs an atomic RMW (like xchg, not mov + mfence).  And if you're lucky release the mutex could be just a plain store (like mo_release).  There is zero contention so acquiring the lock always succeeds.

It's certainly plausible that the the code behind those mutex lock / unlock library functions is less expensive than mfence, especially on Skylake CPUs with updated microcode where mfence is a full barrier for out-of-order execution as well as memory.  (See the bottom of this answer, and also Does lock xchg have the same behavior as mfence?)

Also, note that your mutex loop optimized the local bool var into a register and isn't actually updating it in memory inside the loop.  (Your code on the Godbolt compiler explorer with gcc4.8.5).

```<code># the main loop from testMutex
.L80:                                                       # do {
        mov     rdi, rsp                                      # pointer to _mutex on the stack
        call    __gthrw_pthread_mutex_lock(pthread_mutex_t*)
        test    eax, eax
        jne     .L91                                          # mutex error handling
        mov     rdi, rsp                                      # pointer to _mutex again
        call    __gthrw_pthread_mutex_unlock(pthread_mutex_t*)
        sub     rbx, 1
        jne     .L80                                        # }while(--counter)
</code>```

xor bl, 1 inside the loop would be irrelevant; out-of-order exec could overlap that with other work.

If a reference to var escaped the function so the compiler had to have it in sync in memory before non-inline function calls (including to pthread library functions), we'd expect something like xor byte ptr [rsp+8], 1.  That would also be pretty cheap and perhaps mostly hidden by out-of-order exec, although the load/ALU/store could be something that a full barrier would have to wait for when draining the store buffer.

Speeding up your std::atomic code:

You're intentionally avoiding doing an atomic RMW, it seems, instead loading into a tmp var and doing a separate store.  If you use only release instead of seq_cst, that lets it compile to just a plain store instruction on x86.  (Or to cheaper barriers on most other ISAs).

```<code>      bool tmp = _value.load(std::memory_order_relaxed);   // or acquire
      _value.store(!tmp, std::memory_order_release);
</code>```

This should run at about 6 cycles per inversion, just the latency of one ALU operation plus store-forwarding latency for the store/reload.  vs. maybe 33 cycles per iteration for the best-case throughput for mfence (https://uops.info/).

Or since this is a non-atomic modification, just store alternating values without re-reading the old value.  You can usually only avoid an atomic RMW in cases where only one producer is writing a value, and other threads are reading.  So let the producer keep the value it's modifying in a register (non-atomic local var), and store copies if it.

```<code>   bool var = true;
   for(size_t counter = 0; counter < CYCLES; counter++)
   {
      var = !var;
      _value.store(var, std::memory_order_release);
   }
</code>```

Also, don't use leading underscores for your own var names.  Such names are reserved for the implementation.  (single _ with lowercase is only reserved at file / global scope, but it's still bad practice.)

Body:
I am considering options for implementation of a queue for a project, a requirement of which is that the producer, at least, must be as low latency as possibe. To this end, I have been investigating "lock free" queues using std::atomic to control access to the data structure by the producer and consumer threads.  It was my hope that this would avoid overheads in std::mutex, and specifically std::unique_lock, which the code currently uses.

To this end, I have written a simple test program to assess the relative performance of std::mutex (coupled with std::unique_lock) and std::atomic.  The program also does a check to ensure the atomic object is lock free, which it is.

#include <mutex>
#include <atomic>
#include <thread>
#include <chrono>
#include <iostream>

#define CYCLES 100000000

void testAtomic()
{
   bool var(true);
   std::atomic_bool _value(true);

   std::cout << "atomic bool is ";

   if(!_value.is_lock_free())
      std::cout << "not ";
   std::cout << "lock free" << std::endl;
   const auto _start_time = std::chrono::high_resolution_clock::now();

   for(size_t counter = 0; counter < CYCLES; counter++)
   {
      var = _value.load();
      var = !var;
      _value.store(var);
   }

   const auto _end_time = std::chrono::high_resolution_clock::now();

   std::cout << 1e-6 * std::chrono::duration_cast<std::chrono::microseconds>
      (_end_time - _start_time).count() << " s" << std::endl;
}

void testMutex()
{
   bool var(true);
   std::mutex _mutex;
   std::chrono::high_resolution_clock _clock;

   const auto _start_time = std::chrono::high_resolution_clock::now();

   for(size_t counter = 0; counter < CYCLES; counter++)
   {
      std::unique_lock<std::mutex> lock(_mutex);
      var = !var;
   }

   const auto _end_time = std::chrono::high_resolution_clock::now();

   std::cout << 1e-6 * std::chrono::duration_cast<std::chrono::microseconds>
      (_end_time - _start_time).count() << " s" << std::endl;
}

int main()
{
   std::thread t1(testAtomic);
   t1.join();
   std::thread t2(testMutex);
   t2.join();
   return 0;
}

When running this program, I get the following output:

atomic bool is lock free
3.49434 s
2.31755 s

This would indicate to me that std::mutex (and std::unique_lock) is significantly faster, which is the opposite of what I've come to expect from reading up about atomics vs mutexes. Are my findings correct? Is there a problem with my test program? Is my understanding about the differences between the two incorrect?

The code was compiled with GCC 4.8.5 on CentOS7

Body:
What hardware are you testing on?

Since you're using GCC, the std::atomic seq_cst store will be using a mov + slow mfence instead of a somewhat less slow xchg-with-mem (which is also a full barrier, like all other x86 atomic RMW operations).

Taking a mutex costs an atomic RMW (like xchg, not mov + mfence).  And if you're lucky release the mutex could be just a plain store (like mo_release).  There is zero contention so acquiring the lock always succeeds.

It's certainly plausible that the the code behind those mutex lock / unlock library functions is less expensive than mfence, especially on Skylake CPUs with updated microcode where mfence is a full barrier for out-of-order execution as well as memory.  (See the bottom of this answer, and also Does lock xchg have the same behavior as mfence?)

Also, note that your mutex loop optimized the local bool var into a register and isn't actually updating it in memory inside the loop.  (Your code <a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tLgA5SW9ABk8tTADljAI0zEQ3AKykADqgWE6rR6hibmvv6BdLb2Tkau7l6KypiqQQwEzMQEIcamAOzJKmp0GVkEMY4ubh7eCpnZuWGF9eWVcQm1AJSKqAbEyBwA5FIAzHbIhlgA1OKjOkYGBJgAHnPY4gAMAIJjE1OYs/PMREZ4EqMbO3u0kwYzczoECMSYzOjrW7uS47cHRzpkC86KhPtcfvt7odHup6q9mEYwbtwaMsFQ7IcdABNHTWbAMaacTbEknEr5fABuqDw6Gmy3q21O5wgXXJ%2BVkO2mXOcqH00wpWQgBGIBkwrNGHO2XOm9XQIBAJ1QZ2QAH0eXyVQLDJghSKxXNJV9pbL5WglgDHrNJJJFcrpurWNM8AorZIDeTOVy8FQIGAwJq2KKAHTOlWsVDIADWKqorx1XVZnulMoIcpQfQIFvmrtoqEzUjdEqNXJN6fNj0tBfDUemscwmALWZ0KbTVlY7qTaFo9WmzCWqGmKta2RVaiM0NGABEW6bgbn5Qg8MAECrXgp9EsgirJhHI/LcwB3Fkd5FSrk0YgQAIAL0wo%2BmZvobiO082BoffSfxAB02xuPx76PssxByHIiZnrM7LFsmArfnM04BtqQbhu8x5Fkm0qwS%2B0x%2BrBJ7JlyiHBvUJA6rB4qStK4j5JOHoQV2PZ9kQg5WKOeDjthpZAsQIILkuK5rhuJS0Nu1Z7iAh5oYaSZcRmTaEpgAC0ABs0wAFQzigc6oPK6D9CcW4sPUjxcdp8rKjxShdugChIgR0wQCqrFjocimDsOBBseOXRBkBLLyY2tnWvJpZtie1G0dcOxUjSdKYPUACySyrMe1xQUmDr8oKwqihR0GlosywrIOhWrPhJaprOPHziAi7Lqu8VCYZYmDjuUbhZ2dCMf27kNJ5LmcZVWnVTptX8Q166GMJom7vuqBHnlUUQReV54Le95Ac%2B8HTG%2BEofgYX4/n%2BeIMIBn7AaBMjgVR6UQcaQ0HXgACOophruJlDaVayXNMYmOV9i13VyWHbbhWTlZBkWntKDGZkxA5OdoXkTtOpkjXx9WCVNzWzRJ81SXR91pma%2BbzJanBKapGlo7xIB6cQBl0NuzDGfMNM1RZ/ipHQNl2QRjnOexrm9eUyM%2BX5XQBcFQWSCFQ1hehuw0XRdiZkYzB2KlSuURVabPPCtIEJwQrxQQjJKucgPSkbQZ8NStAEzJQ3628huSCbiXJSsVtcgQki2/bjsQa8BD9LQO3hTRQw9KwIBDJ4QykKYQybInOlDDol3SDKfQDNCPycInBBx6nCakHunibEIcfcInyep6Q6eJwoIBV8XKfR6QcCwEgaBGD4eDsGQFAQH3A9DyAwDcGY3joqwwEtxAzgl4nzh2FkACeceF6QffjvQADytCsFvHekFg6uiOwK/n3grxpBS8U36sqTJdvieq8oN%2BsHgzgM8QG89BYHfqQYU7F349BoPQJgbAOA8H4IIYQogUBZyEL/FusBaAIg4K4W4CB1bEEjKQR%2B7ghg8FLj0VAPhhItyGIpWU8EJAyDkJwTg0xFIH1GM3FIaQNAQCsE0UwnBLDaHaNUdwowACcVc/ABGEoIwQsioi0DEfEGoUiq5KGKOkPqCjhFaNSMJMo2RVGdFGGYfRuiNxhEsW0DEHR1EWJ6OufogwuAxzjgnJON904rDMMpFS3BpjAGQMgaY3AgxmCDJ4ByuBCAkCtKMYRv4lTjy2gXSWmdmEyCLivMuFcq6xyGLXbxZ8m6KFbqAvJHihiSDrj4uOuSO5lxIQEDQ3AgA" rel="nofollow noreferrer">on the Godbolt compiler explorer with gcc4.8.5).

# the main loop from testMutex
.L80:                                                       # do {
        mov     rdi, rsp                                      # pointer to _mutex on the stack
        call    __gthrw_pthread_mutex_lock(pthread_mutex_t*)
        test    eax, eax
        jne     .L91                                          # mutex error handling
        mov     rdi, rsp                                      # pointer to _mutex again
        call    __gthrw_pthread_mutex_unlock(pthread_mutex_t*)
        sub     rbx, 1
        jne     .L80                                        # }while(--counter)

xor bl, 1 inside the loop would be irrelevant; out-of-order exec could overlap that with other work.

If a reference to var escaped the function so the compiler had to have it in sync in memory before non-inline function calls (including to pthread library functions), we'd expect something like xor byte ptr [rsp+8], 1.  That would also be pretty cheap and perhaps mostly hidden by out-of-order exec, although the load/ALU/store could be something that a full barrier would have to wait for when draining the store buffer.

Speeding up your std::atomic code:

You're intentionally avoiding doing an atomic RMW, it seems, instead loading into a tmp var and doing a separate store.  If you use only release instead of seq_cst, that lets it compile to just a plain store instruction on x86.  (Or to cheaper barriers on most other ISAs).

      bool tmp = _value.load(std::memory_order_relaxed);   // or acquire
      _value.store(!tmp, std::memory_order_release);

This should run at about 6 cycles per inversion, just the latency of one ALU operation plus store-forwarding latency for the store/reload.  vs. maybe 33 cycles per iteration for the best-case throughput for mfence (https://uops.info/).

Or since this is a non-atomic modification, just store alternating values without re-reading the old value.  You can usually only avoid an atomic RMW in cases where only one producer is writing a value, and other threads are reading.  So let the producer keep the value it's modifying in a register (non-atomic local var), and store copies if it.

   bool var = true;
   for(size_t counter = 0; counter < CYCLES; counter++)
   {
      var = !var;
      _value.store(var, std::memory_order_release);
   }

Also, don't use leading underscores for your own var names.  Such names are reserved for the implementation.  (single _ with lowercase is only reserved at file / global scope, but it's still bad practice.)


问:
Firebase CLI always shows Error: Invalid project id: \
Every time I use a firebase command this error occurs:

```<code>...\WEBRTCTest\FirebaseRTC> firebase use --add

Error: Invalid project id: \.
</code>```

```<code>\WEBRTCTest\FirebaseRTC> firebase use --clear

Error: Invalid project id: \.
</code>```

The error occured after I accidently run the command:

```<code>firebase use \
</code>```

Prior to that all was working fine.

I tried to reinstall firebase-tools using npm and also re-cloning the example project from github.
Also tried to logout using firebase logout but it gives me the same error:

```<code>\WEBRTCTest\FirebaseRTC> firebase use --clear

Error: Invalid project id: \.
</code>```

I´m thankful for any idea as i´m stuck right now.

答:
In my case, I changed the "default" in .firebaserc, then it works:

From:

```<code>{
    "projects": {
        "default": "YOUR DEFAULT PROJECT ID"
    }
}
</code>```

TO my project id "pwa-proj"

```<code>{
    "projects": {
        "default": "pwa-proj"
    }
}
</code>```

Body:
Every time I use a firebase command this error occurs:

...\WEBRTCTest\FirebaseRTC> firebase use --add

Error: Invalid project id: \.

\WEBRTCTest\FirebaseRTC> firebase use --clear

Error: Invalid project id: \.

The error occured after I accidently run the command:

firebase use \

Prior to that all was working fine.

I tried to reinstall firebase-tools using npm and also re-cloning the example project from github.
Also tried to logout using firebase logout but it gives me the same error:

\WEBRTCTest\FirebaseRTC> firebase use --clear

Error: Invalid project id: \.

I´m thankful for any idea as i´m stuck right now.

Body:
In my case, I changed the "default" in .firebaserc, then it works:

From:

{
    "projects": {
        "default": "YOUR DEFAULT PROJECT ID"
    }
}

TO my project id "pwa-proj"

{
    "projects": {
        "default": "pwa-proj"
    }
}


问:
can we insert date into varchar2 in oracle without converting by to_char?
can we insert date into varchar2  in oracle without converting by to_char?</p>

答:
Oracle will convert the date into a string using what localization settings are in place during the insert. This is true not only of Oracle but of any database. For a date, that might commonly be in the format "DD-MON-YY".

Here is an example of inserting a date into a varchar2 column.

That said, you should not do this. You should be storing date/time values in the database using the correct data type -- and that would be either date or timestamp. If you want to insert a constant, then use the date or timestamp qualifier with the appropriate value following it.


问:
Excel function to return sum of corresponding items in array
I am pretty new to Excel and VBA, but I was trying to make a function that would provide this result.

```<code>    A    B
  -----------
1 | A  |  1 |
2 | B  |  2 |        =TotalItems("A", A1:A4, B1:B4)
3 | C  |  3 |        =5
4 | A  |  4 |
  -----------
</code>```

It searches through an array to find all occurrences, and then sums up the corresponding values in another array. I'm not sure if there is already a function to do this, but I tried creating one.  Here's the code:

```<code>Function TotalItems(itemToFind, itemsToReference, resultArr)

    Dim i As Integer
    Dim total As Double
    Dim r As Integer

    For i = 1 To UBound(itemsToReference)

       If StrComp(itemToFind, itemsToReference(i)) = 0 Then
            total = total + CDbl(resultArr(i))
        End If

    Next i

    TotalItems = total

End Function
</code>```

It returns #VALUE! whenever I run it. I'm not sure what the problem is, and all help will be appreciated.

答:
You are passing Ranges, not arrays, so:

```<code>Function TotalItems(itemToFind As String, itemsToReference As Range, resultArr As Range) As Long

    Dim i As Long, rng As Range
    Dim total As Long

    For i = 1 To (itemsToReference.Rows.Count)

       If StrComp(itemToFind, itemsToReference(i, 1)) = 0 Then
            total = total + CLng(resultArr(i, 1))
        End If

    Next i

    TotalItems = total

End Function
</code>```

(based on your example, I DIMed Long rather than Double)
(note I index the ranges just like 2-D arrays)

In a worksheet cell, you could use:

```<code>=SUMPRODUCT(--(A1:A4="A")*(B1:B4))
</code>```

Body:
I am pretty new to Excel and VBA, but I was trying to make a function that would provide this result.

    A    B
  -----------
1 | A  |  1 |
2 | B  |  2 |        =TotalItems("A", A1:A4, B1:B4)
3 | C  |  3 |        =5
4 | A  |  4 |
  -----------

It searches through an array to find all occurrences, and then sums up the corresponding values in another array. I'm not sure if there is already a function to do this, but I tried creating one.  Here's the code:

Function TotalItems(itemToFind, itemsToReference, resultArr)

    Dim i As Integer
    Dim total As Double
    Dim r As Integer

    For i = 1 To UBound(itemsToReference)

       If StrComp(itemToFind, itemsToReference(i)) = 0 Then
            total = total + CDbl(resultArr(i))
        End If

    Next i

    TotalItems = total

End Function

It returns #VALUE! whenever I run it. I'm not sure what the problem is, and all help will be appreciated.

Body:
You are passing Ranges, not arrays, so:

Function TotalItems(itemToFind As String, itemsToReference As Range, resultArr As Range) As Long

    Dim i As Long, rng As Range
    Dim total As Long

    For i = 1 To (itemsToReference.Rows.Count)

       If StrComp(itemToFind, itemsToReference(i, 1)) = 0 Then
            total = total + CLng(resultArr(i, 1))
        End If

    Next i

    TotalItems = total

End Function

(based on your example, I DIMed Long rather than Double)
(note I index the ranges just like 2-D arrays)

In a worksheet cell, you could use:

=SUMPRODUCT(--(A1:A4="A")*(B1:B4))


问:
Expo Camera only opening once with React Navigation
I set the Expo camera to open on the middle tab with react navigation. However, the camera only opens when I click on that tab the first time. If I switch off of it and go back it's just a black screen. Also the take a picture button is not there. (I am new with react native and kinda coding as a whole)</p>

```<code>'use strict';
import React, { Component } from 'react';
import { createBottomTabNavigator } from 'react-navigation';
import { Camera, Permissions } from 'expo';
import {
    AppRegistry,
    Dimensions,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    Button
} from 'react-native';

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Home!</Text>
      </View>
    );
  }
}

class CameraView extends React.Component {
  state = {
    hasCameraPermission: null,
    type: Camera.Constants.Type.back,
  };

  async componentWillMount() {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({ hasCameraPermission: status === 'granted' });
  }
  render() {
     const { hasCameraPermission } = this.state;
    if (hasCameraPermission === null) {
      return <View />;
    } else if (hasCameraPermission === false) {
      return <Text>No access to camera</Text>;
    } else {
      return (
        <View style={{ flex: 1 }}>
          <Camera style={{ flex: 1 }} type={this.state.type}>
            <View
              style={{
                flex: 1,
                backgroundColor: 'transparent',
                flexDirection: 'row',
              }}>
              <TouchableOpacity
                style={{
                  flex: 0.1,
                  alignSelf: 'flex-end',
                  alignItems: 'center',
                }}
                onPress={() => {
                  this.setState({
                    type: this.state.type === Camera.Constants.Type.back
                      ? Camera.Constants.Type.front
                      : Camera.Constants.Type.back,
                  });
                }}>
                <Text
                  style={{ fontSize: 18, marginBottom: 10, color: 'white' }}>
                  {' '}Flip{' '}
                </Text>
              </TouchableOpacity>
            </View>
          </Camera>
        </View>
      );
    }
  }
}

class SettingsScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Settings!</Text>
      </View>
    );
  }
}

export default createBottomTabNavigator({
  Home: HomeScreen,
  Camera:CameraView,
  Settings: SettingsScreen
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        top: 250
    },

    capture: {
        flex: 0,
        backgroundColor: '#fff',
        borderRadius: 5,
        padding: 15,
        paddingHorizontal: 20,
        alignSelf: 'center',
        margin: 20
    }

});
</code>```

答:
With react navigation 5.x

```<code>import { useIsFocused } from '@react-navigation/native';

export const CameraView = (props) => {
    const isFocused = useIsFocused();
    return (
       <View>
         { isFocused && <RNCamera  />  }
       </View>
     )
}
</code>```

useIsFocused Documentation

Body:
I set the Expo camera to open on the middle tab with react navigation. However, the camera only opens when I click on that tab the first time. If I switch off of it and go back it's just a black screen. Also the take a picture button is not there. (I am new with react native and kinda coding as a whole)

'use strict';
import React, { Component } from 'react';
import { createBottomTabNavigator } from 'react-navigation';
import { Camera, Permissions } from 'expo';
import {
    AppRegistry,
    Dimensions,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    Button
} from 'react-native';

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Home!</Text>
      </View>
    );
  }
}

class CameraView extends React.Component {
  state = {
    hasCameraPermission: null,
    type: Camera.Constants.Type.back,
  };

  async componentWillMount() {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({ hasCameraPermission: status === 'granted' });
  }
  render() {
     const { hasCameraPermission } = this.state;
    if (hasCameraPermission === null) {
      return <View />;
    } else if (hasCameraPermission === false) {
      return <Text>No access to camera</Text>;
    } else {
      return (
        <View style={{ flex: 1 }}>
          <Camera style={{ flex: 1 }} type={this.state.type}>
            <View
              style={{
                flex: 1,
                backgroundColor: 'transparent',
                flexDirection: 'row',
              }}>
              <TouchableOpacity
                style={{
                  flex: 0.1,
                  alignSelf: 'flex-end',
                  alignItems: 'center',
                }}
                onPress={() => {
                  this.setState({
                    type: this.state.type === Camera.Constants.Type.back
                      ? Camera.Constants.Type.front
                      : Camera.Constants.Type.back,
                  });
                }}>
                <Text
                  style={{ fontSize: 18, marginBottom: 10, color: 'white' }}>
                  {' '}Flip{' '}
                </Text>
              </TouchableOpacity>
            </View>
          </Camera>
        </View>
      );
    }
  }
}

class SettingsScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Settings!</Text>
      </View>
    );
  }
}

export default createBottomTabNavigator({
  Home: HomeScreen,
  Camera:CameraView,
  Settings: SettingsScreen
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        top: 250
    },

    capture: {
        flex: 0,
        backgroundColor: '#fff',
        borderRadius: 5,
        padding: 15,
        paddingHorizontal: 20,
        alignSelf: 'center',
        margin: 20
    }

});

Body:
With react navigation 5.x

import { useIsFocused } from '@react-navigation/native';

export const CameraView = (props) => {
    const isFocused = useIsFocused();
    return (
       <View>
         { isFocused && <RNCamera  />  }
       </View>
     )
}

useIsFocused Documentation


问:
Get pixels cords from specific angle
I have some problem. I'm using pygame. I would like to take cords of all pixels that are away from one point at a specific angle.

For example, I would like to get cords of all pixels that are away from point (15,20) at an angle of 18%.

I know there are some math to do but I cant figure out how to do this in python. Could you help me?

答:
Assuming you want the pixels in a line from ⟪some point⟫ going off in ⟪some angle⟫.

First let's define some things.

```<code> origin_point  = ( 15, 20 )            # Co-ordinates of starting point
 project_angle = math.radians( 18.0 )  # Angle of projection in degrees
</code>```

We need to change the angle from degrees to radians for the Python math trigonometric functions.  It's not just Python that uses radians, most programming languages do.

We want to define the line that goes from the origin_point in the direction of project_angle.  By working out the end-points of the line, it allows us to calculate the pixels.  So where does the line end? Infinity?  Probably the edge of screen will do.

We need to work out the intersection of the line formed with the edge of the screen, so we can use any sort of length for the line, so long as it's theoretically greater than the screen's maximum possible line-length (which is the diagonal: diagonal_length = √(window_width² + window_length²) ).  So any "long enough" length will do, so we'll cheat and use a constant of 10000.

```<code>MAX_LENGTH = 10000
</code>```

Now for that co-ordinate... using the sine and cosine of the angle, multiply by the length to work out that point:

```<code>final_x = start_x + ( length * math.cos( angle_of_projection ) )
final_y = start_y + ( length * math.sin( angle_of_projection ) )
</code>```

Turning this into a function:

```<code>def getEndOfLine( start_point, angle_of_projection, length ):
    """ Given a co-ordinate, projection angle, and line length, return
        the co-ordinate of the end of line """
    start_x, start_y = start_point
    final_x = start_x + length * math.cos( angle_of_projection )
    final_y = start_y + length * math.sin( angle_of_projection )
    return ( final_x, final_y )
</code>```

Using this function, we can now do something like:

```<code>end_point = getEndOfLine( origin_point, project_angle, MAX_LENGTH )
</code>```

Giving us two points to define the line.  So, now we have a line, we can intersect that with the screen edges.  Because our line is so long, it's guaranteed to exit the screen somewhere.

Where are the edges of the screen - these are easy to know:

```<code>top_side    = [ ( 0, 0 ), ( SCREEN_WIDTH-1, 0 ) ]
bottom_side = [ ( 0, SCREEN_HEIGHT-1 ), ( SCREEN_WIDTH-1, SCREEN_HEIGHT-1 ) ]
left_side   = [ ( 0, 0 ), ( SCREEN_WIDTH-1, SCREEN_HEIGHT-1 ) ]
right_side  = [ ( SCREEN_WIDTH-1, 0 ), ( SCREEN_WIDTH-1, SCREEN_HEIGHT-1 ) ]
all_sides = [ top_side, right_side, bottom_side, left_side ]
</code>```

Now we need to intersect the angled-line with the screen-edge lines.  I don't want to go into the maths too much here, but if two, straight, infinitely-long lines are not parallel they must intersect. So first determine that your lines are not parallel, then calculate the intersection point using the determinant method.  The lines might intersect off-screen, we don't care about these points.

```<code>def intersectionPoint( x1,y1, x2,y2, x3,y3, x4,y4 ):
    #Use determinant method, as per
    #Ref: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
    Px = ((((x1*y2)-(y1*x2))*(x3 - x4)) - ((x1-x2)*((x3*y4)-(y3*x4)))) / (((x1-x2)*(y3-y4)) - ((y1-y2)*(x3-x4)))
    Py = ((((x1*y2)-(y1*x2))*(y3 - y4)) - ((y1-y2)*((x3*y4)-(y3*x4)))) / (((x1-x2)*(y3-y4)) - ((y1-y2)*(x3-x4)))
    return Px,Py

def getIntersectionPoint( line_start, line_end, screen_edges ):
    x1, y1 = line_start
    x2, y2 = line_end

    for edge in screen_edges:
        x3, y3 = edge[0]  # line forming the screen edge
        x4, y4 = edge[1]
        is_parallel = (((x1-x2)*(y3-y4)) - ((y1-y2)*(x3-x4)) == 0)

        if ( not is_parallel ):
           int_x, int_y = intersectionPoint( x1,y1, x2,y2, x3,y3, x4,y4 )
           # but is the intersection point on-screen (otherwise we don't care)
           if ( int_x >= 0 and int_y >= 0 and int_x < SCREEN_WIDTH and int_y < SCREEN_HEIGHT ):
               return ( int_x, int_y )

    return None  # should never happen
</code>```

So now using this function, we can determine the point at the edge of the screen:

```<code># Work out the long long line:
peliminary_point = getEndOfLine( origin_point, project_angle, MAX_LENGTH )
print( "Peliminary End Point from %3.1f° is (%3.1f,%3.1f)" % ( project_angle, peliminary_point[0], peliminary_point[1] ) )

# Work out where this line exits the screen/window:
end_point = getIntersectionPoint( origin_point, peliminary_point, all_sides )
print( "End Point is (%3.1f,%3.1f)" % ( end_point[0], end_point[1] ) )
</code>```

For a 200x200 window, and MAX_LENGTH of 10000 I get:

Peliminary End Point from 0.31° is (38052.3,12370.7)

  End Point is (199.0,71.4)

Now we have the co-ordinate of the end of the line, it's easy to use Bresenhnam's Midpoint Line Algorithm to calculate the pixels.  Best go read about this, I'm not going to explain it here (not even sure I could).

```<code>def _plotLineLow( x0,y0, x1,y1 ):
    points = []
    dx = x1 - x0
    dy = y1 - y0
    yi = 1
    if dy < 0:
        yi = -1
        dy = -dy
    D = 2*dy - dx
    y = y0

    for x in range( x0, x1 ):
        points.append( (x,y) )
        if D > 0:
           y = y + yi
           D = D - 2*dx
        D = D + 2*dy
    return points

def _plotLineHigh( x0,y0, x1,y1 ):
    points = []
    dx = x1 - x0
    dy = y1 - y0
    xi = 1
    if dx < 0:
        xi = -1
        dx = -dx
    D = 2*dx - dy
    x = x0

    for y in range( y0, y1 ):
        points.append( (x,y) )
        if D > 0:
            x = x + xi
            D = D - 2*dy
        D = D + 2*dx
    return points

def getMidLinePoints( pointA, pointB ):
    x0, y0 = int( pointA[0] ), int( pointA[1] )
    x1, y1 = int( pointB[0] ), int( pointB[1] )
    points = []
    if ( abs(y1 - y0) < abs(x1 - x0) ):
        if ( x0 > x1 ):
            points += _plotLineLow( x1, y1, x0, y0 )
        else:
            points += _plotLineLow( x0, y0, x1, y1 )
    else:
        if ( y0 > y1 ):
            points += _plotLineHigh( x1, y1, x0, y0 )
        else:
            points += _plotLineHigh( x0, y0, x1, y1 )
    return points
</code>```

Adding in this code, gives the co-ordinates of the pixels along the line from origin_point at project_angle to the edge of the screen:

```<code># Work out the long long line:
peliminary_point = getEndOfLine( origin_point, project_angle, MAX_LENGTH )
print( "Peliminary End Point from %3.1f° is (%3.1f,%3.1f)" % ( project_angle, peliminary_point[0], peliminary_point[1] ) )

# Work out where this line exits the screen/window:
end_point = getIntersectionPoint( origin_point, peliminary_point, all_sides )
print( "End Point is (%3.1f,%3.1f)" % ( end_point[0], end_point[1] ) )

line_points = getMidLinePoints( origin_point, end_point )
print( "Line Points are: " + str( line_points ) )
</code>```

Which gives me (this time on a 100x100 window):

Peliminary End Point from 0.31° is (9520.6,3100.2)

  End Point is (99.0,38.9)

  Line Points are: [(10, 10), (11, 10), (12, 11), (13, 11), (14, 11), (15, 12), (16, 12), (17, 12), (18, 13), (19, 13), (20, 13), (21, 13), (22, 14), (23, 14), (24, 14), (25, 15), (26, 15), (27, 15), (28, 16), (29, 16), (30, 16), (31, 17), (32, 17), (33, 17), (34, 18), (35, 18), (36, 18), (37, 18), (38, 19), (39, 19), (40, 19), (41, 20), (42, 20), (43, 20), (44, 21), (45, 21), (46, 21), (47, 22), (48, 22), (49, 22), (50, 23), (51, 23), (52, 23), (53, 24), (54, 24), (55, 24), (56, 24), (57, 25), (58, 25), (59, 25), (60, 26), (61, 26), (62, 26), (63, 27), (64, 27), (65, 27), (66, 28), (67, 28), (68, 28), (69, 29), (70, 29), (71, 29), (72, 30), (73, 30), (74, 30), (75, 30), (76, 31), (77, 31), (78, 31), (79, 32), (80, 32), (81, 32), (82, 33), (83, 33), (84, 33), (85, 34), (86, 34), (87, 34), (88, 35), (89, 35), (90, 35), (91, 35), (92, 36), (93, 36), (94, 36), (95, 37), (96, 37), (97, 37), (98, 38)]

Pretty simple heh!  ;)

Title: Get pixels cords from specific angle

Body:
Assuming you want the pixels in a line from ⟪some point⟫ going off in ⟪some angle⟫.

First let's define some things.

 origin_point  = ( 15, 20 )            # Co-ordinates of starting point
 project_angle = math.radians( 18.0 )  # Angle of projection in degrees

We need to change the angle from degrees to radians for the Python math trigonometric functions.  It's not just Python that uses radians, most programming languages do.

We want to define the line that goes from the origin_point in the direction of project_angle.  By working out the end-points of the line, it allows us to calculate the pixels.  So where does the line end? Infinity?  Probably the edge of screen will do.

We need to work out the intersection of the line formed with the edge of the screen, so we can use any sort of length for the line, so long as it's theoretically greater than the screen's maximum possible line-length (which is the diagonal: diagonal_length = √(window_width² + window_length²) ).  So any "long enough" length will do, so we'll cheat and use a constant of 10000.

MAX_LENGTH = 10000

Now for that co-ordinate... using the sine and cosine of the angle, multiply by the length to work out that point:

final_x = start_x + ( length * math.cos( angle_of_projection ) )
final_y = start_y + ( length * math.sin( angle_of_projection ) )

Turning this into a function:

def getEndOfLine( start_point, angle_of_projection, length ):
    """ Given a co-ordinate, projection angle, and line length, return
        the co-ordinate of the end of line """
    start_x, start_y = start_point
    final_x = start_x + length * math.cos( angle_of_projection )
    final_y = start_y + length * math.sin( angle_of_projection )
    return ( final_x, final_y )

Using this function, we can now do something like:

end_point = getEndOfLine( origin_point, project_angle, MAX_LENGTH )

Giving us two points to define the line.  So, now we have a line, we can intersect that with the screen edges.  Because our line is so long, it's guaranteed to exit the screen somewhere.

Where are the edges of the screen - these are easy to know:

top_side    = [ ( 0, 0 ), ( SCREEN_WIDTH-1, 0 ) ]
bottom_side = [ ( 0, SCREEN_HEIGHT-1 ), ( SCREEN_WIDTH-1, SCREEN_HEIGHT-1 ) ]
left_side   = [ ( 0, 0 ), ( SCREEN_WIDTH-1, SCREEN_HEIGHT-1 ) ]
right_side  = [ ( SCREEN_WIDTH-1, 0 ), ( SCREEN_WIDTH-1, SCREEN_HEIGHT-1 ) ]
all_sides = [ top_side, right_side, bottom_side, left_side ]

Now we need to intersect the angled-line with the screen-edge lines.  I don't want to go into the maths too much here, but if two, straight, infinitely-long lines are not parallel they must intersect. So first determine that your lines are not parallel, then calculate the intersection point using the determinant method.  The lines might intersect off-screen, we don't care about these points.

def intersectionPoint( x1,y1, x2,y2, x3,y3, x4,y4 ):
    #Use determinant method, as per
    #Ref: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
    Px = ((((x1*y2)-(y1*x2))*(x3 - x4)) - ((x1-x2)*((x3*y4)-(y3*x4)))) / (((x1-x2)*(y3-y4)) - ((y1-y2)*(x3-x4)))
    Py = ((((x1*y2)-(y1*x2))*(y3 - y4)) - ((y1-y2)*((x3*y4)-(y3*x4)))) / (((x1-x2)*(y3-y4)) - ((y1-y2)*(x3-x4)))
    return Px,Py

def getIntersectionPoint( line_start, line_end, screen_edges ):
    x1, y1 = line_start
    x2, y2 = line_end

    for edge in screen_edges:
        x3, y3 = edge[0]  # line forming the screen edge
        x4, y4 = edge[1]
        is_parallel = (((x1-x2)*(y3-y4)) - ((y1-y2)*(x3-x4)) == 0)

        if ( not is_parallel ):
           int_x, int_y = intersectionPoint( x1,y1, x2,y2, x3,y3, x4,y4 )
           # but is the intersection point on-screen (otherwise we don't care)
           if ( int_x >= 0 and int_y >= 0 and int_x < SCREEN_WIDTH and int_y < SCREEN_HEIGHT ):
               return ( int_x, int_y )

    return None  # should never happen

So now using this function, we can determine the point at the edge of the screen:

# Work out the long long line:
peliminary_point = getEndOfLine( origin_point, project_angle, MAX_LENGTH )
print( "Peliminary End Point from %3.1f° is (%3.1f,%3.1f)" % ( project_angle, peliminary_point[0], peliminary_point[1] ) )

# Work out where this line exits the screen/window:
end_point = getIntersectionPoint( origin_point, peliminary_point, all_sides )
print( "End Point is (%3.1f,%3.1f)" % ( end_point[0], end_point[1] ) )

For a 200x200 window, and MAX_LENGTH of 10000 I get:

Peliminary End Point from 0.31° is (38052.3,12370.7)

  End Point is (199.0,71.4)

Now we have the co-ordinate of the end of the line, it's easy to use Bresenhnam's Midpoint Line Algorithm to calculate the pixels.  Best go read about this, I'm not going to explain it here (not even sure I could).

def _plotLineLow( x0,y0, x1,y1 ):
    points = []
    dx = x1 - x0
    dy = y1 - y0
    yi = 1
    if dy < 0:
        yi = -1
        dy = -dy
    D = 2*dy - dx
    y = y0

    for x in range( x0, x1 ):
        points.append( (x,y) )
        if D > 0:
           y = y + yi
           D = D - 2*dx
        D = D + 2*dy
    return points

def _plotLineHigh( x0,y0, x1,y1 ):
    points = []
    dx = x1 - x0
    dy = y1 - y0
    xi = 1
    if dx < 0:
        xi = -1
        dx = -dx
    D = 2*dx - dy
    x = x0

    for y in range( y0, y1 ):
        points.append( (x,y) )
        if D > 0:
            x = x + xi
            D = D - 2*dy
        D = D + 2*dx
    return points

def getMidLinePoints( pointA, pointB ):
    x0, y0 = int( pointA[0] ), int( pointA[1] )
    x1, y1 = int( pointB[0] ), int( pointB[1] )
    points = []
    if ( abs(y1 - y0) < abs(x1 - x0) ):
        if ( x0 > x1 ):
            points += _plotLineLow( x1, y1, x0, y0 )
        else:
            points += _plotLineLow( x0, y0, x1, y1 )
    else:
        if ( y0 > y1 ):
            points += _plotLineHigh( x1, y1, x0, y0 )
        else:
            points += _plotLineHigh( x0, y0, x1, y1 )
    return points

Adding in this code, gives the co-ordinates of the pixels along the line from origin_point at project_angle to the edge of the screen:

# Work out the long long line:
peliminary_point = getEndOfLine( origin_point, project_angle, MAX_LENGTH )
print( "Peliminary End Point from %3.1f° is (%3.1f,%3.1f)" % ( project_angle, peliminary_point[0], peliminary_point[1] ) )

# Work out where this line exits the screen/window:
end_point = getIntersectionPoint( origin_point, peliminary_point, all_sides )
print( "End Point is (%3.1f,%3.1f)" % ( end_point[0], end_point[1] ) )

line_points = getMidLinePoints( origin_point, end_point )
print( "Line Points are: " + str( line_points ) )

Which gives me (this time on a 100x100 window):

Peliminary End Point from 0.31° is (9520.6,3100.2)

  End Point is (99.0,38.9)

  Line Points are: [(10, 10), (11, 10), (12, 11), (13, 11), (14, 11), (15, 12), (16, 12), (17, 12), (18, 13), (19, 13), (20, 13), (21, 13), (22, 14), (23, 14), (24, 14), (25, 15), (26, 15), (27, 15), (28, 16), (29, 16), (30, 16), (31, 17), (32, 17), (33, 17), (34, 18), (35, 18), (36, 18), (37, 18), (38, 19), (39, 19), (40, 19), (41, 20), (42, 20), (43, 20), (44, 21), (45, 21), (46, 21), (47, 22), (48, 22), (49, 22), (50, 23), (51, 23), (52, 23), (53, 24), (54, 24), (55, 24), (56, 24), (57, 25), (58, 25), (59, 25), (60, 26), (61, 26), (62, 26), (63, 27), (64, 27), (65, 27), (66, 28), (67, 28), (68, 28), (69, 29), (70, 29), (71, 29), (72, 30), (73, 30), (74, 30), (75, 30), (76, 31), (77, 31), (78, 31), (79, 32), (80, 32), (81, 32), (82, 33), (83, 33), (84, 33), (85, 34), (86, 34), (87, 34), (88, 35), (89, 35), (90, 35), (91, 35), (92, 36), (93, 36), (94, 36), (95, 37), (96, 37), (97, 37), (98, 38)]

Pretty simple heh!  ;)


问:
Call a method before startActivity automatically
I want a method(); to be called automatically before each call to startActivity(intent); for the whole project because I cannot modify the other dependencies.

EDIT:

I found something called AOP using AspectJ

https://medium.com/@jdvp/aspect-oriented-programming-in-android-159054d52757

But I can intercept only my own app methods, Not the firmware startActivity()

答:
Call this method() in onCreate() assuming you're not using any flag to startActivity

Explanation:

Whenever an activity starts, the activity lifecycle by order is

onCreate() -> onStart() -> onResume()

EDIT:

Use a helper class AppUtils.java

```<code>public class AppUtils {

    public static void startActivity(Activity activity, Intent intent) {
        method(); // your method, you can put it inside AppUtils
        activity.startActivity(intent);
    }
}
</code>```

then simply call AppUtils.startActivity(intent) from anywhere in your project. If your method needs a context, pass the activity context to it.

Body:
Call this method() in onCreate() assuming you're not using any flag to startActivity

Explanation:

Whenever an activity starts, the activity lifecycle by order is

onCreate() -> onStart() -> onResume()

EDIT:

Use a helper class AppUtils.java

public class AppUtils {

    public static void startActivity(Activity activity, Intent intent) {
        method(); // your method, you can put it inside AppUtils
        activity.startActivity(intent);
    }
}

then simply call AppUtils.startActivity(intent) from anywhere in your project. If your method needs a context, pass the activity context to it.


问:
Do require restart dmgr manager after changed value properties of object on websphere?
Cause I'm operating Live system based on Websphere Network deployment version.

Sometimes I have adjust value such as Mail session username/ password , JVM min max heapsize.

Most common tasks, I usually restart both dmgr manager, node agent, cluster to apply changed value.

Could anybody confirm that, If I have changed value, just only require dmgr manager is enough, no need to restart node agent -> It is important because restart dmgr manager not impact to application's running state.

答: Restarting everything is safest, otherwise it depends on knowing about what you've changed.  For example, if you change a jvm property on the app servers, then you only need to restart the app servers.  You only need to restart the dmgr if you changed something that affects it.  It's not always easy to know, so if in doubt, restart everything.</p>


问:
Plot 2 pandas dataframes with same columns
I have 2 pandas dataframes that are the same length with the same column names.  I'd like to loop through and plot the columns against one another - column1 in df1 against col1 in df2. I'd like bar graphs

df1:

```<code>   A  B  C
1  0  4  8
2  5  6  9
3  2  5  1
</code>```

df2:

```<code>   A  B  C
1  9  4  5
2  1  4  2
3  5  5  1
</code>```

答:
It is called a grouped bar chart/clustered bar chart/multi-series bar chart

If I got the gist of what you are saying here is the easiest way to what you want.

Creating the data frames you mentioned:

```<code>df1 = pd.DataFrame(np.array([[0, 4, 8], [5, 6, 9], [2, 5, 1]]), columns=['a', 'b', 'c'])
df2 = pd.DataFrame(np.array([[9, 4, 5], [1, 4, 2], [5, 5, 1]]), columns=['a', 'b', 'c'])
</code>```

Stacking them on top of each other (if the index isn't important use ignore_index=True option in append method):

```<code>combined = df1.append(df2)
</code>```

Since you want to plot the columns you need them as rows first because, by default, DataFrame.plot plots with the rows as the X-axis.

To get them as rows we transpose as follows and that's it.

```<code>combined.transpose().plot(kind='bar')
</code>```

or

```<code>combined.T.plot(kind='bar')
</code>```

Here is the plot:
Cluster bar chart

Body:
I have 2 pandas dataframes that are the same length with the same column names.  I'd like to loop through and plot the columns against one another - column1 in df1 against col1 in df2. I'd like bar graphs

df1:

   A  B  C
1  0  4  8
2  5  6  9
3  2  5  1

df2:

   A  B  C
1  9  4  5
2  1  4  2
3  5  5  1

Body:
It is called a grouped bar chart/clustered bar chart/multi-series bar chart

If I got the gist of what you are saying here is the easiest way to what you want.

Creating the data frames you mentioned:

df1 = pd.DataFrame(np.array([[0, 4, 8], [5, 6, 9], [2, 5, 1]]), columns=['a', 'b', 'c'])
df2 = pd.DataFrame(np.array([[9, 4, 5], [1, 4, 2], [5, 5, 1]]), columns=['a', 'b', 'c'])

Stacking them on top of each other (if the index isn't important use ignore_index=True option in append method):

combined = df1.append(df2)

Since you want to plot the columns you need them as rows first because, by default, DataFrame.plot plots with the rows as the X-axis.

To get them as rows we transpose as follows and that's it.

combined.transpose().plot(kind='bar')

or

combined.T.plot(kind='bar')

Here is the plot:
Cluster bar chart


问:
uiactivityindicator when page is loading
How can I show an uiactivityindicator when I click a cell in my tableview as sometimes it takes a few moments for it to get pushed to the next view since it's getting information from the internet.

I have successfully done it for my uiwebview but just stuck on this.

Thanks.

答:
```<code>-(void)viewDidAppear:(BOOL)animated {
[super viewdDidAppear:YES];
[indicator startAnimating];
NSTimer* timerLoad = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(stopIndicator) userInfo:nil repeats:NO];
}

-(void)stopIndicator {
[indicator stopAnimating];
}
</code>```

I think this give you a time for load your tableView

Put it in navigation controller

```<code>indicator.frame = CGRect(11,130,37,37);
[navBar addSubview:indicator];
</code>```

Body:
-(void)viewDidAppear:(BOOL)animated {
[super viewdDidAppear:YES];
[indicator startAnimating];
NSTimer* timerLoad = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(stopIndicator) userInfo:nil repeats:NO];
}

-(void)stopIndicator {
[indicator stopAnimating];
}

I think this give you a time for load your tableView

Put it in navigation controller

indicator.frame = CGRect(11,130,37,37);
[navBar addSubview:indicator];


问:
Normalizing data for prediction
I'm sorry I'm new to machine learning concept but i'm trying to make a song genre classifier so
I have trained my model after normalizing the data using the min_max as so after getting all the features from a csv file

```<code>X = data.drop(data.columns[len(data.columns)-1], axis=1, inplace=True)
X = data.values #returns a numpy array
myscaler = preprocessing.MinMaxScaler()
x_scaled = myscaler.fit_transform(X)
X = pd.DataFrame(x_scaled)
</code>```

and trained the model but now in the prediction phase and i wanna predict the genre of a new song so i got the song and went through the process i used for the feature extraction in the training I'm not sure if i should normalize this new data or not when i didnt normalize it i kept getting same prediction and i tried to normalize it first i was getting wrong shape for the model and then i tried to reshape it but i think i'm still not getting the same result as the normalization from the training seeing that even predicting a song that is in the training dataset gives wrong prediction and i'm sure that my model is correct with 0.8 accuracy

```<code>scaler = StandardScaler()
song = np.array(make_dataset_ml("C:\\Users\\USER\\Desktop\\sem8\\AI\\project\\try\\disco.mp3")).reshape(-1,1)
myscaler = preprocessing.MinMaxScaler()
scaled_song = myscaler.fit_transform(song)
song = pd.DataFrame(scaled_song.reshape(1,-1))
prediction = model.predict(song)
</code>```

this is the only way i could get the correct shape after normalizing and the make_dataset_ml function is the function that returns the features like the trained ones

答: You are defining a NEW MinMaxScaler for each song, so this will produce garbage. You should use the previous scaler you defined at training phase.

Title: Normalizing data for prediction

Body:
I'm sorry I'm new to machine learning concept but i'm trying to make a song genre classifier so
I have trained my model after normalizing the data using the min_max as so after getting all the features from a csv file

X = data.drop(data.columns[len(data.columns)-1], axis=1, inplace=True)
X = data.values #returns a numpy array
myscaler = preprocessing.MinMaxScaler()
x_scaled = myscaler.fit_transform(X)
X = pd.DataFrame(x_scaled)

and trained the model but now in the prediction phase and i wanna predict the genre of a new song so i got the song and went through the process i used for the feature extraction in the training I'm not sure if i should normalize this new data or not when i didnt normalize it i kept getting same prediction and i tried to normalize it first i was getting wrong shape for the model and then i tried to reshape it but i think i'm still not getting the same result as the normalization from the training seeing that even predicting a song that is in the training dataset gives wrong prediction and i'm sure that my model is correct with 0.8 accuracy

scaler = StandardScaler()
song = np.array(make_dataset_ml("C:\\Users\\USER\\Desktop\\sem8\\AI\\project\\try\\disco.mp3")).reshape(-1,1)
myscaler = preprocessing.MinMaxScaler()
scaled_song = myscaler.fit_transform(song)
song = pd.DataFrame(scaled_song.reshape(1,-1))
prediction = model.predict(song)

this is the only way i could get the correct shape after normalizing and the make_dataset_ml function is the function that returns the features like the trained ones


问:
SQL Server - boolean literal?
How to write literal boolean value in SQL Server? See sample use:

```<code>select * from SomeTable where PSEUDO_TRUE
</code>```

another sample:

```<code>if PSEUDO_TRUE
begin
  select 'Hello, SQL!'
end
</code>```

Note: The query above has nothing to do with how I'm going to use it. It is just to test the literal boolean.

答:
You can use 'True' or 'False' strings for simulate bolean type data.

```<code>Select *
From <table>
Where <columna> = 'True'
</code>```

I think this way maybe slow than just put 1 because it's resolved with Convert_implicit function.

Title: SQL Server - boolean literal?

Body:
How to write literal boolean value in SQL Server? See sample use:

select * from SomeTable where PSEUDO_TRUE

another sample:

if PSEUDO_TRUE
begin
  select 'Hello, SQL!'
end

Note: The query above has nothing to do with how I'm going to use it. It is just to test the literal boolean.

Body:
You can use 'True' or 'False' strings for simulate bolean type data.

Select *
From <table>
Where <columna> = 'True'

I think this way maybe slow than just put 1 because it's resolved with Convert_implicit function.


问:
MailItem.GetInspector.WordEditor in Office 2016 generates Application-defined or object defined error
I wrote an Excel macro to send email from a spreadsheet. It works on Office 2013, but not Office 2016.

I looked at the VBA differences between Office 2013 and 2016, but couldn't see anything about changes to the inspector or word editor for message objects.

Once it gets to .GetInspector.WordEditor it throws:

Run-time error '287':

  Application-defined or object defined error

Here is the relevant part of the macro:

```<code>Sub SendEmail()
    Dim actSheet As Worksheet
    Set actSheet = ActiveSheet

    'directories of attachment and email template
    Dim dirEmail as String, dirAttach As String

    ' Directory of email template as word document
    dirEmail = _
        "Path_To_Word_Doc_Email_Body"

    ' Directories of attachments
    dirAttach = _
        "Path_To_Attachment"

    ' Email Subject line
    Dim subjEmail As String
    subjEmail = "Email Subject"

    Dim wordApp As Word.Application
    Dim docEmail As Word.Document

    ' Opens email template and copies it
    Set wordApp = New Word.Application
    Set docEmail = wordApp.Documents.Open(dirEmail, ReadOnly:=True)
    docEmail.Content.Copy

    Dim OutApp As Outlook.Application
    Set OutApp = New Outlook.Application
    Dim OutMail As MailItem
    Dim outEdit As Word.Document

    ' The names/emails to send to
    Dim docName As String, sendEmail As String, ccEmail As String, siteName As String
    Dim corName As String

    Dim row As Integer
    For row = 2 To 20

        sendName = actSheet.Cells(row, 1)
        sendEmail = actSheet.Cells(row, 2)
        ccEmail = actSheet.Cells(row, 3)
        siteName = actSheet.Cells(row, 4)

        Set OutMail = OutApp.CreateItem(olMailItem)
        With OutMail
            .SendUsingAccount = OutApp.Session.Accounts.Item(1)
            .To = sendEmail
            .CC = ccEmail
            .Subject = subjEmail & " (Site: " & siteName & ")"

            Set outEdit = .GetInspector.WordEditor
            outEdit.Content.Paste

            outEdit.Range(0).InsertBefore ("Dear " & sendName & "," & vbNewLine)

            .Attachments.Add dirAttach

            .Display
            '.Send

        End With
        Debug.Print row

        Set OutMail = Nothing
        Set outEdit = Nothing
    Next row

    docEmail.Close False
    wordApp.Quit
End Sub
</code>```

Things I've tried based on suggestions:

Checked Outlook settings - default is HTML text

Moved .display over .GetInspector.WordEditor

答:
Problem:
For security purposes, the HTMLBody, HTMLEditor, Body and WordEditor properties all are subject to address-information security prompts because the body of a message often contains the sender's or other people's e-mail addresses. And, if Group Policy does not permit then these prompts do not come on-screen. In simple words, as a developer, you are bound to change your code, because neither registry changes can be made nor group policy can be modified.

Hence, if your code suddenly stopped working after migrating to Office 365 or for any other reasons, please refer to the solutions below. Comments have been added for easy understanding and implementation.

Solution 1:
If you have administrative rights then try the registry changes given at below link:
https://support.microsoft.com/en-au/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

However, as developer, I recommend a code that's rather compatible with all versions of Excel instead of making system changes because system changes will be required on each end user's machine as well.

Solution 2: VBA Code
Code Compatible: Excel 2003, Excel 2007, Excel 2010, Excel 2013, Excel 2016, Office 365

```<code>Option Explicit

Sub Create_Email(ByVal strTo As String, ByVal strSubject As String)

    Dim rngToPicture As Range
    Dim outlookApp As Object
    Dim Outmail As Object
    Dim strTempFilePath As String
    Dim strTempFileName As String

    'Name it anything, doesn't matter
    strTempFileName = "RangeAsPNG"

    'rngToPicture is defined as NAMED RANGE in the workbook, do modify this name before use
    Set rngToPicture = Range("rngToPicture")
    Set outlookApp = CreateObject("Outlook.Application")
    Set Outmail = outlookApp.CreateItem(olMailItem)

    'Create an email
    With Outmail
        .To = strTo
        .Subject = strSubject

        'Create the range as a PNG file and store it in temp folder
        Call createPNG(rngToPicture, strTempFileName)

        'Embed the image in Outlook
        strTempFilePath = Environ$("temp") & "\" & strTempFileName & ".png"
        .Attachments.Add strTempFilePath, olByValue, 0

        'Change the HTML below to add Header (Dear John) or signature (Kind Regards) using newline tag (<br />)
        .HTMLBody = "<img src='cid:DashboardFile.png' style='border:0'>"

        .Display

    End With

    Set Outmail = Nothing
    Set outlookApp = Nothing
    Set rngToPicture = Nothing

End Sub

Sub createPNG(ByRef rngToPicture As Range, nameFile As String)

    Dim wksName As String

    wksName = rngToPicture.Parent.Name

    'Delete the existing PNG file of same name, if exists
    On Error Resume Next
        Kill Environ$("temp") & "\" & nameFile & ".png"
    On Error GoTo 0

    'Copy the range as picture
    rngToPicture.CopyPicture

    'Paste the picture in Chart area of same dimensions
    With ThisWorkbook.Worksheets(wksName).ChartObjects.Add(rngToPicture.Left, rngToPicture.Top, rngToPicture.Width, rngToPicture.Height)
        .Activate
        .Chart.Paste
        'Export the chart as PNG File to Temp folder
        .Chart.Export Environ$("temp") & "\" & nameFile & ".png", "PNG"
    End With
    Worksheets(wksName).ChartObjects(Worksheets(wksName).ChartObjects.Count).Delete

End Sub
</code>```

Body:
I wrote an Excel macro to send email from a spreadsheet. It works on Office 2013, but not Office 2016.

I looked at the VBA differences between Office 2013 and 2016, but couldn't see anything about changes to the inspector or word editor for message objects.

Once it gets to .GetInspector.WordEditor it throws:

Run-time error '287':

  Application-defined or object defined error

Here is the relevant part of the macro:

Sub SendEmail()
    Dim actSheet As Worksheet
    Set actSheet = ActiveSheet

    'directories of attachment and email template
    Dim dirEmail as String, dirAttach As String

    ' Directory of email template as word document
    dirEmail = _
        "Path_To_Word_Doc_Email_Body"

    ' Directories of attachments
    dirAttach = _
        "Path_To_Attachment"

    ' Email Subject line
    Dim subjEmail As String
    subjEmail = "Email Subject"

    Dim wordApp As Word.Application
    Dim docEmail As Word.Document

    ' Opens email template and copies it
    Set wordApp = New Word.Application
    Set docEmail = wordApp.Documents.Open(dirEmail, ReadOnly:=True)
    docEmail.Content.Copy

    Dim OutApp As Outlook.Application
    Set OutApp = New Outlook.Application
    Dim OutMail As MailItem
    Dim outEdit As Word.Document

    ' The names/emails to send to
    Dim docName As String, sendEmail As String, ccEmail As String, siteName As String
    Dim corName As String

    Dim row As Integer
    For row = 2 To 20

        sendName = actSheet.Cells(row, 1)
        sendEmail = actSheet.Cells(row, 2)
        ccEmail = actSheet.Cells(row, 3)
        siteName = actSheet.Cells(row, 4)

        Set OutMail = OutApp.CreateItem(olMailItem)
        With OutMail
            .SendUsingAccount = OutApp.Session.Accounts.Item(1)
            .To = sendEmail
            .CC = ccEmail
            .Subject = subjEmail & " (Site: " & siteName & ")"

            Set outEdit = .GetInspector.WordEditor
            outEdit.Content.Paste

            outEdit.Range(0).InsertBefore ("Dear " & sendName & "," & vbNewLine)

            .Attachments.Add dirAttach

            .Display
            '.Send

        End With
        Debug.Print row

        Set OutMail = Nothing
        Set outEdit = Nothing
    Next row

    docEmail.Close False
    wordApp.Quit
End Sub

Things I've tried based on suggestions:

Checked Outlook settings - default is HTML text

Moved .display over .GetInspector.WordEditor

Body:
Problem:
For security purposes, the HTMLBody, HTMLEditor, Body and WordEditor properties all are subject to address-information security prompts because the body of a message often contains the sender's or other people's e-mail addresses. And, if Group Policy does not permit then these prompts do not come on-screen. In simple words, as a developer, you are bound to change your code, because neither registry changes can be made nor group policy can be modified.

Hence, if your code suddenly stopped working after migrating to Office 365 or for any other reasons, please refer to the solutions below. Comments have been added for easy understanding and implementation.

Solution 1:
If you have administrative rights then try the registry changes given at below link:
https://support.microsoft.com/en-au/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

However, as developer, I recommend a code that's rather compatible with all versions of Excel instead of making system changes because system changes will be required on each end user's machine as well.

Solution 2: VBA Code
Code Compatible: Excel 2003, Excel 2007, Excel 2010, Excel 2013, Excel 2016, Office 365

Option Explicit

Sub Create_Email(ByVal strTo As String, ByVal strSubject As String)

    Dim rngToPicture As Range
    Dim outlookApp As Object
    Dim Outmail As Object
    Dim strTempFilePath As String
    Dim strTempFileName As String

    'Name it anything, doesn't matter
    strTempFileName = "RangeAsPNG"

    'rngToPicture is defined as NAMED RANGE in the workbook, do modify this name before use
    Set rngToPicture = Range("rngToPicture")
    Set outlookApp = CreateObject("Outlook.Application")
    Set Outmail = outlookApp.CreateItem(olMailItem)

    'Create an email
    With Outmail
        .To = strTo
        .Subject = strSubject

        'Create the range as a PNG file and store it in temp folder
        Call createPNG(rngToPicture, strTempFileName)

        'Embed the image in Outlook
        strTempFilePath = Environ$("temp") & "\" & strTempFileName & ".png"
        .Attachments.Add strTempFilePath, olByValue, 0

        'Change the HTML below to add Header (Dear John) or signature (Kind Regards) using newline tag (<br />)
        .HTMLBody = "<img src='cid:DashboardFile.png' style='border:0'>"

        .Display

    End With

    Set Outmail = Nothing
    Set outlookApp = Nothing
    Set rngToPicture = Nothing

End Sub

Sub createPNG(ByRef rngToPicture As Range, nameFile As String)

    Dim wksName As String

    wksName = rngToPicture.Parent.Name

    'Delete the existing PNG file of same name, if exists
    On Error Resume Next
        Kill Environ$("temp") & "\" & nameFile & ".png"
    On Error GoTo 0

    'Copy the range as picture
    rngToPicture.CopyPicture

    'Paste the picture in Chart area of same dimensions
    With ThisWorkbook.Worksheets(wksName).ChartObjects.Add(rngToPicture.Left, rngToPicture.Top, rngToPicture.Width, rngToPicture.Height)
        .Activate
        .Chart.Paste
        'Export the chart as PNG File to Temp folder
        .Chart.Export Environ$("temp") & "\" & nameFile & ".png", "PNG"
    End With
    Worksheets(wksName).ChartObjects(Worksheets(wksName).ChartObjects.Count).Delete

End Sub


问:
Compare two images if they have almost identical RGB color distribution
I have two colored images img1 and img2 as defined below

```<code> img1 = cv2.imread("source1")
 img2 = cv2.imread("source2")
</code>```

Now I want to know if the distribution of the RGB value of two images is almost identical.  As a human, I can see from the RGB histogram distribution of the two images that they are almost identical or not. But is there a way that I can do this via OpenCV, that it can tell that two images are almost identical with it comes to its RGB distribution?

```<code>color = ('b','g','r')
for i,col in enumerate(color):
   histr = cv.calcHist([img1],[i],None,[256],[0,256])
   plt.subplot(1,2,1)
   plt.plot(histr,color = col)
   plt.xlim([0,256])
   plt.title("Img 1")

   histr = cv.calcHist([img2],[i],None,[256],[0,256])
   plt.subplot(1,2,2)
   plt.plot(histr,color = col)
   plt.xlim([0,256])
   plt.title("Img 2")
plt.show()
</code>```

答:
If you take each point on the x-axis of the two histograms A and B, then the amount of overlap between the two at that point is the height of the smaller:

```<code>min(A,B)
</code>```

So, you just need to sum over the points:

```<code>np.sum(np.minimum(A,B))
</code>```

As an empirical explanation, if both histograms are tall in the same places, the histogram overlap will be high, as will min(A,B). If one is high and one is low, the histogram overlap and min(A,B) will be low.

I found a nice illustration here which usefully also suggests normalisation by dividing by the total number of pixels.

Body:
I have two colored images img1 and img2 as defined below

 img1 = cv2.imread("source1")
 img2 = cv2.imread("source2")

Now I want to know if the distribution of the RGB value of two images is almost identical.  As a human, I can see from the RGB histogram distribution of the two images that they are almost identical or not. But is there a way that I can do this via OpenCV, that it can tell that two images are almost identical with it comes to its RGB distribution?

color = ('b','g','r')
for i,col in enumerate(color):
   histr = cv.calcHist([img1],[i],None,[256],[0,256])
   plt.subplot(1,2,1)
   plt.plot(histr,color = col)
   plt.xlim([0,256])
   plt.title("Img 1")

   histr = cv.calcHist([img2],[i],None,[256],[0,256])
   plt.subplot(1,2,2)
   plt.plot(histr,color = col)
   plt.xlim([0,256])
   plt.title("Img 2")
plt.show()

Body:
If you take each point on the x-axis of the two histograms A and B, then the amount of overlap between the two at that point is the height of the smaller:

min(A,B)

So, you just need to sum over the points:

np.sum(np.minimum(A,B))

As an empirical explanation, if both histograms are tall in the same places, the histogram overlap will be high, as will min(A,B). If one is high and one is low, the histogram overlap and min(A,B) will be low.

I found a nice illustration here which usefully also suggests normalisation by dividing by the total number of pixels.


问:
Last record per transaction
I am trying to select the last record per sales order.

My query is simple in SQL Server management.

```<code>SELECT *
FROM DOCSTATUS
</code>```

The problem is that this database has tens of thousands of records, as it tracks all SO steps.

```<code>ID    SO    SL      Status        Reason      Attach    Name   Name       Systemdate
22  951581  3     Processed       Customer      NULL    NULL    BW  2016-12-05 13:33:27.857
23  951581  3     Submitted       Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
24  947318  1        Hold         Customer      NULL    NULL    bw  2016-12-05 13:54:27.173
25  947318  1   Invoices Submit   Customer      NULL    NULL    bw  2016-13-05 13:54:27.300
26  947318  1        Ship         Customer      NULL    NULL    bw  2016-14-05 13:54:27.440
</code>```

I would to see the most recent record per the SO

```<code> ID    SO    SL       Status          Reason      Attach    Name   Name       Systemdate
 23  951581  4       Submitted        Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
 26  947318  1         Ship           Customer      NULL    NULL    bw  2016-14-05 13:54:27.440
</code>```

答:
Well I'm not sure how that table has two Name columns, but one easy way to do this is with ROW_NUMBER():

```<code>;WITH cte AS
(
  SELECT *,
    rn = ROW_NUMBER() OVER (PARTITION BY SO ORDER BY Systemdate DESC)
  FROM dbo.DOCSTATUS
)
SELECT ID, SO, SL, Status, Reason, ..., Systemdate
FROM cte WHERE rn = 1;
</code>```

Also please always reference the schema, even if today everything is under dbo.

Title: Last record per transaction

Body:
I am trying to select the last record per sales order.

My query is simple in SQL Server management.

SELECT *
FROM DOCSTATUS

The problem is that this database has tens of thousands of records, as it tracks all SO steps.

ID    SO    SL      Status        Reason      Attach    Name   Name       Systemdate
22  951581  3     Processed       Customer      NULL    NULL    BW  2016-12-05 13:33:27.857
23  951581  3     Submitted       Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
24  947318  1        Hold         Customer      NULL    NULL    bw  2016-12-05 13:54:27.173
25  947318  1   Invoices Submit   Customer      NULL    NULL    bw  2016-13-05 13:54:27.300
26  947318  1        Ship         Customer      NULL    NULL    bw  2016-14-05 13:54:27.440

I would to see the most recent record per the SO

 ID    SO    SL       Status          Reason      Attach    Name   Name       Systemdate
 23  951581  4       Submitted        Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
 26  947318  1         Ship           Customer      NULL    NULL    bw  2016-14-05 13:54:27.440

Body:
Well I'm not sure how that table has two Name columns, but one easy way to do this is with ROW_NUMBER():

;WITH cte AS
(
  SELECT *,
    rn = ROW_NUMBER() OVER (PARTITION BY SO ORDER BY Systemdate DESC)
  FROM dbo.DOCSTATUS
)
SELECT ID, SO, SL, Status, Reason, ..., Systemdate
FROM cte WHERE rn = 1;

Also please always reference the schema, even if today everything is under dbo.


答:
You can do it in onCreate() method which executes before onStart(). OR

Use static method and run it before startActiviy().

Title: Call a method before startActivity automatically

Body:
I want a method(); to be called automatically before each call to startActivity(intent); for the whole project because I cannot modify the other dependencies.

EDIT:

I found something called AOP using AspectJ

https://medium.com/@jdvp/aspect-oriented-programming-in-android-159054d52757

But I can intercept only my own app methods, Not the firmware startActivity()


问:
How to play an .m4a file in the browser? (React/HTML5)
I'm building a website that queries the iTunes API, and in the browser I need to be able to play the 30-second song previews associated with each song in the API (which are in .m4a format)

I've tried playing the file in both of the following ways, but neither worked:

<audio controls="controls">
    <source src={track1} type="audio/m4a" />
</audio>

<video width="320" height="240">
    <source src={track1} type="video/mp4">
    </source>
</video>
```

When I tried using the audio tag, a media player appeared on the page, but it didn't actually load the file.

I've been researching this for a couple of hours but I haven't been able to find a way of accomplishing this (it doesn't seem like it should be this hard). Does anyone have any ideas of how I might make get this working? Thanks very much

答:
Did you check the path of your sound files is correct? I was having this same issue on a React project.

Check the network tab in Dev tools to see what the status code is for your sound file resource. If it's 206 then it's most likely a file path issue:

Body:
I'm building a website that queries the iTunes API, and in the browser I need to be able to play the 30-second song previews associated with each song in the API (which are in .m4a format)

I've tried playing the file in both of the following ways, but neither worked:

<audio controls="controls">
    <source src={track1} type="audio/m4a" />
</audio>

<video width="320" height="240">
    <source src={track1} type="video/mp4">
    </source>
</video>

When I tried using the audio tag, a media player appeared on the page, but it didn't actually load the file.

I've been researching this for a couple of hours but I haven't been able to find a way of accomplishing this (it doesn't seem like it should be this hard). Does anyone have any ideas of how I might make get this working? Thanks very much


Title: Append list nested dictionary based on dictionary value

Body:
Edited here... I am getting real time data like below from following  current_tick = json.loads(response)

{'symbol': 'TSLA', 'minute': '2020/06/02 17:31', 'open': '882.4', 'high': '882.4', 'low': '882.93', 'close': '885.93'},
{'symbol': 'SPY', 'minute': '2020/06/02 17:33', 'open': '307.96', 'high': '307.99', 'low': '307.96', 'close': '307.99'},
{'symbol': 'TSLA', 'minute': '2020/06/02 17:32', 'open': '882.0', 'high': '882.0', 'low': '307.94', 'close': '307.94'},
{'symbol': 'SPY', 'minute': '2020/06/02 17:34', 'open': '307.94', 'high': '307.97', 'low': '307.94', 'close': '307.96'},
{'symbol': 'SPY', 'minute': '2020/06/02 17:35', 'open': '307.96', 'high': '307.98', 'low': '307.96', 'close': '307.98'},
{'symbol': 'SPY', 'minute': '2020/06/02 17:36', 'open': '308.02', 'high': '308.04', 'low': '308.02', 'close': '308.04'}

I have inserted like below in variable current_tick:

Edited here...

{'symbol': 'TSLA', 'minute': '2020/06/02 17:31', 'open': '882.4', 'high': '882.4', 'low': '882.93', 'close': '885.93'}
{'symbol': 'SPY', 'minute': '2020/06/02 17:33', 'open': '307.96', 'high': '307.99', 'low': '307.96', 'close': '307.99'}
{'symbol': 'TSLA', 'minute': '2020/06/02 17:32', 'open': '882.0', 'high': '882.0', 'low': '307.94', 'close': '307.94'}
{'symbol': 'SPY', 'minute': '2020/06/02 17:34', 'open': '307.94', 'high': '307.97', 'low': '307.94', 'close': '307.96'}
{'symbol': 'SPY', 'minute': '2020/06/02 17:35', 'open': '307.96', 'high': '307.98', 'low': '307.96', 'close': '307.98'}
{'symbol': 'SPY', 'minute': '2020/06/02 17:36', 'open': '308.02', 'high': '308.04', 'low': '308.02', 'close': '308.04'}

I have implemented code which works fine if the stock symbol is one and takes data from variable current_tick, however if it is more than one stock symbol then it overwrites existing one and lead to other issue.

if not tick_dt in minutes_processed:
    minutes_processed[tick_dt] = True
    print(minutes_processed)

    if len(minute_candlesticks) > 0:
        minute_candlesticks[-1]["close"] = previous_tick["last"]

    minute_candlesticks.append(
        {
            "symbol": current_tick["symbol"],
            "minute": tick_dt,
            "open": current_tick["last"],
            "high": current_tick["last"],
            "low": current_tick["last"],
        }
    )

if len(minute_candlesticks) > 0:
    current_candlestick = minute_candlesticks[-1]
    if current_tick["last"] > current_candlestick["high"]:
        current_candlestick["high"] = current_tick["last"]
    if current_tick["last"] < current_candlestick["low"]:
        current_candlestick["low"] = current_tick["last"]

Now I am trying to create list of dictionaries on dictionary and insert stock symbols live data to map their specific symbol like below.

app_stock_list = [
{'TSLA': {'symbol': 'TSLA', 'minute': '2020/06/02 17:31', 'open': '882.4', 'high': '882.4', 'low': '882.93', 'close': '885.93'},
{'symbol': 'TSLA', 'minute': '2020/06/02 17:32', 'open': '882.0', 'high': '882.0', 'low': '307.94', 'close': '307.94'}},

{'SPY': {'symbol': 'SPY', 'minute': '2020/06/02 17:33', 'open': '307.96', 'high': '307.99', 'low': '307.96', 'close': '307.99'},
{'symbol': 'SPY', 'minute': '2020/06/02 17:34', 'open': '307.94', 'high': '307.97', 'low': '307.94', 'close': '307.96'},
{'symbol': 'SPY', 'minute': '2020/06/02 17:35', 'open': '307.96', 'high': '307.98', 'low': '307.96', 'close': '307.98'},
{'symbol': 'SPY', 'minute': '2020/06/02 17:36', 'open': '308.02', 'high': '308.04', 'low': '308.02', 'close': '308.04'}
]

How do I correct the above code to create as above dictionary or what is the correct way to write a code to append live data for each symbol?

Note: I edited little bit to have a correct understanding.

Body:
I think this dict comprehension will work for you:

stock_list = [
    {'symbol': 'TSLA', 'minute': '2020/06/02 17:31', 'open': '882.4', 'high': '882.4', 'low': '882.93', 'close': '885.93'},
    {'symbol': 'SPY', 'minute': '2020/06/02 17:33', 'open': '307.96', 'high': '307.99', 'low': '307.96', 'close': '307.99'},
    {'symbol': 'TSLA', 'minute': '2020/06/02 17:32', 'open': '882.0', 'high': '882.0', 'low': '307.94', 'close': '307.94'},
    {'symbol': 'SPY', 'minute': '2020/06/02 17:34', 'open': '307.94', 'high': '307.97', 'low': '307.94', 'close': '307.96'},
    {'symbol': 'SPY', 'minute': '2020/06/02 17:35', 'open': '307.96', 'high': '307.98', 'low': '307.96', 'close': '307.98'},
    {'symbol': 'SPY', 'minute': '2020/06/02 17:36', 'open': '308.02', 'high': '308.04', 'low': '308.02', 'close': '308.04'}
]

stocks = {symbol: [i for i in stock_list if i['symbol'] == symbol]
          for symbol in {i['symbol'] for i in stock_list}} # use a set() comprehension to get the unique items

# how to update with a price dict
updated_price = {'symbol': 'TSLA', 'minute': '2020/06/02 17:33', 'open': '123.0', 'high': '456.0', 'low': '789.94', 'close': '032.94'}
stocks[updated_price['symbol']].append(updated_price)

import json
print(json.dumps(stocks, indent=4))

Output (jsonified):

{
    "TSLA": [
        {
            "symbol": "TSLA",
            "minute": "2020/06/02 17:31",
            "open": "882.4",
            "high": "882.4",
            "low": "882.93",
            "close": "885.93"
        },
        {
            "symbol": "TSLA",
            "minute": "2020/06/02 17:32",
            "open": "882.0",
            "high": "882.0",
            "low": "307.94",
            "close": "307.94"
        },
        {
            "symbol": "TSLA",
            "minute": "2020/06/02 17:33",
            "open": "123.0",
            "high": "456.0",
            "low": "789.94",
            "close": "032.94"
        }
    ],
    "SPY": [
        {
            "symbol": "SPY",
            "minute": "2020/06/02 17:33",
            "open": "307.96",
            "high": "307.99",
            "low": "307.96",
            "close": "307.99"
        },
        {
            "symbol": "SPY",
            "minute": "2020/06/02 17:34",
            "open": "307.94",
            "high": "307.97",
            "low": "307.94",
            "close": "307.96"
        },
        {
            "symbol": "SPY",
            "minute": "2020/06/02 17:35",
            "open": "307.96",
            "high": "307.98",
            "low": "307.96",
            "close": "307.98"
        },
        {
            "symbol": "SPY",
            "minute": "2020/06/02 17:36",
            "open": "308.02",
            "high": "308.04",
            "low": "308.02",
            "close": "308.04"
        }
    ]
}


问:
Geolocation API Permissions Web Browser
I'm using this code to get the user geoposition. All goes well until the user deny permission to get the location. It seems this option gets cached and I don't know how reset it.

Is there any way to re-ask permission? Thanks in advance!

```<code>if (navigator.geolocation) {

        navigator.geolocation.getCurrentPosition(function(position) {

            // Success Callback

        }, function(error) {
            //error Callback

        },{
                  //options
            });
     }else{
        //geolocation not available
     }
</code>```

答: Pretty sure this is a browser/device setting stored per site.  I think the point is that you can't reset this from a script as it would defeat the point of the prompt in the first place.  I believe the only way to reset is to change the setting in the browser/device.</p>

Title: Geolocation API Permissions Web Browser

Body:
I'm using this code to get the user geoposition. All goes well until the user deny permission to get the location. It seems this option gets cached and I don't know how reset it.

Is there any way to re-ask permission? Thanks in advance!

if (navigator.geolocation) {

        navigator.geolocation.getCurrentPosition(function(position) {

            // Success Callback

        }, function(error) {
            //error Callback

        },{
                  //options
            });
     }else{
        //geolocation not available
     }