问:
C++ alloc array of objects
I've got this issue with allocation of an array of some objects that I need to initialize with some constructor. Let me show what I mean:

```<code>ofstream* out = new ofstream[10];

for(int i = 0; i < 10; i++){
    stringstream ss;
    ss << "file" << i << ".txt";
    string str(ss.str());
    char *fileName = (char*)str.c_str();
    out[i] = ofstream(fileName); //Now, this is wrong
}
</code>```

And I need some help on the wrong marked line. How do I allocate each member of that array?

And thank you for not pointing me to other posts (I looked on a lot before posting)

答: If you really need to call the constructor by the time you insert the element (maybe because your class doesn't have a default constructor), try placement new as described here http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.5</p>

Title: C++ alloc array of objects

Body:
I've got this issue with allocation of an array of some objects that I need to initialize with some constructor. Let me show what I mean:

ofstream* out = new ofstream[10];

for(int i = 0; i < 10; i++){
    stringstream ss;
    ss << "file" << i << ".txt";
    string str(ss.str());
    char *fileName = (char*)str.c_str();
    out[i] = ofstream(fileName); //Now, this is wrong
}

And I need some help on the wrong marked line. How do I allocate each member of that array?

And thank you for not pointing me to other posts (I looked on a lot before posting)


来源: stackexchange

问:
Reverse byte order in XMM or YMM register?
Let's say I want to reverse the byte order of a very large byte array. I can do this the slow way using the main registers but I would like to speed it up using the XMM or YMM registers.

Is there a way to reverse the byte order in an XMM or YMM register?

答:
Yes, use SSSE3 _mm_shuffle_epi8 or AVX2 _mm256_shuffle_epi8 to shuffle bytes within 16-byte AVX2 "lanes".  Depending on the shuffle control vector, you can swap pairs of bytes, reverse 4-byte units, or reverse 8-byte units.  Or reverse all 16 bytes.

But vpshufb isn't lane-crossing, so you can't reverse 32 bytes with one instruction until AVX512VBMI vpermb.  vpshufb ymm does 2x 16-byte shuffles in the two 128-bit lanes of the YMM vector.

So if you're byte-reversing an entire array, rather than the endianness / byte-order of individual elements in an array, you have 3 options:

Stick to 128-bit vectors (simple and portable, and probably not slower on current CPUs).  And only needs 16-byte alignment for best performance.

Load with vmovdqu / vinsert128, then vpshufb then 32-byte store.  (Or do 32-byte loads and split 16-byte stores, but that's probably not as good).  Vectorize random init and print for BigInt with decimal digit array, with AVX2? includes a cache-blocked byte-aarray reverse into a tmp buffer to feed fwrite in 8kiB chunks.

Use vpermq to lane-swap before or after vpshufb (not great on AMD, and bottlenecks on 1 per clock shuffle throughput on current Intel).  But potentially very good on Ice Lake (2 shuffle ports)

vpshufb is a single uop instruction on Intel, or 2 on AMD, and processes 32 bytes of data at once.

For very large inputs, it's probably worth it to reach a 32 or 64-byte alignment boundary before your vectorized loop, so none of the loads/stores cross cache-line boundaries.  (For small inputs the minor benefit isn't worth the extra prologue/epilogue code and branching.)

But potentially even better is to only swap a 16kiB chunk before you use it, so it's still hot in L1d cache when the next step reads it.  This is called cache blocking.  Or maybe use 128kiB chunks to block for L2 cache size.

You might swap in chunks as you read the data from a file.  e.g. do read() system calls in chunks of 64k or 128k and swap the result while it's still hot in cache after the kernel copied data from the pagecache into your user-space buffer.  Or use mmap to memory-map a file, and run a copy-and-swap loop from that.  (Or for a private mapping, in-place swap; but that will trigger copy-on-write anyway so not much benefit.  And file-backed mmap on Linux can't use anonymous hugepages).

Another option is to simply swap on the fly if you only read the data a couple times; if the later uses are still memory bound, or have room for a shuffle uop without bottlenecking, it probably won't slow them down to shuffle on the fly.

A pass that touches all your data and only byte-swaps it has very poor computational intensity; you want to be doing more things with your data while it's in registers, or at least while it's hot in cache.  But if you only byte-swap once and then read the data many times, or in a random access pattern, or from another language like Python or JavaScript that can't efficiently swap on the fly, then sure do a swap pass.

Or a swap pass is helpful if you will make multiple passes over it that aren't memory-bound, and an extra shuffle would slow down each later pass.  In that case you do want to cache-block the swapping so the later pass's input is hot in cache.

The scalar option, bswap, is limited to at best 8 bytes per clock cycle, and every 8 bytes needs a separate load and store instruction.  (movbe to load from memory with byte-swapping saves an instruction, but on mainstream CPUs doesn't micro-fuse into a single load+swap uop.  On Silvermont it's single-uop, though.)  Also, Intel bswap r64 is 2 uops, so it's not great.

This might saturate single-threaded memory bandwidth on modern CPUs with some loop unrolling, but SIMD with fewer total uops to process the same data lets out-of-order execution "see" farther ahead and start processing TLB misses for upcoming pages sooner, for example.  HW data prefetch and TLB prefetch do help a lot, but it's typically at least slightly better to use wider loads/stores for memcpy.

(vpshufb is cheap enough that this will still basically perform like memcpy.  Or better if rewriting in place.)

And of course if you ever have any cache hits, even just L3 cache, SIMD will really shine.

ContentLicense: CC BY-SA 4.0


问:
How to implement this in Scheme
I'm pretty new in Scheme and I'm having some problems with one exercise.

Here it goes: Write the genlist function taking two integer as parameter and returning a list containing the set of integers contained between the two provided

For example: (genlist 5 12) => (5 6 7 8 9 10 11 12)

I already did in Python but I dont know how to implement in Scheme.

