问:
Lock-free SPSC queue implementation on ARM
I'm trying to write a single producer single consumer queue for ARM and I think I'm close to wrapping my head around DMB, but need some checking (I'm more familiar with std::atomic.)

Here's where I'm at:

```<code>bool push(const_reference value)
{
    // Check for room
    const size_type currentTail = tail;
    const size_type nextTail = increment(currentTail);
    if (nextTail == head)
        return false;

    // Write the value
    valueArr[currentTail] = value;

    // Prevent the consumer from seeing the incremented tail before the
    // value is written.
    __DMB();

    // Increment tail
    tail = nextTail;

    return true;
}

bool pop(reference valueLocation)
{
    // Check for data
    const size_type currentHead = head;
    if (currentHead == tail)
        return false;

    // Write the value.
    valueLocation = valueArr[currentHead];

    // Prevent the producer from seeing the incremented head before the
    // value is written.
    __DMB();

    // Increment the head
    head = increment(head);

    return true;
}
</code>```

My question is: is my DMB placement and justification accurate? Or is there still understanding that I'm missing? I'm particularly uncertain about whether the conditionals need some guard when dealing with the variable that's updated by the other thread (or interrupt).

答:
A barrier there is necessary but not sufficient, you also need "acquire" semantics for loading the var modified by the other thread.  (Or at least consume, but getting that without a barrier would require asm to create a data dependency.  A compiler wouldn't do that after already having a control dependency.)

A single-core system can use just a compiler barrier like GNU C asm("":::"memory") or std::atomic_signal_fence(std::memory_order_release), not dmb.  Make a macro so you can choose between SMP-safe barriers or UP (uniprocessor) barriers.

head = increment(head); is a pointless reload of head, use the local copy.

use std::atomic to get the necessary code-gen portably.

You normally don't need to roll your own atomics; modern compilers for ARM do implement std::atomic<T>.  But AFAIK, no std::atomic<> implementations are aware of single-core systems to avoid actual barriers and just be safe wrt. interrupts that can cause a context switch.

On a single-core system, you don't need dsb, just a compiler barrier.  The CPU will preserve the illusion of asm instructions executing sequentially, in program order.  You just need to make sure the compiler generates asm that does things in the right order.  You can do that by using std::atomic with std::memory_order_relaxed, and manual atomic_signal_fence(memory_order_acquire) or release barriers.  (Not atomic_thread_fence; that would emit asm instructions, typically dsb).

Each thread reads a variable that the other thread modifies.  You're correctly making the modifications release-stores by making sure they're visible only after access to the array.

But those reads also need to be acquire-loads to sync with those release stores.  E.g. to make sure push isn't writing valueArr[currentTail] = value; before pop finishes reading that same element.  Or reading an entry before it's fully written.

Without any barrier, the failure mode would be that if (currentHead == tail) return false; doesn't actually check the value of tail from memory until after
valueLocation = valueArr[currentHead]; happens.  Runtime load reordering can easily do that on weakly-ordered ARM.  If the load address had a data dependency on tail, that could avoid needing a barrier there on an SMP system (ARM guarantees dependency ordering in asm; the feature that mo_consume was supposed to expose).  But if the compiler just emits a branch, that's only a control dependency, not data.  If you were writing by hand in asm, a predicated load like ldrne r0, [r1, r2] on flags set by the compare would I think create a data dependency.

Compile-time reordering is less plausible, but a compiler-only barrier is free if it's only stopping the compiler from doing something it wasn't going to do anyway.

untested implementation, compiles to asm that looks ok but no other testing

Do something similar for push.  I included wrapper functions for load acquire / store release, and fullbarrier().  (Equivalent of Linux kernel's smp_mb() macro, defined as a compile time or compile+runtime barrier.)

```<code>#include <atomic>

#define UNIPROCESSOR

#ifdef UNIPROCESSOR
#define fullbarrier()  asm("":::"memory")   // GNU C compiler barrier
                          // atomic_signal_fence(std::memory_order_seq_cst)
#else
#define fullbarrier() __DMB()    // or atomic_thread_fence(std::memory_order_seq_cst)
#endif

template <class T>
T load_acquire(std::atomic<T> &x) {
#ifdef UNIPROCESSOR
    T tmp = x.load(std::memory_order_relaxed);
    std::atomic_signal_fence(std::memory_order_acquire);
    // or fullbarrier();  if you want to use that macro
    return tmp;
#else
    return x.load(std::memory_order_acquire);
    // fullbarrier() / __DMB();
#endif
}

template <class T>
void store_release(std::atomic<T> &x, T val) {
#ifdef UNIPROCESSOR
    std::atomic_signal_fence(std::memory_order_release);
    // or fullbarrier();
    x.store(val, std::memory_order_relaxed);
#else
    // fullbarrier() / __DMB(); before plain store
    return x.store(val, std::memory_order_release);
#endif
}

template <class T>
struct SPSC_queue {
  using size_type = unsigned;
  using value_type = T;
  static const size_type size = 1024;

  std::atomic<size_type> head;
  value_type valueArr[size];
  std::atomic<size_type> tail;  // in a separate cache-line from head to reduce contention

  bool push(const value_type &value)
  {
    // Check for room
    const size_type currentTail = tail.load(std::memory_order_relaxed);  // no other writers to tail, no ordering needed
    const size_type nextTail = currentTail + 1;    // modulo separately so empty and full are distinguishable.
    if (nextTail == load_acquire(head))
        return false;

    valueArr[currentTail % size] = value;
    store_release(tail, nextTail);
    return true;
  }
};

// instantiate the template for  int  so we can look at the asm
template bool SPSC_queue<int>::push(const value_type &value);
</code>```

Compiles cleanly on the Godbolt compiler explorer with zero barriers if you use -DUNIPROCESSOR, with g++9.2 -O3 -mcpu=cortex-a15 (just to pick a random modern-ish ARM core so GCC can inline std::atomic load/store function and barriers for the non-uniprocessor case.

Body:
I'm trying to write a single producer single consumer queue for ARM and I think I'm close to wrapping my head around DMB, but need some checking (I'm more familiar with std::atomic.)

Here's where I'm at:

bool push(const_reference value)
{
    // Check for room
    const size_type currentTail = tail;
    const size_type nextTail = increment(currentTail);
    if (nextTail == head)
        return false;

    // Write the value
    valueArr[currentTail] = value;

    // Prevent the consumer from seeing the incremented tail before the
    // value is written.
    __DMB();

    // Increment tail
    tail = nextTail;

    return true;
}

bool pop(reference valueLocation)
{
    // Check for data
    const size_type currentHead = head;
    if (currentHead == tail)
        return false;

    // Write the value.
    valueLocation = valueArr[currentHead];

    // Prevent the producer from seeing the incremented head before the
    // value is written.
    __DMB();

    // Increment the head
    head = increment(head);

    return true;
}

My question is: is my DMB placement and justification accurate? Or is there still understanding that I'm missing? I'm particularly uncertain about whether the conditionals need some guard when dealing with the variable that's updated by the other thread (or interrupt).

Body:
A barrier there is necessary but not sufficient, you also need "acquire" semantics for loading the var modified by the other thread.  (Or at least consume, but getting that without a barrier would require asm to create a data dependency.  A compiler wouldn't do that after already having a control dependency.)

A single-core system can use just a compiler barrier like GNU C asm("":::"memory") or std::atomic_signal_fence(std::memory_order_release), not dmb.  Make a macro so you can choose between SMP-safe barriers or UP (uniprocessor) barriers.

head = increment(head); is a pointless reload of head, use the local copy.

use std::atomic to get the necessary code-gen portably.

You normally don't need to roll your own atomics; modern compilers for ARM do implement std::atomic<T>.  But AFAIK, no std::atomic<> implementations are aware of single-core systems to avoid actual barriers and just be safe wrt. interrupts that can cause a context switch.

On a single-core system, you don't need dsb, just a compiler barrier.  The CPU will preserve the illusion of asm instructions executing sequentially, in program order.  You just need to make sure the compiler generates asm that does things in the right order.  You can do that by using std::atomic with std::memory_order_relaxed, and manual atomic_signal_fence(memory_order_acquire) or release barriers.  (Not atomic_thread_fence; that would emit asm instructions, typically dsb).

Each thread reads a variable that the other thread modifies.  You're correctly making the modifications release-stores by making sure they're visible only after access to the array.

But those reads also need to be acquire-loads to sync with those release stores.  E.g. to make sure push isn't writing valueArr[currentTail] = value; before pop finishes reading that same element.  Or reading an entry before it's fully written.

Without any barrier, the failure mode would be that if (currentHead == tail) return false; doesn't actually check the value of tail from memory until after
valueLocation = valueArr[currentHead]; happens.  Runtime load reordering can easily do that on weakly-ordered ARM.  If the load address had a data dependency on tail, that could avoid needing a barrier there on an SMP system (ARM guarantees dependency ordering in asm; the feature that mo_consume was supposed to expose).  But if the compiler just emits a branch, that's only a control dependency, not data.  If you were writing by hand in asm, a predicated load like ldrne r0, [r1, r2] on flags set by the compare would I think create a data dependency.

Compile-time reordering is less plausible, but a compiler-only barrier is free if it's only stopping the compiler from doing something it wasn't going to do anyway.

untested implementation, compiles to asm that looks ok but no other testing

Do something similar for push.  I included wrapper functions for load acquire / store release, and fullbarrier().  (Equivalent of Linux kernel's smp_mb() macro, defined as a compile time or compile+runtime barrier.)

#include <atomic>

#define UNIPROCESSOR

#ifdef UNIPROCESSOR
#define fullbarrier()  asm("":::"memory")   // GNU C compiler barrier
                          // atomic_signal_fence(std::memory_order_seq_cst)
#else
#define fullbarrier() __DMB()    // or atomic_thread_fence(std::memory_order_seq_cst)
#endif

template <class T>
T load_acquire(std::atomic<T> &x) {
#ifdef UNIPROCESSOR
    T tmp = x.load(std::memory_order_relaxed);
    std::atomic_signal_fence(std::memory_order_acquire);
    // or fullbarrier();  if you want to use that macro
    return tmp;
#else
    return x.load(std::memory_order_acquire);
    // fullbarrier() / __DMB();
#endif
}

template <class T>
void store_release(std::atomic<T> &x, T val) {
#ifdef UNIPROCESSOR
    std::atomic_signal_fence(std::memory_order_release);
    // or fullbarrier();
    x.store(val, std::memory_order_relaxed);
#else
    // fullbarrier() / __DMB(); before plain store
    return x.store(val, std::memory_order_release);
#endif
}

template <class T>
struct SPSC_queue {
  using size_type = unsigned;
  using value_type = T;
  static const size_type size = 1024;

  std::atomic<size_type> head;
  value_type valueArr[size];
  std::atomic<size_type> tail;  // in a separate cache-line from head to reduce contention

  bool push(const value_type &value)
  {
    // Check for room
    const size_type currentTail = tail.load(std::memory_order_relaxed);  // no other writers to tail, no ordering needed
    const size_type nextTail = currentTail + 1;    // modulo separately so empty and full are distinguishable.
    if (nextTail == load_acquire(head))
        return false;

    valueArr[currentTail % size] = value;
    store_release(tail, nextTail);
    return true;
  }
};

// instantiate the template for  int  so we can look at the asm
template bool SPSC_queue<int>::push(const value_type &value);

Compiles cleanly <a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tEADZJpLegAyeWpgByxgEaZi5ywAdUCwuto9QxNPUh8/NTo7B2cjNw8LRWVMVQCGAmZiAiDjU04klUjadMyCaKdXd0EFDKyckPya0vLY%2BK4ASkVUA2JkDgByKQBme2RDLABqcSGdZiIjPAkh7HEABgBBNc3JIawqe0wJgFVHAEkABQAlAHkdbAYGa8utl43hvCo947Or2/vH55vHZ7A4TKgGVisFyZYh4dwQdoTCbMBRGCBSSQYkDYjFGTBGEgATwxiKRAHoyRMAOKOI4THQTNBGLx4djECbQ4iw9xbJF8/kCwWCinI%2BaLAD6fmAtDY4qoWj6EBq6GxeIJxEJ4pIWGIkswAEdxcgau0XjtlEozbtMPsHGCIVCYXDiAiJuLxQARACy0ldfJFJFFqAWyHFBAQxEwzHQcoVmCVBBVIDVRK1xB1esNxoIpqBQ2sH1e6wI%2BK8whLUxmYxRCgmABVpisNnWJqxUNHxcxkPqDHhIwmk3Ng4tpjoG8sppIzAAPRHiADssjzHy%2BJwuNzuDyevL5LYIzMrHom04AdG3owPVfjU9r3OLI8Jp5h0Kahkv1vzldihyHJXhpbK8q0IqX7JteGpphmXY9n2mCvu%2B/IBuy4KQpy3IuvBSIfBMhLdBMADuIgEBMRATAYSgkQgcwTEYXbEKgO5IpGBA9LQJHMtM77DBamCMRMzGsceZ7tugl5geqmq3rq0G9pG8F8SKKGOlyzqupS7rer68l5gWVAvPOHpFiWzLloco7Vgotbjk26wAG6oHg6ATDUJCYPeyQovGoE/iOMzWZOM6kPWEy2Wwc6LlaK42t865/FugIfny3liqGUoyqwsbAV5iZXhJkF3g%2BUZKNpiXkpSgZKWhqklfyp4uf2oWsEFoEphBUnuY%2Bz4ldxrCWhsiGUpVTrwoi6mej6CKcRyNquRMZbMPYzlEJGfECcQbF1ct8aNc1OXiTe6YFR5xWcVaun6YZbwbMZ80VuZwiWfWjZbDUxAGKoEwMOcDA6OKPaYAYZkRf1ZF%2BKIzl4AAXm5BCEl4ZlDEeBi0Glz6nSD5H2MAIVsIDYZwwjR7jghS1zIsjJ0DUEPQ/j8PU4TEycKskjcOjmwg8lw5LDofg07D8ONhMCBRugbNIo1eP84cEuYOsXLiAArNIvO8QrhlvjunMhqOKu07xE4ZKyU0TCKi3MM5mBeJkcyHCwyDCwAtKwoJUPRRhCyLJGoPxz7vbbdAlvQARFkiLioPoc3kQgEBoCjxEy3rAUy7miULiTZX0sLyAANZgoG9HBnxsdU7rUuMj0kb0HWC2sIeJE18JF4teBkmHbqD7ME%2BL7GyKtDe6g4buARsIlsQtakYbTUTH3ExSVj0%2BYM%2BaMg0ixfEaXBML9OBDV6ydfIBXWg7zXk7SIzxsZwS6AQt7ShW8QNusISzne6WsPIto9qQsikYTPgNRY17AoKiLh2Anj4thCADht671rtMdWR5zwxhkrBCAwtoztBTkKH2LF1pgjYJaDWV1So40MLLeWSsD5ciPrAycCt6aKyPPA0hgMxZJS2h1Iq8ZJ5BWgcfVkNU%2BRrTYgQN6%2BsSYLkupsAybMtg3VMhycOtcvo/T%2BoDVhMx7AEEbNiLwUcY6U3jrjGGm8pBmGTpxfonRWAgH6ArfopBTD9FWA41AtidByDkC/HofRJxDE4A4ggtiXGYNINnEACtVhCFsdwBxTiXGkDcf0BxCgQBRKCc4qxpA4CwBgIgFAwYWRsnIJQJkRSqiZCMAATkkPkfYrBR6pIgC4YJDiXD2EyISWxATSBMjxPQa4tAn6tNIFgWioh2AjPwJGVItlMCpMyVYJ8B8SzdIcVo5QIznYuAfhqPQWA1mkFEXgIwazOg0HoEwNgHAeD8EEMIUQKBPEyCEHgFwqTICdFQF4IoCyHbXCGBMB2RhkB6PgWgLImBpwO2YJwexBQUhFE0NoeoeQrDaBaJUDw%2BRwj%2BDoKiwQuKiiYriFURoyRUh0BKHUfQuRqgUqKNSsoBxWhksULUbItKGjsuaCyrFHQug%2BJuaQQiAyfmnFoDQM50S7FxJGUk9YlwvQTGAMgZAEwqknkkCeTgEwoF0Dgnq3AhBAzDHyPSQprIh5msRB4mQchAmtNCeEyJMrYmkFOWYAAHCeL1CsFZVKGJISQqwhhDC9VUr1vB4muNsSktJRynXZLyWgkA3QCB6IICUgxzIrXYqsPgZaggLmMBYJM25%2BEH5eGlTY2Vjj5W2LNQRQgCAJiKuVaq9VmrtW6v1Q4dojrMmhPQTqSg1iYkONOf4nV3BuCrDMPOecVSzBmCZpwFd9bFlJPjekp1nQXVRNrUMOVW642JqHeO/okgT0JO3eekJnQ5ljwCCAbgQA%3D%3D" rel="nofollow noreferrer">on the Godbolt compiler explorer with zero barriers if you use -DUNIPROCESSOR, with g++9.2 -O3 -mcpu=cortex-a15 (just to pick a random modern-ish ARM core so GCC can inline std::atomic load/store function and barriers for the non-uniprocessor case.


来源: stackexchange

问:
How do I create a column such that its values is count of the number of,1, in that row, which are appearing for the first time in their own column?
How do I do this operation using pandas?

Initial Df:

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

Final Df:

```<code>    A B C D Param
0   0 1 0 0     1
1   0 1 0 0     0
2   0 0 1 1     2
3   0 1 0 1     0
4   1 1 0 0     1
5   1 1 1 0     0
</code>```

Basically Param is the number of the 1 in that row which is appearing for the first time in its own column.
Example:
index 0 : 1 in the column B is appearing for the first time hence Param1 = 1

index 1 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 2 : 1 in the column C and D is appearing for the first time  in their columns hence Paramm1 = 2

index 3 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 4 : 1 in the column A is appearing for the first time  in the column hence Paramm1 = 1

index 5 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

答:
You can check for duplicated values, multiply with df and sum:

```<code>df['Param'] = df.apply(lambda x: ~x.duplicated()).mul(df).sum(1)
</code>```

Output:

```<code>   A  B  C  D  Param
0  0  1  0  0      1
1  0  1  0  0      0
2  0  0  1  1      2
3  0  1  0  1      0
4  1  1  0  0      1
5  1  1  1  0      0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I do this operation using pandas?

Initial Df:

    A B C D
0   0 1 0 0
1   0 1 0 0
2   0 0 1 1
3   0 1 0 1
4   1 1 0 0
5   1 1 1 0

Final Df:

    A B C D Param
0   0 1 0 0     1
1   0 1 0 0     0
2   0 0 1 1     2
3   0 1 0 1     0
4   1 1 0 0     1
5   1 1 1 0     0

Basically Param is the number of the 1 in that row which is appearing for the first time in its own column.
Example:
index 0 : 1 in the column B is appearing for the first time hence Param1 = 1

index 1 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 2 : 1 in the column C and D is appearing for the first time  in their columns hence Paramm1 = 2

index 3 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 4 : 1 in the column A is appearing for the first time  in the column hence Paramm1 = 1

index 5 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

Body:
You can check for duplicated values, multiply with df and sum:

df['Param'] = df.apply(lambda x: ~x.duplicated()).mul(df).sum(1)

Output:

   A  B  C  D  Param
0  0  1  0  0      1
1  0  1  0  0      0
2  0  0  1  1      2
3  0  1  0  1      0
4  1  1  0  0      1
5  1  1  1  0      0


问:
How do I download the Android SDK without downloading Android Studio?
As of the moment, I am running a Windows 8.1 PC that does not have the storage or the RAM for a IDE like Android Studio or Eclipse. I want to download the Android SDK tools, without the IDE. How can this be accomplished?</p>

答:
To download the SDK over command line, the link has changed slightly than previously mentioned:

wget --quiet --output-document=/tmp/sdk-tools-linux.zip https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_SDK_TOOLS}.zip

Latest version listed on the downloads page.

ContentLicense: CC BY-SA 3.0


问:
Get email subject and sender using imaplib?
I am getting the following response after executing the code shown below the response. How can I parse through this response to get the sender (John Smith) and the subject (test)?

```<code>[('13010 (BODY[HEADER.FIELDS (SUBJECT FROM)] {57}', 'From: John Smith <jsmith@gmail.com>\r\nSubject: test\r\n\r\n'), ')']
</code>```

-

```<code>conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')
</code>```

答:
Perhaps the question/answer here will help. Try something like this:

```<code>from email.parser import HeaderParser
data = conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')
header_data = data[1][0][1]
parser = HeaderParser()
msg = parser.parsestr(header_data)
</code>```

and then msg should be a dictionary.

Body:
I am getting the following response after executing the code shown below the response. How can I parse through this response to get the sender (John Smith) and the subject (test)?

[('13010 (BODY[HEADER.FIELDS (SUBJECT FROM)] {57}', 'From: John Smith <jsmith@gmail.com>\r\nSubject: test\r\n\r\n'), ')']

-

conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')

Body:
Perhaps the question/answer here will help. Try something like this:

from email.parser import HeaderParser
data = conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')
header_data = data[1][0][1]
parser = HeaderParser()
msg = parser.parsestr(header_data)

and then msg should be a dictionary.


问:
How to move 'get UI element button' [+] to right side panel
How can I add the get UI element button to the right side panel of my screen like shown in this image:

答:
It seem that's not possible to go back how it was before.
But a workaround is to dock a window of the library by simply option+click the "+" sign.</p>


问:
Find and click element by... Python Selenium
I'm trying to click an element. In inspect element i can see this:

```<code><a href="/sondc.phtml"><b>S</b>ondeos por territorios</a>
</code>```

And this is my code:

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.ogimet.com/")

bsObj = BeautifulSoup(html.read());

#print(bsObj)

nameList = bsObj.findAll("a")
</code>```

I don't know what does it mean href. I don't know if that is an atributte. Can you help me?

答:
If you want to click the "Sondeos por territorios" link with selenium, this will do it. </p>

```<code>from selenium import webdriver

#this path may be different on your cpu, you need to install a browser driver
driver_loc = r'C:\chromedriver_win32\chromedriver.exe'
url = 'http://www.ogimet.com/'

driver = webdriver.Chrome(driver_loc)
driver.get(url)

the_link = driver.find_element_by_xpath('/html/body/table/tbody/tr[2]/td[1]/div[19]/a')
the_link.click()
</code>```

Body:
I'm trying to click an element. In inspect element i can see this:

Sondeos por territorios

And this is my code:

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.ogimet.com/")

bsObj = BeautifulSoup(html.read());

#print(bsObj)

nameList = bsObj.findAll("a")

I don't know what does it mean href. I don't know if that is an atributte. Can you help me?

Body:
If you want to click the "Sondeos por territorios" link with selenium, this will do it.

from selenium import webdriver

#this path may be different on your cpu, you need to install a browser driver
driver_loc = r'C:\chromedriver_win32\chromedriver.exe'
url = 'http://www.ogimet.com/'

driver = webdriver.Chrome(driver_loc)
driver.get(url)

the_link = driver.find_element_by_xpath('/html/body/table/tbody/tr[2]/td[1]/div[19]/a')
the_link.click()


问:
Set color scheme in global options on Rmarkdown R
I want to set a global color scheme in Rmarkdown, I read that this is possible with options but I tried this without success:

```<code>---
title: "Iris"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(ggplot2.continuous.color = "viridis")
options(ggplot2.continuous.fill = "viridis")
options(ggplot2.discrete.fill = "viridis")
```

```{r}
library(tidyverse)
iris %>% ggplot(aes(Sepal.Length, Sepal.Width, color = Species)) +
   geom_point()
```
</code>```

The plot I get uses the default color scheme, and I want the viridis scheme. Any help will be greatly appreciated.

答:
Following this excellent blog post by Jim Hester, you can reassign to the default scale_colour_*() functions the scales you want:

```<code>---
title: "Iris"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
scale_colour_continuous <- scale_colour_viridis_c
scale_colour_discrete   <- scale_colour_viridis_d
scale_colour_binned     <- scale_colour_viridis_b
```

```{r}
iris %>% ggplot(aes(Sepal.Length, Sepal.Width, color = Species)) +
   geom_point()
```
</code>```

Body:
I want to set a global color scheme in Rmarkdown, I read that this is possible with options but I tried this without success:

---
title: "Iris"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(ggplot2.continuous.color = "viridis")
options(ggplot2.continuous.fill = "viridis")
options(ggplot2.discrete.fill = "viridis")
```

```{r}
library(tidyverse)
iris %>% ggplot(aes(Sepal.Length, Sepal.Width, color = Species)) +
   geom_point()
```

The plot I get uses the default color scheme, and I want the viridis scheme. Any help will be greatly appreciated.

Body:
Following this excellent blog post by Jim Hester, you can reassign to the default scale_colour_*() functions the scales you want:

---
title: "Iris"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
scale_colour_continuous <- scale_colour_viridis_c
scale_colour_discrete   <- scale_colour_viridis_d
scale_colour_binned     <- scale_colour_viridis_b
```

```{r}
iris %>% ggplot(aes(Sepal.Length, Sepal.Width, color = Species)) +
   geom_point()
```


问:
Convert a call method Cdecl convention to a call method pascal convention
I'm trying to develop some code to make generic calls to methods by it's name.
For example, some one from web send me a text as 'TTest.MethodTest.Param1.Param2', and I find the class and call it method by it's name with the parameters.
Ok, I did this, I got some code from Andreas Hausladen did little adjusts to work where I need. But, the implementation of ExecuteAsyncCall, was create to cdecl functions I need to change it's code to work with pascal convention methods.

Here is the code sample, if some one would like to test.
Some one can help me ? I'm studying to solve this but it's complicated to me.

```<code>unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  published
    { Public declarations }
    procedure Test(AString: string; AInteger: Integer); cdecl;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function CopyVarRec(const Data: TVarRec): TVarRec;
begin
  if (Data.VPointer <> nil) and
     (Data.VType in [vtString, vtAnsiString, vtWideString,
                     {$IFDEF UNICODE}vtUnicodeString,{$ENDIF} vtExtended,
                     vtCurrency, vtInt64, vtVariant, vtInterface]) then
  begin
    Result.VType := Data.VType;
    Result.VPointer := nil;
    { Copy and redirect TVarRec data to prevent conflicts with other threads,
      especially the calling thread. Otherwise reference counted types could
      be freed while this asynchron function is still executed. }
    case Result.VType of
      vtAnsiString: AnsiString(Result.VAnsiString) := AnsiString(Data.VAnsiString);
      vtWideString: WideString(Result.VWideString) := WideString(Data.VWideString);
      {$IFDEF UNICODE}
      vtUnicodeString: UnicodeString(Result.VUnicodeString) := UnicodeString(data.VUnicodeString);
      {$ENDIF UNICODE}
      vtInterface : IInterface(Result.VInterface) := IInterface(Data.VInterface);

      vtString    : begin New(Result.VString);   Result.VString^ := Data.VString^; end;
      vtExtended  : begin New(Result.VExtended); Result.VExtended^ := Data.VExtended^; end;
      vtCurrency  : begin New(Result.VCurrency); Result.VCurrency^ := Data.VCurrency^; end;
      vtInt64     : begin New(Result.VInt64);    Result.VInt64^ := Data.VInt64^; end;
      vtVariant   : begin New(Result.VVariant);  Result.VVariant^ := Data.VVariant^; end;
    end;
  end
  else
    Result := Data;
end;

function ExecuteAsyncCall(AProc: Pointer; MethodData: TObject; const AArgs: array of const): Integer;
var
  I: Integer;
  V: ^TVarRec;
  ByteCount: Integer;
  FArgs: array of TVarRec;
  FProc: function: Integer register;
begin
  FProc := AProc;
  SetLength(FArgs, 1 + Length(AArgs));

  // insert "Self"
  FArgs[0].VType := vtObject;
  FArgs[0].VObject := MethodData;

  for I := 0 to High(AArgs) do
    FArgs[I + 1] := CopyVarRec(AArgs[I]);

  ByteCount := Length(FArgs) * SizeOf(Integer) + $40;
  { Create a zero filled buffer for functions that want more arguments than
    specified. }
  asm
    xor eax, eax
    mov ecx, $40 / 8
@@FillBuf:
    push eax
    push eax
//    push eax
    dec ecx
    jnz @@FillBuf
  end;

  for I := High(FArgs) downto 0 do // cdecl => right to left
  begin
    V := @FArgs[I];
    case V.VType of
      vtInteger:     // [const] Arg: Integer
        asm
          mov eax, V
          push [eax].TVarRec.VInteger
        end;

      vtBoolean,     // [const] Arg: Boolean
      vtChar:        // [const] Arg: AnsiChar
        asm
          mov eax, V
          xor edx, edx
          mov dl, [eax].TVarRec.VBoolean
          push edx
        end;

      vtWideChar:    // [const] Arg: WideChar
        asm
          mov eax, V
          xor edx, edx
          mov dx, [eax].TVarRec.VWideChar
          push edx
        end;

      vtExtended:    // [const] Arg: Extended
        asm
          add [ByteCount], 8 // two additional DWORDs
          mov eax, V
          mov edx, [eax].TVarRec.VExtended
          movzx eax, WORD PTR [edx + 8]
          push eax
          push DWORD PTR [edx + 4]
          push DWORD PTR [edx]
        end;

      vtCurrency,    // [const] Arg: Currency
      vtInt64:       // [const] Arg: Int64
        asm
          add [ByteCount], 4 // an additional DWORD
          mov eax, V
          mov edx, [eax].TVarRec.VCurrency
          push DWORD PTR [edx + 4]
          push DWORD PTR [edx]
        end;

      vtString,      // [const] Arg: ShortString
      vtPointer,     // [const] Arg: Pointer
      vtPChar,       // [const] Arg: PChar
      vtObject,      // [const] Arg: TObject
      vtClass,       // [const] Arg: TClass
      vtAnsiString,  // [const] Arg: AnsiString
      {$IFDEF UNICODE}
      vtUnicodeString, // [const] Arg: UnicodeString
      {$ENDIF UNICODE}
      vtPWideChar,   // [const] Arg: PWideChar
      vtVariant,     // const Arg: Variant
      vtInterface,   // [const]: IInterface
      vtWideString:  // [const] Arg: WideString
        asm
          mov eax, V
          push [eax].TVarRec.VPointer
        end;
    end;
  end;

  Result := FProc;

  asm // cdecl => we must clean up
    add esp, [ByteCount]
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ExecuteAsyncCall(Self.MethodAddress('Test'), Self, ['Test ', 1])
end;

procedure TForm1.Test(AString: string; AInteger: Integer);
begin
  ShowMessage(AString +   IntToStr(AInteger));
end;

end.
</code>```

Att.

Obs: I'm working on Delphi 2007

答:
I agree but I think that Self have to be pushed last:

http://docwiki.embarcadero.com/RADStudio/en/Program_Control

```<code>  // insert "Self"
    for I := 0 to High(AArgs) do
     FArgs[I] := CopyVarRec(AArgs[I]);
   FArgs[High(AArgs)+1].VType := vtObject;
   FArgs[High(AArgs)+1].VObject := MethodData;
</code>```

But I don't believe this code can be used and it'll crash:

1) all parameters of all methods must be variants

2) wrong number of parameters

3) wrong type (or order) of parameters

I think you have to find other solution.

Body:
I'm trying to develop some code to make generic calls to methods by it's name.
For example, some one from web send me a text as 'TTest.MethodTest.Param1.Param2', and I find the class and call it method by it's name with the parameters.
Ok, I did this, I got some code from Andreas Hausladen did little adjusts to work where I need. But, the implementation of ExecuteAsyncCall, was create to cdecl functions I need to change it's code to work with pascal convention methods.

Here is the code sample, if some one would like to test.
Some one can help me ? I'm studying to solve this but it's complicated to me.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  published
    { Public declarations }
    procedure Test(AString: string; AInteger: Integer); cdecl;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function CopyVarRec(const Data: TVarRec): TVarRec;
begin
  if (Data.VPointer <> nil) and
     (Data.VType in [vtString, vtAnsiString, vtWideString,
                     {$IFDEF UNICODE}vtUnicodeString,{$ENDIF} vtExtended,
                     vtCurrency, vtInt64, vtVariant, vtInterface]) then
  begin
    Result.VType := Data.VType;
    Result.VPointer := nil;
    { Copy and redirect TVarRec data to prevent conflicts with other threads,
      especially the calling thread. Otherwise reference counted types could
      be freed while this asynchron function is still executed. }
    case Result.VType of
      vtAnsiString: AnsiString(Result.VAnsiString) := AnsiString(Data.VAnsiString);
      vtWideString: WideString(Result.VWideString) := WideString(Data.VWideString);
      {$IFDEF UNICODE}
      vtUnicodeString: UnicodeString(Result.VUnicodeString) := UnicodeString(data.VUnicodeString);
      {$ENDIF UNICODE}
      vtInterface : IInterface(Result.VInterface) := IInterface(Data.VInterface);

      vtString    : begin New(Result.VString);   Result.VString^ := Data.VString^; end;
      vtExtended  : begin New(Result.VExtended); Result.VExtended^ := Data.VExtended^; end;
      vtCurrency  : begin New(Result.VCurrency); Result.VCurrency^ := Data.VCurrency^; end;
      vtInt64     : begin New(Result.VInt64);    Result.VInt64^ := Data.VInt64^; end;
      vtVariant   : begin New(Result.VVariant);  Result.VVariant^ := Data.VVariant^; end;
    end;
  end
  else
    Result := Data;
end;

function ExecuteAsyncCall(AProc: Pointer; MethodData: TObject; const AArgs: array of const): Integer;
var
  I: Integer;
  V: ^TVarRec;
  ByteCount: Integer;
  FArgs: array of TVarRec;
  FProc: function: Integer register;
begin
  FProc := AProc;
  SetLength(FArgs, 1 + Length(AArgs));

  // insert "Self"
  FArgs[0].VType := vtObject;
  FArgs[0].VObject := MethodData;

  for I := 0 to High(AArgs) do
    FArgs[I + 1] := CopyVarRec(AArgs[I]);

  ByteCount := Length(FArgs) * SizeOf(Integer) + $40;
  { Create a zero filled buffer for functions that want more arguments than
    specified. }
  asm
    xor eax, eax
    mov ecx, $40 / 8
@@FillBuf:
    push eax
    push eax
//    push eax
    dec ecx
    jnz @@FillBuf
  end;

  for I := High(FArgs) downto 0 do // cdecl => right to left
  begin
    V := @FArgs[I];
    case V.VType of
      vtInteger:     // [const] Arg: Integer
        asm
          mov eax, V
          push [eax].TVarRec.VInteger
        end;

      vtBoolean,     // [const] Arg: Boolean
      vtChar:        // [const] Arg: AnsiChar
        asm
          mov eax, V
          xor edx, edx
          mov dl, [eax].TVarRec.VBoolean
          push edx
        end;

      vtWideChar:    // [const] Arg: WideChar
        asm
          mov eax, V
          xor edx, edx
          mov dx, [eax].TVarRec.VWideChar
          push edx
        end;

      vtExtended:    // [const] Arg: Extended
        asm
          add [ByteCount], 8 // two additional DWORDs
          mov eax, V
          mov edx, [eax].TVarRec.VExtended
          movzx eax, WORD PTR [edx + 8]
          push eax
          push DWORD PTR [edx + 4]
          push DWORD PTR [edx]
        end;

      vtCurrency,    // [const] Arg: Currency
      vtInt64:       // [const] Arg: Int64
        asm
          add [ByteCount], 4 // an additional DWORD
          mov eax, V
          mov edx, [eax].TVarRec.VCurrency
          push DWORD PTR [edx + 4]
          push DWORD PTR [edx]
        end;

      vtString,      // [const] Arg: ShortString
      vtPointer,     // [const] Arg: Pointer
      vtPChar,       // [const] Arg: PChar
      vtObject,      // [const] Arg: TObject
      vtClass,       // [const] Arg: TClass
      vtAnsiString,  // [const] Arg: AnsiString
      {$IFDEF UNICODE}
      vtUnicodeString, // [const] Arg: UnicodeString
      {$ENDIF UNICODE}
      vtPWideChar,   // [const] Arg: PWideChar
      vtVariant,     // const Arg: Variant
      vtInterface,   // [const]: IInterface
      vtWideString:  // [const] Arg: WideString
        asm
          mov eax, V
          push [eax].TVarRec.VPointer
        end;
    end;
  end;

  Result := FProc;

  asm // cdecl => we must clean up
    add esp, [ByteCount]
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ExecuteAsyncCall(Self.MethodAddress('Test'), Self, ['Test ', 1])
end;

procedure TForm1.Test(AString: string; AInteger: Integer);
begin
  ShowMessage(AString +   IntToStr(AInteger));
end;

end.

Att.

Obs: I'm working on Delphi 2007

Body:
I agree but I think that Self have to be pushed last:

http://docwiki.embarcadero.com/RADStudio/en/Program_Control

  // insert "Self"
    for I := 0 to High(AArgs) do
     FArgs[I] := CopyVarRec(AArgs[I]);
   FArgs[High(AArgs)+1].VType := vtObject;
   FArgs[High(AArgs)+1].VObject := MethodData;

But I don't believe this code can be used and it'll crash:

1) all parameters of all methods must be variants

2) wrong number of parameters

3) wrong type (or order) of parameters

I think you have to find other solution.


问:
Generate multiple PDFs and zip them for download, all in a single view
I am using xhtml2pdf to generate PDFs in my Django View. The idea is to loop over all the instances that are there in the query, then for each instance create a PDF, then add all the generated PDFs to one zip File for download. The xtml2pdf logic is working okay but the looping logic is what gives me headache.

So this is my function so far:

```<code>def bulk_cover_letter(request, ward_id, school_cat_id, cheque_number):
    school_type = SchoolType.objects.get(id=school_cat_id)

    schools_in_school_type = Applicant.objects.filter(
        school_type=school_type, ward_id=ward_id, award_status='awarded'
    ).order_by().values_list('school_name', flat=True).distinct()

    for school in schools_in_school_type:
        beneficiaries = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school)
        total_amount_to_beneficiaries = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school).aggregate(total=Sum('school_type__amount_allocated'))
        context = {
            'school_name' : school,
            'beneficiaries' : beneficiaries,
            'total_amount_to_beneficiaries' : total_amount_to_beneficiaries,
            'title' : school + ' Disbursement Details',
            'cheque_number': cheque_number
        }

        response = HttpResponse('<title>Cover Letter</title>', content_type='application/pdf')
        filename = "%s.pdf" %(cheque_number)
        content = "inline; filename=%s" %(filename)
        response['Content-Disposition'] = content
        template = get_template('cover_letter.html')
        html = template.render(context)
        result = io.BytesIO()
        pdf = pisa.CreatePDF(
            html, dest=response, link_callback=link_callback)
        if not pdf.error:
            # At this point I can generate a single PDF.
            # But no idea on what to do next.

    # The zipping logic should follow here after looping all the instances - (schools)
</code>```

From that Point I have no idea on what to do next. Any help will be highly appreciated.

答:
Try this:

Utils.py

```<code>def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html  = template.render(context_dict)
    buffer = BytesIO()
    p = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), buffer)
    pdf = buffer.getvalue()
    buffer.close()
    if not p.err:
        return pdf#HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

def generate_zip(files):
    mem_zip = BytesIO()

    with zipfile.ZipFile(mem_zip, mode="w",compression=zipfile.ZIP_DEFLATED) as zf:
        for f in files:
            zf.writestr(f[0], f[1])

    return mem_zip.getvalue()
</code>```

Views.py

```<code>def generate_attendance_pdf(modeladmin, request, queryset):

    template_path = 'student/pdf_template.html'

    files = []

    for q in queryset:
        context = {
            'firstname': q.firstname,
            'lastname': q.lastname,
            'p_firstname': q.bceID.firstname
        }
        pdf = render_to_pdf(template_path, context)
        files.append((q.firstname + ".pdf", pdf))

    full_zip_in_memory = generate_zip(files)

    response = HttpResponse(full_zip_in_memory, content_type='application/force-download')
    response['Content-Disposition'] = 'attachment; filename="{}"'.format('attendnace.zip')

    return response
</code>```

Obviously, you have to modify the context/names to what you need.

Credit to -> Neil Grogan https://www.neilgrogan.com/py-bin-zip/

Body:
I am using xhtml2pdf to generate PDFs in my Django View. The idea is to loop over all the instances that are there in the query, then for each instance create a PDF, then add all the generated PDFs to one zip File for download. The xtml2pdf logic is working okay but the looping logic is what gives me headache.

So this is my function so far:

def bulk_cover_letter(request, ward_id, school_cat_id, cheque_number):
    school_type = SchoolType.objects.get(id=school_cat_id)

    schools_in_school_type = Applicant.objects.filter(
        school_type=school_type, ward_id=ward_id, award_status='awarded'
    ).order_by().values_list('school_name', flat=True).distinct()

    for school in schools_in_school_type:
        beneficiaries = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school)
        total_amount_to_beneficiaries = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school).aggregate(total=Sum('school_type__amount_allocated'))
        context = {
            'school_name' : school,
            'beneficiaries' : beneficiaries,
            'total_amount_to_beneficiaries' : total_amount_to_beneficiaries,
            'title' : school + ' Disbursement Details',
            'cheque_number': cheque_number
        }

        response = HttpResponse('<title>Cover Letter</title>', content_type='application/pdf')
        filename = "%s.pdf" %(cheque_number)
        content = "inline; filename=%s" %(filename)
        response['Content-Disposition'] = content
        template = get_template('cover_letter.html')
        html = template.render(context)
        result = io.BytesIO()
        pdf = pisa.CreatePDF(
            html, dest=response, link_callback=link_callback)
        if not pdf.error:
            # At this point I can generate a single PDF.
            # But no idea on what to do next.

    # The zipping logic should follow here after looping all the instances - (schools)

