问:
How do you set the maven artifact ID of a Gradle project?
From the gradle maven-publish plugin's documentation, it's clear that you set the groupId and version of the project directly in build.gradle:

```<code>group = 'org.gradle.sample'
version = '1.0'
</code>```

However, the artifactId appears to be taken from the name of the folder you are working within.  Is there a way to set the artifactId explicitly?

答:
This is how I did that for my Android library. The solution is in Kotlin DSL (build.gradle.kts):

plugins {
    id("maven-publish")
    // ...
}

afterEvaluate {
    publishing {
        publications {
            create<MavenPublication>("Release") {
                // ...
                groupId = "ir.mahozad.android"
                artifactId = "pie-chart"
                version = project.version.toString()
                artifact(sourcesArtifact)
                artifact(javadocArtifact)
                // ...
            }
        }
    }
}
```

You can see the complete build script file here.

See a similar answer here.

Body:
From the gradle maven-publish plugin's documentation, it's clear that you set the groupId and version of the project directly in build.gradle:

group = 'org.gradle.sample'
version = '1.0'

However, the artifactId appears to be taken from the name of the folder you are working within.  Is there a way to set the artifactId explicitly?

Body:
This is how I did that for my Android library. The solution is in Kotlin DSL (build.gradle.kts):

plugins {
    id("maven-publish")
    // ...
}

afterEvaluate {
    publishing {
        publications {
            create<MavenPublication>("Release") {
                // ...
                groupId = "ir.mahozad.android"
                artifactId = "pie-chart"
                version = project.version.toString()
                artifact(sourcesArtifact)
                artifact(javadocArtifact)
                // ...
            }
        }
    }
}

You can see the complete build script file here.

See a similar answer here.


来源: stackexchange

问:
Trouble with collapsing factor on y axis in ggplot 2
I am having a problem. My ggplot keeps collapsing two equally named vectors into one and I would like to have it as two separate bars labeled QVAR REDIHALER and the rest of the labels of course.

```<code>data.frame(
brand_name = c("QVAR REDIHALER", "QVAR REDIHALER", "XARELTO", "XIFAXAN", "LATUDA", "TRINTELLIX", "VYVANSE", "NUCYNTA"),
n = c(78, 48, 71, 26, 8, 5, 8, 1))