答:
A list like (5 6 7) is made like (cons 5 (cons 6 (cons 7 '()))) so the simplest solution would be that:

```<code>(genlist 8 7) ; ==> ()
(genlist 7 7) ; ==> (cons 7 (genlist 8 7))
</code>```

Now this isn't the best way to do it, just the simplest. The best way would be to create the list from the end to beginning using a helper:

```<code>(genlist-helper 6 7 '())                  ; ==>
(genlist-helper 6 6 (cons 7 '()))         ; ==>
(genlist-helper 6 5 (cons 6 (cons 7 '())) ; ==>
(cons 6 (cons 7 '())
</code>```

Now the genlist just calls the helper by providing the empty list as the initial accumulator. It is also possible to do this with a local procedure where you don't need to add the first parameter since you have it frmo the lexical closure and you can even make it much simpler by using named let.

I have no idea how you did it in Python. I have no recall that python has cons cells. Algol knowledge usually isn't helping when learning your first lisp language. It's like you make the assumption that since Italian and Spanish was so similar Slovenian must be as well.

Title: How to implement this in Scheme

Body:
A list like (5 6 7) is made like (cons 5 (cons 6 (cons 7 '()))) so the simplest solution would be that:

(genlist 8 7) ; ==> ()
(genlist 7 7) ; ==> (cons 7 (genlist 8 7))

Now this isn't the best way to do it, just the simplest. The best way would be to create the list from the end to beginning using a helper:

(genlist-helper 6 7 '())                  ; ==>
(genlist-helper 6 6 (cons 7 '()))         ; ==>
(genlist-helper 6 5 (cons 6 (cons 7 '())) ; ==>
(cons 6 (cons 7 '())

Now the genlist just calls the helper by providing the empty list as the initial accumulator. It is also possible to do this with a local procedure where you don't need to add the first parameter since you have it frmo the lexical closure and you can even make it much simpler by using named let.

I have no idea how you did it in Python. I have no recall that python has cons cells. Algol knowledge usually isn't helping when learning your first lisp language. It's like you make the assumption that since Italian and Spanish was so similar Slovenian must be as well.


问:
How do I redirect a www url to a no-www url using nginx-ingress-controller?
I am trying to get the url www.example.com to redirect itself to example.com while preserving everything about the original request in k8s 1.11.1

I am attempting to do this using a simple Ingress, and am then using annotations to redirect it.

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/tls-acme: "true"
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/permanent-redirect: https://example.com
    nginx.ingress.kubernetes.io/ssl-redirect: "True"
  name: example-redirect
spec:
  tls:
  - hosts:
    - www.example.com
    secretName: example-tls
  rules:
  - host: www.example.com
    http:
      paths:
      - backend:
          serviceName: example
          servicePort: http
</code>```

The issue here is that I don't want to have any rules/backend. I simply want to redirect www.example.com to example.com using an Ingress, but k8s Ingresses require me to have rules. Are there any workarounds here?

答:
Following should do:</p>

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/tls-acme: "true"
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($host = 'www.example.com' ) {
        rewrite ^ https://example.com$request_uri permanent;
      }
  name: example-redirect
spec:
  tls:
  - hosts:
    - www.example.com
    secretName: example-tls
  rules:
  - host: www.example.com
    http:
      paths:
      - backend:
          serviceName: example
          servicePort: http
</code>```

Body:
I am trying to get the url www.example.com to redirect itself to example.com while preserving everything about the original request in k8s 1.11.1

I am attempting to do this using a simple Ingress, and am then using annotations to redirect it.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/tls-acme: "true"
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/permanent-redirect: https://example.com
    nginx.ingress.kubernetes.io/ssl-redirect: "True"
  name: example-redirect
spec:
  tls:
  - hosts:
    - www.example.com
    secretName: example-tls
  rules:
  - host: www.example.com
    http:
      paths:
      - backend:
          serviceName: example
          servicePort: http

The issue here is that I don't want to have any rules/backend. I simply want to redirect www.example.com to example.com using an Ingress, but k8s Ingresses require me to have rules. Are there any workarounds here?

Body:
Following should do:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/tls-acme: "true"
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($host = 'www.example.com' ) {
        rewrite ^ https://example.com$request_uri permanent;
      }
  name: example-redirect
spec:
  tls:
  - hosts:
    - www.example.com
    secretName: example-tls
  rules:
  - host: www.example.com
    http:
      paths:
      - backend:
          serviceName: example
          servicePort: http


问:
Module parse failed: Octal literal in strict mode
I am working in angular 7 and validating contact number using

```<code>"^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$"
</code>```

regular expression but it is throwing the following error : Module parse failed: Octal literal in strict mode (10:76)

I have already tried \\ instead of \ because as per my finding the problem is with \ character.

```<code>registerForm = this.fb.group(
{
  email:['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+.com$')]],
  contact:['',[Validators.required, Validators.pattern('/^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$/')]],
  password:['',[Validators.required]],
  confirmPassword:['',[Validators.required]]
},{ validator: PasswordMatchValidator });
</code>```

Is there any way to replace \ character to make it work?

答:
There are a few problems here but I'd start with this one: The / character is used to start and end a RegExp literal in javascript, it isn't part of the pattern. You shouldn't put it inside quotes (as a string literal) because then angular will incorrectly try to make a pattern which includes the /s.

Instead of:

Validators.pattern('/^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$/')

Remove your string single quotes:

Validators.pattern(/^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$/)

I'm pretty sure this still isn't the regex you want, it looks like you're escaping parentheses you shouldn't be, but it is at least valid.

Where did you get the pattern from originally? If you share that we might be able to sort it out, or try playing around on https://regexr.com and when you get the pattern right just copy it straight in as you see it there, no quotes or additional escaping.

(Confusingly, Validators.pattern also accepts strings, but if you want to pass a string you should omit the /, because those forward slashes are not actually part of the pattern, and you should also omit ^ and $ when passing a string because Angular adds them automatically)

Side note: Validating phone numbers with regex is probably a bad idea anyway. Google libphonenumber

Body:
I am working in angular 7 and validating contact number using

"^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$"

regular expression but it is throwing the following error : Module parse failed: Octal literal in strict mode (10:76)

I have already tried \\ instead of \ because as per my finding the problem is with \ character.

registerForm = this.fb.group(
{
  email:['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+.com$')]],
  contact:['',[Validators.required, Validators.pattern('/^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$/')]],
  password:['',[Validators.required]],
  confirmPassword:['',[Validators.required]]
},{ validator: PasswordMatchValidator });

Is there any way to replace \ character to make it work?


问:
JSONAPI filter by date range
GET api how to send the filter parameter if the filter is a date range

eg :

```<code>GET /products?filter[created][ge]=2018-01-01&filter[created][le]=2017-01-01
</code>```

答:
JSON:API specification is agnostic about filter strategy. But, the next way is implemented on various libraries (like ngx-jsonapi or neomerx json-api):</p>

```<code>GET /products?filter[created][since]=2018-01-01&filter[created][until]=2020-01-01
</code>```

Title: JSONAPI filter by date range

Body:
GET api how to send the filter parameter if the filter is a date range

eg :

GET /products?filter[created][ge]=2018-01-01&filter[created][le]=2017-01-01

Body:
JSON:API specification is agnostic about filter strategy. But, the next way is implemented on various libraries (like ngx-jsonapi or neomerx json-api):

GET /products?filter[created][since]=2018-01-01&filter[created][until]=2020-01-01


问:
How to match cell to lookup table?
I am trying to set up an expense tracker. I copy-paste my credit card transactions directly in Google Sheets. I want to categorize them into say grocery, restaurant, gas, movies, etc. I want to do this using some sort of lookup table which I can keep adding to in the future.

The lookup table could look something like:

```<code>A          B
cafe       restaurant
cuisine    restaurant
restaurant restuarant
gas        gas
amc        movies
safeway    grocery
costco     grocery
</code>```

Now, the copy-paste from my credit card statement looks something like this:

```<code>A                   B
AMC20 BILL          12
RRCAFE              20
COSTCOPAYMNET       80
ARCOGAS             30
THE CUISINE BLOCK   20
</code>```

The final outcome that I want is this:

```<code>A                   B       C
AMC20 BILL          12      movies
RRCAFE              20      restaurant
COSTCOPAYMNET       80      grocery
ARCOGAS             30      gas
THE CUISINE BLOCK   20      restaurant
</code>```

I tried looking at VLOOKUP and MATCH but couldn't figure out a way to do this reverse lookup.

答:
```<code>=ARRAYFORMULA(IF(LEN(D1:D),
 VLOOKUP(REGEXEXTRACT(LOWER(D1:D), TEXTJOIN("|", 1, A1:A)), A:B, 2, 0), ))
</code>```

Title: How to match cell to lookup table?

Body:
I am trying to set up an expense tracker. I copy-paste my credit card transactions directly in Google Sheets. I want to categorize them into say grocery, restaurant, gas, movies, etc. I want to do this using some sort of lookup table which I can keep adding to in the future.

The lookup table could look something like:

A          B
cafe       restaurant
cuisine    restaurant
restaurant restuarant
gas        gas
amc        movies
safeway    grocery
costco     grocery

Now, the copy-paste from my credit card statement looks something like this:

A                   B
AMC20 BILL          12
RRCAFE              20
COSTCOPAYMNET       80
ARCOGAS             30
THE CUISINE BLOCK   20

The final outcome that I want is this:

A                   B       C
AMC20 BILL          12      movies
RRCAFE              20      restaurant
COSTCOPAYMNET       80      grocery
ARCOGAS             30      gas
THE CUISINE BLOCK   20      restaurant

I tried looking at VLOOKUP and MATCH but couldn't figure out a way to do this reverse lookup.


问:
Issue with money counting script
I've got an issue with my money counting script.
It works fine but I need to format output in two ways but I cannot use any string functions including format but I suppose to use math lib floor ceil function.

```<code>import math

coins1 = int(input("Quantity of 1 cent coins ? ")) * 0.01

coins2 = int(input("Quantity of 2 cent coins ? ")) * 0.02

coins3 = int(input("Quantity of 5 cent coins ? ")) * 0.05

coins4 = int(input("Quantity of 10 cent coins ? ")) * 0.10

coins5 = int(input("Quantity of 20 cent coins ? ")) * 0.20

coins6 = int(input("Quantity of 50 cent coins ? ")) * 0.50

coins7 = int(input("Quantity of 1 euro coins ? ")) * 1

coins8 = int(input("Quantity of 2 euro coins ? ")) * 2

bills1 = int(input("Quantity of 5 euro bills ? ")) * 5

bills2 = int(input("Quantity of 10 euro bills ? ")) * 10

bills3 = int(input("Quantity of 20 euro bills ? ")) * 20

bills4 = int(input("Quantity of 50 euro bills ? ")) * 50

total = coins1 + coins2 + coins3 + coins4 + coins5 + coins6 + coins7 + coins8 + coins1 + bills2 + bills3 + bills4

print("You've got", total, "euro and",)
</code>```

My current output is:

```<code>You've got 32792039464.8 euro and
</code>```

My goal is:

```<code>You've got 32792039464 euro and 80 cents.
$32.792.39.464,80
</code>```

答:
Just use int() to get the whole number part and modulo % to get the decimal part:

```<code>print("You've got", int(total), "euro and", total % 1, "cents.")
</code>```

You will notice a classical issue of floating point numbers very soon :)

Title: Issue with money counting script

Body:
I've got an issue with my money counting script.
It works fine but I need to format output in two ways but I cannot use any string functions including format but I suppose to use math lib floor ceil function.

import math

coins1 = int(input("Quantity of 1 cent coins ? ")) * 0.01

coins2 = int(input("Quantity of 2 cent coins ? ")) * 0.02

coins3 = int(input("Quantity of 5 cent coins ? ")) * 0.05

coins4 = int(input("Quantity of 10 cent coins ? ")) * 0.10

coins5 = int(input("Quantity of 20 cent coins ? ")) * 0.20

coins6 = int(input("Quantity of 50 cent coins ? ")) * 0.50

coins7 = int(input("Quantity of 1 euro coins ? ")) * 1

coins8 = int(input("Quantity of 2 euro coins ? ")) * 2

bills1 = int(input("Quantity of 5 euro bills ? ")) * 5

bills2 = int(input("Quantity of 10 euro bills ? ")) * 10

bills3 = int(input("Quantity of 20 euro bills ? ")) * 20

bills4 = int(input("Quantity of 50 euro bills ? ")) * 50

total = coins1 + coins2 + coins3 + coins4 + coins5 + coins6 + coins7 + coins8 + coins1 + bills2 + bills3 + bills4

print("You've got", total, "euro and",)

My current output is:

You've got 32792039464.8 euro and

My goal is:

You've got 32792039464 euro and 80 cents.
$32.792.39.464,80

Body:
Just use int() to get the whole number part and modulo % to get the decimal part:

print("You've got", int(total), "euro and", total % 1, "cents.")

You will notice a classical issue of floating point numbers very soon :)


问:
Makefile string with spaces
```<code>var := 'C:/some/path here' labas
all:
    @echo $(words $(var))
</code>```

This returns 3.
How to make it return 2? Or make does not work the way I think??

答:
Make definitely doesn't work the way you think, if you think that make has any interest in quotes of any type :).  Make ignores (i.e., treats as normal characters like any other) both single- and double-quote characters in virtually every situation, and all make functions work in simple whitespace delimiters without regard to quote characters.

In general, it's not practical to use make with any system that requires spaces in target names.  It just doesn't work: too much of make is based on whitespace as a separator character and there's no general, common way to escape the whitespace that works everywhere.

In your very particular case you can play a trick like this:

```<code>E :=
S := $E $E

path := C:/some/path here
xpath := $(subst $S,^,$(path))

var := $(xpath) labas
all:
        @echo $(words $(var))
        @echo $(subst ^,$S,$(var))
</code>```

Basically, this creates a variable $S which contains a space, then it substitutes all spaces in the variable path with some other, non-space character (here I chose ^ but you can pick what you like, just note it has to be a character which is guaranteed to not appear in the path).

Now this path doesn't contain whitespace so you can use it with make functions.

This has major downsides: not only the complexity visible here, but note these paths cannot be used in target names since they won't actually exist on disk.

In general, you should simply not use paths containing whitespace with make.  If you must use paths containing whitespace, then very likely make is not the right tool for you to be using.

Title: Makefile string with spaces

Body:
var := 'C:/some/path here' labas
all:
    @echo $(words $(var))

This returns 3.
How to make it return 2? Or make does not work the way I think??

Body:
Make definitely doesn't work the way you think, if you think that make has any interest in quotes of any type :).  Make ignores (i.e., treats as normal characters like any other) both single- and double-quote characters in virtually every situation, and all make functions work in simple whitespace delimiters without regard to quote characters.

In general, it's not practical to use make with any system that requires spaces in target names.  It just doesn't work: too much of make is based on whitespace as a separator character and there's no general, common way to escape the whitespace that works everywhere.

In your very particular case you can play a trick like this:

E :=
S := $E $E

path := C:/some/path here
xpath := $(subst $S,^,$(path))

var := $(xpath) labas
all:
        @echo $(words $(var))
        @echo $(subst ^,$S,$(var))

Basically, this creates a variable $S which contains a space, then it substitutes all spaces in the variable path with some other, non-space character (here I chose ^ but you can pick what you like, just note it has to be a character which is guaranteed to not appear in the path).

Now this path doesn't contain whitespace so you can use it with make functions.

This has major downsides: not only the complexity visible here, but note these paths cannot be used in target names since they won't actually exist on disk.

In general, you should simply not use paths containing whitespace with make.  If you must use paths containing whitespace, then very likely make is not the right tool for you to be using.


问:
How to create 120 questions with images in Qualtrics (not manually)
I am trying to create 120 questions that have the same text and options (multiple choice) but with different images below in Qualtrics. Any idea on how to do it without manually creating 120 blocks?</p>

答: Use a Loop & Merge block and pipe in the image url as a loop & merge field.</p>


问:
What is the fastest way to encapsulate an index offset access for an array?
For modeling quite an amount of calculations, I need to combine speed with some convenience for the writer and reader of the code.

The first important part is to calculate and store data indexed by year of birth, gender, age, etc .

For example I have a year of birth range from 1900 to 2050. Because I cant declare a non zero indexed array from 1950 to 2050, I want to encapsulate the index shift from [0..150] to [1900..2050]. Obviously it is less error prone and easier to read and write code like

```<code>valueArray.setValue(1950, someValue);
</code>```

than

```<code>valueArray[1950 - 1900] = someValue;
</code>```

if you have to do it hundreds of times with multiple different array ranges.

Speed is crucial for my task. So I want to know is there a better faster way than the for me obvious one shown below. Are there completly different approaches to solving this problem you would take?

public class OffsetArray {

    private int min;
    private int max;
    private double initValue;
    private double[] values;

    public OffsetArray( int min, int max, double initValue ) {
        this.min = min;
        this.max = max;
        this.values = new double[max-min+1];
        this.initValue = initValue;
        this.init();
    }

    private void init() {
        for ( int i = 0; i<max-min+1;i++) {
            values[i] = this.initValue;
        }
    }

    public double getValue(int index) {
        return values[index-min];
    }

    public void setValue(int index, double value ) {
        this.values[index-min] = value;
    }

    public int getMin() {
        return min;
    }

    public int getMax() {
        return max;
    }

```

Edited additional requirements:

I need these kind of arrays with multiple dimensions and with ranges starting with negative numbers, i.e. [-50..50].

答:
Why not use a HashMap?  They are pretty efficient and let you "index" based on a key.

      Map<String, List<Integer>> map = new HashMap<>();
      map.computeIfAbsent("1900-2000", k -> new ArrayList<>()).add(10);
      map.computeIfAbsent("1900-2000", k -> new ArrayList<>()).add(20);
      map.computeIfAbsent("1900-2000", k -> new ArrayList<>()).add(30);

      System.out.println(map.get("1900-2000"));

```

You could have some method that creates the key based on the state of the value (Object) in question.

Body:
For modeling quite an amount of calculations, I need to combine speed with some convenience for the writer and reader of the code.

The first important part is to calculate and store data indexed by year of birth, gender, age, etc .

For example I have a year of birth range from 1900 to 2050. Because I cant declare a non zero indexed array from 1950 to 2050, I want to encapsulate the index shift from [0..150] to [1900..2050]. Obviously it is less error prone and easier to read and write code like

valueArray.setValue(1950, someValue);

than

valueArray[1950 - 1900] = someValue;

if you have to do it hundreds of times with multiple different array ranges.

Speed is crucial for my task. So I want to know is there a better faster way than the for me obvious one shown below. Are there completly different approaches to solving this problem you would take?

public class OffsetArray {

    private int min;
    private int max;
    private double initValue;
    private double[] values;

    public OffsetArray( int min, int max, double initValue ) {
        this.min = min;
        this.max = max;
        this.values = new double[max-min+1];
        this.initValue = initValue;
        this.init();
    }

    private void init() {
        for ( int i = 0; i<max-min+1;i++) {
            values[i] = this.initValue;
        }
    }

    public double getValue(int index) {
        return values[index-min];
    }

    public void setValue(int index, double value ) {
        this.values[index-min] = value;
    }

    public int getMin() {
        return min;
    }

    public int getMax() {
        return max;
    }

Edited additional requirements:

I need these kind of arrays with multiple dimensions and with ranges starting with negative numbers, i.e. [-50..50].

Body:
Why not use a HashMap?  They are pretty efficient and let you "index" based on a key.

      Map<String, List<Integer>> map = new HashMap<>();
      map.computeIfAbsent("1900-2000", k -> new ArrayList<>()).add(10);
      map.computeIfAbsent("1900-2000", k -> new ArrayList<>()).add(20);
      map.computeIfAbsent("1900-2000", k -> new ArrayList<>()).add(30);

      System.out.println(map.get("1900-2000"));

You could have some method that creates the key based on the state of the value (Object) in question.


问:
skipping the complete row if len() of column is lower than 10 in python
I'm trying to apply an if statement in my django view script that would skip the complete row of the product if the description lenght is less than 10, but I don't know how to achieve this..

This is my Django view that calls an API and save the data into my database and as you will see in the commented section this is what I came out with so far:

```<code>def api_data(request):
    if request.GET.get('mybtn'):  # to improve, == 'something':
        resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.headout.com/api/public/v1/product/get/"

        translator = Translator()

        for item in resp_1_data['items']:
            print('parsing, translating and saving item {}'.format(item['id']))
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
                })
            resp_2_data = resp_2.json()

            descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...'

            soup = BeautifulSoup(descriptiontxt, 'lxml')
            parsed = soup.find('p').text

            #what I tried so far

            #if len(parsed) < 10:
            #   skip the complete row and go to the next one

            translation = translator.translate(parsed, dest='fr')

            titlename = item['name']
            titlefr = translator.translate(titlename, dest='fr')

            destinationname = item['city']['name']
            destinationfr = translator.translate(destinationname, dest='fr')

            Product.objects.get_or_create(
                title=titlefr.text,
                destination=destinationfr.text,
                description=translation.text,
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

            time.sleep(2)

    return render(request, "form.html")
</code>```

Please help.

答:
You just need to continue if your length is less than 10 like so,

```<code>if len(parsed) < 10:
    continue
</code>```

This will skip you current iteration.

Hope this helps!

Body:
I'm trying to apply an if statement in my django view script that would skip the complete row of the product if the description lenght is less than 10, but I don't know how to achieve this..

This is my Django view that calls an API and save the data into my database and as you will see in the commented section this is what I came out with so far:

def api_data(request):
    if request.GET.get('mybtn'):  # to improve, == 'something':
        resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.headout.com/api/public/v1/product/get/"

        translator = Translator()

        for item in resp_1_data['items']:
            print('parsing, translating and saving item {}'.format(item['id']))
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
                })
            resp_2_data = resp_2.json()

            descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...'

            soup = BeautifulSoup(descriptiontxt, 'lxml')
            parsed = soup.find('p').text

            #what I tried so far

            #if len(parsed) < 10:
            #   skip the complete row and go to the next one

            translation = translator.translate(parsed, dest='fr')

            titlename = item['name']
            titlefr = translator.translate(titlename, dest='fr')

            destinationname = item['city']['name']
            destinationfr = translator.translate(destinationname, dest='fr')

            Product.objects.get_or_create(
                title=titlefr.text,
                destination=destinationfr.text,
                description=translation.text,
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

            time.sleep(2)

    return render(request, "form.html")

Please help.

Body:
You just need to continue if your length is less than 10 like so,

if len(parsed) < 10:
    continue

This will skip you current iteration.

Hope this helps!


问:
long running task that is viewable having only 1 instance
General question.  A webpage is served to a user, data goes in n out for that session.  In c# and asp.net, how can u create a page on server that continually does a task and also has only 1 instance running.  it does something over and over.  Then as needed a person could view what it's doing.  </p>

答:
You can run a long task in a separate thread and communicate with it when you need. something like this.

```<code>protected void btnRun_Click(object sender, EventArgs e)
{
    var jobState = new StateInfo()
    {
        Id = 1,
        Counter = 0,
        Content = "Start the job",
        Cancelled = false,
        Completed = false
    };
    Session["job"] = jobState;
    System.Threading.ThreadPool.QueueUserWorkItem(
        new System.Threading.WaitCallback(LongJob),
        jobState
        );//returns immediately
    lblToken.Text += "<br />" + jobState.Counter.ToString()
        + " Completed: " + jobState.Completed.ToString()
        + " Cancelled: " + jobState.Cancelled.ToString()
        + "<br />" + jobState.Content;
    btnCancel.Visible = true;
    btnCheck.Visible = true;
}

protected void btnCancel_Click(object sender, EventArgs e)
{
    var jobState = Session["job"] as StateInfo;
    if (!jobState.Completed)
        jobState.Cancelled = true;
    System.Threading.Thread.Sleep(1000);//wait for the next loop to complete
    lblToken.Text += "<br />" + jobState.Counter.ToString()
        + " Completed: " + jobState.Completed.ToString()
        + " Cancelled: " + jobState.Cancelled.ToString()
        + (jobState.Completed || jobState.Cancelled ? "<br />" + jobState.Content : "");
}

protected void btnCheck_Click(object sender, EventArgs e)
{
    var jobState = Session["job"] as StateInfo;
    lblToken.Text += "<br />" + jobState.Counter.ToString()
        + " Completed: " + jobState.Completed.ToString()
        + " Cancelled: " + jobState.Cancelled.ToString()
        + (jobState.Completed || jobState.Cancelled ? "<br />" + jobState.Content : "");
}

private void LongJob(object state)
{
    var jobState = state as StateInfo;
    do
    {
        System.Threading.Thread.Sleep(1000);
        jobState.Counter++;
        if (jobState.Counter >= 100)
        {
            jobState.Completed = true;
            jobState.Content = "The job is completed";
        }
        else if (jobState.Cancelled)
            jobState.Content = "The job is cancelled";
    }
    while (!jobState.Cancelled && !jobState.Completed);
}
[Serializable]
class StateInfo
{
    public int Id { get; set; }
    public int Counter { get; set; }
    public string Content { get; set; }
    public bool Cancelled { get; set; }
    public bool Completed { get; set; }
}
</code>```

and obvious client controls.

```<code><asp:Label ID="lblToken" runat="server"></asp:Label><br />
<asp:Button runat="server" ID="btnRun" OnClick="btnRun_Click" Text="Run" />
<asp:Button runat="server" ID="btnCheck" OnClick="btnCheck_Click" Text="Check State" Visible="false" />
<asp:Button runat="server" ID="btnCancel" OnClick="btnCancel_Click" Text="Cancel" Visible="true" />
</code>```

Body:
You can run a long task in a separate thread and communicate with it when you need. something like this.

protected void btnRun_Click(object sender, EventArgs e)
{
    var jobState = new StateInfo()
    {
        Id = 1,
        Counter = 0,
        Content = "Start the job",
        Cancelled = false,
        Completed = false
    };
    Session["job"] = jobState;
    System.Threading.ThreadPool.QueueUserWorkItem(
        new System.Threading.WaitCallback(LongJob),
        jobState
        );//returns immediately
    lblToken.Text += "<br />" + jobState.Counter.ToString()
        + " Completed: " + jobState.Completed.ToString()
        + " Cancelled: " + jobState.Cancelled.ToString()
        + "<br />" + jobState.Content;
    btnCancel.Visible = true;
    btnCheck.Visible = true;
}

protected void btnCancel_Click(object sender, EventArgs e)
{
    var jobState = Session["job"] as StateInfo;
    if (!jobState.Completed)
        jobState.Cancelled = true;
    System.Threading.Thread.Sleep(1000);//wait for the next loop to complete
    lblToken.Text += "<br />" + jobState.Counter.ToString()
        + " Completed: " + jobState.Completed.ToString()
        + " Cancelled: " + jobState.Cancelled.ToString()
        + (jobState.Completed || jobState.Cancelled ? "<br />" + jobState.Content : "");
}

protected void btnCheck_Click(object sender, EventArgs e)
{
    var jobState = Session["job"] as StateInfo;
    lblToken.Text += "<br />" + jobState.Counter.ToString()
        + " Completed: " + jobState.Completed.ToString()
        + " Cancelled: " + jobState.Cancelled.ToString()
        + (jobState.Completed || jobState.Cancelled ? "<br />" + jobState.Content : "");
}

private void LongJob(object state)
{
    var jobState = state as StateInfo;
    do
    {
        System.Threading.Thread.Sleep(1000);
        jobState.Counter++;
        if (jobState.Counter >= 100)
        {
            jobState.Completed = true;
            jobState.Content = "The job is completed";
        }
        else if (jobState.Cancelled)
            jobState.Content = "The job is cancelled";
    }
    while (!jobState.Cancelled && !jobState.Completed);
}
[Serializable]
class StateInfo
{
    public int Id { get; set; }
    public int Counter { get; set; }
    public string Content { get; set; }
    public bool Cancelled { get; set; }
    public bool Completed { get; set; }
}

and obvious client controls.

<asp:Label ID="lblToken" runat="server"></asp:Label><br />
<asp:Button runat="server" ID="btnRun" OnClick="btnRun_Click" Text="Run" />
<asp:Button runat="server" ID="btnCheck" OnClick="btnCheck_Click" Text="Check State" Visible="false" />
<asp:Button runat="server" ID="btnCancel" OnClick="btnCancel_Click" Text="Cancel" Visible="true" />


问:
Django auth model: combine multiple fields into one username_field
I have multiple fields users have to specify on signup: date_of_birth, first_name, last_name.

What I now want is to combine these fields to one for USERNAME_FIELD, like so:
John_Doe_01011988

The following obviously doesn't work:

```<code>USERNAME_FIELD='%s-%s' % ('first_name', 'last_name')
</code>```

答:
If your date_of_birth is a datetime you could transform it into a string and append all the strings together like so :

```<code>import datetime

first_name = 'John'
last_name = 'Doe'
date_of_birth = datetime.datetime(1988, 1, 1)

str_dob = str(date_of_birth).split(' ')[0].replace('-', '')
username = "{}_{}_{}".format(first_name,last_name, str_dob)
</code>```

Out :

```<code>'John_Doe_19880101'
</code>```

Body:
I have multiple fields users have to specify on signup: date_of_birth, first_name, last_name.

What I now want is to combine these fields to one for USERNAME_FIELD, like so:
John_Doe_01011988

The following obviously doesn't work:

USERNAME_FIELD='%s-%s' % ('first_name', 'last_name')

Body:
If your date_of_birth is a datetime you could transform it into a string and append all the strings together like so :

import datetime

first_name = 'John'
last_name = 'Doe'
date_of_birth = datetime.datetime(1988, 1, 1)

str_dob = str(date_of_birth).split(' ')[0].replace('-', '')
username = "{}_{}_{}".format(first_name,last_name, str_dob)

Out :

'John_Doe_19880101'


问:
Why can not we use `std::multiset` with custom compare lambda as the value of a `std::map`?
This is a follow-up question of asked
How to provide custom comparator for `std::multiset` without overloading `operator()`, `std::less`, `std::greater`?

and I have tried to solve by the following manner.

Basic

One can provide custom compare lambda function(since c++11) to the std::multiset of a member of a class as follows:

```<code>#include <iostream>
#include <set>

const auto compare = [](int lhs, int rhs) noexcept { return lhs > rhs; };
struct Test
{
    std::multiset<int, decltype(compare)> _set{compare};
    Test() = default;
};
</code>```

Simple enough.

My Situation

The member of Test class is

```<code>std::map<std::string, std::multiset<int, /* custom compare */>> scripts{};
</code>```

I tried to use the std::multiset with custom

functor Compare (case - 1)

std::greater<>  (case - 2)

lambda function   (case - 3)

The first two options are a success. But the case of lambda as a custom compare function it did not work. Here is the MCVC:https://godbolt.org/z/mSHi1p

```<code>#include <iostream>
#include <functional>
#include <string>
#include <map>
#include <set>

const auto compare = [](int lhs, int rhs) noexcept { return lhs > rhs; };
class Test
{
private:
    struct Compare
    {
        bool operator()(const int lhs, const int rhs) const noexcept { return lhs > rhs; }
    };

private:
    // std::multiset<int, Compare> dummy;                      // works fine
    // std::multiset<int, std::greater<>> dummy;               // works fine
    std::multiset<int, decltype(compare)> dummy{ compare };    // does not work
    using CustomMultiList = decltype(dummy);

public:
    std::map<std::string, CustomMultiList> scripts{};
};

int main()
{
    Test t{};
    t.scripts["Linux"].insert(5);
    t.scripts["Linux"].insert(8);
    t.scripts["Linux"].insert(0);

    for (auto a : t.scripts["Linux"]) {
        std::cout << a << '\n';
    }
}
</code>```

Error message:

```<code>error C2280 : '<lambda_778ad726092eb2ad4bce2e3abb93017f>::<lambda_778ad726092eb2ad4bce2e3abb93017f>(void)' : attempting to reference a deleted function
note: see declaration of '<lambda_778ad726092eb2ad4bce2e3abb93017f>::<lambda_778ad726092eb2ad4bce2e3abb93017f>'
note: '<lambda_778ad726092eb2ad4bce2e3abb93017f>::<lambda_778ad726092eb2ad4bce2e3abb93017f>(void)' : function was explicitly deleted
note: while compiling class template member function 'std::multiset<int,const <lambda_778ad726092eb2ad4bce2e3abb93017f>,std::allocator<int>>::multiset(void)'
note: see reference to function template instantiation 'std::multiset<int,const <lambda_778ad726092eb2ad4bce2e3abb93017f>,std::allocator<int>>::multiset(void)' being compiled
note: see reference to class template instantiation 'std::multiset<int,const <lambda_778ad726092eb2ad4bce2e3abb93017f>,std::allocator<int>>' being compiled
</code>```

It sounds like I tried to default construct the passed lambda, which is not possible until c++20.

If that the case where has it happened?
Is it possible to solve this using a lambda compare function within the scope of c++11 till c++17?

答:
To do it in one line, you need something like this:

```<code>t.scripts.try_emplace("Linux", compare).first->second.insert(5);
</code>```

This is because the lambda compare has to be passed to the constructor of your multiset.  Otherwise there's no comparison object and the multiset cannot be constructed.

Demo: https://godbolt.org/z/rVb3-D

Body:
This is a follow-up question of asked
How to provide custom comparator for `std::multiset` without overloading `operator()`, `std::less`, `std::greater`?

and I have tried to solve by the following manner.

Basic

One can provide custom compare lambda function(since c++11) to the std::multiset of a member of a class as follows:

#include <iostream>
#include <set>

const auto compare = [](int lhs, int rhs) noexcept { return lhs > rhs; };
struct Test
{
    std::multiset<int, decltype(compare)> _set{compare};
    Test() = default;
};

Simple enough.

My Situation

The member of Test class is

std::map<std::string, std::multiset<int, /* custom compare */>> scripts{};

I tried to use the std::multiset with custom

functor Compare (case - 1)

std::greater<>  (case - 2)

lambda function   (case - 3)

The first two options are a success. But the case of lambda as a custom compare function it did not work. Here is the MCVC:https://godbolt.org/z/mSHi1p

#include <iostream>
#include <functional>
#include <string>
#include <map>
#include <set>

const auto compare = [](int lhs, int rhs) noexcept { return lhs > rhs; };
class Test
{
private:
    struct Compare
    {
        bool operator()(const int lhs, const int rhs) const noexcept { return lhs > rhs; }
    };

private:
    // std::multiset<int, Compare> dummy;                      // works fine
    // std::multiset<int, std::greater<>> dummy;               // works fine
    std::multiset<int, decltype(compare)> dummy{ compare };    // does not work
    using CustomMultiList = decltype(dummy);

public:
    std::map<std::string, CustomMultiList> scripts{};
};

int main()
{
    Test t{};
    t.scripts["Linux"].insert(5);
    t.scripts["Linux"].insert(8);
    t.scripts["Linux"].insert(0);

    for (auto a : t.scripts["Linux"]) {
        std::cout << a << '\n';
    }
}

Error message:

error C2280 : '<lambda_778ad726092eb2ad4bce2e3abb93017f>::<lambda_778ad726092eb2ad4bce2e3abb93017f>(void)' : attempting to reference a deleted function
note: see declaration of '<lambda_778ad726092eb2ad4bce2e3abb93017f>::<lambda_778ad726092eb2ad4bce2e3abb93017f>'
note: '<lambda_778ad726092eb2ad4bce2e3abb93017f>::<lambda_778ad726092eb2ad4bce2e3abb93017f>(void)' : function was explicitly deleted
note: while compiling class template member function 'std::multiset<int,const <lambda_778ad726092eb2ad4bce2e3abb93017f>,std::allocator<int>>::multiset(void)'
note: see reference to function template instantiation 'std::multiset<int,const <lambda_778ad726092eb2ad4bce2e3abb93017f>,std::allocator<int>>::multiset(void)' being compiled
note: see reference to class template instantiation 'std::multiset<int,const <lambda_778ad726092eb2ad4bce2e3abb93017f>,std::allocator<int>>' being compiled

It sounds like I tried to default construct the passed lambda, which is not possible until c++20.

If that the case where has it happened?
Is it possible to solve this using a lambda compare function within the scope of c++11 till c++17?

Body:
To do it in one line, you need something like this:

t.scripts.try_emplace("Linux", compare).first->second.insert(5);

This is because the lambda compare has to be passed to the constructor of your multiset.  Otherwise there's no comparison object and the multiset cannot be constructed.

Demo: https://godbolt.org/z/rVb3-D


问:
unable to install libpng12-0 on kali
I am using the latest version of Kali.
I installed the Cisco Packet Tracer version 7.2.
I ran it I got this error

./PacketTracer7: error while loading shared libraries: libpng12.so.0:
  cannot open shared object file: No such file or directory

Now I am going to install libpng12

but I get this error

(Reading database ... 485972 files and directories currently
  installed.) Preparing to unpack libpng12-0_1.2.50-2+deb8u3_amd64.deb
  ... Unpacking libpng12-0:amd64 (1.2.50-2+deb8u3) ... dpkg: error
  processing archive libpng12-0_1.2.50-2+deb8u3_amd64.deb (--install):
  unable to install new version of
  '/usr/lib/x86_64-linux-gnu/libpng12.so.0': No such file or directory
  Errors were encountered while processing:
  libpng12-0_1.2.50-2+deb8u3_amd64.deb

I am using Debian sources list

https://packages.debian.org/jessie/amd64/libpng12-0/download

答:
I have been through the same problem a solution I found was to :

1-Extract the content of the debian package
mkdir out; dpkg -x libpng12-0_1.2.50-2+deb8u3_amd64.deb  ./out

2-Copy the file libpng12.so.0 to your Packet tracer's installation directory inside the .../pt/bin folder like this:

cp ./out/lib/x86_64-linux-gnu/libpng12.so.0 /opt/packettracer/bin/

Title: unable to install libpng12-0 on kali


问:
How to select letters from a string until predefined point?
I would like to extract all consonants in a string before the first vowel, ideally without using regex. If I have the word truck for example I would like to extract the "tr", for "street" I would like to extract "str".

I tried the following but received the error wrong number of arguments (given 0, expected 1) for the execution of the block in vowels.

Can someone explain where the error is or suggest an easier way to do this?

```<code>vowels = ["a", "e", "i", "o", "u"]

def vowels(words)
  letters = words.split("")
  consonants = []
  letters.each do |letter|
    consonants << letter until vowels.include?(letter)
  end
  consonants
end
</code>```

答:
You said "ideally without using regex". Sorry, but I think most Rubyists would agree that a regex is the tool of choice here:

```<code>"whatchamacallit"[/\A[^aeiou]*/] #=> "wh"
"apple"[/\A[^aeiou]*/]           #=> ""
</code>```

The regex reads, "match the beginning of the string (\A) followed by zero or more (*) characters that are not (^) vowels", [^aeiou] being a character class.

Body:
I would like to extract all consonants in a string before the first vowel, ideally without using regex. If I have the word truck for example I would like to extract the "tr", for "street" I would like to extract "str".

I tried the following but received the error wrong number of arguments (given 0, expected 1) for the execution of the block in vowels.

Can someone explain where the error is or suggest an easier way to do this?

vowels = ["a", "e", "i", "o", "u"]

def vowels(words)
  letters = words.split("")
  consonants = []
  letters.each do |letter|
    consonants << letter until vowels.include?(letter)
  end
  consonants
end

Body:
You said "ideally without using regex". Sorry, but I think most Rubyists would agree that a regex is the tool of choice here:

"whatchamacallit"[/\A[^aeiou]*/] #=> "wh"
"apple"[/\A[^aeiou]*/]           #=> ""

The regex reads, "match the beginning of the string (\A) followed by zero or more (*) characters that are not (^) vowels", [^aeiou] being a character class.


问:
Which one would be efficient design for firebase database?
I tried to design a book sharing app. A user can enroll in different group and share his books. Each book contains field currentGroupId and ownerID.
I need to show all books of a user and all books shared in particular group. Will it be efficient to keep all books together? Or should I keep books under each group and user?

答:
```<code>{
  books: {
    1: { _id: 1, userId: 10, groupId: 10 }
  },
  users: {
    10: { _id: 10 }
  }
}
</code>```

so

```<code>const booksFromUser = firestore.collection(`books`).where(`userId`, `==`, WHATEVER_USER_ID)

const booksFromGroup = firestore.collection(`books`).where(`groupId`, `==`, WHATEVER_GROUP_ID)
</code>```

that should give you a starting point, it's a common pattern :), I wouldn't even create a group collection if you really dont need it.

Body:
{
  books: {
    1: { _id: 1, userId: 10, groupId: 10 }
  },
  users: {
    10: { _id: 10 }
  }
}

so

const booksFromUser = firestore.collection(`books`).where(`userId`, `==`, WHATEVER_USER_ID)

const booksFromGroup = firestore.collection(`books`).where(`groupId`, `==`, WHATEVER_GROUP_ID)

that should give you a starting point, it's a common pattern :), I wouldn't even create a group collection if you really dont need it.


问:
Why do I get an error TS2339: Property 'classList' does not exist on type 'never'?
I am developing a simple component "BackToTop"

const BackToTop: React.FC = () => {
  const bttEl = useRef(null);
  function scrollHandler(): void {
    var bttHtmlEl: HTMLElement | null = bttEl.current;
    // console.log(bttHtmlEl); Element OK!
    if ( bttHtmlEl ) {
      window.pageYOffset > 50 ? bttHtmlEl.classList.remove('is-hide'): bttHtmlEl.classList.add('is-hide');
    } else {
      console.error('BackToTop is null.');
    }
  }
  useEffect( ()=>{
    window.addEventListener('scroll', scrollHandler);
      return ()=>{
        window.removeEventListener('scroll', scrollHandler);
      }
    }
  )
```

src/components/BackToTop.tsx:54:43 - error TS2339: Property 'classList' does not exist on type 'never'.

54       window.pageYOffset > 50 ? bttHtmlEl.classList.remove('is-hide'): bttHtmlEl.classList.add('is-hide');
                                             ~~~~~~~~~

src/components/BackToTop.tsx:54:82 - error TS2339: Property 'classList' does not exist on type 'never'.

54       window.pageYOffset > 50 ? bttHtmlEl.classList.remove('is-hide'): bttHtmlEl.classList.add('is-hide');
                                                                                ~~~~~~~~~

答:
TypeScript is telling you that the code block inside the if statement will never run.

```<code>const bttEl = useRef(null);
function scrollHandler(): void {
  var bttHtmlEl: HTMLElement | null = bttEl.current;
  if (bttHtmlEl) {
    // According to the type definitions,
    // this code block will never execute,
    // because useRef(null).current is always null.
  }
}
</code>```

That code block will never run because useRef(null).current will always return null.

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).

In other words, TypeScript is interpreting your code like this:

```<code>var bttHtmlEl = null;
if (bttHtmlEl) {
  // This code block will never execute.
}
</code>```

Since the code block will never execute, any variable inside that code block will never have a value. That's what the never type represents.

Body:
I am developing a simple component "BackToTop"

const BackToTop: React.FC = () => {
  const bttEl = useRef(null);
  function scrollHandler(): void {
    var bttHtmlEl: HTMLElement | null = bttEl.current;
    // console.log(bttHtmlEl); Element OK!
    if ( bttHtmlEl ) {
      window.pageYOffset > 50 ? bttHtmlEl.classList.remove('is-hide'): bttHtmlEl.classList.add('is-hide');
    } else {
      console.error('BackToTop is null.');
    }
  }
  useEffect( ()=>{
    window.addEventListener('scroll', scrollHandler);
      return ()=>{
        window.removeEventListener('scroll', scrollHandler);
      }
    }
  )

src/components/BackToTop.tsx:54:43 - error TS2339: Property 'classList' does not exist on type 'never'.

54       window.pageYOffset > 50 ? bttHtmlEl.classList.remove('is-hide'): bttHtmlEl.classList.add('is-hide');
                                             ~~~~~~~~~

src/components/BackToTop.tsx:54:82 - error TS2339: Property 'classList' does not exist on type 'never'.

54       window.pageYOffset > 50 ? bttHtmlEl.classList.remove('is-hide'): bttHtmlEl.classList.add('is-hide');
                                                                                ~~~~~~~~~

Body:
TypeScript is telling you that the code block inside the if statement will never run.

const bttEl = useRef(null);
function scrollHandler(): void {
  var bttHtmlEl: HTMLElement | null = bttEl.current;
  if (bttHtmlEl) {
    // According to the type definitions,
    // this code block will never execute,
    // because useRef(null).current is always null.
  }
}

That code block will never run because useRef(null).current will always return null.

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).

In other words, TypeScript is interpreting your code like this:

var bttHtmlEl = null;
if (bttHtmlEl) {
  // This code block will never execute.
}

Since the code block will never execute, any variable inside that code block will never have a value. That's what the never type represents.


问:
array manipulation
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:</p>

```<code>int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}
</code>```

答:
In c++, try to avoid raw pointers. But since this is an exercise, this is a c++ way :

```<code>int *expand(int *&arr, int size)
{
    int *newArray = new int[2*size];

    std::copy( &arr[0],&arr[size], &newArray[0] );
    // delete [] arr; // need to delete?

    return newArray;
}
</code>```

To do in place :

```<code>void expand(int *&arr, int size)
{
    int *newArray = new int[2*size];

    std::copy( &arr[0],&arr[size], &newArray[0] );
    delete [] arr;

    arr = newArray;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: array manipulation

Body:
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:

int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}

Body:
In c++, try to avoid raw pointers. But since this is an exercise, this is a c++ way :

int *expand(int *&arr, int size)
{
    int *newArray = new int[2*size];

    std::copy( &arr[0],&arr[size], &newArray[0] );
    // delete [] arr; // need to delete?

    return newArray;
}

To do in place :

void expand(int *&arr, int size)
{
    int *newArray = new int[2*size];

    std::copy( &arr[0],&arr[size], &newArray[0] );
    delete [] arr;

    arr = newArray;
}


问:
Looking for an appropriate synchronization mechanism
Presume I have the following (pseudo) code:

class Cache {
    Entry addIfMissing(String data) {
        // omitted for brevity
    }
    void evictOldEntries() {
        // omitted for brevity
    }
}
```

<pre class="lang-java prettyprint-override"><code>class Program {
    private Cache cache = new Cache();

    doWork() { // called from multiple threads
        var entry = cache.addIfMissing("omitted for brevity");
        // work with entry
    }

    static {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            cache.evictOldEntries();
        }, 10, 10, TimeUnit.MINUTES);
    }
}
</code>```

I want to make sure while the evictOldEntries method is running all the other threads in the program have to wait for it to be done.

Which synchronization mechanism would be appropriate in such a scenario?

答:
I think ReentrantReadWriteLock is just what I need:

class Program {
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

    void doWork() { // called from multiple threads
        rwl.readLock().lock();
        try {
            var entry = cache.addIfMissing("omitted for brevity");
            // work with entry
        } finally {
            rwl.readLock().unlock();
        }
    }

    static {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            rwl.writeLock().lock();
            try {
                cache.evictOldEntries();
            } finally {
                rwl.writeLock().unlock();
            }
        }, 10, 10, TimeUnit.MINUTES);
    }
}
```

This way once the writeLock is aquired doWork has to block and vice-versa.

Body:
Presume I have the following (pseudo) code:

class Cache {
    Entry addIfMissing(String data) {
        // omitted for brevity
    }
    void evictOldEntries() {
        // omitted for brevity
    }
}

class Program {
    private Cache cache = new Cache();

    doWork() { // called from multiple threads
        var entry = cache.addIfMissing("omitted for brevity");
        // work with entry
    }

    static {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            cache.evictOldEntries();
        }, 10, 10, TimeUnit.MINUTES);
    }
}

I want to make sure while the evictOldEntries method is running all the other threads in the program have to wait for it to be done.

Which synchronization mechanism would be appropriate in such a scenario?

Body:
I think ReentrantReadWriteLock is just what I need:

class Program {
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

    void doWork() { // called from multiple threads
        rwl.readLock().lock();
        try {
            var entry = cache.addIfMissing("omitted for brevity");
            // work with entry
        } finally {
            rwl.readLock().unlock();
        }
    }

    static {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            rwl.writeLock().lock();
            try {
                cache.evictOldEntries();
            } finally {
                rwl.writeLock().unlock();
            }
        }, 10, 10, TimeUnit.MINUTES);
    }
}

This way once the writeLock is aquired doWork has to block and vice-versa.


问:
Create and Filling arc progressively with css - circle progress bar
I'm struggling to fill an arc like a progress bar because I'm not that good working with css.

I want to achieve a "progress" arc like this:

I came across with this: https://codepen.io/enslavedeagle/pen/AXzaKE

```<code>#arc,
#arc::before {
  display: block;
  box-sizing: border-box;
  border-radius: 100%;
  width: 100px;
  height: 100px;
  position: absolute;
  background-color: transparent;
  padding: 0;
  margin: 0;
}

#arc {
  border: solid #00BBEE 12px;
  clip: rect(0px, 100px, 50px, 0px);
  margin: 25px;
}

#arc::before {
  content: '';
  border: solid black 12px;
  top: -12px;
  left: -12px;
  clip: rect(0px, 100px, 50px, 0px);
  transform: rotate(-150deg);
  /* define the fill length, using the rotation above.
     from -180deg (0% fill) to 0deg (100% fill) */
  /* if you have a better solution to make thing like this
     work, please let me know! :) */
}
</code>```

and try to customize to be like what I want to but with no sucess until now: here: https://codepen.io/anon/pen/qpNrEP

Could any one give some help with this? Can also be alternative solution to achieve this.

I appreciate

Kind regards,

答:
After not finding the answer I liked here I did some work myself and made a Codepen that you can use that makes progress bars exactly as you described with the inputs being: the amount of degrees of a circle that should be 100%, the radius of the circle and the percentage you to have filled.
Progress bar example (image)

HTML:

```<code><section class="stat" id="sectionId">
  <svg viewbox="0 0 100 100">
    <path class="bar" d="
    M 10, 50
    a 40,40 0 1,0 80,0
    a 40,40 0 1,0 -80,0
   "/>
    <path class="progress" d="
      M 10, 50
    a 40,40 0 1,0 80,0
    a 40,40 0 1,0 -80,0
    "/>
  </svg>

  <script type="text/javascript">
    _.makeProgressBar("01", 240, 40, 86);
  </script>
</section>
</code>```

CSS:

```<code>.stat {
  width: 200px;
}

svg {
  display: block;
  transform-origin: center center;
  transform: rotate( 90deg );
}

path {
  stroke-linecap: round;
  stroke-width: 6px ;
  fill:none;
}
</code>```

JS:

```<code>_ = {};

//this is a self executing function, it keeps the global namespace clean
(function(win, doc, helper){

  helper.makeProgressBar = function(id, totalDegrees, radius, percentage) {
    var section = doc.getElementById(id);
    var svg = section.children[0];
    var bar = svg.children[0];
    var progress = svg.children[1];

    if(percentage > 100){
        percentage = 100;
    }
    if(percentage < 0){
        percentage = 0;
    }

    var percentageDegrees = calculateDegreesFromPercentage(totalDegrees, percentage);

    var barDash = calculateDash(totalDegrees, radius);
    var barGap = calculateDash ( 360 - totalDegrees, radius) * 2;

    var progressDash = calculateDash(percentageDegrees, radius);
    var progressGap = calculateDash(360 - percentageDegrees, radius) * 2;

    var rotation = 0 - ((totalDegrees - percentageDegrees) / 2);

    bar.setAttribute("style", "stroke: #707070; fill: none; stroke-dasharray: " + barDash + " " + barGap + ";");
    progress.setAttribute("style", "stroke: #23CE39; fill: none; stroke-dasharray: " + progressDash + " " + progressGap + "; transform-origin: center center; transform: rotate("+ rotation +"deg)");
  }

  calculateDegreesFromPercentage = function(totalDegrees, percentage) {
    return totalDegrees/100*percentage;
  }

  calculateDash = function(degrees, radius) {
    return degrees * Math.PI / 180 * 0.5 * radius;
  }
})(window, document, _);
</code>```

Body:
I'm struggling to fill an arc like a progress bar because I'm not that good working with css.

I want to achieve a "progress" arc like this:

I came across with this: https://codepen.io/enslavedeagle/pen/AXzaKE

#arc,
#arc::before {
  display: block;
  box-sizing: border-box;
  border-radius: 100%;
  width: 100px;
  height: 100px;
  position: absolute;
  background-color: transparent;
  padding: 0;
  margin: 0;
}

#arc {
  border: solid #00BBEE 12px;
  clip: rect(0px, 100px, 50px, 0px);
  margin: 25px;
}

#arc::before {
  content: '';
  border: solid black 12px;
  top: -12px;
  left: -12px;
  clip: rect(0px, 100px, 50px, 0px);
  transform: rotate(-150deg);
  /* define the fill length, using the rotation above.
     from -180deg (0% fill) to 0deg (100% fill) */
  /* if you have a better solution to make thing like this
     work, please let me know! :) */
}

and try to customize to be like what I want to but with no sucess until now: here: https://codepen.io/anon/pen/qpNrEP

Could any one give some help with this? Can also be alternative solution to achieve this.

I appreciate

Kind regards,

Body:
After not finding the answer I liked here I did some work myself and made a Codepen that you can use that makes progress bars exactly as you described with the inputs being: the amount of degrees of a circle that should be 100%, the radius of the circle and the percentage you to have filled.
Progress bar example (image)

HTML:

<section class="stat" id="sectionId">
  <svg viewbox="0 0 100 100">
    <path class="bar" d="
    M 10, 50
    a 40,40 0 1,0 80,0
    a 40,40 0 1,0 -80,0
   "/>
    <path class="progress" d="
      M 10, 50
    a 40,40 0 1,0 80,0
    a 40,40 0 1,0 -80,0
    "/>
  </svg>

  <script type="text/javascript">
    _.makeProgressBar("01", 240, 40, 86);
  </script>
</section>

CSS:

.stat {
  width: 200px;
}

svg {
  display: block;
  transform-origin: center center;
  transform: rotate( 90deg );
}

path {
  stroke-linecap: round;
  stroke-width: 6px ;
  fill:none;
}

JS:

_ = {};

//this is a self executing function, it keeps the global namespace clean
(function(win, doc, helper){

  helper.makeProgressBar = function(id, totalDegrees, radius, percentage) {
    var section = doc.getElementById(id);
    var svg = section.children[0];
    var bar = svg.children[0];
    var progress = svg.children[1];

    if(percentage > 100){
        percentage = 100;
    }
    if(percentage < 0){
        percentage = 0;
    }

    var percentageDegrees = calculateDegreesFromPercentage(totalDegrees, percentage);

    var barDash = calculateDash(totalDegrees, radius);
    var barGap = calculateDash ( 360 - totalDegrees, radius) * 2;

    var progressDash = calculateDash(percentageDegrees, radius);
    var progressGap = calculateDash(360 - percentageDegrees, radius) * 2;

    var rotation = 0 - ((totalDegrees - percentageDegrees) / 2);

    bar.setAttribute("style", "stroke: #707070; fill: none; stroke-dasharray: " + barDash + " " + barGap + ";");
    progress.setAttribute("style", "stroke: #23CE39; fill: none; stroke-dasharray: " + progressDash + " " + progressGap + "; transform-origin: center center; transform: rotate("+ rotation +"deg)");
  }

  calculateDegreesFromPercentage = function(totalDegrees, percentage) {
    return totalDegrees/100*percentage;
  }

  calculateDash = function(degrees, radius) {
    return degrees * Math.PI / 180 * 0.5 * radius;
  }
})(window, document, _);


问:
What does key mean when creating a kubernetes configmap from a file
I see here a syntax like this:

```<code>kubectl create cm configmap4 --from-file=special=config4.txt
</code>```

I did not find a description of what repetition of = and the special means here.
Kubernetes documentation here only denotes one time usage of = after --from-file while creating configmaps in kubectl.

答:
```<code>kubectl create configmap my-config --from-file=path/to/bar
</code>```

When creating a configmap based on a file, the key will default to the basename of the file, and the value will default to the file content.  If the basename is an invalid key, you may specify an alternate key.

Create a new configmap named my-config with specified keys instead of file basenames on disk

```<code>kubectl create configmap my-config --from-file=key1=/path/to/bar/file1.txt --from-file=key2=/path/to/bar/file2.txt
</code>```

Body:
I see here a syntax like this:

kubectl create cm configmap4 --from-file=special=config4.txt

I did not find a description of what repetition of = and the special means here.
Kubernetes documentation here only denotes one time usage of = after --from-file while creating configmaps in kubectl.

Body:
kubectl create configmap my-config --from-file=path/to/bar

When creating a configmap based on a file, the key will default to the basename of the file, and the value will default to the file content.  If the basename is an invalid key, you may specify an alternate key.

Create a new configmap named my-config with specified keys instead of file basenames on disk

kubectl create configmap my-config --from-file=key1=/path/to/bar/file1.txt --from-file=key2=/path/to/bar/file2.txt


问:
AttributeError: module 'theano' has no attribute 'tests'
I am trying to use theano gpu on my ubuntu, but each time after it running one time successfully, it will give me the error like this when I try to run next time. No idea why, could anyone help me ?

import theano
      Traceback (most recent call last):
        File "", line 1, in
        File "/home/sirius/anaconda3/lib/python3.5/site-packages/theano/init.py", line 95, in
          if hasattr(theano.tests, "TheanoNoseTester"):
      AttributeError: module 'theano' has no attribute 'tests'

答:
For latest version of Theano (1.04)

import theano generates an error without the nose package installed

install via conda or pip pip install nose / conda install nose


问:
Register a post_load hook after Schema defintion?
I'm trying to implement a Schema that deserializes into an object, where the object class is not known at Schema-definition time. I would have assumed that I can register a post_load function at runtime, but it appears that post_load works only for class methods.

It seems like I could make it work by either:

Updating Schema._hooks manually or by

Somehow creating a bound method at runtime and registering that.

Since both of these options are somewhat hack-ish, is there an official way to achieve the same result?

答:
Just if anyone else need this, I've solved it with a custom metaclass that pre-registers a post_load function whose actual implementation can be supplied at runtime:

from types import MethodType

from marshmallow import Schema, post_load
from marshmallow.schema import SchemaMeta

class MyCustomSchemaMeta(SchemaMeta):

    def __init__(cls, *args, **kwargs):
        super().__init__(*args, **kwargs)

        def make_obj(*args, **kwargs):
            raise NotImplementedError

        # This post_load call registers the method with the Schema._hooks dict
        cls.make_obj = post_load(make_obj)

class MyCustomSchema(Schema, metaclass=MyCustomSchemaMeta):
    """This is the base class that my schemas inherit."""

# The actual implementation of make_obj (and hence the class to deserialize to)
# can now be provided at runtime. The post_load call does not affect the schema
# anymore, but sets some parameters on the method.
MyCustomSchema.make_obj = MethodType(
    post_load(lambda self, data: MyClass(**data)), MyCustomSchema
)
```


问:
express res not working after DB connection
I try to connect the DB with Node.js. If I fire the script from console, all seems fine. But accessing from browser, response stops when connecting

From console, I get
inside contest
Example all listening on port 3000!
Connected Con!

From browser, I get
Hello World!inside restest

Since the the "listening..." message was before "Connected" in console version, I thought that in browser version, maybe the system got res.end() before it got connected to DB. Thus, I moved the res.end() from end of app.get -function to end of restest -function, and put a send()- to original place just in case. But that was not the reason as I still cannot get the "Connected Res!" -message.

```<code>var http = require('http');
const express = require('express');
const app = express();
const port = 3000;
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "login",
  password: "psw",
  database: "db"
});

function restest(req, res) {
    res.write("inside restest");

    con.connect(function(err) {
        if (err) throw err;
        res.write("Connected Res!");
        res.end();
    });
}

function contest() {
    console.log("inside contest");

    con.connect(function(err) {
        if (err) throw err;
        console.log("Connected Con!");
    });
}

contest();

app.get('/nodejs/', function(req, res) {
    res.write('Hello World!');
    restest(req,res);
    res.send("this should not print out");
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));
</code>```

No error messages, it just stops responses after writing "inside restest"

答:
I believe you are mixing up some sync/async concepts.

Try something like this maybe it helps:

```<code>function restest(req, res, next) {
    res.write('inside restest');

    con.connect(function(err) {
        if (err) throw err;
        res.write('Connected Res!');
        next();
    });
}

function contest(req, res, next) {
    console.log('inside contest');

    con.connect(function(err) {
        if (err) throw err;
        console.log('Connected Con!');
        next();
    });
}

app.get('/nodejs/', [contest, restest],function(req, res) {
    res.write('Hello World!');
    restest(req,res);
});
</code>```

Body:
I try to connect the DB with Node.js. If I fire the script from console, all seems fine. But accessing from browser, response stops when connecting

From console, I get
inside contest
Example all listening on port 3000!
Connected Con!

From browser, I get
Hello World!inside restest

Since the the "listening..." message was before "Connected" in console version, I thought that in browser version, maybe the system got res.end() before it got connected to DB. Thus, I moved the res.end() from end of app.get -function to end of restest -function, and put a send()- to original place just in case. But that was not the reason as I still cannot get the "Connected Res!" -message.

var http = require('http');
const express = require('express');
const app = express();
const port = 3000;
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "login",
  password: "psw",
  database: "db"
});

function restest(req, res) {
    res.write("inside restest");

    con.connect(function(err) {
        if (err) throw err;
        res.write("Connected Res!");
        res.end();
    });
}

function contest() {
    console.log("inside contest");

    con.connect(function(err) {
        if (err) throw err;
        console.log("Connected Con!");
    });
}

contest();

app.get('/nodejs/', function(req, res) {
    res.write('Hello World!');
    restest(req,res);
    res.send("this should not print out");
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

No error messages, it just stops responses after writing "inside restest"

Body:
I believe you are mixing up some sync/async concepts.

Try something like this maybe it helps:

function restest(req, res, next) {
    res.write('inside restest');

    con.connect(function(err) {
        if (err) throw err;
        res.write('Connected Res!');
        next();
    });
}

function contest(req, res, next) {
    console.log('inside contest');

    con.connect(function(err) {
        if (err) throw err;
        console.log('Connected Con!');
        next();
    });
}

app.get('/nodejs/', [contest, restest],function(req, res) {
    res.write('Hello World!');
    restest(req,res);
});


问:
How to open a specific web page once submit button is clicked in the form?
I would like the submit button to display a specific page once it's clicked.

I know how to process the data sent from the form, but after processing the data I want to go to a specific page like "homepage" which I have already created before.

答:
use header(location...) at the bottom of the php page that handles the form data to then redirect the user to the desired location (ie the index.html that serves as your homepage).</p>

```<code>< ?php header("Location: index.html"); ?>
</code>```

Body:
use header(location...) at the bottom of the php page that handles the form data to then redirect the user to the desired location (ie the index.html that serves as your homepage).

< ?php header("Location: index.html"); ?>


问:
bind click event to child component using v-bind
I created a simple Minesweeper game and when it comes to the decision, which cell to render there are three possibilities:

Unrevealed cell

Revealed mine cell

Revealed neutral cell

I created a row component that renders all the cells contained by the row.

```<code><template>
  <div>

    <component
      v-for="(cell, columnIndex) in row"
      :key="columnIndex"
      v-bind="getCellProps(cell, columnIndex)"
      :is="getComponentCell(cell)"
    />

  </div>
</template>

<script>
// imports here

export default {
  components: {
    UnrevealedCell,
    RevealedNeutralCell,
    RevealedMineCell
  },
  props: {
    row: Array,
    rowIndex: Number
  },
  methods: {
    getCellProps: function(cell, columnIndex) {
      if(cell.revealed) {
        if (cell.isMine) {
          return {};
        } else {
          return {
            mineNeighbours: cell.mineNeighbours
          };
        }
      } else {
        return {
          unrevealedCell: cell,
          x: columnIndex,
          y: this.rowIndex,
          cellClicked: this.onCellClicked
        };
      }
    },
    getComponentCell: function(cell) {
      if(cell.revealed) {
        if (cell.isMine) {
          return RevealedMineCell;
        } else {
          return RevealedNeutralCell;
        }
      } else {
        return UnrevealedCell;
      }
    },
    onCellClicked: function(x, y) {
      debugger;
    }
  }
}
</script>
</code>```

Unfortunately my cellClicked event is not working. The child component is able to emit the event correctly but my onCellClicked doesn't get executed. I think this is because I can't write

cellClicked: this.onCellClicked

as it would normally be

@cellClicked

Without the @ the attribute might get added as a component property. How can I fix this to listen to the emitted cellClicked event?

答:
A few thoughts occur.

Firstly, the reason this isn't working is because v-bind is used to set component props and element attributes. The @ prefix is a shorthand for v-on, so it isn't a prop or attribute in this sense, it's a directive in its own right. v-on does support an object version, just like v-bind, so you can do something like v-on="getCellEvents(cell, columnIndex)" and return a suitable object for each cell type. This is probably the cleanest direct answer to your original question. Less clean and less direct answers are also available...

You could implement this by making cellClicked a prop of the child cell and then calling it as a callback function rather than emitting an event. Not saying you should, but you could. That would work with the code you posted above completely unchanged.

Another alternative is just to add the event listener for all cells. Include @cellClicked="onCellCicked" in the template without worrying about the cell type. If the other cell types don't emit that event then nothing will happen. Vue doesn't know what events a component can fire, you can listen for anything.

Further thoughts...

Your cell template is a bit anaemic. I know people generally advise keeping logic out of the template but in your case I'd say you've probably taken it too far and it just makes things harder to understand. There are two ways you could address this:

Rewrite your component to use a render function instead. Templates exist because humans find them easier to read than render functions but in your case you've got all the logic in JavaScript anyway. The template isn't really adding anything and going all-in with a render function would probably be easier to understand than what you have currently.

Move the logic into the template. I don't see any obvious reason not to do it that way from the code you've posted. I'll post an example at the end.

Either of these two approaches would remove the problem you had adding an event listener.

A final thought on the click events is that you could use event propagation to handle them instead. Add a single click listener on a suitable element of the surrounding component and don't listen for events on the cells/rows at all. The single listener could then establish which cell was clicked (potentially fiddly) and whether anything needs to be done about it. While this would increase the coupling between the components I would imagine that it wouldn't really matter as these components aren't really reusable elsewhere anyway. I'm not recommending this as an approach at this stage but it is worth keeping in mind whenever you find yourself creating large numbers of repetitive components that all need the same events. In your scenario it would probably only make sense if you start to run into performance problems, and even then there will likely be better ways to fix such problems.

So, I promised an example of the template approach:

<template>

    <template v-for="(cell, columnIndex) in row">
      <unrevealed-cell
        v-if="!cell.revealed"
        :key="columnIndex"
        :unrevealed-cell="cell"
        :x="columnIndex"
        :y="rowIndex"
        @cellClicked="onCellClicked"
      />
      <revealed-mine-cell
        v-else-if="cell.mine"
      />
      <revealed-neutral-cell
        v-else
        :mineNeighbours="cell.mineNeighbours"
      />
    </template>

</template>
```

I'm not sure why the UnrevealedCell needs the x and y but if it's just so that it can emit them as part of the event then you might want to consider registering the listener as @cellClicked="onCellClicked(columnIndex, rowIndex)" and then there's no need to emit the co-ordinates from the cell. I also wonder whether you need 3 separate components for these cells. My gut reaction is that one component would be more appropriate with the row component not needing to have any understanding of the individual cells at all.

Body:
I created a simple Minesweeper game and when it comes to the decision, which cell to render there are three possibilities:

Unrevealed cell

Revealed mine cell

Revealed neutral cell

I created a row component that renders all the cells contained by the row.

<template>

    <component
      v-for="(cell, columnIndex) in row"
      :key="columnIndex"
      v-bind="getCellProps(cell, columnIndex)"
      :is="getComponentCell(cell)"
    />

</template>

Unfortunately my cellClicked event is not working. The child component is able to emit the event correctly but my onCellClicked doesn't get executed. I think this is because I can't write

cellClicked: this.onCellClicked

as it would normally be

@cellClicked

Without the @ the attribute might get added as a component property. How can I fix this to listen to the emitted cellClicked event?

Body:
A few thoughts occur.

Firstly, the reason this isn't working is because v-bind is used to set component props and element attributes. The @ prefix is a shorthand for v-on, so it isn't a prop or attribute in this sense, it's a directive in its own right. v-on does support an object version, just like v-bind, so you can do something like v-on="getCellEvents(cell, columnIndex)" and return a suitable object for each cell type. This is probably the cleanest direct answer to your original question. Less clean and less direct answers are also available...

You could implement this by making cellClicked a prop of the child cell and then calling it as a callback function rather than emitting an event. Not saying you should, but you could. That would work with the code you posted above completely unchanged.

Another alternative is just to add the event listener for all cells. Include @cellClicked="onCellCicked" in the template without worrying about the cell type. If the other cell types don't emit that event then nothing will happen. Vue doesn't know what events a component can fire, you can listen for anything.

Further thoughts...

Your cell template is a bit anaemic. I know people generally advise keeping logic out of the template but in your case I'd say you've probably taken it too far and it just makes things harder to understand. There are two ways you could address this:

Rewrite your component to use a render function instead. Templates exist because humans find them easier to read than render functions but in your case you've got all the logic in JavaScript anyway. The template isn't really adding anything and going all-in with a render function would probably be easier to understand than what you have currently.

Move the logic into the template. I don't see any obvious reason not to do it that way from the code you've posted. I'll post an example at the end.

Either of these two approaches would remove the problem you had adding an event listener.

A final thought on the click events is that you could use event propagation to handle them instead. Add a single click listener on a suitable element of the surrounding component and don't listen for events on the cells/rows at all. The single listener could then establish which cell was clicked (potentially fiddly) and whether anything needs to be done about it. While this would increase the coupling between the components I would imagine that it wouldn't really matter as these components aren't really reusable elsewhere anyway. I'm not recommending this as an approach at this stage but it is worth keeping in mind whenever you find yourself creating large numbers of repetitive components that all need the same events. In your scenario it would probably only make sense if you start to run into performance problems, and even then there will likely be better ways to fix such problems.

So, I promised an example of the template approach:

<template>
  <div>
    <template v-for="(cell, columnIndex) in row">
      <unrevealed-cell
        v-if="!cell.revealed"
        :key="columnIndex"
        :unrevealed-cell="cell"
        :x="columnIndex"
        :y="rowIndex"
        @cellClicked="onCellClicked"
      />
      <revealed-mine-cell
        v-else-if="cell.mine"
      />
      <revealed-neutral-cell
        v-else
        :mineNeighbours="cell.mineNeighbours"
      />
    </template>
  </div>
</template>

I'm not sure why the UnrevealedCell needs the x and y but if it's just so that it can emit them as part of the event then you might want to consider registering the listener as @cellClicked="onCellClicked(columnIndex, rowIndex)" and then there's no need to emit the co-ordinates from the cell. I also wonder whether you need 3 separate components for these cells. My gut reaction is that one component would be more appropriate with the row component not needing to have any understanding of the individual cells at all.


问:
setup.py egg_info error code 3221225477
I've been trying to install IMGAUG package for an ML project. But the installation gets stuck when it tries to install scikit-image

My input: pip install scikit-image

output:

```<code>Collecting imgaug
Using cached
https://files.pythonhosted.org/...
Requirement already satisfied: scipy in
c:\users\*<username>*\appdata\local\programs\python\python37\lib\site-
packages (from imgaug) (1.1.0)
Collecting scikit-image>=0.11.0 (from imgaug)
Using cached https://files.pythonhosted.org/packages/...
Complete output from command python setup.py egg_info:
----------------------------------------
Command "python setup.py egg_info" failed with error code 3221225477 in
C:\Users\<name>~1.<name2>\AppData\Local\Temp\pip-install-qmdp6ysz\scikit-image\
</code>```

Note: I've already tried installing other versions of it, upgrading setuptools and pip. Error persists.

PS: Now it's showing up on everything I try to install.

答: This happened to me also. However I resolved it by uninstalling the package (pip uninstall ), then installing it using conda rather than pip (conda install ). </p>

Title: setup.py egg_info error code 3221225477

Body:
I've been trying to install IMGAUG package for an ML project. But the installation gets stuck when it tries to install scikit-image

My input: pip install scikit-image

output:

Collecting imgaug
Using cached
https://files.pythonhosted.org/...
Requirement already satisfied: scipy in
c:\users\*<username>*\appdata\local\programs\python\python37\lib\site-
packages (from imgaug) (1.1.0)
Collecting scikit-image>=0.11.0 (from imgaug)
Using cached https://files.pythonhosted.org/packages/...
Complete output from command python setup.py egg_info:
----------------------------------------
Command "python setup.py egg_info" failed with error code 3221225477 in
C:\Users\<name>~1.<name2>\AppData\Local\Temp\pip-install-qmdp6ysz\scikit-image\

Note: I've already tried installing other versions of it, upgrading setuptools and pip. Error persists.

PS: Now it's showing up on everything I try to install.


问:
Eclipse Java Missing required source folder: 'src'
I imported a jar file into workspace and this is the error I get:

Description   Resource    Path    Location    Type

  Project 'Interpreter1' is missing required source folder: 'src'   Interpreter1        Build path  Build Path Problem

How can i get rid of this error?

答:
Go to the Build Path dialog (right-click project > Build Path > Configure Build Path) and make sure you have the correct source folder listed, and make sure it exists.

The source folder is the one that holds your sources, usuglaly in the form: project/src/com/yourpackage/...


问:
How to add comments to a specific post?
I am very new to rails and I don't know much about where my problem lies. Just started a few days ago and right now I am trying to add comments to a specific post. Well, technically these are not comments but more of logs added to a certain request when other people have interacted with the request like Request A has log B, log C, log D so its basically the same as a comment sytem.

I already can create the logs and display them but my main problem is showing the right logs for the right request. My logs already have the correct request id but I don't know how to get the specific logs to display for the specific request

This is my historys_controller.rb

```<code>class HistorysController < ActionController::Base
  before_action :require_login

  def index
    @historys = History.where(job_order: 1)
  end

  def require_login
    unless session['user_credentials_id']
      redirect_to '/'
    end
  end
end
</code>```

It is still set as 1 as a temporary placeholder and trying something like

```<code>History.where(job_order: @job_order.id)
</code>```

and

```<code>History.where(job_order: params [:id])
</code>```

does not work so what should I put there?

EDIT

history.rb

```<code>class History < ApplicationRecord
    belongs_to :job_order, polymorphic: true
    belongs_to :actor, class_name: "User"
end
</code>```

routes.rb

```<code>Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root 'user_sessions#new'

  get '/sign_in', to: 'user_sessions#new', as: :sign_in
  get '/signup' => 'users#signup', as: 'signup_user'
  delete '/sign_out', to: 'user_sessions#destroy', as: :sign_out
  post '/register' => 'users#register', as: 'register_user'

  get '/users/activate/:id' => 'users#activate', as: 'activate_user'
  get '/users/deactivate/:id' => 'users#deactivate', as: 'deactivate_user'

  get '/job_order_tracking_system' => 'job_orders#dashboard', as: 'job_order_tracking_system'
  get '/job_orders/approve_job_order/:id' => 'job_orders#approve_job_order', as: 'approve_job_order'
  get '/job_orders/reject_job_order/:id' => 'job_orders#reject_job_order', as: 'reject_job_order'
  get '/job_orders/start_job_order/:id' => 'job_orders#start_job_order', as: 'start_job_order'
  get '/job_orders/done_job_order/:id' => 'job_orders#done_job_order', as: 'done_job_order'
  get '/job_orders/cancel_job_order/:id' => 'job_orders#cancel_job_order', as: 'cancel_job_order'

  resources :job_orders do
    resources :historys
  end
  resources :users
  resources :offices
  resources :user_sessions, only: [:create, :destroy]
  resources :notifications do
    collection do
      post :mark_as_read
    end
  end
  # resources :historys
end

</code>```

答: I also noticed you've got some spacing between params and [:id]. It should look this way: params[:id].

Title: How to add comments to a specific post?

Body:
I am very new to rails and I don't know much about where my problem lies. Just started a few days ago and right now I am trying to add comments to a specific post. Well, technically these are not comments but more of logs added to a certain request when other people have interacted with the request like Request A has log B, log C, log D so its basically the same as a comment sytem.

I already can create the logs and display them but my main problem is showing the right logs for the right request. My logs already have the correct request id but I don't know how to get the specific logs to display for the specific request

This is my historys_controller.rb

class HistorysController < ActionController::Base
  before_action :require_login

  def index
    @historys = History.where(job_order: 1)
  end

  def require_login
    unless session['user_credentials_id']
      redirect_to '/'
    end
  end
end

It is still set as 1 as a temporary placeholder and trying something like

History.where(job_order: @job_order.id)

and

History.where(job_order: params [:id])

does not work so what should I put there?

EDIT

history.rb

class History < ApplicationRecord
    belongs_to :job_order, polymorphic: true
    belongs_to :actor, class_name: "User"
end

routes.rb

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root 'user_sessions#new'

  get '/sign_in', to: 'user_sessions#new', as: :sign_in
  get '/signup' => 'users#signup', as: 'signup_user'
  delete '/sign_out', to: 'user_sessions#destroy', as: :sign_out
  post '/register' => 'users#register', as: 'register_user'

  get '/users/activate/:id' => 'users#activate', as: 'activate_user'
  get '/users/deactivate/:id' => 'users#deactivate', as: 'deactivate_user'

  get '/job_order_tracking_system' => 'job_orders#dashboard', as: 'job_order_tracking_system'
  get '/job_orders/approve_job_order/:id' => 'job_orders#approve_job_order', as: 'approve_job_order'
  get '/job_orders/reject_job_order/:id' => 'job_orders#reject_job_order', as: 'reject_job_order'
  get '/job_orders/start_job_order/:id' => 'job_orders#start_job_order', as: 'start_job_order'
  get '/job_orders/done_job_order/:id' => 'job_orders#done_job_order', as: 'done_job_order'
  get '/job_orders/cancel_job_order/:id' => 'job_orders#cancel_job_order', as: 'cancel_job_order'

  resources :job_orders do
    resources :historys
  end
  resources :users
  resources :offices
  resources :user_sessions, only: [:create, :destroy]
  resources :notifications do
    collection do
      post :mark_as_read
    end
  end
  # resources :historys
end