From that Point I have no idea on what to do next. Any help will be highly appreciated.

Body:
Try this:

Utils.py

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html  = template.render(context_dict)
    buffer = BytesIO()
    p = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), buffer)
    pdf = buffer.getvalue()
    buffer.close()
    if not p.err:
        return pdf#HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

def generate_zip(files):
    mem_zip = BytesIO()

    with zipfile.ZipFile(mem_zip, mode="w",compression=zipfile.ZIP_DEFLATED) as zf:
        for f in files:
            zf.writestr(f[0], f[1])

    return mem_zip.getvalue()

Views.py

def generate_attendance_pdf(modeladmin, request, queryset):

    template_path = 'student/pdf_template.html'

    files = []

    for q in queryset:
        context = {
            'firstname': q.firstname,
            'lastname': q.lastname,
            'p_firstname': q.bceID.firstname
        }
        pdf = render_to_pdf(template_path, context)
        files.append((q.firstname + ".pdf", pdf))

    full_zip_in_memory = generate_zip(files)

    response = HttpResponse(full_zip_in_memory, content_type='application/force-download')
    response['Content-Disposition'] = 'attachment; filename="{}"'.format('attendnace.zip')

    return response

Obviously, you have to modify the context/names to what you need.

Credit to -> Neil Grogan https://www.neilgrogan.com/py-bin-zip/