brand_name1 %>%
  ggplot(mapping = aes(x = reorder(brand_name, (-n)), y = n, fill = brand_name)) +
  geom_bar(stat = "identity", position = "dodge", ) +
  geom_text(aes(label = n), position = position_dodge(width = 0.9), hjust = -1) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  theme(plot.title = element_text(face = "bold"),
        axis.text.y = element_text(size = 14, colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank()) +
  ylab("Count") +
  xlab("") +
  labs(fill = "Brand name", title = "Top Rebate Eligable - Brand") +
  scale_fill_brewer(palette = "Set2") +
  coord_flip()
</code>```

The issue is where the arrow is pointed. I would like to have "QVAR REDIHALER" repeat twice as in data frame instead of it collapsing to one bar

答:
Not 100% sure about how you want to split the duplicated category into two columns. But I give it a try.

One option would be to make the duplicated categories unique by using a helper column e.g. adding a number 1, 2, ... to each and mapping this helper column on y. Doing so you get separate columns. To get rid of the numbers showing up on the axis labels you could make use of a labeller function via scale_y_discrete, i.e. use e.g. gsub to remove the numbers:

library(ggplot2)
library(dplyr)

brand_name1 <- brand_name1 %>%
  group_by(brand_name) %>%
  mutate(brand_name_uniq = paste0(brand_name, row_number()))

ggplot(brand_name1, mapping = aes(x = reorder(brand_name_uniq, (-n)), y = n, fill = brand_name)) +
  geom_bar(stat = "identity", position = "dodge", ) +
  geom_text(aes(label = n), position = position_dodge(width = 0.9), hjust = -1) +
  scale_x_discrete(labels = ~gsub("\\d$", "", .x)) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  theme(plot.title = element_text(face = "bold"),
        axis.text.y = element_text(size = 14, colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank()) +
  ylab("Count") +
  xlab("") +
  labs(fill = "Brand name", title = "Top Rebate Eligable - Brand") +
  scale_fill_brewer(palette = "Set2") +
  coord_flip()
```

ContentLicense: CC BY-SA 4.0

Body:
I am having a problem. My ggplot keeps collapsing two equally named vectors into one and I would like to have it as two separate bars labeled QVAR REDIHALER and the rest of the labels of course.

data.frame(
brand_name = c("QVAR REDIHALER", "QVAR REDIHALER", "XARELTO", "XIFAXAN", "LATUDA", "TRINTELLIX", "VYVANSE", "NUCYNTA"),
n = c(78, 48, 71, 26, 8, 5, 8, 1))

brand_name1 %>%
  ggplot(mapping = aes(x = reorder(brand_name, (-n)), y = n, fill = brand_name)) +
  geom_bar(stat = "identity", position = "dodge", ) +
  geom_text(aes(label = n), position = position_dodge(width = 0.9), hjust = -1) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  theme(plot.title = element_text(face = "bold"),
        axis.text.y = element_text(size = 14, colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank()) +
  ylab("Count") +
  xlab("") +
  labs(fill = "Brand name", title = "Top Rebate Eligable - Brand") +
  scale_fill_brewer(palette = "Set2") +
  coord_flip()

The issue is where the arrow is pointed. I would like to have "QVAR REDIHALER" repeat twice as in data frame instead of it collapsing to one bar


问:
Prevent submit form with ENTER jquery not working with alerts
I have a form with a text input.

I managed to prevent ENTER from submitting the form by doing this:

```<code>jQuery("#inputTags").keydown(function(event) {
      if (event.keyCode == '13') {
         event.preventDefault();

         tagManagerCreate(true);

         return false;
      }
    });
</code>```

tagManagerCreate() does some stuff. Sometimes, this function triggers a javascript "alert".
For some reason when that happens, the form still gets submitted!

答:
I think you should use .keypress instead of .keydown

http://api.jquery.com/keypress/

http://api.jquery.com/keydown/

and what the tagManagerCreate(true); do?

ContentLicense: CC BY-SA 3.0

Body:
I have a form with a text input.

I managed to prevent ENTER from submitting the form by doing this:

jQuery("#inputTags").keydown(function(event) {
      if (event.keyCode == '13') {
         event.preventDefault();

         tagManagerCreate(true);

         return false;
      }
    });

tagManagerCreate() does some stuff. Sometimes, this function triggers a javascript "alert".
For some reason when that happens, the form still gets submitted!


问:
Implementation of a lock using test and set
Below is the code is given in OSTEP book regarding the implementation of a lock using test and set instruction. My question is that in such implementation, couldn't a thread that is not holding the lock call the unlock function and take away the lock?</p>

```<code>typedef struct __lock_t {
 int flag;
 } lock_t;

 void init(lock_t *lock) {
 // 0 indicates that lock is available, 1 that it is held
 lock->flag = 0;
 }

 void lock(lock_t *lock) {
 while (TestAndSet(&lock->flag, 1) == 1)
 ; // spin-wait (do nothing)
 }

 void unlock(lock_t *lock) {
 lock->flag = 0;
 }
</code>```

答:
My question is that in such implementation, couldn't a thread that is not holding the lock call the unlock function and take away the lock?

There's nothing wrong with (e.g.) one thread acquiring a lock, notifying another thread that it can proceed (or maybe spawning a new thread), then the other thread releasing the lock.

Something is very wrong if a single thread acquires a lock and then releases it twice.

To detect bugs (while still supporting all legitimate scenarios), you'd want to detect "unlock() called when lock not held". You could do that by using an atomic TestAndClear() in the unlock().

If you want to enforce "only the thread that acquired the lock may release the lock" then you have to know which thread acquired the lock, so you have to store a thread ID in the lock when its acquired (e.g. maybe by using an atomic "compare, and exchange if it was equal").

Body:
Below is the code is given in OSTEP book regarding the implementation of a lock using test and set instruction. My question is that in such implementation, couldn't a thread that is not holding the lock call the unlock function and take away the lock?

typedef struct __lock_t {
 int flag;
 } lock_t;

 void init(lock_t *lock) {
 // 0 indicates that lock is available, 1 that it is held
 lock->flag = 0;
 }

 void lock(lock_t *lock) {
 while (TestAndSet(&lock->flag, 1) == 1)
 ; // spin-wait (do nothing)
 }

 void unlock(lock_t *lock) {
 lock->flag = 0;
 }


问:
R handle vector values in addition to scalar values with rounding function
```<code>round2 <- function(x, y) {
  if(is.na(x)) { return ('') }
  return(paste0(round(100 * x, 0), '% ', round(100 * y, 0), '%'))
}

mydf <- data.frame(a = c(NA, .323, .555), b = c(NA, .232, .541))
mydf %>% dplyr::mutate(c = round2(a, b))
</code>```

The main part of the function paste0(round(...)) works just fine, however the if(is.na(x)) { return ('') } does not properly handle that x and y are vectors. As a result, the entire column c in mydf is an empty string. How can we update this so only the first row in mydf returns an empty string?

答:
if/else are not vectorized - expect a single TRUE/FALSE it can work if we use rowwise as grouping

```<code>library(dplyr)
mydf %>%
   rowwise %>%
   dplyr::mutate(c = round2(a, b)) %>%
   ungroup
</code>```

-output

```<code># A tibble: 3 × 3
       a      b c
   <dbl>  <dbl> <chr>
1 NA     NA     ""
2  0.323  0.232 "32% 23%"
3  0.555  0.541 "56% 54%"
</code>```

as grouping or Vectorize the function

```<code>mydf %>%
   dplyr::mutate(c = Vectorize(round2)(a, b))
</code>```

If we want to create a vectorized function, make use of ifelse/case_when etc which are already vectorized

```<code>round2new <- function(x, y) {
    case_when(is.na(x) ~ "",
   TRUE ~ paste0(round(100 * x, 0), '% ', round(100 * y, 0), '%'))
}
mydf %>%
   dplyr::mutate(c = round2new(a, b))
      a     b       c
1    NA    NA
2 0.323 0.232 32% 23%
3 0.555 0.541 56% 54%
</code>```

NOTE: Calling Vectorize or using rowwise grouping is iterating over each row and will be slower than making use of vectorized functions (ifelse/case_when/if_else) while constructing the function

Body:
round2 <- function(x, y) {
  if(is.na(x)) { return ('') }
  return(paste0(round(100 * x, 0), '% ', round(100 * y, 0), '%'))
}

mydf <- data.frame(a = c(NA, .323, .555), b = c(NA, .232, .541))
mydf %>% dplyr::mutate(c = round2(a, b))

The main part of the function paste0(round(...)) works just fine, however the if(is.na(x)) { return ('') } does not properly handle that x and y are vectors. As a result, the entire column c in mydf is an empty string. How can we update this so only the first row in mydf returns an empty string?

Body:
if/else are not vectorized - expect a single TRUE/FALSE it can work if we use rowwise as grouping

library(dplyr)
mydf %>%
   rowwise %>%
   dplyr::mutate(c = round2(a, b)) %>%
   ungroup

-output

# A tibble: 3 × 3
       a      b c
   <dbl>  <dbl> <chr>
1 NA     NA     ""
2  0.323  0.232 "32% 23%"
3  0.555  0.541 "56% 54%"

as grouping or Vectorize the function

mydf %>%
   dplyr::mutate(c = Vectorize(round2)(a, b))

If we want to create a vectorized function, make use of ifelse/case_when etc which are already vectorized

round2new <- function(x, y) {
    case_when(is.na(x) ~ "",
   TRUE ~ paste0(round(100 * x, 0), '% ', round(100 * y, 0), '%'))
}
mydf %>%
   dplyr::mutate(c = round2new(a, b))
      a     b       c
1    NA    NA
2 0.323 0.232 32% 23%
3 0.555 0.541 56% 54%

NOTE: Calling Vectorize or using rowwise grouping is iterating over each row and will be slower than making use of vectorized functions (ifelse/case_when/if_else) while constructing the function


问:
'function' object has no attribute 'dumps'
I imported pickle from copyreg.
I then use the attribute dumps to convert a dictionary into bytes b'\x80\x04...' but it results in the error shown below:

```<code>from copyreg import pickle
d={"name":value}
d=pickle.dumps(d)
</code>```

Error:

```<code>AttributeError: 'function' object has no attribute
</code>```

答:
I imported from the wrong library.
The code should have been:</p>
```<code>import pickle
d={...}
d=pickle.dumps(d)
</code>```

Body:
I imported pickle from copyreg.
I then use the attribute dumps to convert a dictionary into bytes b'\x80\x04...' but it results in the error shown below:

from copyreg import pickle
d={"name":value}
d=pickle.dumps(d)

Error:

AttributeError: 'function' object has no attribute

Body:
I imported from the wrong library.
The code should have been:

import pickle
d={...}
d=pickle.dumps(d)


问:
Refresh other frame, from another frame. Jquery
Is it possible to reload the page, where the user came from or, even better, reload the frame the user came from, if it matches an URL?

I have a link. The user clicks it, and it opens in a new window, a new url. A form will run in that new window. What I want, is a function to reload the first window (Where the user came from)

Is that possible?

答:
Alright. Here is what you do (just an example, tested, works):

test.html

```<code><frameset cols="50%, 50%">
<frame name="f1" src="frame1.html">
<frame name="f2" src="frame2.html">
</frameset>
</code>```

frame1.html

```<code><input type="button" name="test" value="Refresh" onclick="parent.f2.location.reload()">
</code>```

frame2.html

```<code><span>Hello World</span>
</code>```

variable parent is the parent of the current frame.

Read this page. its really helpful

Hope that helps

Body:
Alright. Here is what you do (just an example, tested, works):

test.html

<frameset cols="50%, 50%">
<frame name="f1" src="frame1.html">
<frame name="f2" src="frame2.html">
</frameset>

frame1.html

<input type="button" name="test" value="Refresh" onclick="parent.f2.location.reload()">

frame2.html

<span>Hello World</span>

variable parent is the parent of the current frame.

Read this page. its really helpful

Hope that helps


问:
Getting wrong output in C program
Expected output : "total is equal to 114"

Current output : "total is equal to -334"

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

#define SZ 3

int main(void) {
    int i, one = 0, two = 0, total = 0;

    printf(
        "Enter two whole numbers separated by a space: ");  // user enters 56 2

    total = scanf("%d %d", &two, &one);

    for (i = 0; i < SZ; i++) {
        if (i / two) {
            total = two + one / total;
        } else {
            total -= one * two;
        }
    }

    printf("total is equal to %d\n", total);

    return 0;
}
</code>```

答:
if(i / two) is always false:

1st iteration -> 0 / 56 = 0

2nd iteration -> 1 / 56 = 0.02 which is treatead as int, so 0

3rd iteration -> 2 / 56 = 0.04 same as before

Given the above, and knowing that 0 is false, only the else block is executed 3 times, since scanf returns the number of read inputs, which is 2, and you assign it to total, total begins with the value 2, so:

2 -= 56 * 2 is -110

-110 -= 56 * 2 is -222

-222 -= 56 * 2 is -334

And that's how you get that value.

As for the 114 value you want, it's not clear how or for what reason or logic it should be achieved.

Title: Getting wrong output in C program

Body:
Expected output : "total is equal to 114"

Current output : "total is equal to -334"

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

#define SZ 3

int main(void) {
    int i, one = 0, two = 0, total = 0;

    printf(
        "Enter two whole numbers separated by a space: ");  // user enters 56 2

    total = scanf("%d %d", &two, &one);

    for (i = 0; i < SZ; i++) {
        if (i / two) {
            total = two + one / total;
        } else {
            total -= one * two;
        }
    }

    printf("total is equal to %d\n", total);

    return 0;
}


问:
LNK2038 mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MTd_StaticDebug' in xxx.obj
I am building my application in debug mode using VS 2017. I have built the  3rd party libraries in release mode that it depends on and links to. Is this allowed or is that the cause of the reported error.

```<code>LNK2038 mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MTd_StaticDebug' in xxx.obj   my-application  <path-to>\libboost_filesystem-mt-s.lib(path_traits.obj) 1
</code>```

This page states:

RuntimeLibrary
  Indicates the version of the C++ Standard Library and C runtime that's used by an app or library. Code that uses one version of the C++ Standard Library or C runtime is incompatible with code that uses a different version. For more information, see /MD, /MT, /LD (Use Run-Time Library).

I understand that the DLL runtime library can't be mixed with the non-DLL library. Is the same true for the debug and release libraries?

I haven't had any problems doing the same thing on Linux.

答:
No, you cannot mix debug and release runtime libraries with Visual Studio 2017. They are not ABI compatible.

There additional checks and member variables for debug checks in the C++ runtime and the memory allocation routines add additional space and checks in debug mode.

Example code taken from <xmemory0> (_Adjust_manually_vector_aligned)

```<code>    // Extra paranoia on aligned allocation/deallocation; ensure _Ptr_container is
    // in range [_Min_back_shift, _Non_user_size]
  #ifdef _DEBUG
    constexpr uintptr_t _Min_back_shift = 2 * sizeof(void *);
  #else /* ^^^ _DEBUG ^^^ // vvv !_DEBUG vvv */
    constexpr uintptr_t _Min_back_shift = sizeof(void *);
  #endif /* _DEBUG */
    const uintptr_t _Back_shift = reinterpret_cast<uintptr_t>(_Ptr) - _Ptr_container;
    _STL_VERIFY(_Back_shift >= _Min_back_shift && _Back_shift <= _Non_user_size, "invalid argument");
</code>```

Here the _DEBUG variant of the function allocates additional 2 * sizeof(void*) for checks, whereas the release variant uses only sizeof(void*).

From here it is quite obvious that a pointer created by the release variant and used by the debug variant (or vice versa) would trigger all kinds of confusion and error checks.

Hence the Linker error to prevent this from happening.

That said, it would be possible to mix them under specific circumstances, although I would not recommend it.

You must basically create two partitions, which have a very tight and narrow interface. You must make sure that no data of any kind except PODs or fully opaque data types are transferred between "partitions". Also you cannot statically link both debug and release libraries (because of ABI and symbol clashes) to the same binary.

So you could create an std::string in your 'Debug' routine, but wouldn't be allowed to pass this to a 'Release' routine. But you would be able to pass the 'std::string::c_str()' return value to the 'Release' routine, because that is just a pointer to char.

To do that you would put all 'release' binaries in one DLL and statically link this DLL with the static 'release' runtime and put all 'debug' binaries in another DLL (or EXE) and statically link this with the 'debug' runtime. That way the runtimes are completely hidden inside their respective DLLs and are not visible to the outside world.

(It is possible to link one or more DLLs with a static runtime and others with the dynamic runtime. But again, I wouldn't recommend it).

Basically this is what happens, when you run your 'debug' application under Windows. You don't need a 'Debug' Windows to run your 'Debug' application. Your 'Debug' application runs fine with the 'Release' Windows, which is using its own 'release' runtimes. It's just that the 'release' runtime used by Windows is completely hidden from your 'debug' release time.

Body:
I am building my application in debug mode using VS 2017. I have built the  3rd party libraries in release mode that it depends on and links to. Is this allowed or is that the cause of the reported error.

LNK2038 mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MTd_StaticDebug' in xxx.obj   my-application  <path-to>\libboost_filesystem-mt-s.lib(path_traits.obj) 1

This page states:

RuntimeLibrary
  Indicates the version of the C++ Standard Library and C runtime that's used by an app or library. Code that uses one version of the C++ Standard Library or C runtime is incompatible with code that uses a different version. For more information, see /MD, /MT, /LD (Use Run-Time Library).

I understand that the DLL runtime library can't be mixed with the non-DLL library. Is the same true for the debug and release libraries?

I haven't had any problems doing the same thing on Linux.

Body:
No, you cannot mix debug and release runtime libraries with Visual Studio 2017. They are not ABI compatible.

There additional checks and member variables for debug checks in the C++ runtime and the memory allocation routines add additional space and checks in debug mode.

Example code taken from <xmemory0> (_Adjust_manually_vector_aligned)

    // Extra paranoia on aligned allocation/deallocation; ensure _Ptr_container is
    // in range [_Min_back_shift, _Non_user_size]
  #ifdef _DEBUG
    constexpr uintptr_t _Min_back_shift = 2 * sizeof(void *);
  #else /* ^^^ _DEBUG ^^^ // vvv !_DEBUG vvv */
    constexpr uintptr_t _Min_back_shift = sizeof(void *);
  #endif /* _DEBUG */
    const uintptr_t _Back_shift = reinterpret_cast<uintptr_t>(_Ptr) - _Ptr_container;
    _STL_VERIFY(_Back_shift >= _Min_back_shift && _Back_shift <= _Non_user_size, "invalid argument");

Here the _DEBUG variant of the function allocates additional 2 * sizeof(void*) for checks, whereas the release variant uses only sizeof(void*).

From here it is quite obvious that a pointer created by the release variant and used by the debug variant (or vice versa) would trigger all kinds of confusion and error checks.

Hence the Linker error to prevent this from happening.

That said, it would be possible to mix them under specific circumstances, although I would not recommend it.

You must basically create two partitions, which have a very tight and narrow interface. You must make sure that no data of any kind except PODs or fully opaque data types are transferred between "partitions". Also you cannot statically link both debug and release libraries (because of ABI and symbol clashes) to the same binary.

So you could create an std::string in your 'Debug' routine, but wouldn't be allowed to pass this to a 'Release' routine. But you would be able to pass the 'std::string::c_str()' return value to the 'Release' routine, because that is just a pointer to char.

To do that you would put all 'release' binaries in one DLL and statically link this DLL with the static 'release' runtime and put all 'debug' binaries in another DLL (or EXE) and statically link this with the 'debug' runtime. That way the runtimes are completely hidden inside their respective DLLs and are not visible to the outside world.

(It is possible to link one or more DLLs with a static runtime and others with the dynamic runtime. But again, I wouldn't recommend it).

Basically this is what happens, when you run your 'debug' application under Windows. You don't need a 'Debug' Windows to run your 'Debug' application. Your 'Debug' application runs fine with the 'Release' Windows, which is using its own 'release' runtimes. It's just that the 'release' runtime used by Windows is completely hidden from your 'debug' release time.


问:
EOF while reading packet - connection failed
I use cyberduck for SFTP my website files to the server. Dreamhost is the server.

In setting up a new bookmark in cyberduck I received this error "Connection failed - EOF while reading packet." [end of file]

The website is up and working fine, http://ce-t.org

Initially I thought this error had to do with the connection opening with cyberduck. So I setup a different bookmark to test and was able to do without a problem.

I have also deleted my first attempt to setup and reset up. This did not alter anything.

Now after doing more reading, may be in one of the website files?

As you can see i am a novice.

Help appreciated.

答:
In my case I have used dropbear ssh server.
I replace this server with openssh server, and now i can open the sftp connection without any issues.</p>


问:
Replace items in array with elements from a different set
I'm not sure the proper way to go about this recursively.
Let's say I have two arrays

```<code>array1 = [a, null, c, d, e]

array2 = [1, 2, 3]
</code>```

I want to create a resulting array of the form

```<code>[
   [a, 1, c, d, e],
   [a, 2, c, d, e],
   [a, 3, c, d, e]
]
</code>```

where each element of the second array fills in the place of null. I was able to do this just fine, but what if I have two cases of null?

```<code>array1 = [a, null, c, null, e]

array2 = [1, 2, 3]
</code>```

how do I get the following?

```<code>[
   [a, 1, c, 1, e],
   [a, 1, c, 2, e],
   [a, 1, c, 3, e],
   [a, 2, c, 1, e],
   ...
   [a, 3, c, 3, e]
]
</code>```

答:
The first case you describe is an instance of map pattern, and the second -- flatMap.

Seen otherwise, map is just like a loop, and flatMap is like a two-level nested loops, creating the result's elements one by one from the deepest level loop:

Map:

```<code>      for x in [1, 2, 3]:
         let res = { result of replacing
                     the first `null` with `x`
                     in [a, null, c, d, e] }
         yield res

             -------------------------
               [a, null, c, d, e]
             ----------------------
   1           [a,  1,   c, d, e],
   2           [a,  2,   c, d, e],
   3           [a,  3,   c, d, e]
</code>```

flatMap:

```<code>      for x in [1, 2, 3]:
         let res = { result of replacing
                     the first `null` with `x`
                     in [a, null, c, null, e] }

         for x in [1, 2, 3]:
             let res2 = { result of replacing
                          the first `null` with `x`
                          in res }                   ## res NB!
             yield res2

             -------------------------
             [  a, null, c, null, e  ]
             -------------------------
   1:        [  a,  1,   c, null, e  ],

        1      [a,  1,   c,   1 , e],
        2      [a,  1,   c,   2 , e],
        3      [a,  1,   c,   3 , e],

   2:        [  a,  2,   c, null, e  ],

        1      [a,  2,   c,   1 , e],
        2      [a,  2,   c,   2 , e],
        3      [a,  2,   c,   3 , e],

   3:        [  a,  3,   c, null, e  ]

        1      [a,  3,   c,   1 , e],
        2      [a,  3,   c,   2 , e],
        3      [a,  3,   c,   3 , e]
</code>```

The first is like replacing each element in [1,2,3] with the replacement result; and the second is like replacing each element in [1,2,3] with the list of the replacement results and appending the resulting lists together; i.e. splicing the resulting lists' elements in place; i.e. creating the combined map, flattened (hence the name, flatMap).

Body:
I'm not sure the proper way to go about this recursively.
Let's say I have two arrays

array1 = [a, null, c, d, e]

array2 = [1, 2, 3]

I want to create a resulting array of the form

[
   [a, 1, c, d, e],
   [a, 2, c, d, e],
   [a, 3, c, d, e]
]

where each element of the second array fills in the place of null. I was able to do this just fine, but what if I have two cases of null?

array1 = [a, null, c, null, e]

array2 = [1, 2, 3]

how do I get the following?

[
   [a, 1, c, 1, e],
   [a, 1, c, 2, e],
   [a, 1, c, 3, e],
   [a, 2, c, 1, e],
   ...
   [a, 3, c, 3, e]
]

Body:
The first case you describe is an instance of map pattern, and the second -- flatMap.

Seen otherwise, map is just like a loop, and flatMap is like a two-level nested loops, creating the result's elements one by one from the deepest level loop:

Map:

      for x in [1, 2, 3]:
         let res = { result of replacing
                     the first `null` with `x`
                     in [a, null, c, d, e] }
         yield res

             -------------------------
               [a, null, c, d, e]
             ----------------------
   1           [a,  1,   c, d, e],
   2           [a,  2,   c, d, e],
   3           [a,  3,   c, d, e]

flatMap:

      for x in [1, 2, 3]:
         let res = { result of replacing
                     the first `null` with `x`
                     in [a, null, c, null, e] }

         for x in [1, 2, 3]:
             let res2 = { result of replacing
                          the first `null` with `x`
                          in res }                   ## res NB!
             yield res2

             -------------------------
             [  a, null, c, null, e  ]
             -------------------------
   1:        [  a,  1,   c, null, e  ],

        1      [a,  1,   c,   1 , e],
        2      [a,  1,   c,   2 , e],
        3      [a,  1,   c,   3 , e],

   2:        [  a,  2,   c, null, e  ],

        1      [a,  2,   c,   1 , e],
        2      [a,  2,   c,   2 , e],
        3      [a,  2,   c,   3 , e],

   3:        [  a,  3,   c, null, e  ]

        1      [a,  3,   c,   1 , e],
        2      [a,  3,   c,   2 , e],
        3      [a,  3,   c,   3 , e]

The first is like replacing each element in [1,2,3] with the replacement result; and the second is like replacing each element in [1,2,3] with the list of the replacement results and appending the resulting lists together; i.e. splicing the resulting lists' elements in place; i.e. creating the combined map, flattened (hence the name, flatMap).


问:
How to make dynamic link in Vue JS?
I have:

```<code><b-dropdown text="Select Factory" block variant="primary" class="m-2" menu-class="w-100">
<b-dropdown-item @click="selectedFactory='China'">China</b-dropdown-item>
<b-dropdown-item @click="selectedFactory='Europe'">Europe</b-dropdown-item>
</b-dropdown>

<b-dropdown text="Select Toy" block variant="primary" class="m-2" menu-class="w-100">
<b-dropdown-item @click="selectedToy='Marvel'">Marvel</b-dropdown-item>
<b-dropdown-item @click="selectedToy='Toy Story'">Toy Story</b-dropdown-item>
</b-dropdown>
</code>```

How can I make this line of code work, such that the source link is dynamic? Currently it does work with the dropdown selection when embeded into an iframe. I am guessing probably something to do with the compute function, am not very sure

```<code>export default {

el: '#apps',
  data () {
     return {

        source:'http://127.0.0.1:5503/src/html/`{{this.selectedFactory}}`_{{this.selectedToy}}.html',
        selectedFactory: '',
        selectedToy:'',
     }
  },
  computed:{

  }

}
</code>```

答:
You should be able to make use of v-bind directive in your template, like so:

{{selectedFactory + selectedToy}}

As for your data property, I believe you can use normal string concatenation to make your dynamic url:

```<code>data () {
     return {
        source:'http://127.0.0.1:5503/src/html/' + this.selectedFactory + '_' + this.selectedToy + '.html',
        selectedFactory: '',
        selectedToy:'',
     }
  }
</code>```

The {{}} double curly brace syntax is for use in your html code of your vue app. Hope it helps!

Title: How to make dynamic link in Vue JS?

Body:
I have:

China
Europe

Marvel
Toy Story

How can I make this line of code work, such that the source link is dynamic? Currently it does work with the dropdown selection when embeded into an iframe. I am guessing probably something to do with the compute function, am not very sure

export default {

el: '#apps',
  data () {
     return {

        source:'http://127.0.0.1:5503/src/html/`{{this.selectedFactory}}`_{{this.selectedToy}}.html',
        selectedFactory: '',
        selectedToy:'',
     }
  },
  computed:{

  }

}

Body:
You should be able to make use of v-bind directive in your template, like so:

<a v-bind:href="source">{{selectedFactory + selectedToy}}</a>

As for your data property, I believe you can use normal string concatenation to make your dynamic url:

data () {
     return {
        source:'http://127.0.0.1:5503/src/html/' + this.selectedFactory + '_' + this.selectedToy + '.html',
        selectedFactory: '',
        selectedToy:'',
     }
  }

The {{}} double curly brace syntax is for use in your html code of your vue app. Hope it helps!


问:
Qt 4.8 how to do get properties of a QPushButton placed in a QList<QWidget *>?
Do someone know a solution to do get properties of a QPushButton placed in a QList<QWidget *> ?

```<code>.h
QList<QWidget *> list;

.cpp
QPushButton *button = new QPushButton("Push", this);
list->append(button);
qDebug() << list.at(0)->text(); // Not working : text() is not a property of QWidget but a property of QPushButton
</code>```

Thx

答:
The problem is more to do with c++ and polymorphism in general rather than anything specific to Qt.  The expression...

```<code>list.at(0)
</code>```

returns a QWidget *.  Hence the call...

```<code>list.at(0)->text()
</code>```

fails to compile as QWidget has no member function named text.  If you think the pointer returned by list.at(0) points to a specific subclass of QWidget then you need to downcast it and check the result before using it.  e.g.

```<code>if (auto *b = dynamic_cast<QPushButton *>(list.at(0)))
    qDebug() << b->text();
</code>```

Alternatively -- since you are using Qt -- you can make use of qobject_cast in a similar fashion...

```<code>if (auto *b = qobject_cast<QPushButton *>(list.at(0)))
    qDebug() << b->text();
</code>```

Body:
Do someone know a solution to do get properties of a QPushButton placed in a QList<QWidget *> ?

.h
QList<QWidget *> list;

.cpp
QPushButton *button = new QPushButton("Push", this);
list->append(button);
qDebug() << list.at(0)->text(); // Not working : text() is not a property of QWidget but a property of QPushButton

Thx

Body:
The problem is more to do with c++ and polymorphism in general rather than anything specific to Qt.  The expression...

list.at(0)

returns a QWidget *.  Hence the call...

list.at(0)->text()

fails to compile as QWidget has no member function named text.  If you think the pointer returned by list.at(0) points to a specific subclass of QWidget then you need to downcast it and check the result before using it.  e.g.

if (auto *b = dynamic_cast<QPushButton *>(list.at(0)))
    qDebug() << b->text();

Alternatively -- since you are using Qt -- you can make use of qobject_cast in a similar fashion...

if (auto *b = qobject_cast<QPushButton *>(list.at(0)))
    qDebug() << b->text();


问:
How to get a contract by a transaction uising web3j?
I need to check if a transaction is a ERC721/ERC1155 transaction and fetch information like receiving address, token address, value, etc. If I understand correctly, I have to load a contract for the transaction and check if it inherits ERC165 in order to confirm that it is a ERC721/ERC1155 transaction.

Problem: I don't understand how I can get a contract having a transaction object. I also haven't found a way to get token address.

I have an Ethereum node on Infura, I read blocks from there and iterate over transactions. I get a transaction and its receipt. My code looks like this:

```<code>var tr = web3j.ethGetTransactionByBlockNumberAndIndex(blockIdParam, transactionIndex).sendAsync().get();
var hash = tr.getTransaction().get().getHash();
var receipt = web3.ethGetTransactionReceipt(hash).send().getTransactionReceipt();
</code>```

Right now I am working in the direction of reading transaction logs, checking their topics and verifying if they include Transfer events. But transfer events are also emitted by ERC20 transactions, so I am a bit confused here.

答:
You're going in the right direction checking the Transfer() event logs. Even though both ERC20 and ERC721 use the same event signature, the ERC721 (NFT) standard defines the 3rd topic (token ID) as indexed, which stores its value in the set of indexed topics. While the ERC20 defines the 3rd topic (amount) as non-indexed, making the total length of indexed topics set just 2.

I picked a random transaction that contains event logs of both ERC20 and ERC721 transfers. Looks like the logic behind it is payment in the form of an ERC20 token to mint a new ERC721 token.

Note: I'm not a Java dev, so I'll use a JS code in my answer that you can hopefully use as a reference to find the correct syntax and methods in the Java implementation of the Web3 library.

```<code>const Web3 = require("web3");
const web3 = new Web3("<provider_url>");

// keccak256 of string "Transfer(address,address,uint256)"
const TRANSFER_SIGNATURE = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";

async function run() {
    const txHash = "0xfb4dc20b4a8d0b72442a396aced0fc537de757c6aac69609ab3d09d19f9c9aa8";
    const txReceipt = await web3.eth.getTransactionReceipt(txHash);

    for (let log of txReceipt.logs) {
        if (_isERC20Log(log)) {
            // Unindexed topics are concatenated in the `data` field.
            // There's only one unindexed topic in this case,
            // so you don't need to do any parsing and just use the whole value.
            const amount = web3.utils.hexToNumberString(log.data);
            console.log("ERC20 token amount: ", amount);
            console.log("ERC20 token contract: ", log.address);
        } else if (_isERC721Log(log)) {
            // 3rd indexed topic
            // index 0 of the array is the event signature, see `_isERC721Log()`
            const tokenId = web3.utils.hexToNumberString(log.topics[3]);
            console.log("ERC721 token ID: ", tokenId);
            console.log("ERC721 token contract: ", log.address);
        }
    }
}

function _isERC20Log(log) {
    return (
        log.topics[0] == TRANSFER_SIGNATURE
        && log.topics.length == 3 // index 0 is the signature, and then 2 indexed topics
    );
}

function _isERC721Log(log) {
    return (
        log.topics[0] == TRANSFER_SIGNATURE
        && log.topics.length == 4 // index 0 is the signature, and then 3 indexed topics
    );
}

run();
</code>```

Output:

```<code>ERC20 token amount:  40000000000000000000
ERC20 token contract:  0x54a7cee7B02976ACE1bdd4aFad87273251Ed34Cf
ERC721 token ID:  12013
ERC721 token contract:  0x41cB4a771FdD019ADBF4685bd4885fbBeedE1784
</code>```

Body:
I need to check if a transaction is a ERC721/ERC1155 transaction and fetch information like receiving address, token address, value, etc. If I understand correctly, I have to load a contract for the transaction and check if it inherits ERC165 in order to confirm that it is a ERC721/ERC1155 transaction.

Problem: I don't understand how I can get a contract having a transaction object. I also haven't found a way to get token address.

I have an Ethereum node on Infura, I read blocks from there and iterate over transactions. I get a transaction and its receipt. My code looks like this:

var tr = web3j.ethGetTransactionByBlockNumberAndIndex(blockIdParam, transactionIndex).sendAsync().get();
var hash = tr.getTransaction().get().getHash();
var receipt = web3.ethGetTransactionReceipt(hash).send().getTransactionReceipt();

Right now I am working in the direction of reading transaction logs, checking their topics and verifying if they include Transfer events. But transfer events are also emitted by ERC20 transactions, so I am a bit confused here.

Body:
You're going in the right direction checking the Transfer() event logs. Even though both ERC20 and ERC721 use the same event signature, the ERC721 (NFT) standard defines the 3rd topic (token ID) as indexed, which stores its value in the set of indexed topics. While the ERC20 defines the 3rd topic (amount) as non-indexed, making the total length of indexed topics set just 2.

I picked a random transaction that contains event logs of both ERC20 and ERC721 transfers. Looks like the logic behind it is payment in the form of an ERC20 token to mint a new ERC721 token.

Note: I'm not a Java dev, so I'll use a JS code in my answer that you can hopefully use as a reference to find the correct syntax and methods in the Java implementation of the Web3 library.

const Web3 = require("web3");
const web3 = new Web3("<provider_url>");

// keccak256 of string "Transfer(address,address,uint256)"
const TRANSFER_SIGNATURE = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";

async function run() {
    const txHash = "0xfb4dc20b4a8d0b72442a396aced0fc537de757c6aac69609ab3d09d19f9c9aa8";
    const txReceipt = await web3.eth.getTransactionReceipt(txHash);

    for (let log of txReceipt.logs) {
        if (_isERC20Log(log)) {
            // Unindexed topics are concatenated in the `data` field.
            // There's only one unindexed topic in this case,
            // so you don't need to do any parsing and just use the whole value.
            const amount = web3.utils.hexToNumberString(log.data);
            console.log("ERC20 token amount: ", amount);
            console.log("ERC20 token contract: ", log.address);
        } else if (_isERC721Log(log)) {
            // 3rd indexed topic
            // index 0 of the array is the event signature, see `_isERC721Log()`
            const tokenId = web3.utils.hexToNumberString(log.topics[3]);
            console.log("ERC721 token ID: ", tokenId);
            console.log("ERC721 token contract: ", log.address);
        }
    }
}

function _isERC20Log(log) {
    return (
        log.topics[0] == TRANSFER_SIGNATURE
        && log.topics.length == 3 // index 0 is the signature, and then 2 indexed topics
    );
}

function _isERC721Log(log) {
    return (
        log.topics[0] == TRANSFER_SIGNATURE
        && log.topics.length == 4 // index 0 is the signature, and then 3 indexed topics
    );
}

run();

Output:

ERC20 token amount:  40000000000000000000
ERC20 token contract:  0x54a7cee7B02976ACE1bdd4aFad87273251Ed34Cf
ERC721 token ID:  12013
ERC721 token contract:  0x41cB4a771FdD019ADBF4685bd4885fbBeedE1784


问:
Redirect URL to another URL by regex with Traefik
I want to redirect one URL to another URL through traefik.

I am using docker for this configuration and below is my docker-compose.yml file

```<code>version: '3'

services:
  reverse-proxy:
    # The official v2.0 Traefik docker image
    image: containous/whoami
    container_name: "whoami_cont"
    # Enables the web UI and tells Traefik to listen to docker
    ports:
      # The HTTP port
      - 80:80
      # The Web UI (enabled by --api.insecure=true)
      - 8080:8080
    labels:
      - traefik.http.middlewares.test-replacepathregex.replacepathregex.regex=^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]
      - traefik.http.middlewares.test-replacepathregex.replacepathregex.replacement=http://localhost:8081/4
</code>```

then I am running docker-compose command successfully. Then I am going to hit any URL which matching regex pattern but URL is not redirecting to another URL - http://localhost:8081/4 as per configuration.
I am using traefik version 2.0

Please let me know if any configuration is missing.

答:
It's pretty straightforward if you are using an Ingressroute. Let say I want to redirect from example.com to app.example.com using traefik

First thing would be to create a Middleware :

```<code>apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: example-redirectregex
spec:
  redirectRegex:
    regex: ^https://example.com/(.*)
    replacement: https://app.example.com/${1}
</code>```

If you already have an Ingressroute then you can add an additional rule that will point example.com to the same backend service used by app.example.com and use the middleware we created above

```<code>- kind: Rule
    match: Host(`example.com`)
    middlewares:
    - name: example-redirectregex
      namespace: traefik
    services:
    - kind: Service
      name: master-prod
      namespace: app-web
      port: 80
</code>```

So, finally your Ingressroute should look something like the below:

```<code>apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  generation: 3
  labels:
    app: app-web
    product: example.com
  name: example-com
  namespace: traefik
spec:
  entryPoints:
  - websecure
  routes:
  - kind: Rule
    match: Host(`example.com`)
    middlewares:
    - name: example-redirectregex
      namespace: traefik
    services:
    - kind: Service
      name: example
      namespace: app-web
      port: 80
  - kind: Rule
    match: Host(`app.example.com`)
    services:
    - kind: Service
      name: example
      namespace: app-web
      port: 80
  tls:
    secretName: cert-example-com
</code>```

Now, if you browse example.com it should redirect you to app.example.com

Body:
I want to redirect one URL to another URL through traefik.

I am using docker for this configuration and below is my docker-compose.yml file

version: '3'

services:
  reverse-proxy:
    # The official v2.0 Traefik docker image
    image: containous/whoami
    container_name: "whoami_cont"
    # Enables the web UI and tells Traefik to listen to docker
    ports:
      # The HTTP port
      - 80:80
      # The Web UI (enabled by --api.insecure=true)
      - 8080:8080
    labels:
      - traefik.http.middlewares.test-replacepathregex.replacepathregex.regex=^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]
      - traefik.http.middlewares.test-replacepathregex.replacepathregex.replacement=http://localhost:8081/4

then I am running docker-compose command successfully. Then I am going to hit any URL which matching regex pattern but URL is not redirecting to another URL - http://localhost:8081/4 as per configuration.
I am using traefik version 2.0

Please let me know if any configuration is missing.

Body:
It's pretty straightforward if you are using an Ingressroute. Let say I want to redirect from example.com to app.example.com using traefik

First thing would be to create a Middleware :

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: example-redirectregex
spec:
  redirectRegex:
    regex: ^https://example.com/(.*)
    replacement: https://app.example.com/${1}

If you already have an Ingressroute then you can add an additional rule that will point example.com to the same backend service used by app.example.com and use the middleware we created above

- kind: Rule
    match: Host(`example.com`)
    middlewares:
    - name: example-redirectregex
      namespace: traefik
    services:
    - kind: Service
      name: master-prod
      namespace: app-web
      port: 80

So, finally your Ingressroute should look something like the below:

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  generation: 3
  labels:
    app: app-web
    product: example.com
  name: example-com
  namespace: traefik
spec:
  entryPoints:
  - websecure
  routes:
  - kind: Rule
    match: Host(`example.com`)
    middlewares:
    - name: example-redirectregex
      namespace: traefik
    services:
    - kind: Service
      name: example
      namespace: app-web
      port: 80
  - kind: Rule
    match: Host(`app.example.com`)
    services:
    - kind: Service
      name: example
      namespace: app-web
      port: 80
  tls:
    secretName: cert-example-com

Now, if you browse example.com it should redirect you to app.example.com


问:
Unknown CMake Qt5 command
I am currently trying to build a project using CMake.
This is the output that I get

```<code>CMake Warning at ext/quazip/CMakeLists.txt:4 (FIND_PACKAGE):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.

CMake Error at ext/quazip/CMakeLists.txt:19 (qt5_wrap_cpp):
  Unknown CMake command "qt5_wrap_cpp".
</code>```

I have Qt Creator installed and I am not sure why I am getting this error.
I looked around on the web and they states that I should add

```<code>set(QT_USE_QTXML true)
FIND_PACKAGE(Qt5)
</code>```

after the #project in ext/quazip/CMakeLists.txt
I have done that however I am still getting this error any suggestions ?

Update:
So I added the following to my top level CMakeLists.txt

```<code>find_package( Qt5Core REQUIRED )
find_package( Qt5Widgets REQUIRED )
find_package( Qt5Gui REQUIRED )
find_package( Qt5OpenGL REQUIRED )
find_package( Qt5Multimedia REQUIRED )
find_package( Qt5WebKitWidgets REQUIRED )
find_package( Qt5Xml REQUIRED )
</code>```

I cleared the cache and then configured. At that point I get the following error.

```<code>CMake Error at CMakeLists.txt:3 (find_package):
  By not providing "FindQt5Core.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5Core", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5Core" with any
  of the following names:

    Qt5CoreConfig.cmake
    qt5core-config.cmake

  Add the installation prefix of "Qt5Core" to CMAKE_PREFIX_PATH or set
  "Qt5Core_DIR" to a directory containing one of the above files.  If
  "Qt5Core" provides a separate development package or SDK, be sure it has
  been installed.

Configuring incomplete, errors occurred!
</code>```

答:
So finally, with some searching, I was able to get CANDevStudio -- which was also having this Qt5 problem -- working on Ubuntu 20.04 by:

Step 1: Manually download and install Qt from their website (requires free account creation): https://download.qt.io/archive/qt/

According to: This Website, it may be necessary to remove any other versions of libqt5:

```<code>sudo apt purge libqt5svg5-def
sudo apt purge libqt5serialbus5-dev
</code>```

Step 2: Build the Software with the DCMAKE_PREFIX_PATH flag set to the directory of the newly installed software (in my case, I put it in my home directory):

```<code>cmake .. -DCMAKE_PREFIX_PATH=/home/<username>/Qt5.12.0/5.12.0/gcc_64
</code>```

Source: CanDevStudio's Help Page

Title: Unknown CMake Qt5 command

Body:
I am currently trying to build a project using CMake.
This is the output that I get

CMake Warning at ext/quazip/CMakeLists.txt:4 (FIND_PACKAGE):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.

CMake Error at ext/quazip/CMakeLists.txt:19 (qt5_wrap_cpp):
  Unknown CMake command "qt5_wrap_cpp".

I have Qt Creator installed and I am not sure why I am getting this error.
I looked around on the web and they states that I should add

set(QT_USE_QTXML true)
FIND_PACKAGE(Qt5)

after the #project in ext/quazip/CMakeLists.txt
I have done that however I am still getting this error any suggestions ?

Update:
So I added the following to my top level CMakeLists.txt

find_package( Qt5Core REQUIRED )
find_package( Qt5Widgets REQUIRED )
find_package( Qt5Gui REQUIRED )
find_package( Qt5OpenGL REQUIRED )
find_package( Qt5Multimedia REQUIRED )
find_package( Qt5WebKitWidgets REQUIRED )
find_package( Qt5Xml REQUIRED )

I cleared the cache and then configured. At that point I get the following error.

CMake Error at CMakeLists.txt:3 (find_package):
  By not providing "FindQt5Core.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5Core", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5Core" with any
  of the following names:

    Qt5CoreConfig.cmake
    qt5core-config.cmake

  Add the installation prefix of "Qt5Core" to CMAKE_PREFIX_PATH or set
  "Qt5Core_DIR" to a directory containing one of the above files.  If
  "Qt5Core" provides a separate development package or SDK, be sure it has
  been installed.

Configuring incomplete, errors occurred!

Body:
So finally, with some searching, I was able to get CANDevStudio -- which was also having this Qt5 problem -- working on Ubuntu 20.04 by:

Step 1: Manually download and install Qt from their website (requires free account creation): https://download.qt.io/archive/qt/

According to: This Website, it may be necessary to remove any other versions of libqt5:

sudo apt purge libqt5svg5-def
sudo apt purge libqt5serialbus5-dev

Step 2: Build the Software with the DCMAKE_PREFIX_PATH flag set to the directory of the newly installed software (in my case, I put it in my home directory):

cmake .. -DCMAKE_PREFIX_PATH=/home/<username>/Qt5.12.0/5.12.0/gcc_64

Source: CanDevStudio's Help Page


问:
Create fake/virtual DOM in/for web worker?
Is there a way to create a fake DOM or some sort of Virtual DOM for/inside the web worker?

Like, so I can make a copy of the main DOM and sent it over to the web worker to reconstruct, do calculations(involving the DOM), and then send info back to the main thread for it to change stuff in the main DOM.

答:
Here's an implementation of that DOM for workers, and it sends the diff result to the main thread for processing:

https://github.com/ampproject/worker-dom

This is the only implementation of a DOM-like API that I know of that does what you describe. Others, like virtual DOM libs, have a different API that is not identical to DOM APIs.

(Sorry mods, this is a link only example because I don't wish to copy the project over to here)


问:
How can I have PHP avoid lazy evaluation?
I have an interesting question about the way PHP evaluates boolean expressions.   When you have, for example,

```<code>$expression = $expression1 and $expression2;
</code>```

or

```<code>if ($expression1 and $expression2)
</code>```

PHP first checks if $expression1 evaluates to true. If this is not the case, then $expression2 is simply skipped to avoid unnecessary calculations.  In a script I am writing, I have:

```<code>if ($validator->valid("title") and $validator->valid("text"))
</code>```

I need to have the second statement ($validator->valid("text")) evaluated even if the first one evaluates to false.  I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you!

答:
This is known as short circuit evaluation, and to avoid it you need to do this, using a single &:

```<code>if($validator->valid("title") & $validator->valid("text")) {

}
</code>```

Note that this is not using logical operators but actually bitwise operators:

They're operators that act on the binary representations of numbers. They do not take logical values (i.e., "true" or "false") as arguments without first converting them to the numbers 1 and 0 respectively. Nor do they return logical values, but numbers. Sure, you can later treat those numbers as though they were logical values (in which case 0 is cast to "false" and anything else is cast to "true"), but that's a consequence of PHP's type casting rules, and nothing to do with the behavior of the operators.

As such, there is some debate as to whether it is good practice to use this side effect to circumvent short-circuit evaluation. I would personally at least put a comment that the & is intentional, but if you want to be as pure as possible you should evaluate whether they are valid first and then do the if.

LastEditorDisplayName: Eddie

ContentLicense: CC BY-SA 2.5

Body:
I have an interesting question about the way PHP evaluates boolean expressions.   When you have, for example,

$expression = $expression1 and $expression2;

or

if ($expression1 and $expression2)

PHP first checks if $expression1 evaluates to true. If this is not the case, then $expression2 is simply skipped to avoid unnecessary calculations.  In a script I am writing, I have:

if ($validator->valid("title") and $validator->valid("text"))

I need to have the second statement ($validator->valid("text")) evaluated even if the first one evaluates to false.  I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you!

Body:
This is known as short circuit evaluation, and to avoid it you need to do this, using a single &:

if($validator->valid("title") & $validator->valid("text")) {

}

Note that this is not using logical operators but actually bitwise operators:

They're operators that act on the binary representations of numbers. They do not take logical values (i.e., "true" or "false") as arguments without first converting them to the numbers 1 and 0 respectively. Nor do they return logical values, but numbers. Sure, you can later treat those numbers as though they were logical values (in which case 0 is cast to "false" and anything else is cast to "true"), but that's a consequence of PHP's type casting rules, and nothing to do with the behavior of the operators.

As such, there is some debate as to whether it is good practice to use this side effect to circumvent short-circuit evaluation. I would personally at least put a comment that the & is intentional, but if you want to be as pure as possible you should evaluate whether they are valid first and then do the if.

OwnerDisplayName: Paolo Bergantino

LastEditorDisplayName: Paolo Bergantino


问:
What is the best practice for validating parameters in JSP?
I'm implementing a JSP which expects a few parameters which have to be validated before running the jsp.

Suggestion: Validate the parameters inside the JSP using
Taglibraries

Suggestion: Pre-parse the Parameters in a Filter

What do you think?

Edit

Thank you for the good answers, but I was wondering what would be the best practice in case you are offering a service like google chart API where you can't expect that the parameters are checked by a form before they are sent.
example:
https://chart.googleapis.com/chart?cht=&chd=&chs=&...additional_parameters...

答:
Use an MVC Framework (Spring MVC, Stripes, Struts 2 etc.) and validate the parameters in the controller class. Every MVC framework supports parameter validation, and you get a clean separation of concerns.

Example: Spring MVC automatically registers JSR-303-style parameter Validation (if you have a JSR-303 provider, e.g. Hibernate-Validator, on the classpath) when using mvc:annotation-driven


问:
For the use of the LocalizedResourceName property
I wish to customize my own folder style, I tried to make the folder get remarks by modifying the LocalizedResourceName property in desktop.ini.

I try to set LocalizedResourceName to a Chinese string. But it is displayed as garbled characters when it is actually displayed.

I noticed the following code in the desktop.ini of the system folder:
LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21798

So I try to write a .dll file by myself, encapsulate the icon and string, and use it.

I already know how to make a resource-only dll file, but I don't know how to get a certain resource in the file. (ie, get the number -21798 in the above example code)

How should I do ?

答:
By convention, a positive resource number is an index (0 is the first resource etc.) and negative numbers are resource ids. In this specific case, it is the string resource with the id of abs(-21798) that Windows would pass to LoadString.

If you want to create your own .dll, add a string with an id of 2 for example (any number between 2 and 0xffff) and in your .ini you would use @c:\path\mydll.dll,-2.

Before you go to all this trouble, just try saving the .ini as UTF-16 LE (Unicode in Notepad) and use Chinese strings directly without the @.


问:
docker arm32 gdb ptrace: Could not trace the inferior process
I am struggling with the arm32v7/ubuntu image. My host is Win10 professional and docker with command:

```<code>docker container run --cap-add=CAP_SYS_PTRACE --security-opt seccomp=unconfined --privileged -it --name ubuntuTest -h arm32 -v /C/WS/Docker:/WS arm32v7/ubuntu
</code>```

the binaries are built with crosscompiler(on host) and with gcc (on docker). The problem which I am facing with is:

```<code>root@arm32:/WS/workspace/out# gdb TCP_server_arm32.out
GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "arm-linux-gnueabihf".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from TCP_server_arm32.out...
(gdb) run
Starting program: /WS/workspace/out/TCP_server_arm32.out
warning: Could not trace the inferior process.
warning: ptrace: Function not implemented
During startup program exited with code 127.
(gdb)
</code>```

for some reason, the gdb can't work. I am interested if this is because of the QEMU layer since the OS is emulated. But I have no idea what to try next.
My idea was to build arm32 docker and debug applications in it with VS code.

Does someone knows how to make gdb or QEMU run with ptrace or enable ptrace somehow?

Thanks

答:
The solution is to install qemu-user and qemu-user-static in the docker container. On the Docker start the application with GDB stub on which you can connect from the host via gdb-multiarch.

which means:

In the docker container start the application (built with gcc -g...)

qemu-arm localhost:1234 ./app.out

On the host environment(my is ubuntu 20.04 LTS) run:

gdb-multiarch -q --nh -ex 'set architecture arm' -ex 'file app.out'
-ex 'target remote docker_container_ip:1234'

and that is it.

Body:
I am struggling with the arm32v7/ubuntu image. My host is Win10 professional and docker with command:

docker container run --cap-add=CAP_SYS_PTRACE --security-opt seccomp=unconfined --privileged -it --name ubuntuTest -h arm32 -v /C/WS/Docker:/WS arm32v7/ubuntu

the binaries are built with crosscompiler(on host) and with gcc (on docker). The problem which I am facing with is:

root@arm32:/WS/workspace/out# gdb TCP_server_arm32.out
GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "arm-linux-gnueabihf".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from TCP_server_arm32.out...
(gdb) run
Starting program: /WS/workspace/out/TCP_server_arm32.out
warning: Could not trace the inferior process.
warning: ptrace: Function not implemented
During startup program exited with code 127.
(gdb)

for some reason, the gdb can't work. I am interested if this is because of the QEMU layer since the OS is emulated. But I have no idea what to try next.
My idea was to build arm32 docker and debug applications in it with VS code.

Does someone knows how to make gdb or QEMU run with ptrace or enable ptrace somehow?

Thanks


问:
How to access state and template children in callback in GTK-rs
The tutorials and examples for gtk-rs are honestly really incomplete and spotty, so I'm trying to piece together how to modify the application's state, as well as the state of some of the child elements, inside a button callback. So, in brief, I have:

// ...
mod imp {
    pub struct Window {
        #[template_child]
        pub headerbar: TemplateChild<gtk::HeaderBar>,
        #[template_child]
        pub open_button: TemplateChild<gtk::Button>,

        // Internal state
        pub state: Rc<RefCell<ScribeDownWindowState>>,
    }

    #[derive(Default)]
    pub struct ScribeDownWindowState {
        pub project_path: Option<String>,
    }
}
```
<p>In the <code>ObjectImpl</code> for this struct, I have the <code>constructed</code> method, which calls the parent constructed method, then calls <code>setup_callbacks</code> on the parent object, which is the <code>Window</code> type that actually is part of the GTK inheritance hierarchy:</p>
<pre class="lang-rust prettyprint-override"><code>mod imp;
glib::wrapper! {
    pub struct Window(ObjectSubclass<imp::Window>)
        @extends gtk::ApplicationWindow, gtk::Window, gtk::Widget,
        @implements gio::ActionGroup, gio::ActionMap;
}

impl Window {
    pub fn new<P: glib::IsA<gtk::Application>>(app: &P) -> Self {
        glib::Object::new(&[("application", app)]).expect("Failed to create ScribeDownWindow")
    }

    fn setup_callbacks(&self) {
        let state = self.imp().state;
        let headerbar = Rc::new(&self.imp().headerbar);
        self.imp().open_button
            .connect_clicked(clone!(@strong state, @strong headerbar => move |_| {
                let s = state.borrow_mut();
                s.project_path = Some("fuck".to_string());
                headerbar.set_subtitle(Some("fuck"));
            }))
    }
}
</code>```

I need to access both the state and headerbar properties of the imp::Window struct, and modify the project_path property of state and call set_subtitle on the headerbar. I've tried all sorts of variations of this, using all combinations of variables and Rcs and RefCells and I just cannot seem to get past this error (or some permutation of it):

```<code>error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
  --> src/scribedown_window/mod.rs:22:39
   |
20 |     fn setup_callbacks(&self) {
   |                        ----- this data with an anonymous lifetime `'_`...
21 |         let state = self.imp().state;
22 |         let headerbar = Rc::new(&self.imp().headerbar);
   |                                  ---- ^^^
   |                                  |
   |                                  ...is captured here...
23 |         self.imp().open_button.connect_clicked(
   |                                --------------- ...and is required to live as long as `'static` here
</code>```

There has to be a way to get what I need done done, if you couldn't modify any other interface objects inside a button click callback your UI would be seriously hindered, but I don't see how.

答:
The solution to this problem was to create a struct to hold both the UI state and the application state, like so:

pub struct App {
    pub window: crate::scribedown_window::Window,
    pub state: State,
    pub document_list_model: Option<document_list::Model>,
}
```
<p>With this struct in hand, you can wrap it in an <code>Rc<RefCell<T>></code> so that other threads and scopes can access it (just not thread-safely/at the same time, you need a Mutex or Arc for that):</p>
<pre class="lang-rust prettyprint-override"><code>let scribedown = Rc::new(RefCell::new(app::App {
    window: win,
    state: app::State {
        project: None,
        open_files: vec![],
    },
    document_list_model: None,
}));
</code>```

Now, you can just pass a reference counted pointer to this central state holder to all the callbacks you want, and the callbacks themselves will keep the state alive and keep access to it, while also enforcing a crash if multiple callbacks try to modify the RefCell at the same time. Note that for this to work, all the methods to set up the application's UI callbacks need to be passed the reference counted state variable, scribedown, so they can't be methods of the App struct taking &self, since that would be useless and borrow it. They can be static methods though:

app::App::connect_all(scribedown.clone());
```
<p>Then, to wire up the callbacks, each callback needs its own pointer to the state to use, and on top of that, since you can't move a cloned reference counted pointer out of the enclosing scope, and you don't want to move the original reference counted pointer out, you need to create an outer RCP to then use to clone the actual RCP for the callback. That ends up looking like this:</p>
<pre class="lang-rust prettyprint-override"><code>// NOTE: the outer pointers to `sd`, formatted like `sd_for_*`, are
// done in order to prevent the callback from borrowing the original
// pointer when it creates its own pointer, which we need to keep free
// to continue making more pointers. This happens because using
// something inside a `move` callback borrows it.

// Connect open button callback
let sd_for_button = sd.clone();
{
    let osd = sd.borrow();
    let button = &osd.window.imp().open_button;
    button.connect_clicked(move |_| {
        // Launch dialog in new thread so it doesn't hang this one
        gtk::glib::MainContext::default()
    .spawn_local(Self::open_project_dialog(Rc::clone(&sd_for_button)));
    });
}
</code>```

I'm not sure this is the "official" or idiomatic solution to this, but I looked at the source code for Fractal (a Matrix messenger client written in Rust with GTK-rs), and they seemed to be using a similar solution.

Body:
The tutorials and examples for gtk-rs are honestly really incomplete and spotty, so I'm trying to piece together how to modify the application's state, as well as the state of some of the child elements, inside a button callback. So, in brief, I have:

// ...
mod imp {
    pub struct Window {
        #[template_child]
        pub headerbar: TemplateChild<gtk::HeaderBar>,
        #[template_child]
        pub open_button: TemplateChild<gtk::Button>,

        // Internal state
        pub state: Rc<RefCell<ScribeDownWindowState>>,
    }

    #[derive(Default)]
    pub struct ScribeDownWindowState {
        pub project_path: Option<String>,
    }
}

In the ObjectImpl for this struct, I have the constructed method, which calls the parent constructed method, then calls setup_callbacks on the parent object, which is the Window type that actually is part of the GTK inheritance hierarchy:

mod imp;
glib::wrapper! {
    pub struct Window(ObjectSubclass<imp::Window>)
        @extends gtk::ApplicationWindow, gtk::Window, gtk::Widget,
        @implements gio::ActionGroup, gio::ActionMap;
}

impl Window {
    pub fn new<P: glib::IsA<gtk::Application>>(app: &P) -> Self {
        glib::Object::new(&[("application", app)]).expect("Failed to create ScribeDownWindow")
    }

    fn setup_callbacks(&self) {
        let state = self.imp().state;
        let headerbar = Rc::new(&self.imp().headerbar);
        self.imp().open_button
            .connect_clicked(clone!(@strong state, @strong headerbar => move |_| {
                let s = state.borrow_mut();
                s.project_path = Some("fuck".to_string());
                headerbar.set_subtitle(Some("fuck"));
            }))
    }
}

I need to access both the state and headerbar properties of the imp::Window struct, and modify the project_path property of state and call set_subtitle on the headerbar. I've tried all sorts of variations of this, using all combinations of variables and Rcs and RefCells and I just cannot seem to get past this error (or some permutation of it):

error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
  --> src/scribedown_window/mod.rs:22:39
   |
20 |     fn setup_callbacks(&self) {
   |                        ----- this data with an anonymous lifetime `'_`...
21 |         let state = self.imp().state;
22 |         let headerbar = Rc::new(&self.imp().headerbar);
   |                                  ---- ^^^
   |                                  |
   |                                  ...is captured here...
23 |         self.imp().open_button.connect_clicked(
   |                                --------------- ...and is required to live as long as `'static` here

There has to be a way to get what I need done done, if you couldn't modify any other interface objects inside a button click callback your UI would be seriously hindered, but I don't see how.

Body:
The solution to this problem was to create a struct to hold both the UI state and the application state, like so:

pub struct App {
    pub window: crate::scribedown_window::Window,
    pub state: State,
    pub document_list_model: Option<document_list::Model>,
}

With this struct in hand, you can wrap it in an Rc<RefCell<T>> so that other threads and scopes can access it (just not thread-safely/at the same time, you need a Mutex or Arc for that):

let scribedown = Rc::new(RefCell::new(app::App {
    window: win,
    state: app::State {
        project: None,
        open_files: vec![],
    },
    document_list_model: None,
}));

Now, you can just pass a reference counted pointer to this central state holder to all the callbacks you want, and the callbacks themselves will keep the state alive and keep access to it, while also enforcing a crash if multiple callbacks try to modify the RefCell at the same time. Note that for this to work, all the methods to set up the application's UI callbacks need to be passed the reference counted state variable, scribedown, so they can't be methods of the App struct taking &self, since that would be useless and borrow it. They can be static methods though:

app::App::connect_all(scribedown.clone());

Then, to wire up the callbacks, each callback needs its own pointer to the state to use, and on top of that, since you can't move a cloned reference counted pointer out of the enclosing scope, and you don't want to move the original reference counted pointer out, you need to create an outer RCP to then use to clone the actual RCP for the callback. That ends up looking like this:

// NOTE: the outer pointers to `sd`, formatted like `sd_for_*`, are
// done in order to prevent the callback from borrowing the original
// pointer when it creates its own pointer, which we need to keep free
// to continue making more pointers. This happens because using
// something inside a `move` callback borrows it.

// Connect open button callback
let sd_for_button = sd.clone();
{
    let osd = sd.borrow();
    let button = &osd.window.imp().open_button;
    button.connect_clicked(move |_| {
        // Launch dialog in new thread so it doesn't hang this one
        gtk::glib::MainContext::default()
    .spawn_local(Self::open_project_dialog(Rc::clone(&sd_for_button)));
    });
}

I'm not sure this is the "official" or idiomatic solution to this, but I looked at the source code for Fractal (a Matrix messenger client written in Rust with GTK-rs), and they seemed to be using a similar solution.


问:
Why do non-exhaustive guards cause irrefutable pattern match to fail?
I have this function in Haskell:

```<code>test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b = Just a
test _ _ = Nothing
</code>```

This is what I got when I tried the function with different inputs:

```<code>ghci>test 3 4
Nothing
ghci>test 3 3
Just 3
</code>```

According to Real World Haskell, the first pattern is irrefutable.  But it seems like test 3 4 doesn't fails the first pattern, and matches the second.  I expected some kind of error -- maybe 'non-exhaustive guards'.  So what is really going on here, and is there a way to enable compiler warnings in case this accidentally happens?

答:
Guards aren't irrefutable. But is very common (and good) practise to add one last guard that catch the other cases, so your function becomes:</p>

```<code>test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b = Just a
  | True = Nothing
</code>```

Body:
I have this function in Haskell:

test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b = Just a
test _ _ = Nothing

This is what I got when I tried the function with different inputs:

ghci>test 3 4
Nothing
ghci>test 3 3
Just 3

According to Real World Haskell, the first pattern is irrefutable.  But it seems like test 3 4 doesn't fails the first pattern, and matches the second.  I expected some kind of error -- maybe 'non-exhaustive guards'.  So what is really going on here, and is there a way to enable compiler warnings in case this accidentally happens?

Body:
Guards aren't irrefutable. But is very common (and good) practise to add one last guard that catch the other cases, so your function becomes:

test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b = Just a
  | True = Nothing


问:
Reading a remote file using Java
I am looking for an easy way to get files that are situated on a remote server. For this I created a local ftp server on my Windows XP, and now I am trying to give my test applet the following address:

```<code>try
{
    uri = new URI("ftp://localhost/myTest/test.mid");
    File midiFile = new File(uri);
}
catch (Exception ex)
{
}
</code>```

and of course I receive the following error:

URI scheme is not "file"

I've been trying some other ways to get the file, they don't seem to work. How should I do it? (I am also keen to perform an HTTP request)

答:
```<code>org.apache.commons.io.FileUtils.copyURLToFile(new URL(REMOTE_URL), new File(FILE_NAME), CONNECT_TIMEOUT, READ_TIMEOUT);
</code>```

Title: Reading a remote file using Java

Body:
I am looking for an easy way to get files that are situated on a remote server. For this I created a local ftp server on my Windows XP, and now I am trying to give my test applet the following address:

try
{
    uri = new URI("ftp://localhost/myTest/test.mid");
    File midiFile = new File(uri);
}
catch (Exception ex)
{
}

and of course I receive the following error:

URI scheme is not "file"

I've been trying some other ways to get the file, they don't seem to work. How should I do it? (I am also keen to perform an HTTP request)


问:
How do you unzip a zipped observable in RxJs?
I would like to "unzip" a zipped Observable, I searched for something akin to the "Spread" operator but it's just not there, I tried to make my own unzip but I have to hardcode the length of the zip. Is there a way to do this without hardcoding it

(p =>
//[0,1,2] is hardcoded.
  rxjs.zip(...[0, 1, 2].map(i => p.pipe(rxjs.map(a => a[i]))))
)(
  rxjs.zip(rxjs.range(3, 4), rxjs.range(9, 4), rxjs.range(124, 7))
).subscribe(console.log)
```

答:
If I understood correctly, you just want to flatten the zip result into separate elements down the stream.

This can be easily achieved with an additional mergeMap, for example:

```<code>zip(of(1), of(2), of(3))
.subscribe(value => console.log(value));
</code>```

Will output [1, 2, 3], however if you add a merge map to unwrap the array, like this:

```<code>zip(of(1), of(2), of(3))
.pipe(mergeMap(e => of(...e)))
.subscribe(value => console.log(value));
</code>```

the output will be:

```<code>1
2
3
</code>```

Body:
If I understood correctly, you just want to flatten the zip result into separate elements down the stream.

This can be easily achieved with an additional mergeMap, for example:

zip(of(1), of(2), of(3))
.subscribe(value => console.log(value));

Will output [1, 2, 3], however if you add a merge map to unwrap the array, like this:

zip(of(1), of(2), of(3))
.pipe(mergeMap(e => of(...e)))
.subscribe(value => console.log(value));

the output will be:

1
2
3


问:
Is class.getName() expensive?
In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

```<code>public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}
</code>```

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?

答: No, it's not expensive at all. The only benefits I can think of is that an IDE can quickly show you where this particular constant is being used, and that for long classnames, the constant would be shorter, making the code a bit cleaner.</p>

Title: Is class.getName() expensive?

Body:
In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?


问:
How to get $refs using Composition API in Vue3?
I am trying to get $refs in Vue 3 using Composition API. This is my template that has two child components and I need to get reference to one child component instance:

```<code><template>
    <comp-foo />
    <comp-bar ref="table"/>
</template>
</code>```

In my code I use Template Refs: ref is a special attribute, that allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted.

If I use Options API then I don't have any problems:

```<code>  mounted() {
    console.log("Mounted - ok");
    console.log(this.$refs.table.temp());
  }
</code>```

However, using Composition API I get error:

```<code>setup() {
    const that: any = getCurrentInstance();
    onMounted(() => {
      console.log("Mounted - ok");
      console.log(that.$refs.table.temp());//ERROR that.$refs is undefined
    });
    return {};
  }
</code>```

Could anyone say how to do it using Composition API?

答:
You need to create the ref const inside the setup then return it so it can be used in the html.</p>
```<code><template>
    <div ref="table"/>
</template>

import { ref, onMounted } from 'vue';

setup() {
    const table = ref(null);

    onMounted(() => {
      console.log(table.value);
    });

    return { table };
}
</code>```

Body:
I am trying to get $refs in Vue 3 using Composition API. This is my template that has two child components and I need to get reference to one child component instance:

<template>
    <comp-foo />
    <comp-bar ref="table"/>
</template>

In my code I use Template Refs: ref is a special attribute, that allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted.

If I use Options API then I don't have any problems:

  mounted() {
    console.log("Mounted - ok");
    console.log(this.$refs.table.temp());
  }

However, using Composition API I get error:

setup() {
    const that: any = getCurrentInstance();
    onMounted(() => {
      console.log("Mounted - ok");
      console.log(that.$refs.table.temp());//ERROR that.$refs is undefined
    });
    return {};
  }

Could anyone say how to do it using Composition API?

Body:
You need to create the ref const inside the setup then return it so it can be used in the html.

<template>
    <div ref="table"/>
</template>

import { ref, onMounted } from 'vue';

setup() {
    const table = ref(null);

    onMounted(() => {
      console.log(table.value);
    });

    return { table };
}


问:
'function' object has no attribute 'dumps'
I imported pickle from copyreg.
I then use the attribute dumps to convert a dictionary into bytes b'\x80\x04...' but it results in the error shown below:

```<code>from copyreg import pickle
d={"name":value}
d=pickle.dumps(d)
</code>```

Error:

```<code>AttributeError: 'function' object has no attribute
</code>```

答:
Your import seems incorrect. It should be:

from pickle import dumps

d = {..}
d = dumps(d)
```

Body:
I imported pickle from copyreg.
I then use the attribute dumps to convert a dictionary into bytes b'\x80\x04...' but it results in the error shown below:

from copyreg import pickle
d={"name":value}
d=pickle.dumps(d)

Error:

AttributeError: 'function' object has no attribute


问:
How to get multi value of checkox with data serialize in ajax jquery?
hey guys I have a problem when I select more than one checkbox the serialize from doesn't put them in an array
here is the result

product-category=29&product-category=27

and I want it to be like that

product-category=29,27

this is my php code:

```<code>  <form id="myform">
    <fieldset>
      <label>Categorys</label>
      <?php
                $cats = get_terms([
                    'taxonomy' => 'product_cat',
                    'hide_empty' => false,
                ]);
      ?>
        <?php foreach($cats as $cat) : ?>

          <input type="checkbox" id="product-category-checkbox" name="product-category" value="<?php echo $cat->term_id; ?>">

        <?php endforeach; ?>

    </fieldset>
  </form>
</code>```

and this is the js code:

```<code><script>
  (function($){

    $(document).ready(function(){

      $(document).on('submit', '#myform', function(e) {

        e.preventDefault();

        var data = $(this).serialize();

        console.log(data);
        var settings = {
            "url": "<?php echo WC_AJAX::get_endpoint( 'kia_search' ) ?>",
            "method": "POST",
            "data": data
          }
          $.ajax(settings).done(function (response) {
                        $('.products').html(response);

                });

      });
    });
  })(jQuery);
</script>
</code>```

答:
Instead of serializing the data directly via .serialize(), you should instead use .serializeArray() to get the data as an array. You can manipulate the array and then serialize it with $.param().

So remove below line, and make it more dynamic

```<code>var data = $(this).serialize();
</code>```

Like so. This is to ensure that, even if more form elements are added later, there will be no need to alter the code.

```<code><script>
    (function($){
        $(document).ready(function(){
            $(document).on('submit', '#myform', function(e) {
                e.preventDefault();

                // get data
                var data = $(this).serializeArray();

                // get 'product-category` values from array and join them
                var categories = data.filter(obj => obj.name === 'product-category').map(obj => obj.value).join(',');

                // add the joined 'product-category' back to data
                if( categories.length > 0 ){
                    data = data.filter(obj => obj.name !== 'product-category')
                               .concat({name: 'product-category', value: categories});
                }

                // serialize data
                data = $.param(data);

                console.log(data);
                var settings = {
                    "url": "<?php echo WC_AJAX::get_endpoint( 'kia_search' ) ?>",
                    "method": "POST",
                    "data": data
                }
                $.ajax(settings).done(function (response) {
                    $('.products').html(response);
                });
            });
        });
    })(jQuery);