问:
Angular binding width to ContentChildren
I am trying to build a table component in Angular.

I have a StackBlitz Demo Here

When I try to bind width of a
 to my column components i get
ExpressionChangedAfterItHasBeenCheckedError

Is there a better way to achieve this

Thanks

答:
Stackblitz demo

The first change detection cycle happens after OnInit. On that occasion, angular runs change detection to update the model and the view. Then it runs again at NgAfterViewInit and it doesn't expect any changes to happen on your template. What is changing is the width in your TableComponent. You can avoid it if you manage to delay the execution of the expression that change the width. One way of doing that that has come to me is using a pipe that returns an observable that can delay the emission of the width to change the property:

-

```

<p>The <code>offsetWidth</code> pipe would be like this:</p>

```transform(column: ColumnComponent): Observable<string> {
    return of(1).pipe(
      delay(0), // <= this will delay the emision
      switchMap(_ =>
        of(column && column.elementRef.nativeElement.offsetWidth))
    );
  }
```

Body:
Stackblitz demo

The first change detection cycle happens after OnInit. On that occasion, angular runs change detection to update the model and the view. Then it runs again at NgAfterViewInit and it doesn't expect any changes to happen on your template. What is changing is the width in your TableComponent. You can avoid it if you manage to delay the execution of the expression that change the width. One way of doing that that has come to me is using a pipe that returns an observable that can delay the emission of the width to change the property:

<div class="cell" [style.width.px]="column | offsetWidth | async">-</div>

The offsetWidth pipe would be like this:

transform(column: ColumnComponent): Observable<string> {
    return of(1).pipe(
      delay(0), // <= this will delay the emision
      switchMap(_ =>
        of(column && column.elementRef.nativeElement.offsetWidth))
    );
  }


问:
Calling Graph API inside a javascript Azure Function
I'm quite new to Azure Functions. I'm trying to consume Graph APIs inside an HTTP triggered Azure Function in javascript.
I found few docs related to this argument. Also a couple of questions here on Stack Overflow, but all the material is quite old and both Graph and Azure Functions have improved from then.
When I just create the function, it work perfectly. If I simple add a binding to Auth Token (https://graph.microsoft.com), without even touching the index.js, the function stops working and returns 404 error (file not found). The connection try is not even logged in monitor or Applications Insights. I'm building the function directly from the Azure portal (no local deployment). I already created an app on AAD and changed the authentication on my function app to connect to this app. Also authorized the Azure user on Microsoft Graph (through Graph Explorer), but still get this 404 error. What should I check ?

Edit based on Tony Ju answer:

I turned off App Service Authentication and followed the steps here, as suggested. I just changed few things to make it work in Azure Function (the post was for pure Node.js). actually, this is my index.js:

```<code>const APP_ID = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
const APP_SECERET = 'XXXX~-XXX~XXXXXXXXXXXXX~XXXXXXXXX~';
const TOKEN_ENDPOINT ='https://login.microsoftonline.com/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/oauth2/v2.0/token';
const MS_GRAPH_SCOPE = 'https://graph.microsoft.com/.default';

const axios = require('axios');
const qs = require('qs');

const postData = {
  client_id: APP_ID,
  scope: MS_GRAPH_SCOPE,
  client_secret: APP_SECERET,
  grant_type: 'client_credentials'
};

module.exports = function (context, req) {
    axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded';

    let token = '';

    axios
    .post(TOKEN_ENDPOINT, qs.stringify(postData))
    .then(response => {
        context.log(response.data);
    })
    .catch(error => {
        context.log(error);
    });
};
</code>```

the XXXX are taken from AAD app, repectively: Application (client) ID, App Client secret and Directory (tenant) ID.

My function.json is the following:

```<code>{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "graphToken",
      "direction": "in",
      "type": "token",
      "resource": "https://graph.microsoft.com",
      "identity": "userFromRequest"
    }
  ]
}
</code>```

Still get 404 error. Doesn't seem something related to code, but something related to function bindings.

Edit after new comment from Tony Ju and further experiments:

Thanks to Tony: auth binding is not necessary.

Also need to go to Function App Service, then to Console (under Development Tools) and issue

```<code>npm install axios
npm install qs
</code>```

Also, in my previous listing for index.js, function need to be async:

```<code>module.exports = async function (context, req) {
</code>```

In this way, it work. Thanks Tony.

答:
I already created an app on AAD and changed the authentication on my
  function app to connect to this app.

Based on your description, you have enabled authentication to your function. In this case, you can refer to the answer here.

If you don't want to add authentication to your function, and you just want to call Microsoft API in your function. You can use client credential flow. Please refer to my answer here.

Body:
I'm quite new to Azure Functions. I'm trying to consume Graph APIs inside an HTTP triggered Azure Function in javascript.
I found few docs related to this argument. Also a couple of questions here on Stack Overflow, but all the material is quite old and both Graph and Azure Functions have improved from then.
When I just create the function, it work perfectly. If I simple add a binding to Auth Token (https://graph.microsoft.com), without even touching the index.js, the function stops working and returns 404 error (file not found). The connection try is not even logged in monitor or Applications Insights. I'm building the function directly from the Azure portal (no local deployment). I already created an app on AAD and changed the authentication on my function app to connect to this app. Also authorized the Azure user on Microsoft Graph (through Graph Explorer), but still get this 404 error. What should I check ?

Edit based on Tony Ju answer:

I turned off App Service Authentication and followed the steps here, as suggested. I just changed few things to make it work in Azure Function (the post was for pure Node.js). actually, this is my index.js:

const APP_ID = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
const APP_SECERET = 'XXXX~-XXX~XXXXXXXXXXXXX~XXXXXXXXX~';
const TOKEN_ENDPOINT ='https://login.microsoftonline.com/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/oauth2/v2.0/token';
const MS_GRAPH_SCOPE = 'https://graph.microsoft.com/.default';

const axios = require('axios');
const qs = require('qs');

const postData = {
  client_id: APP_ID,
  scope: MS_GRAPH_SCOPE,
  client_secret: APP_SECERET,
  grant_type: 'client_credentials'
};

module.exports = function (context, req) {
    axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded';

    let token = '';

    axios
    .post(TOKEN_ENDPOINT, qs.stringify(postData))
    .then(response => {
        context.log(response.data);
    })
    .catch(error => {
        context.log(error);
    });
};

the XXXX are taken from AAD app, repectively: Application (client) ID, App Client secret and Directory (tenant) ID.

My function.json is the following:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "graphToken",
      "direction": "in",
      "type": "token",
      "resource": "https://graph.microsoft.com",
      "identity": "userFromRequest"
    }
  ]
}

Still get 404 error. Doesn't seem something related to code, but something related to function bindings.

Edit after new comment from Tony Ju and further experiments:

Thanks to Tony: auth binding is not necessary.

Also need to go to Function App Service, then to Console (under Development Tools) and issue

npm install axios
npm install qs

Also, in my previous listing for index.js, function need to be async:

module.exports = async function (context, req) {

In this way, it work. Thanks Tony.


问:
Creating a property for Python Class instance
I am learning how to code in Python.
 I have created a Bandwidth class, which has _get_bandwidth and _set_bandwidth private methods. Created a property for bandwidth used. Not sure how to create a property, which when called on the Bandwidth object, will give the percentage of used bandwidth. See code below, thank you.

```<code>class Bandwidth():
    def __init__(self, total_bandwidth, used_bandwidth = 0):
        self.total_bandwidth = total_bandwidth
        self._used_bandwidth = used_bandwidth

    #get used bandwidth
    def _get_bandwidth(self):
        return self._used_bandwidth

    #set bandwidth
    def _set_bandwidth(self, bandwidth):
        if bandwidth < self.total_bandwidth:
            self._used_bandwidth = bandwidth

    bandwidth_used = property(_get_bandwidth, _set_bandwidth)

    # A percentage property that calculates how much bandwidth has been used
    # The percentage property should be read-only.

    #percentage = property()

lebara = Bandwidth(8)
lebara.bandwidth_used = 2
# print(lebara.percentage) # should give 0.25

# lebara.bandwidth_used = 4
# print(lebara.percentage) # should give 0.5

# lebara.bandwidth_used = 10 # _bandwidth used should not change because there's only 8 bits in a byte
# print(lebara.percentage) #  should give 0.5
</code>```

Thank you in advance.

答:
You can use @property decorator to modify the behavior of a getter, and access it like you would access an attribute. In the same vein, you use @attribute.getter decorator to mimic the behavior of directly setting the value of an attribute:

In your example:

```<code>class Bandwidth():
    def __init__(self, total_bandwidth, used_bandwidth=0):
        self._total_bandwidth = total_bandwidth
        self._used_bandwidth = used_bandwidth

    @property
    def used_bandwidth(self):
        return self._used_bandwidth

    @used_bandwidth.setter
    def used_bandwidth(self, bw):
        if 0 < bw <= self._total_bandwidth:
            self._used_bandwidth = bw

    @property
    def pcent_used(self):
        print(f'used_bandwidth: {self.used_bandwidth}, total_bandwidth: {self._total_bandwidth}')
        return (self.used_bandwidth / self._total_bandwidth) * 100  #<-- remove * 100 if you need a decimal between 0 and 1

lebara = Bandwidth(8)
lebara.used_bandwidth = 2
print(lebara.pcent_used) # should give 25

lebara.used_bandwidth = 4
print(lebara.pcent_used) # should give 50

lebara.used_bandwidth = 10
print(lebara.pcent_used) # should give 50   # remains unchanged
</code>```

output:

```<code>used_bandwidth: 2, total_bandwidth: 8
25.0
used_bandwidth: 4, total_bandwidth: 8
50.0
used_bandwidth: 4, total_bandwidth: 8
50.0
</code>```

Body:
I am learning how to code in Python.
 I have created a Bandwidth class, which has _get_bandwidth and _set_bandwidth private methods. Created a property for bandwidth used. Not sure how to create a property, which when called on the Bandwidth object, will give the percentage of used bandwidth. See code below, thank you.

class Bandwidth():
    def __init__(self, total_bandwidth, used_bandwidth = 0):
        self.total_bandwidth = total_bandwidth
        self._used_bandwidth = used_bandwidth

    #get used bandwidth
    def _get_bandwidth(self):
        return self._used_bandwidth

    #set bandwidth
    def _set_bandwidth(self, bandwidth):
        if bandwidth < self.total_bandwidth:
            self._used_bandwidth = bandwidth

    bandwidth_used = property(_get_bandwidth, _set_bandwidth)

    # A percentage property that calculates how much bandwidth has been used
    # The percentage property should be read-only.

    #percentage = property()

lebara = Bandwidth(8)
lebara.bandwidth_used = 2
# print(lebara.percentage) # should give 0.25

# lebara.bandwidth_used = 4
# print(lebara.percentage) # should give 0.5

# lebara.bandwidth_used = 10 # _bandwidth used should not change because there's only 8 bits in a byte
# print(lebara.percentage) #  should give 0.5

Thank you in advance.

Body:
You can use @property decorator to modify the behavior of a getter, and access it like you would access an attribute. In the same vein, you use @attribute.getter decorator to mimic the behavior of directly setting the value of an attribute:

In your example:

class Bandwidth():
    def __init__(self, total_bandwidth, used_bandwidth=0):
        self._total_bandwidth = total_bandwidth
        self._used_bandwidth = used_bandwidth

    @property
    def used_bandwidth(self):
        return self._used_bandwidth

    @used_bandwidth.setter
    def used_bandwidth(self, bw):
        if 0 < bw <= self._total_bandwidth:
            self._used_bandwidth = bw

    @property
    def pcent_used(self):
        print(f'used_bandwidth: {self.used_bandwidth}, total_bandwidth: {self._total_bandwidth}')
        return (self.used_bandwidth / self._total_bandwidth) * 100  #<-- remove * 100 if you need a decimal between 0 and 1

lebara = Bandwidth(8)
lebara.used_bandwidth = 2
print(lebara.pcent_used) # should give 25

lebara.used_bandwidth = 4
print(lebara.pcent_used) # should give 50

lebara.used_bandwidth = 10
print(lebara.pcent_used) # should give 50   # remains unchanged

output:

used_bandwidth: 2, total_bandwidth: 8
25.0
used_bandwidth: 4, total_bandwidth: 8
50.0
used_bandwidth: 4, total_bandwidth: 8
50.0


问:
how to fix "undefined is not an object (evaluating 'form.submit.addEventListener')"
I'm having a lot of trouble trying to get a basic AJAX form to work and am particularly stumped with the current issue.
I have a bit of code which always errors. Here is the error message:

undefined is not an object (evaluating 'form.submit.addEventListener')

... and here is the bit of code that causes the error:

```<code>form.submit.addEventListener('click', () => {

  console.log('button pressed!');

});
</code>```

I honestly have no idea why, as I'm using the arrow function so it shouldn't be undefined should it? I'm pretty new to javascript so I've probably missed something I'm just very confused as of now.

答:
If you want to AJAXify your form, listen to the form submit Event, not to button clicks.

```<code>const form = document.querySelector("#formidable");

form.addEventListener("submit", async (ev) => {

  ev.preventDefault(); // prevent browser triggering action
  console.log('Someone tried to submit my formidable form!');

  // Than do your Ajax Magic!
  const response = await fetch(form.action, {
    method: form.method || "post",
    body: new FormData(form)
  });

  const result = await response.json();
  console.log(result.message); // log the response JSON from server!

});
</code>```

If not deferred, make sure your

Body:
I'm having a lot of trouble trying to get a basic AJAX form to work and am particularly stumped with the current issue.
I have a bit of code which always errors. Here is the error message:

undefined is not an object (evaluating 'form.submit.addEventListener')

... and here is the bit of code that causes the error:

form.submit.addEventListener('click', () => {

  console.log('button pressed!');

});

I honestly have no idea why, as I'm using the arrow function so it shouldn't be undefined should it? I'm pretty new to javascript so I've probably missed something I'm just very confused as of now.

Body:
If you want to AJAXify your form, listen to the form submit Event, not to button clicks.

const form = document.querySelector("#formidable");

form.addEventListener("submit", async (ev) => {

  ev.preventDefault(); // prevent browser triggering action
  console.log('Someone tried to submit my formidable form!');

  // Than do your Ajax Magic!
  const response = await fetch(form.action, {
    method: form.method || "post",
    body: new FormData(form)
  });

  const result = await response.json();
  console.log(result.message); // log the response JSON from server!

});

If not deferred, make sure your <script> tag is placed right before the closing </body> tag in order to make sure DOM is parsed and ready.


问:
How to call affected_rows method from ci4 model
I have a model that extends CI4 builtin Model..

```<code>use CodeIgniter\Model;
use CodeIgniter\I18n\Time;

class ArticleModel extends Model { .. }
</code>```

Any idea how do i perform the following?

```<code>$this->db->affected_rows();
</code>```

thinking of getting it after deleting a row, most of the example using custom model, not extending ci4 model.

答:
Addition from above answer, to do it probably by getting the builder from CI4 model, since the model already has a db connection.

for example:

```<code>$model = new ArticleModel();
$builder = $model->builder();
$builder->db->affectedRows(); // this return
</code>```

Body:
I have a model that extends CI4 builtin Model..

use CodeIgniter\Model;
use CodeIgniter\I18n\Time;

class ArticleModel extends Model { .. }

Any idea how do i perform the following?

$this->db->affected_rows();

thinking of getting it after deleting a row, most of the example using custom model, not extending ci4 model.

Body:
Addition from above answer, to do it probably by getting the builder from CI4 model, since the model already has a db connection.

for example:

$model = new ArticleModel();
$builder = $model->builder();
$builder->db->affectedRows(); // this return


问:
Powershell Get-Verb installation lacking some features
Completely new to Powershell, using the default installation on Windows 10.

On my system, running Get-Verb gives me:

```<code>> Get-Verb un*
Verb       Group
----       -----
Undo       Common
Unlock     Common
Unpublish  Data
Uninstall  Lifecycle
Unregister Lifecycle
Unblock    Security
Unprotect  Security
</code>```

which is different from that from the tutorial I was watching (on Pluralsight) and on the Microsoft docs:

```<code>> Get-Verb un*
Verb       AliasPrefix Group     Description
----       ----------- -----     -----------
Undo       un          Common    Sets a resource to its previous state
Unlock     uk          Common    Releases a resource that was locked
Unpublish  ub          Data      Makes a resource unavailable to others
Uninstall  us          Lifecycle Removes a resource from an indicated location
Unregister ur          Lifecycle Removes the entry for a resource from a repository
Unblock    ul          Security  Removes restrictions to a resource
Unprotect  up          Security  Removes safeguards from a resource that were added to prevent it from attack or loss
</code>```

I've also noticed that some other features seem to be missing, such as certain attributes; I am getting the error:

```<code>> Get-Verb -Group Security | Format-List

Get-Verb : A parameter cannot be found that matches parameter name 'Group'.
At line:1 char:10
+ get-verb -Group Security | format-list
+          ~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Verb], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Get-Verb
</code>```

when in the manpages and the tutorial, the use of the -Group option is valid. My manpage seems to be missing the -Group option, i.e. it looks like this (compare with the version from the documentation):

```<code>> man Get-Verb