</script>
</code>```

Body:
hey guys I have a problem when I select more than one checkbox the serialize from doesn't put them in an array
here is the result

product-category=29&product-category=27

and I want it to be like that

product-category=29,27

this is my php code:

  <form id="myform">
    <fieldset>
      Categorys
      <?php
                $cats = get_terms([
                    'taxonomy' => 'product_cat',
                    'hide_empty' => false,
                ]);
      ?>
        <?php foreach($cats as $cat) : ?>

          <input type="checkbox" id="product-category-checkbox" name="product-category" value="<?php echo $cat->term_id; ?>">

        <?php endforeach; ?>

    </fieldset>
  </form>

and this is the js code:

Body:
Instead of serializing the data directly via .serialize(), you should instead use .serializeArray() to get the data as an array. You can manipulate the array and then serialize it with $.param().

So remove below line, and make it more dynamic

var data = $(this).serialize();

Like so. This is to ensure that, even if more form elements are added later, there will be no need to alter the code.

<script>
    (function($){
        $(document).ready(function(){
            $(document).on('submit', '#myform', function(e) {
                e.preventDefault();

                // get data
                var data = $(this).serializeArray();

                // get 'product-category` values from array and join them
                var categories = data.filter(obj => obj.name === 'product-category').map(obj => obj.value).join(',');

                // add the joined 'product-category' back to data
                if( categories.length > 0 ){
                    data = data.filter(obj => obj.name !== 'product-category')
                               .concat({name: 'product-category', value: categories});
                }

                // serialize data
                data = $.param(data);

                console.log(data);
                var settings = {
                    "url": "<?php echo WC_AJAX::get_endpoint( 'kia_search' ) ?>",
                    "method": "POST",
                    "data": data
                }
                $.ajax(settings).done(function (response) {
                    $('.products').html(response);
                });
            });
        });
    })(jQuery);
</script>