NAME
    Get-Verb

SYNOPSIS

SYNTAX
    Get-Verb [[-verb] <String[]>] [<CommonParameters>]

DESCRIPTION

RELATED LINKS
    https://go.microsoft.com/fwlink/?LinkID=160712

REMARKS
    To see the examples, type: "get-help Get-Verb -examples".
    For more information, type: "get-help Get-Verb -detailed".
    For technical information, type: "get-help Get-Verb -full".
    For online help, type: "get-help Get-Verb -online"
</code>```

What is the cause of this discrepancy?

Other details (may or may not be relevant):

I installed .NET core and the RSAT tools recently, but I don't think they should cause this problem.

I'm using Windows 10 Education N.

Output of $PSVersionTable:

```<code>Name                           Value
----                           -----
PSVersion                      5.1.18362.752
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.18362.752
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
</code>```

答:
I believe the more descriptive output for Get-Verb is for PowerShell Core (6+). Windows PowerShell (the one installed on Windows by default; 5.1 or lower) does not provide that functionality.

Unfortunately, there seems to be discrepancy on the documentation site. It does not reflect the proper usage if you use the dropdown to switch to PS 5.1.

Body:
Completely new to Powershell, using the default installation on Windows 10.

On my system, running Get-Verb gives me:

> Get-Verb un*
Verb       Group
----       -----
Undo       Common
Unlock     Common
Unpublish  Data
Uninstall  Lifecycle
Unregister Lifecycle
Unblock    Security
Unprotect  Security

which is different from that from the tutorial I was watching (on Pluralsight) and on the Microsoft docs:

> Get-Verb un*
Verb       AliasPrefix Group     Description
----       ----------- -----     -----------
Undo       un          Common    Sets a resource to its previous state
Unlock     uk          Common    Releases a resource that was locked
Unpublish  ub          Data      Makes a resource unavailable to others
Uninstall  us          Lifecycle Removes a resource from an indicated location
Unregister ur          Lifecycle Removes the entry for a resource from a repository
Unblock    ul          Security  Removes restrictions to a resource
Unprotect  up          Security  Removes safeguards from a resource that were added to prevent it from attack or loss

I've also noticed that some other features seem to be missing, such as certain attributes; I am getting the error:

> Get-Verb -Group Security | Format-List

Get-Verb : A parameter cannot be found that matches parameter name 'Group'.
At line:1 char:10
+ get-verb -Group Security | format-list
+          ~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Verb], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Get-Verb

when in the manpages and the tutorial, the use of the -Group option is valid. My manpage seems to be missing the -Group option, i.e. it looks like this (compare with the version from the documentation):

> man Get-Verb

NAME
    Get-Verb

SYNOPSIS

SYNTAX
    Get-Verb [[-verb] <String[]>] [<CommonParameters>]

DESCRIPTION

RELATED LINKS
    https://go.microsoft.com/fwlink/?LinkID=160712

REMARKS
    To see the examples, type: "get-help Get-Verb -examples".
    For more information, type: "get-help Get-Verb -detailed".
    For technical information, type: "get-help Get-Verb -full".
    For online help, type: "get-help Get-Verb -online"

What is the cause of this discrepancy?

Other details (may or may not be relevant):

I installed .NET core and the RSAT tools recently, but I don't think they should cause this problem.

I'm using Windows 10 Education N.

Output of $PSVersionTable:

Name                           Value
----                           -----
PSVersion                      5.1.18362.752
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.18362.752
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1


问:
Why reborrowing &mut[u8] makes its size unknown at compile time?
I'm creating a mutable [u8] buffer as this:

```<code>let buffer: &mut [u8] = &mut [0u8; 34];
</code>```

and using here:

```<code>repr.emit(&mut *buffer, &caps.checksum);
</code>```

and reborrowing here:

```<code>assert_eq!(processor!(iface).process_ip_payload(&mut ip, &mut socket_set, Instant::from_millis(0), &mut *buffer), Ok(Some(expected_repr)));
</code>```

I get:

the size for values of type [u8] cannot be known at compilation time

doesn't have a size known at compile-time

for the ...,&mut *buffer) reborrow (the last one, on assert).

The original buffer has its size known at compile time. Why reborrowing makes the size unknown?

Here are the signatures if needed:

```<code>    pub fn emit<T: AsRef<[u8]> + AsMut<[u8]>>(
        &self,
        buffer: T,
        _checksum_caps: &ChecksumCapabilities,
    )
    fn process_ip_payload<'frame, T: AsRef<[u8]>>(
        &mut self,
        ip: &mut ip::Processor,
        sockets: &mut SocketSet,
        timestamp: Instant,
        frame: &'frame T,
    ) -> Result<Option<ip::Packet<'frame>>>
</code>```

答:
Don't dereference buffer when you pass it in as an argument:

```<code>assert_eq!(processor!(iface).process_ip_payload(
    &mut ip, &mut socket_set, Instant::from_millis(0), &mut buffer),
    Ok(Some(expected_repr)));
</code>```

(&mut buffer instead of &mut *buffer).

Body:
I'm creating a mutable [u8] buffer as this:

let buffer: &mut [u8] = &mut [0u8; 34];

and using here:

repr.emit(&mut *buffer, &caps.checksum);

and reborrowing here:

assert_eq!(processor!(iface).process_ip_payload(&mut ip, &mut socket_set, Instant::from_millis(0), &mut *buffer), Ok(Some(expected_repr)));

I get:

the size for values of type [u8] cannot be known at compilation time

doesn't have a size known at compile-time

for the ...,&mut *buffer) reborrow (the last one, on assert).

The original buffer has its size known at compile time. Why reborrowing makes the size unknown?

Here are the signatures if needed:

    pub fn emit<T: AsRef<[u8]> + AsMut<[u8]>>(
        &self,
        buffer: T,
        _checksum_caps: &ChecksumCapabilities,
    )
    fn process_ip_payload<'frame, T: AsRef<[u8]>>(
        &mut self,
        ip: &mut ip::Processor,
        sockets: &mut SocketSet,
        timestamp: Instant,
        frame: &'frame T,
    ) -> Result<Option<ip::Packet<'frame>>>

Body:
Don't dereference buffer when you pass it in as an argument:

assert_eq!(processor!(iface).process_ip_payload(
    &mut ip, &mut socket_set, Instant::from_millis(0), &mut buffer),
    Ok(Some(expected_repr)));

(&mut buffer instead of &mut *buffer).


答:
You can group_by year and calculate correlation for x and y in each year. Also since correlation would give you only one number for each year it is better to summarise instead of mutate because mutate would repeat the same value for all rows.

```<code>library(dplyr)
library(lubridate)

df %>% group_by(year = year(date)) %>% summarise(correlation = cor(x, y))
</code>```

Title: How can I simplify a correlation code in R?

Body:
This is my df:

                  date                     z         x                    y
   <dttm>                               <dbl>    <dbl>                <dbl>
 1 2019-01-01 00:00:00                   1333  3339072.         456700000000
 2 2019-02-01 00:00:00                    915  4567582.         904600000000
 3 2019-03-01 00:00:00                   1433  7887962.         247900000000
 4 2019-04-01 00:00:00                   1444  3454559.         905700000000
 5 2019-05-01 00:00:00                   1231  9082390.         245600000000
 6 2019-06-01 00:00:00                    346   781224.         346700000000

How can I simplify this code to a for loop?

df %>%
filter(year(df$date) == 2017) %>%
mutate(correlation = cor(x, y))

df %>%
filter(year(df$date) == 2018) %>%
mutate(correlation = cor(x, y))

df %>%
filter(year(df$date) == 2019) %>%
mutate(correlation = cor(x, y))

df %>%
filter(year(df$date) == 2020) %>%
mutate(correlation = cor(x, y))

That's what I tried so far, but I've got some NAs:

years <- c(2017, 2018, 2019, 2020)
for (y in years) {
  df %>%
    filter(date == y) %>%
    mutate(correlation = cor(x, y))
    print(df$correlation[y])
}

My desired output would be something like

[1] 2017: 0.23
[1] 2018: -0.38
[1] 2019: 0.40
[1] 2020: 0.15

Body:
You can group_by year and calculate correlation for x and y in each year. Also since correlation would give you only one number for each year it is better to summarise instead of mutate because mutate would repeat the same value for all rows.

library(dplyr)
library(lubridate)

df %>% group_by(year = year(date)) %>% summarise(correlation = cor(x, y))


问:
git reset --hard ~1 too many times, deleted files
I was trying to squash my commits and went too far back, now all my files have been deleted.

I attempted a git reset HEAD@{0} but this ended up with a "Unstaged changes after reset:" and a list of the DELETED files. The files had not been restored.

How do I restore the files?

EDITED to note that I also did not commit the most recent changes I had made but I had done a git add . and I need those changes back

答:
Perhaps the easiest fix you could try now would be to just hard reset your local branch to is remote tracking branch.  Assuming your local branch is called local, you may try:

```<code># from local
git reset --hard origin/local
</code>```

This would leave your local branch in the state it was last time you committed.  If you have already committed the result of the squash, then this approach won't work.  In that case, you might have to git reflog and try to find the commit to which you want to reset your branch.

Body:
Perhaps the easiest fix you could try now would be to just hard reset your local branch to is remote tracking branch.  Assuming your local branch is called local, you may try:

# from local
git reset --hard origin/local

This would leave your local branch in the state it was last time you committed.  If you have already committed the result of the squash, then this approach won't work.  In that case, you might have to git reflog and try to find the commit to which you want to reset your branch.


问:
Make button width fit to the text
While I was fiddling with this 'Fancy 3D Button' example, I found that the width seemed to be hard-coded to fit the text's width.

Here is the HTML / CSS:

body {
  background-image: url(http://subtlepatterns.com/patterns/ricepaper.png)
}
a {
  position: relative;
  color: rgba(255, 255, 255, 1);
  text-decoration: none;
  background-color: rgba(219, 87, 5, 1);
  font-family: 'Yanone Kaffeesatz';
  font-weight: 700;
  font-size: 3em;
  display: block;
  padding: 4px;
  -webkit-border-radius: 8px;
  -moz-border-radius: 8px;
  border-radius: 8px;
  -webkit-box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  -moz-box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  margin: 100px auto;
  width: 160px;
  text-align: center;
  -webkit-transition: all .1s ease;
  -moz-transition: all .1s ease;
  -ms-transition: all .1s ease;
  -o-transition: all .1s ease;
  transition: all .1s ease;
}
a:active {
  -webkit-box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  -moz-box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  position: relative;
  top: 6px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:700' rel='stylesheet' type='text/css'>

Push me!</code>```

If I remove the width property, the button would fill the page width.

Is there any way to make the button's width fit to the text, automatically?

答: If you are aiming for maximum browser support, modern approach is to place button in a div with display:flex; and flex-direction:row; The same trick will work for height with flex-direction:column; or both height and width(will require 2 divs)

Title: Make button width fit to the text

Body:
While I was fiddling with this 'Fancy 3D Button' example, I found that the width seemed to be hard-coded to fit the text's width.

Here is the HTML / CSS:

body {
  background-image: url(http://subtlepatterns.com/patterns/ricepaper.png)
}
a {
  position: relative;
  color: rgba(255, 255, 255, 1);
  text-decoration: none;
  background-color: rgba(219, 87, 5, 1);
  font-family: 'Yanone Kaffeesatz';
  font-weight: 700;
  font-size: 3em;
  display: block;
  padding: 4px;
  -webkit-border-radius: 8px;
  -moz-border-radius: 8px;
  border-radius: 8px;
  -webkit-box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  -moz-box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  margin: 100px auto;
  width: 160px;
  text-align: center;
  -webkit-transition: all .1s ease;
  -moz-transition: all .1s ease;
  -ms-transition: all .1s ease;
  -o-transition: all .1s ease;
  transition: all .1s ease;
}
a:active {
  -webkit-box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  -moz-box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  position: relative;
  top: 6px;
}

<link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:700' rel='stylesheet' type='text/css'>

Push me!

If I remove the width property, the button would fill the page width.

Is there any way to make the button's width fit to the text, automatically?


问:
How Can I Send Multiple Events To an Outlook 2003 Calendar in 3 or less clicks?
Basically I want someone to be able to click a bunch of events on my website, and have them all synced in a pain-free way to their primary Outlook calendar.

I know I can send an ics with multiple events in it, but this creates a second calendar (unless you import the calendar which is more than 3 clicks).

I can also have a user sync to a webcal, but that doesn't work in Outlook 2003 or earlier (and also creates a second calendar).

I can also send an email with meeting requests, but that's O(n) (accept each request

This has to work in Firefox too, so no ActiveXObject hackery.

Three clicks is the "spirit" of the answer.  If it takes 4, that's fine.

So far webcal is the best I've got, but being able to stick the events in their original Calendar would be better.

EDIT:  Recurrence Rules have been mentioned - Is there a way to use RRULE (BYDAY, BYMONTH, etc) to lump all the events into one VEVENT, and then set the Summary/Description differently for each one?  This would be a perfect solution.

EDIT2:  Yeah actually Outlook doesn't support recurrences on the same day (or any of the nice BYMONTHDAY, SECONDS etc parameters).  So recurrence can't make arbitrary event times in Outlook.

答:
It can't be done the way I want - Outlook sucks.

Best options:

If you're ok with a second calendar:

Give them a link to a webcal://blah.com/blah.ics that they can subscribe to and keep forever up to date with Outlook 2007.  With Outlook 2003 it'll be static.

If you're ok with 1 event per day and only one set of description for all your events combined:

Give them a single event with RDATE usedto set arbitrary recurrence.

If you only support IE:

ActiveXObject - but don't do this unless you're a jerk.

If you can't afford the above:

Gotta do one event at a time.  Sucks.

OwnerDisplayName: Adam A

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Adam A


问:
Unable to retrieve data from Cassandra
I cannot retrieve data from Cassandra after I exit the cli. When I go back to get the data in another session, I get this error:

org.apache.cassandra.db.marshal.MarshalException: cannot parse 'jsmith' as hex bytes

It seems the column family stays and the keyspace too.

I also changed the keys format to ascii (assume Users keys as ascii;)... And that does not stay set either.

Is there a reason why? What is going on?

答:
All of the "assume" commands are temporary and limited to a single cli session. For those not sitting in front of the cli right now, we're referring to these:

```<code>assume <cf> comparator as <type>;
assume <cf> sub_comparator as <type>;
assume <cf> validator as <type>;
assume <cf> keys as <type>;

Assume one of the attributes (comparator, sub_comparator, validator or keys)
of the given column family match specified type. The specified type will
be used when displaying data returned from the column family.
</code>```

These are purely client side.

What you want to do instead is to record that metadata permanently in the ColumnFamily definition, e.g. from the readme,

```<code>create column family Users with comparator=UTF8Type and default_validation_class=UTF8Type and key_validation_class=UTF8Type;
</code>```

This is different from "assume" in 3 ways:

It is permanently recorded in Cassandra

Cassandra will enforce the specified type against data inserted

All clients can query and use this metadata to do intelligent things with it, not just the cli

Assume is primarily there as a workaround for old data sets that cannot be updated to use a "real" server-side type.

Title: Unable to retrieve data from Cassandra

Body:
All of the "assume" commands are temporary and limited to a single cli session. For those not sitting in front of the cli right now, we're referring to these:

assume <cf> comparator as <type>;
assume <cf> sub_comparator as <type>;
assume <cf> validator as <type>;
assume <cf> keys as <type>;

Assume one of the attributes (comparator, sub_comparator, validator or keys)
of the given column family match specified type. The specified type will
be used when displaying data returned from the column family.

These are purely client side.

What you want to do instead is to record that metadata permanently in the ColumnFamily definition, e.g. from the readme,

create column family Users with comparator=UTF8Type and default_validation_class=UTF8Type and key_validation_class=UTF8Type;

This is different from "assume" in 3 ways:

It is permanently recorded in Cassandra

Cassandra will enforce the specified type against data inserted

All clients can query and use this metadata to do intelligent things with it, not just the cli

Assume is primarily there as a workaround for old data sets that cannot be updated to use a "real" server-side type.


问:
Slow performance observed when inserting data into Hudi table
I am using Datasource Writer API to write 5000 records into Hudi copy-on-write table, each with 8 columns and the total size is less than 1Mb. Please refer to the below code.

```<code>        Dataset<Row> ds1 = spark.read().json(jsc.parallelize(records, 2));
        DataFrameWriter<Row> writer = ds1.write().format("org.apache.hudi")
                .option("hoodie.insert.shuffle.parallelism", 2)
                .option("hoodie.upsert.shuffle.parallelism", 2)
                .option(DataSourceWriteOptions.OPERATION_OPT_KEY(), DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL())
                .option(DataSourceWriteOptions.TABLE_TYPE_OPT_KEY(), tableType)
                .option(DataSourceWriteOptions.RECORDKEY_FIELD_OPT_KEY(), recordKey)
                .option(DataSourceWriteOptions.PARTITIONPATH_FIELD_OPT_KEY(), partitionPath)
                .option(DataSourceWriteOptions.PRECOMBINE_FIELD_OPT_KEY(), precombineKey)
                .option(HoodieWriteConfig.TABLE_NAME, hudiTableName)

                .option(DataSourceWriteOptions.HIVE_TABLE_OPT_KEY(), hudiTableName)
                .option(DataSourceWriteOptions.HIVE_DATABASE_OPT_KEY(), hiveDatabase)
                .option(DataSourceWriteOptions.HIVE_URL_OPT_KEY(), hiveServerUrl)
                .option(DataSourceWriteOptions.HIVE_USER_OPT_KEY(), hiveUser)
                .option(DataSourceWriteOptions.HIVE_PASS_OPT_KEY(), hivePassword)
                .option(DataSourceWriteOptions.HIVE_SYNC_ENABLED_OPT_KEY(), hiveSyncEnabled)
                .option(DataSourceWriteOptions.HIVE_PARTITION_FIELDS_OPT_KEY(), partitionPath)
                .mode(SaveMode.Append);

        writer.save(basePath);
</code>```

Application is submitted to yarn through spark-submit. At the beginning, it only takes 3~4 seconds to finish the insert operation, but it gets longer and longer, say 30 seconds after 5 minutes.
From the below spark logs, it shows that most of time is spent on HoodieSparkSqlWriter count task.

```<code>2020-05-25 16:36:37,851 | INFO  | [dag-scheduler-event-loop] | Adding task set 185.0 with 1 tasks | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:36:37,851 | INFO  | [dispatcher-event-loop-0] | Starting task 0.0 in stage 185.0 (TID 190, node-ana-corepOlf, executor 2, partition 0, NODE_LOCAL, 7651 bytes) | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:36:37,858 | INFO  | [dispatcher-event-loop-1] | Added broadcast_124_piece0 in memory on node-ana-corepOlf:36554 (size: 138.1 KB, free: 29.2 GB) | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:36:37,887 | INFO  | [dispatcher-event-loop-1] | Asked to send map output locations for shuffle 53 to 10.155.114.97:32461 | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:37:11,098 | INFO  | [dispatcher-event-loop-0] | Added rdd_381_0 in memory on node-ana-corepOlf:36554 (size: 387.0 B, free: 29.2 GB) | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:37:11,111 | INFO  | [task-result-getter-2] | Finished task 0.0 in stage 185.0 (TID 190) in 33260 ms on node-ana-corepOlf (executor 2) (1/1) | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:37:11,111 | INFO  | [task-result-getter-2] | Removed TaskSet 185.0, whose tasks have all completed, from pool  | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:37:11,112 | INFO  | [dag-scheduler-event-loop] | ResultStage 185 (count at HoodieSparkSqlWriter.scala:254) finished in 33.308 s | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:37:11,113 | INFO  | [Driver] | Job 70 finished: count at HoodieSparkSqlWriter.scala:254, took 33.438673 s | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
</code>```

I tried to tune the parameter hoodie.insert.shuffle.parallelism to 20, but did not help. And the CPU/Heap usages are all normal.

Below is the setting for application. Any advice is appreciated.

```<code>Executor instance: 2
Executor memory: 55g
Executor cores: 4
Driver memory: 4g

</code>```

答: you would ask for help in dev@hudi.apache.org ML or github issues.</p>

Body:
I am using Datasource Writer API to write 5000 records into Hudi copy-on-write table, each with 8 columns and the total size is less than 1Mb. Please refer to the below code.

        Dataset<Row> ds1 = spark.read().json(jsc.parallelize(records, 2));
        DataFrameWriter<Row> writer = ds1.write().format("org.apache.hudi")
                .option("hoodie.insert.shuffle.parallelism", 2)
                .option("hoodie.upsert.shuffle.parallelism", 2)
                .option(DataSourceWriteOptions.OPERATION_OPT_KEY(), DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL())
                .option(DataSourceWriteOptions.TABLE_TYPE_OPT_KEY(), tableType)
                .option(DataSourceWriteOptions.RECORDKEY_FIELD_OPT_KEY(), recordKey)
                .option(DataSourceWriteOptions.PARTITIONPATH_FIELD_OPT_KEY(), partitionPath)
                .option(DataSourceWriteOptions.PRECOMBINE_FIELD_OPT_KEY(), precombineKey)
                .option(HoodieWriteConfig.TABLE_NAME, hudiTableName)

                .option(DataSourceWriteOptions.HIVE_TABLE_OPT_KEY(), hudiTableName)
                .option(DataSourceWriteOptions.HIVE_DATABASE_OPT_KEY(), hiveDatabase)
                .option(DataSourceWriteOptions.HIVE_URL_OPT_KEY(), hiveServerUrl)
                .option(DataSourceWriteOptions.HIVE_USER_OPT_KEY(), hiveUser)
                .option(DataSourceWriteOptions.HIVE_PASS_OPT_KEY(), hivePassword)
                .option(DataSourceWriteOptions.HIVE_SYNC_ENABLED_OPT_KEY(), hiveSyncEnabled)
                .option(DataSourceWriteOptions.HIVE_PARTITION_FIELDS_OPT_KEY(), partitionPath)
                .mode(SaveMode.Append);

        writer.save(basePath);

Application is submitted to yarn through spark-submit. At the beginning, it only takes 3~4 seconds to finish the insert operation, but it gets longer and longer, say 30 seconds after 5 minutes.
From the below spark logs, it shows that most of time is spent on HoodieSparkSqlWriter count task.

2020-05-25 16:36:37,851 | INFO  | [dag-scheduler-event-loop] | Adding task set 185.0 with 1 tasks | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:36:37,851 | INFO  | [dispatcher-event-loop-0] | Starting task 0.0 in stage 185.0 (TID 190, node-ana-corepOlf, executor 2, partition 0, NODE_LOCAL, 7651 bytes) | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:36:37,858 | INFO  | [dispatcher-event-loop-1] | Added broadcast_124_piece0 in memory on node-ana-corepOlf:36554 (size: 138.1 KB, free: 29.2 GB) | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:36:37,887 | INFO  | [dispatcher-event-loop-1] | Asked to send map output locations for shuffle 53 to 10.155.114.97:32461 | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:37:11,098 | INFO  | [dispatcher-event-loop-0] | Added rdd_381_0 in memory on node-ana-corepOlf:36554 (size: 387.0 B, free: 29.2 GB) | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:37:11,111 | INFO  | [task-result-getter-2] | Finished task 0.0 in stage 185.0 (TID 190) in 33260 ms on node-ana-corepOlf (executor 2) (1/1) | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:37:11,111 | INFO  | [task-result-getter-2] | Removed TaskSet 185.0, whose tasks have all completed, from pool  | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:37:11,112 | INFO  | [dag-scheduler-event-loop] | ResultStage 185 (count at HoodieSparkSqlWriter.scala:254) finished in 33.308 s | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)
2020-05-25 16:37:11,113 | INFO  | [Driver] | Job 70 finished: count at HoodieSparkSqlWriter.scala:254, took 33.438673 s | org.apache.spark.internal.Logging$class.logInfo(Logging.scala:54)

I tried to tune the parameter hoodie.insert.shuffle.parallelism to 20, but did not help. And the CPU/Heap usages are all normal.

Below is the setting for application. Any advice is appreciated.

Executor instance: 2
Executor memory: 55g
Executor cores: 4
Driver memory: 4g