问:
Make a toast when parsing data from json
My JSON file looks like [{"Delay":5}] I need to check if Delay is not 0 then put it in toast like (Delay = 5 ) but when I run the application stop and don't show anything

```<code>    private void Affiche (){
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_WAITING,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray waiting = new JSONArray(response);

                            for (int i = 0; i < waiting.length(); i++) {
           JSONObject productObject = waiting.getJSONObject(i);
                                int Delay = productObject.getInt("Delay");
                                if ( Delay ==0) {

                                }else {
Toast.makeText(WaitingActivity.this, Delay, Toast.LENGTH_LONG).show();
}
                                }

                                }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                   Toast.makeText(WaitingActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        Volley.newRequestQueue(this).add(stringRequest);
</code>```

I expect to show "Delay = 5" but it didn't show anything

答:
If by "when I run the application stop" you mean that the app is crashing, then that's probably because you are trying to show an int instead of a String.
 The makeText() method accepts either an Int or a CharSequence as the second parameter, but the int that it accepts refers to a resource id. So in your case, since your int is not referring to a resource id, you might want to convert your Delay variable to a String in order to show it in a Toast.

Example.

```<code>String delayString = "Delay = " + Integer.toString(Delay);
Toast.makeText(WaitingActivity.this, delayString, Toast.LENGTH_LONG).show();
</code>```

Body:
My JSON file looks like [{"Delay":5}] I need to check if Delay is not 0 then put it in toast like (Delay = 5 ) but when I run the application stop and don't show anything

    private void Affiche (){
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_WAITING,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray waiting = new JSONArray(response);

                            for (int i = 0; i < waiting.length(); i++) {
           JSONObject productObject = waiting.getJSONObject(i);
                                int Delay = productObject.getInt("Delay");
                                if ( Delay ==0) {

                                }else {
Toast.makeText(WaitingActivity.this, Delay, Toast.LENGTH_LONG).show();
}
                                }

                                }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                   Toast.makeText(WaitingActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        Volley.newRequestQueue(this).add(stringRequest);

I expect to show "Delay = 5" but it didn't show anything

Body:
If by "when I run the application stop" you mean that the app is crashing, then that's probably because you are trying to show an int instead of a String.
 The makeText() method accepts either an Int or a CharSequence as the second parameter, but the int that it accepts refers to a resource id. So in your case, since your int is not referring to a resource id, you might want to convert your Delay variable to a String in order to show it in a Toast.

Example.

String delayString = "Delay = " + Integer.toString(Delay);
Toast.makeText(WaitingActivity.this, delayString, Toast.LENGTH_LONG).show();


来源: stackexchange

问:
Object initialisation - The relation of the constructor to class type and method access
I have the following code:

```<code>package testapp;

class Calculation {

    public Calculation(){}

    public void addition(int x, int y) {   }

    public void Subtraction(int x, int y) {   }
}

class My_Calculation extends Calculation {

    public My_Calculation(){}

    public void multiplication(int x, int y) {   }
}

public class TestApp {

    public static void main(String[] args) {

        int a = 20, b = 10;

        My_Calculation demo = new My_Calculation();
        demo.addition(a, b);
        demo.Subtraction(a, b);
        demo.multiplication(a, b);
        System.out.println(demo.getClass().getName());

        Calculation d = new Calculation();
        d.Subtraction(b, b);
        d.addition(b, b);
        // no multiplication
        System.out.println(d.getClass().getName());

        Calculation d2 = new My_Calculation();
        d2.Subtraction(b, b);
        d2.addition(b, b);
        // no multiplication
        System.out.println(d2.getClass().getName());
    }
}
</code>```

The output is this:

demo = testapp.My_Calculation

d = testapp.Calculation

d2 = testapp.My_Calculation

The following statement is a declaration that references variable name d2 to object type Calculation:

```<code>Calculation d2;
</code>```

The following statement is an initialisation that calls My_Calculation constructor.

```<code>Calculation d2 = new My_Calculation();
</code>```

When I run the following code, the output states that d2 is of class type My_Calculation but gives access to the methods within Calculation class.

```<code>System.out.println(d2.getClass().getName());
</code>```

Output: testapp.My_Calculation

Access: addition; subtraction

Now, my understanding tells me that if My_Calculation constructor is called I should either have:

1. access to multiplication ONLY, or

2. access to addition, subtraction and multiplication.

But, I actually get the inverse: access to addition and subtraction ONLY. Thus, I see this as counter-intuitive.

Could someone explain to me what is happening here to give me a coherent understanding of why an object of type: My_Calculation would have no access to its own methods but access to only the superclasses methods.

答:
Here:

```<code>Calculation d2 = new My_Calculation();
</code>```

You create an object of type My_Calculation, but you assign it to a variable declared with the supertype! And the compiler isn't smart enough to "see" that d2 is actually of the child type. Thus the compiler prevents you from calling a method defined on that child type. Because to the compiler, d2 is known to be a Calculation!

Note that you can cast to tell the compiler "I know better":

```<code>( (My_Calculation) d2) ).multiplication(...
</code>```

that would work at compile time, and also at runtime!

Your misconception starts here:

```<code>Calculation d2 = new My_Calculation();
</code>```

What you do on the right hand side of the assignment is basically "forgotten" in the next line. Then the compiler only knows that you have some d2 of type Calculation!

Finally: yes, in your specific example, the compiler could easily determine the real type of d2. But there are many situations where that isn't easy, or even impossible. Thus the people behind Java decided to ignore such potential "knowledge".

ContentLicense: CC BY-SA 4.0

Body:
I have the following code:

package testapp;

class Calculation {

    public Calculation(){}

    public void addition(int x, int y) {   }

    public void Subtraction(int x, int y) {   }
}

class My_Calculation extends Calculation {

    public My_Calculation(){}

    public void multiplication(int x, int y) {   }
}

public class TestApp {

    public static void main(String[] args) {

        int a = 20, b = 10;

        My_Calculation demo = new My_Calculation();
        demo.addition(a, b);
        demo.Subtraction(a, b);
        demo.multiplication(a, b);
        System.out.println(demo.getClass().getName());

        Calculation d = new Calculation();
        d.Subtraction(b, b);
        d.addition(b, b);
        // no multiplication
        System.out.println(d.getClass().getName());

        Calculation d2 = new My_Calculation();
        d2.Subtraction(b, b);
        d2.addition(b, b);
        // no multiplication
        System.out.println(d2.getClass().getName());
    }
}

The output is this:

demo = testapp.My_Calculation

d = testapp.Calculation

d2 = testapp.My_Calculation

The following statement is a declaration that references variable name d2 to object type Calculation:

Calculation d2;

The following statement is an initialisation that calls My_Calculation constructor.

Calculation d2 = new My_Calculation();

When I run the following code, the output states that d2 is of class type My_Calculation but gives access to the methods within Calculation class.

System.out.println(d2.getClass().getName());

Output: testapp.My_Calculation

Access: addition; subtraction

Now, my understanding tells me that if My_Calculation constructor is called I should either have:

1. access to multiplication ONLY, or

2. access to addition, subtraction and multiplication.

But, I actually get the inverse: access to addition and subtraction ONLY. Thus, I see this as counter-intuitive.

Could someone explain to me what is happening here to give me a coherent understanding of why an object of type: My_Calculation would have no access to its own methods but access to only the superclasses methods.

Body:
Here:

Calculation d2 = new My_Calculation();

You create an object of type My_Calculation, but you assign it to a variable declared with the supertype! And the compiler isn't smart enough to "see" that d2 is actually of the child type. Thus the compiler prevents you from calling a method defined on that child type. Because to the compiler, d2 is known to be a Calculation!

Note that you can cast to tell the compiler "I know better":

( (My_Calculation) d2) ).multiplication(...

that would work at compile time, and also at runtime!

Your misconception starts here:

Calculation d2 = new My_Calculation();

What you do on the right hand side of the assignment is basically "forgotten" in the next line. Then the compiler only knows that you have some d2 of type Calculation!

Finally: yes, in your specific example, the compiler could easily determine the real type of d2. But there are many situations where that isn't easy, or even impossible. Thus the people behind Java decided to ignore such potential "knowledge".


问:
Sass installation error using npm install -g sass
I just try to install sass and i always get this error everytime i run sass, sass --version, I just update the npm and node to the latest version but still no luck</p>

```<code>C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:1997
    throw H.e(H.cH(a,function(e,f){return e.replace(/[^<,> ]+/g,function(g){return f[g]||g})}(z+y,init.mangledGlobalNames)))},
    ^

TypeError: Instance of 'dz': type 'dz' is not a subtype of type 'List<String>'
    at Object.e (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:1629:3)
    at Object.c (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:1997:9)
    at uZ.dart.fh (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:10234:19)
    at Object.tK (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:1597:69)
    at Object.fy (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:5690:28)
    at dart.Cd (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:7278:10)
    at Object.run_ (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:7266:42)
    at Object.<anonymous> (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.js:8:7)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
</code>```

答:
You can try:

remove the directory sass from the path C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\

then in the console, run again  $ npm install -g sass

Body:
I just try to install sass and i always get this error everytime i run sass, sass --version, I just update the npm and node to the latest version but still no luck

C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:1997
    throw H.e(H.cH(a,function(e,f){return e.replace(/[^<,> ]+/g,function(g){return f[g]||g})}(z+y,init.mangledGlobalNames)))},
    ^

TypeError: Instance of 'dz': type 'dz' is not a subtype of type 'List<String>'
    at Object.e (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:1629:3)
    at Object.c (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:1997:9)
    at uZ.dart.fh (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:10234:19)
    at Object.tK (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:1597:69)
    at Object.fy (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:5690:28)
    at dart.Cd (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:7278:10)
    at Object.run_ (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.dart.js:7266:42)
    at Object.<anonymous> (C:\Users\axel mhar valdepena\AppData\Roaming\npm\node_modules\sass\sass.js:8:7)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)


问:
How to deflate minecraft chunk in c#?
So I am trying to make my own minecraft map editor in Unity3d which uses c#. I am using this as a reference https://minecraft.gamepedia.com/Region_file_format. I am able to parse the region file's chunk table and I can then use the table to find the compressed chunks starting with the zlib magic bytes 78 9C.  My idea is to use System.IO.Compression.DeflateStream to decompress this chunk of data but when I do this I get an error IOException: Corrupted data ReadInternal coming from the CheckResult method of DelfateStreamNative.  If I export the chunk to a temporary file and use nodejs zlib to inflate it, then it works but I think it is skipping the checksum because no matter how much data I give it, it works and gives me something back.

I can't imagine that the .NET inflator is broken so I must be doing something wrong.  The compressed chunk length I parse before the compressed data seems to be wrong because my first chunk is said to be 644 bytes but when I look at the file in a hexdump I have 1,230 bytes before the zero padding.  Unfortunately the 3 bit header of the zlib block indicates that the block is dynamically compressed so I cannot easily determine the EOB code and I really don't understand RFC 1951 so figuring out where the deflate buffer ends and the checksum starts is beyond me.  And again nodejs zlib doesn't care if I give it 644 bytes or 1,230, but to get the full decompressed chunk I assume I need to give it all the compressed data.

Has anyone who has decompress minecraft chunks embedded in anvil region files give me some insights?

答: So I compiled the puff.c example from github which is meant to demonstrate inflating zlib buffers and noticed that the parser was not parsing the first two 'file magic' bytes of the buffer, which I don't understand how it knows the window size since that is encoded in those bytes.  But anyways I got the idea that the .NET inflator also doesn't want these bytes.  And bam! It parses.  So some tips for anyone wanting to inflate minecraft chunks, you need to create your seek offset into the .mca file as sectorIndex * 4096 + 7 not sectorIndex * 4096 + 5 and for anyone getting the checksum error from System.IO.Compression.DeflateStream perhaps you need to make sure you are sending it an RFC 1951 buffer and not an RFC 1950 buffer.

Title: How to deflate minecraft chunk in c#?


答:
Could someone explain to me what is happening here to give me a
  coherent understanding of why an object of type: My_Calculation would
  have no access to its own methods but access to only the superclasses
  methods.

Because this is not the object that accesses to the method in the point of view of the compiler, that is the variable that references that.

If you declare :

```<code>Calculation d2 = new My_Calculation();
</code>```

Or the object reference if you don't declare any variable such as :

```<code>new My_Calculation().doMethod();
</code>```

The compiler consider d2 as a Calculation and so allows to do what this class offers.

That way of doing is called programming by interface/supertype. It means that you may pass any implementation in the instantiated type and the code will always work.

For example with this change :

```<code>Calculation d2 = new MyCalculationOtherSubclass();
</code>```

The whole code could compile if MyCalculationOtherSubclass is another subclass of Calculation.

If you need to work with a specific subtype, declaring the subtype makes sense :

```<code>My_Calculation d2 = new My_Calculation();
</code>```

or so downcast it :     ((My_Calculation)d2).invokeSubclassMethod();.

Similarly String is a subclass of CharSequence but if you want to use subString() that is specific to String, you need to manipulate a String :
So you will declare it :    String aString = "..."; and not     CharSequence aString = "...";.

Title: Object initialisation - The relation of the constructor to class type and method access

Body:
Could someone explain to me what is happening here to give me a
  coherent understanding of why an object of type: My_Calculation would
  have no access to its own methods but access to only the superclasses
  methods.

Because this is not the object that accesses to the method in the point of view of the compiler, that is the variable that references that.

If you declare :

Calculation d2 = new My_Calculation();

Or the object reference if you don't declare any variable such as :

new My_Calculation().doMethod();

The compiler consider d2 as a Calculation and so allows to do what this class offers.

That way of doing is called programming by interface/supertype. It means that you may pass any implementation in the instantiated type and the code will always work.

For example with this change :

Calculation d2 = new MyCalculationOtherSubclass();

The whole code could compile if MyCalculationOtherSubclass is another subclass of Calculation.

If you need to work with a specific subtype, declaring the subtype makes sense :

My_Calculation d2 = new My_Calculation();

or so downcast it :     ((My_Calculation)d2).invokeSubclassMethod();.

Similarly String is a subclass of CharSequence but if you want to use subString() that is specific to String, you need to manipulate a String :
So you will declare it :    String aString = "..."; and not     CharSequence aString = "...";.


问:
Can bloated CacheStorage slow down Service Worker responses?
I am caching opaque responses in SW which bloats CacheStorage exponentially upto order of 6 GB+. At times, I see SW responses slower than that from the browser cache.

Can bloated CacheStorage lead to slow read and hence degraded performance while serving request through SW? How much of this performance is driven by what kind of hard drive the machine is loaded with -- SSD vs HDD?

PS: I am aware that the ideal fix is to either fix the opaque responses or not cache them at all.

答:
The Cache Storage API gives you programmatic control over cache expiration, and allows you to use cached responses within JavaScript to construct complex serving/fallback strategies that work independent of the network, which is generally speaking not possible when just using the browser's HTTP cache.

There is no specific expectation that using the Cache Storage API is going to be faster than the HTTP cache, though.

There's some degree of overhead involved whenever service worker code is run, and the details about that overhead's impact are likely to vary based on storage medium, CPU, browser version, and any number of other criteria. I will say that I don't believe the fact that these are opaque responses comes that heavily into play when it comes to runtime performance, and the additional quota usage is effectively "fictitious". It just translates into a higher number used when calculating available quota, but does not actually result in more data being written to disk.


问:
Python argparse - user defined Action with 'store_true' behavoiur
Hi I suppose that i have parser argument which cannot pass any value, for example:

```<code>parser.add_argument('-s', '--staged', action=FooAction)
</code>```

And my user defined action:

```<code>class FooAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")
</code>```

When i trying call this without any values:

```<code>python my_script -s
</code>```

I receive this error message:

```<code>test.py: error: argument -s/--staged: expected one argument
</code>```

I know that i can add action 'store_true' to my argument, but in this solution i cannot redirect execution of this argument to my defined action class.

Is someone know how to modify FooAction to achieve 'store_true" action behaviour?

edit

class Fooaction with set nargs=0:

```<code>class FooAction(argparse.Action):
    def __init__(self, option_strings, dest, nargs=0, **kwargs):
        super(FooAction, self).__init__(option_strings, dest, nargs, **kwargs)
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")
</code>```

答:
```<code>import argparse

class FooAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")
        print(self)
        print(parser, namespace, values, option_string)

parser = argparse.ArgumentParser()
parser.add_argument('-s', '--staged', action=FooAction, nargs=0)
args = parser.parse_args()
print(args)
</code>```

sample run:

```<code>1151:~/mypy$ python3 stack56348020.py -s
action
FooAction(option_strings=['-s', '--staged'], dest='staged', nargs=0, const=None, default=None, type=None, choices=None, help=None, metavar=None)
ArgumentParser(prog='stack56348020.py', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True) Namespace(staged=None) [] -s
Namespace(staged=None)
</code>```

Using your init

```<code>import argparse

class FooAction(argparse.Action):
    def __init__(self, option_strings, dest, nargs=0, **kwargs):
        super(FooAction, self).__init__(option_strings, dest, nargs=nargs, **kwargs)
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")
        print(parser, namespace, values, option_string)

parser = argparse.ArgumentParser()
a1 = parser.add_argument('-s', '--staged', action=FooAction)
print(a1)   # display the action object and most of its parameters
args = parser.parse_args()
print(args)

1208:~/mypy$ python3 stack56348020.py -s
FooAction(option_strings=['-s', '--staged'], dest='staged', nargs=0, const=None, default=None, type=None, choices=None, help=None, metavar=None)
action
ArgumentParser(prog='stack56348020.py', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True) Namespace(staged=None) [] -s
Namespace(staged=None)
</code>```

add_argument returns the Action object it created.  We usually ignore it, but saving it to a reference, and printing it can be handy during debugging.

Even though the Action subclasses are marked as 'private' (with _) it's a good idea to look at their code to see how they customize the base class.  Action class by itself doesn't do much.  The default action uses _StoreAction.  Store True/False subclass _StoreConst.  _HelpAction is the only one that does not store some sort of value in the namespace; and it does a system exit.

Body:
Hi I suppose that i have parser argument which cannot pass any value, for example:

parser.add_argument('-s', '--staged', action=FooAction)

And my user defined action:

class FooAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")

When i trying call this without any values:

python my_script -s

I receive this error message:

test.py: error: argument -s/--staged: expected one argument

I know that i can add action 'store_true' to my argument, but in this solution i cannot redirect execution of this argument to my defined action class.

Is someone know how to modify FooAction to achieve 'store_true" action behaviour?

edit

class Fooaction with set nargs=0:

class FooAction(argparse.Action):
    def __init__(self, option_strings, dest, nargs=0, **kwargs):
        super(FooAction, self).__init__(option_strings, dest, nargs, **kwargs)
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")

Body:
import argparse

class FooAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")
        print(self)
        print(parser, namespace, values, option_string)

parser = argparse.ArgumentParser()
parser.add_argument('-s', '--staged', action=FooAction, nargs=0)
args = parser.parse_args()
print(args)

sample run:

1151:~/mypy$ python3 stack56348020.py -s
action
FooAction(option_strings=['-s', '--staged'], dest='staged', nargs=0, const=None, default=None, type=None, choices=None, help=None, metavar=None)
ArgumentParser(prog='stack56348020.py', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True) Namespace(staged=None) [] -s
Namespace(staged=None)

Using your init

import argparse

class FooAction(argparse.Action):
    def __init__(self, option_strings, dest, nargs=0, **kwargs):
        super(FooAction, self).__init__(option_strings, dest, nargs=nargs, **kwargs)
    def __call__(self, parser, namespace, values, option_string=None):
        print("action")
        print(parser, namespace, values, option_string)

parser = argparse.ArgumentParser()
a1 = parser.add_argument('-s', '--staged', action=FooAction)
print(a1)   # display the action object and most of its parameters
args = parser.parse_args()
print(args)

1208:~/mypy$ python3 stack56348020.py -s
FooAction(option_strings=['-s', '--staged'], dest='staged', nargs=0, const=None, default=None, type=None, choices=None, help=None, metavar=None)
action
ArgumentParser(prog='stack56348020.py', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True) Namespace(staged=None) [] -s
Namespace(staged=None)

add_argument returns the Action object it created.  We usually ignore it, but saving it to a reference, and printing it can be handy during debugging.

Even though the Action subclasses are marked as 'private' (with _) it's a good idea to look at their code to see how they customize the base class.  Action class by itself doesn't do much.  The default action uses _StoreAction.  Store True/False subclass _StoreConst.  _HelpAction is the only one that does not store some sort of value in the namespace; and it does a system exit.


问:
Does this RegExp string need some escaping?
I was trying to use a RegExp so that I could insert a string variable at some later point. But even this first attempt without said variable won't work. What is missing?

There's a nice jsbin linked that shows the behavior.

```<code>const DOCS = [
    "My Report – March 2019.pdf",
    "My Report – May 2019.pdf",
    "My Diary - April-May 2019.pdf",
    "My Diary - February-March 2019.pdf"
]

const title_month_year = new RegExp("(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")

DOCS.forEach(
    mag = mag.replace(/–/g, "-");
//  if (title_month_year.test(mag)) {   <--- does not match
    if (/(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})/.test(mag)) {
        console.log('we have a match');
    }
</code>```

https://jsbin.com/lomolew/edit?js,console

答:
As the fourth bird already pointed out you're using a different type of hypen.
What you could do is to adjust your regex to include either both type of hypens:
const title_month_year = new RegExp("(.*) (-|–) (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")

Please note that with solution your grouping values will be off by one after the first entry (so instead of 3 elements you now have 4, the first being whatever is in front of the hypen, the second being the hypen type, the third one being the month and the fourth one being the year.

Or to just look for a character instead of a hypen:
const title_month_year = new RegExp("(.*) . (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")

Body:
I was trying to use a RegExp so that I could insert a string variable at some later point. But even this first attempt without said variable won't work. What is missing?

There's a nice jsbin linked that shows the behavior.

const DOCS = [
    "My Report – March 2019.pdf",
    "My Report – May 2019.pdf",
    "My Diary - April-May 2019.pdf",
    "My Diary - February-March 2019.pdf"
]

const title_month_year = new RegExp("(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")

DOCS.forEach(
    mag = mag.replace(/–/g, "-");
//  if (title_month_year.test(mag)) {   <--- does not match
    if (/(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})/.test(mag)) {
        console.log('we have a match');
    }

https://jsbin.com/lomolew/edit?js,console


问:
How to get a entity by ID ngrx
I have the following store

```<code>export const featureAdapter: EntityAdapter<IProduct> = createEntityAdapter<IProduct>({
  selectId: model => model.id,
});

export interface State extends EntityState<IProduct> {
  selectedProduct?: IProduct;
  isLoading?: boolean;
  error?: any;
}

export const initialState: State = featureAdapter.getInitialState({
  selectedProduct: IProduct,
  isLoading: false,
  error: null
});
</code>```

I would like that my selected product always point on a Entity and get updates with it. I believe since actions are always creating new object, the link is not possible, I decided to change the selectedProduct from a reference to a simple id.

```<code>export const initialState: State = featureAdapter.getInitialState({
  selectedProduct: string,
  isLoading: false,
  error: null
});
</code>```

but how do i retrieve my entity with the same ID, and get updates on my observable if it is changed ?

I tried

```<code>export const getSelectedProduct: MemoizedSelector<object, any> = createSelector(
  selectAllEntities,
  selectedProduct,
  (entities, id) => entities[id]
);

export const selectEntityById = createSelector(
  selectAllEntities,
  (entities, props) => entities[props.id]
);
</code>```

my questions are
Is this the only way to select an entity by id ?

```<code>this.store$.pipe(
  select(ProductStoreSelectors.selectEntityById, { id: product.id }),
  map(product => console.log(product))
)
</code>```

and
      this.store$.select(ProductStoreSelectors.getSelectedProduct).subscribe((product: string) => {
        console.log(product)
      }),

this never trigger when I change my selected product Id

EDIT :

the reducer on select do the following

```<code>const SET_SELECTED_PRODUCT = (state: State, action: featureAction.SetSelectedProduct) => {
  return {
    ...state,
    selectedProduct: action.payload.product.id
  };
};
</code>```

答:
Try something like this in your selector:

```<code>export const selectEntityById = (id: number) => createSelector(
  selectAllEntities,
  (entities) => entities[id]
);
</code>```

and your select:

```<code>select(ProductStoreSelectors.selectEntityById(id))
</code>```

Title: How to get a entity by ID ngrx

Body:
I have the following store

export const featureAdapter: EntityAdapter<IProduct> = createEntityAdapter<IProduct>({
  selectId: model => model.id,
});

export interface State extends EntityState<IProduct> {
  selectedProduct?: IProduct;
  isLoading?: boolean;
  error?: any;
}

export const initialState: State = featureAdapter.getInitialState({
  selectedProduct: IProduct,
  isLoading: false,
  error: null
});

I would like that my selected product always point on a Entity and get updates with it. I believe since actions are always creating new object, the link is not possible, I decided to change the selectedProduct from a reference to a simple id.

export const initialState: State = featureAdapter.getInitialState({
  selectedProduct: string,
  isLoading: false,
  error: null
});

but how do i retrieve my entity with the same ID, and get updates on my observable if it is changed ?

I tried

export const getSelectedProduct: MemoizedSelector<object, any> = createSelector(
  selectAllEntities,
  selectedProduct,
  (entities, id) => entities[id]
);

export const selectEntityById = createSelector(
  selectAllEntities,
  (entities, props) => entities[props.id]
);

my questions are
Is this the only way to select an entity by id ?

this.store$.pipe(
  select(ProductStoreSelectors.selectEntityById, { id: product.id }),
  map(product => console.log(product))
)

and
      this.store$.select(ProductStoreSelectors.getSelectedProduct).subscribe((product: string) => {
        console.log(product)
      }),

this never trigger when I change my selected product Id

EDIT :

the reducer on select do the following

const SET_SELECTED_PRODUCT = (state: State, action: featureAction.SetSelectedProduct) => {
  return {
    ...state,
    selectedProduct: action.payload.product.id
  };
};

Body:
Try something like this in your selector:

export const selectEntityById = (id: number) => createSelector(
  selectAllEntities,
  (entities) => entities[id]
);

and your select:

select(ProductStoreSelectors.selectEntityById(id))


问:
How to unpersist in Sparklyr?
I am using Sparklyr for a project and have understood that persisting is very useful. I am using sdf_persist for this, with the following syntax (correct me if I am wrong):

```<code>data_frame <- sdf_persist(data_frame)
</code>```

Now I am reaching a point where I have too many RDDs stored in memory, so I need to unpersist some. However I cannot seem to find the function to do this in Sparklyr. Note that I have tried:

```<code>dplyr::db_drop_table(sc, "data_frame")
dplyr::db_drop_table(sc, data_frame)
unpersist(data_frame)
sdf_unpersist(data_frame)
</code>```

But none of those work.

Also, I am trying to avoid using tbl_cache (in which case it seems that db_drop_table works) as it seems that sdf_persist offers more liberty on the storage level. It might be that I am missing the big picture of how to use persistence here, in which case, I'll be happy to learn more.

答:
If you don't care about granularity then the simplest solution is to invoke Catalog.clearCache:

```<code>spark_session(sc) %>% invoke("catalog") %>% invoke("clearCache")
</code>```

Uncaching specific object is much less straightforward due to sparklyr indirection. If you check the object returned by sdf_cache you'll see that the persisted table is not exposed directly:

```<code>df <- copy_to(sc, iris, memory=FALSE, overwrite=TRUE) %>% sdf_persist()

spark_dataframe(df) %>%
  invoke("storageLevel") %>%
  invoke("equals", invoke_static(sc, "org.apache.spark.storage.StorageLevel", "NONE"))
</code>```

[1] TRUE
```

<p>That's beacuase you don't get registered table directly, but rather a result of subquery like <code>SELECT * FROM ...</code>.</p>

<p>It means you cannot simply call <code>unpersist</code>:</p>

<p><s></p>

```spark_dataframe(df) %>% invoke("unpersist")
```

<p></s></p>

<p>as you would in one of the official API's.</p>

<p>Instead you can try to retrieve the name of the source table, for example like this</p>

```src_name <- as.character(df$ops$x)
```

<p>and then invoke <code>Catalog.uncacheTable</code>:</p>

```spark_session(sc) %>% invoke("catalog") %>% invoke("uncacheTable", src_name)
```

That is likely not the most robust solution, so please use with caution.

Title: How to unpersist in Sparklyr?

Body:
I am using Sparklyr for a project and have understood that persisting is very useful. I am using sdf_persist for this, with the following syntax (correct me if I am wrong):

data_frame <- sdf_persist(data_frame)

Now I am reaching a point where I have too many RDDs stored in memory, so I need to unpersist some. However I cannot seem to find the function to do this in Sparklyr. Note that I have tried:

dplyr::db_drop_table(sc, "data_frame")
dplyr::db_drop_table(sc, data_frame)
unpersist(data_frame)
sdf_unpersist(data_frame)

But none of those work.

Also, I am trying to avoid using tbl_cache (in which case it seems that db_drop_table works) as it seems that sdf_persist offers more liberty on the storage level. It might be that I am missing the big picture of how to use persistence here, in which case, I'll be happy to learn more.

Body:
If you don't care about granularity then the simplest solution is to invoke Catalog.clearCache:

spark_session(sc) %>% invoke("catalog") %>% invoke("clearCache")

Uncaching specific object is much less straightforward due to sparklyr indirection. If you check the object returned by sdf_cache you'll see that the persisted table is not exposed directly:

df <- copy_to(sc, iris, memory=FALSE, overwrite=TRUE) %>% sdf_persist()

spark_dataframe(df) %>%
  invoke("storageLevel") %>%
  invoke("equals", invoke_static(sc, "org.apache.spark.storage.StorageLevel", "NONE"))

[1] TRUE

That's beacuase you don't get registered table directly, but rather a result of subquery like SELECT * FROM ....

It means you cannot simply call unpersist:

<s>

spark_dataframe(df) %>% invoke("unpersist")

</s>

as you would in one of the official API's.

Instead you can try to retrieve the name of the source table, for example like this

src_name <- as.character(df$ops$x)

and then invoke Catalog.uncacheTable:

spark_session(sc) %>% invoke("catalog") %>% invoke("uncacheTable", src_name)

That is likely not the most robust solution, so please use with caution.


问:
Does React have an equivalent for Angular's DatePipe?
I've decided to start learning React this week, since there are so many jobs out there for this particular framework.

I come from an Angular background, and found myself wondering if there is an option in React that matches the purpose of Angular's DatePipe.

答:
React doesn't include an equivalent to Angular's DatePipe, or any built-in Pipe type functionality. It's too bad because Pipes are awesome, though admittedly often abused by Angular novices.

I would also be hesitant to bring in another library/package/dependency for such a limited task, though Mitch's answer is still good.

Instead, I would embrace React's JavaScript-first mentality and simply create a function that takes a date and returns a string formatted how you'd like to display the date.

You could use JavaScript's in-built date parsing tools or parse an ISO Date as a string, like in the following function:

```<code>export const convertISOStringToMonthDay = date => {
  const tempDate = new Date(date).toString().split(' ');
  const formattedDate = `${tempDate[1]} ${+tempDate[2]}`;
  return formattedDate;
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
React doesn't include an equivalent to Angular's DatePipe, or any built-in Pipe type functionality. It's too bad because Pipes are awesome, though admittedly often abused by Angular novices.

I would also be hesitant to bring in another library/package/dependency for such a limited task, though Mitch's answer is still good.

Instead, I would embrace React's JavaScript-first mentality and simply create a function that takes a date and returns a string formatted how you'd like to display the date.

You could use JavaScript's in-built date parsing tools or parse an ISO Date as a string, like in the following function:

export const convertISOStringToMonthDay = date => {
  const tempDate = new Date(date).toString().split(' ');
  const formattedDate = `${tempDate[1]} ${+tempDate[2]}`;
  return formattedDate;
};


问:
how to use new line for BSD sed substitution
I have a sed command as follows:

```<code>sed -i 's/),(/),\n(/g' myfile
</code>```

myfile is like this:

```<code>(237),(238)
</code>```

The expected result is:

```<code>(237),
(238)
</code>```

The actual result is:

```<code>(237),n(238)
</code>```

I have tried many ways to write new line, but all failed. Is it possible to get the expected result?

I found that GNU sed works, but BSD sed not.

答:
This might work for you:

```<code>sed -e 'G' -e 's/,\(.*\)\(.\)/,\2\1/' file
</code>```

The G command will append the hold space to the pattern space, which in effect will, as the hold space is empty, append a newline. Pattern matching can re-arrange this to the desired result.

Body:
I have a sed command as follows:

sed -i 's/),(/),\n(/g' myfile

myfile is like this:

(237),(238)

The expected result is:

(237),
(238)

The actual result is:

(237),n(238)

I have tried many ways to write new line, but all failed. Is it possible to get the expected result?

I found that GNU sed works, but BSD sed not.

Body:
This might work for you:

sed -e 'G' -e 's/,\(.*\)\(.\)/,\2\1/' file

The G command will append the hold space to the pattern space, which in effect will, as the hold space is empty, append a newline. Pattern matching can re-arrange this to the desired result.


问:
why read(1) function call two times in readable event in node js?
There are one file 'foo.txt' where 'koushik' is written.
code:-

```<code>   var fs = require('fs');
   var rr = fs.createReadStream('foo.txt');
   rr.on('readable', function() {
     console.log('readable:', rr.read(1));
   });
   rr.on('end', function() {
     console.log('end');
   });
</code>```

output:-

```<code>k
o
</code>```

答:
The readable event is emitted when there is data available to be read from the stream.

The read(1) you have in that event handler will read one byte from the currently available data, each time the readable event fires.

It triggers twice because the file handling in node.js decides to fire it twice.

You may get the output you expect if you instead use no argument to read()

```<code>var fs = require('fs');
var rr = fs.createReadStream('foo.txt');
rr.on('readable', function() {
  console.log('readable:', rr.read()); // read all available data
});
rr.on('end', function() {
  console.log('end');
});
</code>```

Body:
There are one file 'foo.txt' where 'koushik' is written.
code:-

   var fs = require('fs');
   var rr = fs.createReadStream('foo.txt');
   rr.on('readable', function() {
     console.log('readable:', rr.read(1));
   });
   rr.on('end', function() {
     console.log('end');
   });

output:-

k
o

Body:
The readable event is emitted when there is data available to be read from the stream.

The read(1) you have in that event handler will read one byte from the currently available data, each time the readable event fires.

It triggers twice because the file handling in node.js decides to fire it twice.

You may get the output you expect if you instead use no argument to read()

var fs = require('fs');
var rr = fs.createReadStream('foo.txt');
rr.on('readable', function() {
  console.log('readable:', rr.read()); // read all available data
});
rr.on('end', function() {
  console.log('end');
});


问:
GA eCommerce delete or update tracking data
We have eCommerce tracking from our php backend app, but we found issue where not all events in last year pushed to GA.

We have all data in our DB. Its there options to reset, delete or update collected data on GA and push new from our app with datetime of creation (2018-03-12 13:49:51, ..)?

答: No, there will be no way for you to add in the old data. Your only option would be mergeing it using date or some identifier using something like google datastudio/powerbi/tableau.</p>


问:
How to change v-model value from JS
I'm using Google autocomplete address form. I found example at google official web page. Everything is fine. Everything works! but it's native Javascript,

I have Vue application and I don't like how I change text input values from JS script. The idea is that when I change something in main input, JS event listener should change values for other inputs:

```<code> document.getElementById(addressType).value = val;
</code>```

Problem is that I should use "document" to change values:

```<code> document.getElementById('street_number').value
</code>```

I would like to have something like tat:

```<code> <input type="text" v-model="input.address" ref="addressRef">
</code>```

And to read values:

```<code>export default {
        data() {
            return {
                input: {
                    address: "",
                    ...
                }

            };
        },
        methods: {
            test() {
                console.log(this.input.address);
                console.log(this.$refs.addressRef);
        }
       }
</code>```

So the question is:

How to set the value from JS code to update binding values? Right now values are null because I use "getElementById("id").value = val"

答:
You can emit input event afterwards which v-model relies on for updating its value:

```<code>let el = document.getElementById("id");
el.value = val;
el.dispatchEvent(new Event('input'));
</code>```

In action:

Vue.config.devtools = false

const app = new Vue({
  el: '#app',

  data: {
    message: null
  },

  methods: {
    updateBinding() {
      let el = document.getElementById("input");
      el.value = 'Hello!';
      el.dispatchEvent(new Event('input'));
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="updateBinding">Click me </button><br>
  <input id="input" v-model="message" placeholder="edit me">
  <p>Message is: {{ message }}</p>
</div></code>```

Title: How to change v-model value from JS

Body:
I'm using Google autocomplete address form. I found example at google official web page. Everything is fine. Everything works! but it's native Javascript,

I have Vue application and I don't like how I change text input values from JS script. The idea is that when I change something in main input, JS event listener should change values for other inputs:

 document.getElementById(addressType).value = val;

Problem is that I should use "document" to change values:

 document.getElementById('street_number').value

I would like to have something like tat:

 <input type="text" v-model="input.address" ref="addressRef">

And to read values:

export default {
        data() {
            return {
                input: {
                    address: "",
                    ...
                }

            };
        },
        methods: {
            test() {
                console.log(this.input.address);
                console.log(this.$refs.addressRef);
        }
       }

So the question is:

How to set the value from JS code to update binding values? Right now values are null because I use "getElementById("id").value = val"

Body:
You can emit input event afterwards which v-model relies on for updating its value:

let el = document.getElementById("id");
el.value = val;
el.dispatchEvent(new Event('input'));

In action:

Vue.config.devtools = false

const app = new Vue({
  el: '#app',

  data: {
    message: null
  },

  methods: {
    updateBinding() {
      let el = document.getElementById("input");
      el.value = 'Hello!';
      el.dispatchEvent(new Event('input'));
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="updateBinding">Click me </button><br>
  <input id="input" v-model="message" placeholder="edit me">
  <p>Message is: {{ message }}</p>
</div>


问:
How to compare two arabic string in oracle?
I have two strings:

```<code>a = 'على';
b = 'علي';
</code>```

or

```<code>a = 'محمد';
b ='محــــــــــمد';
</code>```

or

```<code>a= 'بُنْ'
b='بن'

</code>```

```<code>a= 'يسرا'
b='يسرى'

</code>```

and I already have data in database

What I have tried so far:

How can I compare them and return true?
i cant collect all cases

答:
You can use UTL_MATCH, specifically the sub-program UTL_MATCH.EDIT_DISTANCE_SIMILARITY()</p>

```<code>SELECT CASE
    WHEN UTL_MATCH.EDIT_DISTANCE_SIMILARITY('على', 'علي') > 75
    THEN 'Match' ELSE 'No Match' END as "Match Status"
FROM dual;
</code>```

Body:
I have two strings:

a = 'على';
b = 'علي';

or

a = 'محمد';
b ='محــــــــــمد';

or

a= 'بُنْ'
b='بن'

a= 'يسرا'
b='يسرى'

and I already have data in database

What I have tried so far:

How can I compare them and return true?
i cant collect all cases

Body:
You can use UTL_MATCH, specifically the sub-program UTL_MATCH.EDIT_DISTANCE_SIMILARITY()

SELECT CASE
    WHEN UTL_MATCH.EDIT_DISTANCE_SIMILARITY('على', 'علي') > 75
    THEN 'Match' ELSE 'No Match' END as "Match Status"
FROM dual;


问:
how to extract from a numpy array all the zero and non zero values in a new array?
Given a numpy array:

```<code>arr = [0,0,0,0,0,2,0]
</code>```

How can I extract in a new array all the zero elements:

```<code>new_arr = [0,0,0,0,0,0]
</code>```

And the non zero elements:

```<code>new_arr_2 = [2]
</code>```

I tried by transforming the array into a list and with a for loop. Also, I tried with:

```<code>np.argwhere(arr == 0).ravel()
</code>```

However, I am just getting the indices. Any idea of how to extract zero, and non zero, or even specific number values with numpy?

答:
You can use list comprehensions instead of using numpy :

arr = [0,0,0,0,0,2,0]
new_arr = [a for a in arr if a == 0]
new_arr_no_zero = [a for a in arr if a != 0]
```

Body:
Given a numpy array:

arr = [0,0,0,0,0,2,0]

How can I extract in a new array all the zero elements:

new_arr = [0,0,0,0,0,0]

And the non zero elements:

new_arr_2 = [2]

I tried by transforming the array into a list and with a for loop. Also, I tried with:

np.argwhere(arr == 0).ravel()

However, I am just getting the indices. Any idea of how to extract zero, and non zero, or even specific number values with numpy?


问:
How to achieve flexible Object Composition?

Motivation behind the question

I've been learning how to do Object Composition in Javascript using Concatenative Inheritance and wondered how I could accomplish something similar in VBA (which doesn't have inheritance).

Object Composition: I'm trying to figure out how to accomplish a "has a" relationship vs. a "is a" relationship. I want to be able to write simple behavior classes where they can be used by combining them together to make more complex classes.

I've created a simple example to demonstrate what I'd like to accomplish.

Example use case

Testing Module

Here are some examples of what might be used. For this question though, I'll just focus on the example use of the Fighter class.

The Fight method is actually calling the Fight method in the CanFight class. It debugs a message and reduces stamina by 1.

'MOST EXCITING GAME OF ALL TIME! =)
Private Sub StartGame()

    Dim Slasher As Fighter
    Set Slasher = New Fighter
    Slasher.Name = "Slasher"

    Slasher.Fight '-> Slasher slashes at the foe!
    Debug.Print Slasher.Stamina '-> 99

    'MAGES CAN ONLY CAST (ONLY HAS MANA)
    Dim Scorcher As Mage
    Set Scorcher = New Mage
    Scorcher.Name = "Scorcher"
    Scorcher.Cast "fireball" '->Scorcher casts fireball!
    Debug.Print Scorcher.Mana '-> 99

    'CAN BOTH FIGHT & CAST (HAS BOTH STAMINA & MANA)
    Dim Roland As Paladin
    Set Roland = New Paladin
    Roland.Name = "Roland"
    Roland.Fight '-> Roland slashes at the foe!
    Roland.Cast "Holy Light" '-> Roland casts Holy Light!

End Sub
```

<hr>

<h3>Fighter Class</h3>

<p>This class has two public properties <code>Name</code> and <code>Stamina</code>.</p>

<p>This class also contains <code>FightAbility</code> which is an instance of the <code>CanFight</code> class. This is my attempt at trying to accomplish composition.</p>

<pre class="lang-vb prettyprint-override"><code>Option Explicit

Private FightAbility As CanFight
Private pName As String
Private pStamina As Long

Private Sub Class_Initialize()
    pStamina = 100
    Set FightAbility = New CanFight
End Sub

Public Property Get Name() As String
    Name = pName
End Property

Public Property Let Name(ByVal Value As String)
    pName = Value
End Property

Public Property Get Stamina() As String
    Stamina = pStamina
End Property

Public Property Let Stamina(ByVal Value As String)
    pStamina = Value
End Property

'This is the function that uses the ability to fight.
'It passes a reference to itself to the `CanFight` class
'giving it access to its public properties.
'This is my attempt at composition.
Public Sub Fight()
    FightAbility.Fight Me
End Sub
</code>```

CanFight Class

This is the class that can be reused for other characters. An Example is a Paladin class might need to also have the ability to fight.

The obvious issue with how this is laid out is that state is an Object. The user won't know it needs to have Stamina and a Name property unless they look at the code.

Option Explicit

Public Sub Fight(ByRef State As Object)
    Debug.Print State.Name & " slashes at the foe!"
    State.Stamina = State.Stamina - 1
End Sub
```

Summarizing the question

My example feels broken since there is no structure in place as far as what properties are needed in order to use it.

At the same time, I want to make sure my game characters can be flexible in having their own distinct properties. Examples from above:

Fighter uses: canFight (stamina)

Mage uses: canCast (mana)

Paladin uses both: canFight (stamina) and canCast (Mana)

If I created an ICharacter interface class then I feel like it would be locked into having all the properties for all types of Characters.

My question is how do I achieve structured but flexible Composition like this in VBA?

答:
@Robert, I actually like your code.  However, I'm not sure it qualifies as composition. Actually, I think you've discovered a 'mixin' pattern, sort of,  (or maybe even the visitor pattern) so congratulations on that.  Here is composition as I see it.

So with the default member trick, we ship a Base property that allows access to all the base's classes methods (but not private state, which is a good thing IMHO). But because writing foo.Base.Bar in code is ugly, we pull a trick to make the Base property the default member so that it can be replaced with just a pair of brackets.  Thus, the composition becomes less ugly to look at and no need for a subclass to replicate all the base class's methods.

```<code>'* Test Module
Private Sub StartGame2()

    Dim oPaladin As Paladin
    Set oPaladin = New Paladin
    oPaladin().Name = "Pal"

    oPaladin().Fight '-> Pal slashes at the foe!
    Debug.Print oPaladin().Stamina '-> 99
    Debug.Print oPaladin.Mana
End Sub
</code>```

The Fighter class

```<code>Option Explicit

Private pName As String
Private pStamina As Long

Private Sub Class_Initialize()
    pStamina = 100
End Sub

Public Property Get Name() As String
    Name = pName
End Property

Public Property Let Name(ByVal Value As String)
    pName = Value
End Property

Public Property Get Stamina() As String
    Stamina = pStamina
End Property

Public Property Let Stamina(ByVal Value As String)
    pStamina = Value
End Property

'* This is the function that uses the ability to fight.
'* It passes a reference to itself to the `CanFight` class
'* giving it access to its public properties.
'* This is my attempt at composition.
' Public Sub Fight()
'     FightAbility.Fight Me
'End Sub

Public Sub Fight()
    Debug.Print Me.Name & " slashes at the foe!"
    Me.Stamina = Me.Stamina - 1
End Sub
</code>```

The Paladin.cls class as exported to disk and amended to pull the default member trick.

```<code>VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "Paladin"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

Private moBase As Fighter

'* To do the default member trick
'* 1) Export this module to disk;
'* 2) load into text editor;
'* 3) uncomment line with text Attribute Item.VB_UserMemId = 0 ;
'* 4) save the file back to disk
'* 5) remove or rename original file from VBA project to make room
'* 6) Re-import saved file

Private Sub Class_Initialize()
    Set moBase = New Fighter
End Sub

Public Function Base() As Fighter
    Attribute Item.VB_UserMemId = 0
    Set Base = moBase
End Function

Public Function Mana() As String
    Mana = "I don't know what Mana even means"
End Function
</code>```

Body:
Motivation behind the question

I've been learning how to do Object Composition in Javascript using Concatenative Inheritance and wondered how I could accomplish something similar in VBA (which doesn't have inheritance).

Object Composition: I'm trying to figure out how to accomplish a "has a" relationship vs. a "is a" relationship. I want to be able to write simple behavior classes where they can be used by combining them together to make more complex classes.

I've created a simple example to demonstrate what I'd like to accomplish.

Example use case

Testing Module

Here are some examples of what might be used. For this question though, I'll just focus on the example use of the Fighter class.

The Fight method is actually calling the Fight method in the CanFight class. It debugs a message and reduces stamina by 1.

'MOST EXCITING GAME OF ALL TIME! =)
Private Sub StartGame()

    Dim Slasher As Fighter
    Set Slasher = New Fighter
    Slasher.Name = "Slasher"

    Slasher.Fight '-> Slasher slashes at the foe!
    Debug.Print Slasher.Stamina '-> 99

    'MAGES CAN ONLY CAST (ONLY HAS MANA)
    Dim Scorcher As Mage
    Set Scorcher = New Mage
    Scorcher.Name = "Scorcher"
    Scorcher.Cast "fireball" '->Scorcher casts fireball!
    Debug.Print Scorcher.Mana '-> 99

    'CAN BOTH FIGHT & CAST (HAS BOTH STAMINA & MANA)
    Dim Roland As Paladin
    Set Roland = New Paladin
    Roland.Name = "Roland"
    Roland.Fight '-> Roland slashes at the foe!
    Roland.Cast "Holy Light" '-> Roland casts Holy Light!

End Sub

Fighter Class

This class has two public properties Name and Stamina.

This class also contains FightAbility which is an instance of the CanFight class. This is my attempt at trying to accomplish composition.

Option Explicit

Private FightAbility As CanFight
Private pName As String
Private pStamina As Long

Private Sub Class_Initialize()
    pStamina = 100
    Set FightAbility = New CanFight
End Sub

Public Property Get Name() As String
    Name = pName
End Property

Public Property Let Name(ByVal Value As String)
    pName = Value
End Property

Public Property Get Stamina() As String
    Stamina = pStamina
End Property

Public Property Let Stamina(ByVal Value As String)
    pStamina = Value
End Property

'This is the function that uses the ability to fight.
'It passes a reference to itself to the `CanFight` class
'giving it access to its public properties.
'This is my attempt at composition.
Public Sub Fight()
    FightAbility.Fight Me
End Sub

CanFight Class

This is the class that can be reused for other characters. An Example is a Paladin class might need to also have the ability to fight.

The obvious issue with how this is laid out is that state is an Object. The user won't know it needs to have Stamina and a Name property unless they look at the code.

Option Explicit

Public Sub Fight(ByRef State As Object)
    Debug.Print State.Name & " slashes at the foe!"
    State.Stamina = State.Stamina - 1
End Sub

Summarizing the question

My example feels broken since there is no structure in place as far as what properties are needed in order to use it.

At the same time, I want to make sure my game characters can be flexible in having their own distinct properties. Examples from above:

Fighter uses: canFight (stamina)

Mage uses: canCast (mana)

Paladin uses both: canFight (stamina) and canCast (Mana)

If I created an ICharacter interface class then I feel like it would be locked into having all the properties for all types of Characters.

My question is how do I achieve structured but flexible Composition like this in VBA?

Body:
@Robert, I actually like your code.  However, I'm not sure it qualifies as composition. Actually, I think you've discovered a 'mixin' pattern, sort of,  (or maybe even the visitor pattern) so congratulations on that.  Here is composition as I see it.

So with the default member trick, we ship a Base property that allows access to all the base's classes methods (but not private state, which is a good thing IMHO). But because writing foo.Base.Bar in code is ugly, we pull a trick to make the Base property the default member so that it can be replaced with just a pair of brackets.  Thus, the composition becomes less ugly to look at and no need for a subclass to replicate all the base class's methods.

'* Test Module
Private Sub StartGame2()

    Dim oPaladin As Paladin
    Set oPaladin = New Paladin
    oPaladin().Name = "Pal"

    oPaladin().Fight '-> Pal slashes at the foe!
    Debug.Print oPaladin().Stamina '-> 99
    Debug.Print oPaladin.Mana
End Sub

The Fighter class

Option Explicit

Private pName As String
Private pStamina As Long

Private Sub Class_Initialize()
    pStamina = 100
End Sub

Public Property Get Name() As String
    Name = pName
End Property

Public Property Let Name(ByVal Value As String)
    pName = Value
End Property

Public Property Get Stamina() As String
    Stamina = pStamina
End Property

Public Property Let Stamina(ByVal Value As String)
    pStamina = Value
End Property

'* This is the function that uses the ability to fight.
'* It passes a reference to itself to the `CanFight` class
'* giving it access to its public properties.
'* This is my attempt at composition.
' Public Sub Fight()
'     FightAbility.Fight Me
'End Sub

Public Sub Fight()
    Debug.Print Me.Name & " slashes at the foe!"
    Me.Stamina = Me.Stamina - 1
End Sub

The Paladin.cls class as exported to disk and amended to pull the default member trick.

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "Paladin"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

Private moBase As Fighter

'* To do the default member trick
'* 1) Export this module to disk;
'* 2) load into text editor;
'* 3) uncomment line with text Attribute Item.VB_UserMemId = 0 ;
'* 4) save the file back to disk
'* 5) remove or rename original file from VBA project to make room
'* 6) Re-import saved file

Private Sub Class_Initialize()
    Set moBase = New Fighter
End Sub

Public Function Base() As Fighter
    Attribute Item.VB_UserMemId = 0
    Set Base = moBase
End Function

Public Function Mana() As String
    Mana = "I don't know what Mana even means"
End Function


问:
Google Contacts API - PostalAddress Country not working set value
I'm trying to set the value in "PostalAddress Country," but that does not change the country in Google Contacts. Always define Portugal (my country that I live in).
I'm using .NET C#:

```<code>using Google.Apis.Auth.OAuth2;
using Google.Contacts;
using Google.GData.Client;
using Google.GData.Contacts;
using Google.GData.Extensions;
</code>```

I've tried several options:

```<code>StructuredPostalAddress postalAddress = new StructuredPostalAddress();

postalAddress.Country = new Country("SZ").Value;
//OR
postalAddress.Country = "SZ";
//OR
postalAddress.Country = "Suisse";
//OR
postalAddress.Country = "États-Unis";
//OR
postalAddress.Country = "Unites States"; //The same exemple in doc Google API

contact.PostalAddresses.Add(postalAddress);
</code>```

答:
I'm not sure but I think the issue are not set properties of postal adress. Set all necessary properties. This is my code:

```<code>StructuredPostalAddress CreateNewPostalAdress(CIAdress cia)
    {
        // neue Adresse anlegen
        StructuredPostalAddress newPostalAdress = new StructuredPostalAddress()
        {
            Rel = GetRelationShip(cia.RelationShip),
            Primary = false,
            Street = cia.Street,
            City = cia.City,
            Region = cia.Region,
            Postcode = cia.Postcode,
            Country = cia.Country,
        };
        return newPostalAdress;
    }
</code>```

cia.Country is a string value. Try it with United States as value. If this is working you can expand with your code.

Body:
I'm trying to set the value in "PostalAddress Country," but that does not change the country in Google Contacts. Always define Portugal (my country that I live in).
I'm using .NET C#:

using Google.Apis.Auth.OAuth2;
using Google.Contacts;
using Google.GData.Client;
using Google.GData.Contacts;
using Google.GData.Extensions;

I've tried several options:

StructuredPostalAddress postalAddress = new StructuredPostalAddress();

postalAddress.Country = new Country("SZ").Value;
//OR
postalAddress.Country = "SZ";
//OR
postalAddress.Country = "Suisse";
//OR
postalAddress.Country = "États-Unis";
//OR
postalAddress.Country = "Unites States"; //The same exemple in doc Google API

contact.PostalAddresses.Add(postalAddress);

Body:
I'm not sure but I think the issue are not set properties of postal adress. Set all necessary properties. This is my code:

StructuredPostalAddress CreateNewPostalAdress(CIAdress cia)
    {
        // neue Adresse anlegen
        StructuredPostalAddress newPostalAdress = new StructuredPostalAddress()
        {
            Rel = GetRelationShip(cia.RelationShip),
            Primary = false,
            Street = cia.Street,
            City = cia.City,
            Region = cia.Region,
            Postcode = cia.Postcode,
            Country = cia.Country,
        };
        return newPostalAdress;
    }

cia.Country is a string value. Try it with United States as value. If this is working you can expand with your code.


问:
Average 2 hex colors together in javascript
Alright thought I would throw this one out there for the crowd to think over.

Given a function (written in javascript) that expects two strings formated like a hex color (ex #FF0000)

return a hex color that is the average of both of the colors passed.

```<code>function averageColors(firstColor,secondColor)
{
  ...
  return avgColor;
}
</code>```

--edit--

average would be defined as

if the color passed was yellow and the second was light purple the returned color would be a medium orange

答:
A quick/dirty/convenient/ES6 way to blend two hex colors by a specified perecentage:

// blend two hex colors together by an amount
function blendColors(colorA, colorB, amount) {
  const [rA, gA, bA] = colorA.match(/\w\w/g).map((c) => parseInt(c, 16));
  const [rB, gB, bB] = colorB.match(/\w\w/g).map((c) => parseInt(c, 16));
  const r = Math.round(rA + (rB - rA) * amount).toString(16).padStart(2, '0');
  const g = Math.round(gA + (gB - gA) * amount).toString(16).padStart(2, '0');
  const b = Math.round(bA + (bB - bA) * amount).toString(16).padStart(2, '0');
  return '#' + r + g + b;
}

console.log(blendColors('#00FF66', '#443456', 0.5));```

Where amount should be 0 to 1, with 0 being exactly colorA, 1 being exactly colorB, and 0.5 being the "midpoint".

Body:
Alright thought I would throw this one out there for the crowd to think over.

Given a function (written in javascript) that expects two strings formated like a hex color (ex #FF0000)

return a hex color that is the average of both of the colors passed.

function averageColors(firstColor,secondColor)
{
  ...
  return avgColor;
}

--edit--

average would be defined as

if the color passed was yellow and the second was light purple the returned color would be a medium orange

Body:
A quick/dirty/convenient/ES6 way to blend two hex colors by a specified perecentage:

// blend two hex colors together by an amount
function blendColors(colorA, colorB, amount) {
  const [rA, gA, bA] = colorA.match(/\w\w/g).map((c) => parseInt(c, 16));
  const [rB, gB, bB] = colorB.match(/\w\w/g).map((c) => parseInt(c, 16));
  const r = Math.round(rA + (rB - rA) * amount).toString(16).padStart(2, '0');
  const g = Math.round(gA + (gB - gA) * amount).toString(16).padStart(2, '0');
  const b = Math.round(bA + (bB - bA) * amount).toString(16).padStart(2, '0');
  return '#' + r + g + b;
}

console.log(blendColors('#00FF66', '#443456', 0.5));

Where amount should be 0 to 1, with 0 being exactly colorA, 1 being exactly colorB, and 0.5 being the "midpoint".


问:
How to handle the case when FirebaseAuth sign in fails due to network being offline?
I am trying to implement sign in authentication with FirebaseAuth using signInWithEmailAndPassword() for my Android app. How can I handle the case when Internet connection is offline so that I can generate a Toast message regarding network issue.

答:
This is how I do it, I create a class... and then use the following code.

```<code> public class InternetStatus {

    private static InternetStatus instance = new InternetStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static InternetStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            connected = networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected();
            return connected;

        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }

}
</code>```

And then in order to use it...

```<code>if (InternetStatus.getInstance(getApplicationContext()).isOnline()) {
        Log.i(TAG, "User is online");
        // proceed with your firebase auth code.
    } else {
        Log.e(TAG, "User does not have an internet connection");
        //create a toast message, or however you want to handle this error.
    }
</code>```

Body:
This is how I do it, I create a class... and then use the following code.

 public class InternetStatus {

    private static InternetStatus instance = new InternetStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static InternetStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            connected = networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected();
            return connected;

        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }

}

And then in order to use it...

if (InternetStatus.getInstance(getApplicationContext()).isOnline()) {
        Log.i(TAG, "User is online");
        // proceed with your firebase auth code.
    } else {
        Log.e(TAG, "User does not have an internet connection");
        //create a toast message, or however you want to handle this error.
    }


问:
How to parse JSON element that can be either simple string or an object into Class Object
I am not able to unmarshall a JSON key which can hold either a string value or an another JSON Object using Jackson Library.

Ex:- Below are the two possible values.

1)

```<code>"ProviderData": {
    "INVALID": "HEX",
    "#text": "Sample"
}
</code>```

2)

```<code>"ProviderData": "1C"
</code>```

Could someone please verify and suggest me on this issue.

答:
You can write custom deserialiser and handle these both cases or write two constructors for ProviderData POJO class and properly use JsonCreator and JsonCreator annotations. See below example:

```<code>import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();

        System.out.println(mapper.readValue(jsonFile, Response.class));
    }
}

class Response {

    @JsonProperty("ProviderData")
    private ProviderData data;

    // getters, setters, toString
}

class ProviderData {

    private static final String INVALID_NAME = "INVALID";
    private static final String TEXT_NAME = "#text";

    @JsonProperty(INVALID_NAME)
    private final String invalid;

    @JsonProperty(TEXT_NAME)
    private final String text;

    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public ProviderData(String invalid) {
        this(invalid, null);
    }

    @JsonCreator
    public ProviderData(@JsonProperty(INVALID_NAME) String invalid, @JsonProperty(TEXT_NAME) String text) {
        this.invalid = invalid;
        this.text = text;
    }

    // getters, toString
}
</code>```

For this JSON payload:

```<code>{
  "ProviderData": {
    "INVALID": "HEX",
    "#text": "Sample"
  }
}
</code>```

Above example prints:

```<code>Response{data=ProviderData{invalid='HEX', text='Sample'}}
</code>```

And for String primitive JSON payload:

```<code>{
  "ProviderData": "1C"
}
</code>```

Above example prints:

```<code>Response{data=ProviderData{invalid='1C', text='null'}}
</code>```

As you can see, JSON Object is mapped properly using 2-arg constructor and String primitive is mapped using 1-arg constructor and we assume that this value means invalid key from JSON Object example.

See also:

Custom JSON Deserialization with Jackson.

sequentially deserialize using Jackson.

Deserialize strings and objects using jackson annotations in java.

Body:
I am not able to unmarshall a JSON key which can hold either a string value or an another JSON Object using Jackson Library.

Ex:- Below are the two possible values.

1)

"ProviderData": {
    "INVALID": "HEX",
    "#text": "Sample"
}

2)

"ProviderData": "1C"

Could someone please verify and suggest me on this issue.

Body:
You can write custom deserialiser and handle these both cases or write two constructors for ProviderData POJO class and properly use JsonCreator and JsonCreator annotations. See below example:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();

        System.out.println(mapper.readValue(jsonFile, Response.class));
    }
}

class Response {

    @JsonProperty("ProviderData")
    private ProviderData data;

    // getters, setters, toString
}

class ProviderData {

    private static final String INVALID_NAME = "INVALID";
    private static final String TEXT_NAME = "#text";

    @JsonProperty(INVALID_NAME)
    private final String invalid;

    @JsonProperty(TEXT_NAME)
    private final String text;

    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public ProviderData(String invalid) {
        this(invalid, null);
    }

    @JsonCreator
    public ProviderData(@JsonProperty(INVALID_NAME) String invalid, @JsonProperty(TEXT_NAME) String text) {
        this.invalid = invalid;
        this.text = text;
    }

    // getters, toString
}

For this JSON payload:

{
  "ProviderData": {
    "INVALID": "HEX",
    "#text": "Sample"
  }
}

Above example prints:

Response{data=ProviderData{invalid='HEX', text='Sample'}}

And for String primitive JSON payload:

{
  "ProviderData": "1C"
}

Above example prints:

Response{data=ProviderData{invalid='1C', text='null'}}

As you can see, JSON Object is mapped properly using 2-arg constructor and String primitive is mapped using 1-arg constructor and we assume that this value means invalid key from JSON Object example.

See also:

Custom JSON Deserialization with Jackson.

sequentially deserialize using Jackson.

Deserialize strings and objects using jackson annotations in java.


问:
Deserializing xml namespaces with Jackson & Kotlin
I have a xml element with 2 namespaces, and I'm not able to read them with jackson.

<Person xmlns="http://some.namespace.com" xmlns:ns0="http://some.other.namespace.com">
    <name>John</name>
</Person>
```

```internal data class Person(
    val name: String,
    @get:JacksonXmlProperty(isAttribute = true)
    val xmlns: String,
    @get:JacksonXmlProperty(isAttribute = true, localName="xmlns:ns0")
    val ns0: String
)
```

<p>When reading the XML with jackson, I get an error saying that both namespaces should be nullable.</p>

<p>I've tried with some variants like attrs in the body of the class and with the namespace attribute, like</p>

```    @JacksonXmlProperty(isAttribute = true, localName = "ns0", namespace = "xmlns")
    var ns0: String? = null
```

<p>This is the mapper I'm using</p>

```val mapper: XmlMapper = XmlMapper().apply {
        registerModule(KotlinModule())
        setSerializationInclusion(JsonInclude.Include.NON_NULL)
    }
```

How can I read and write again this xml and make them identical?

答:
I solved my problem setting a property to the XMLInputFactory like this:

```<code>val inputFactory = XMLInputFactory.newFactory()
inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false)
XmlMapper(inputFactory).apply {
   registerModule(KotlinModule())
}
</code>```

In this case you can model all the namespaces and do what you want.
Case solved.

Body:
I have a xml element with 2 namespaces, and I'm not able to read them with jackson.

<Person xmlns="http://some.namespace.com" xmlns:ns0="http://some.other.namespace.com">
    <name>John</name>
</Person>

internal data class Person(
    val name: String,
    @get:JacksonXmlProperty(isAttribute = true)
    val xmlns: String,
    @get:JacksonXmlProperty(isAttribute = true, localName="xmlns:ns0")
    val ns0: String
)

When reading the XML with jackson, I get an error saying that both namespaces should be nullable.

I've tried with some variants like attrs in the body of the class and with the namespace attribute, like

    @JacksonXmlProperty(isAttribute = true, localName = "ns0", namespace = "xmlns")
    var ns0: String? = null

This is the mapper I'm using

val mapper: XmlMapper = XmlMapper().apply {
        registerModule(KotlinModule())
        setSerializationInclusion(JsonInclude.Include.NON_NULL)
    }

How can I read and write again this xml and make them identical?

Body:
I solved my problem setting a property to the XMLInputFactory like this:

val inputFactory = XMLInputFactory.newFactory()
inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false)
XmlMapper(inputFactory).apply {
   registerModule(KotlinModule())
}

In this case you can model all the namespaces and do what you want.
Case solved.


问:
How allow use user acts as another one on certificate level
I have problem with design of next business logic.
I had server (S) acts as CA with some services, and many clients (A,B, ...) that registered on server. Each client has it's sertificate. Each client can sign his message so server can authorize him, ie request (pseudocode):

```<code>A -> { from: A, message: ..., signiture: A signiture} -> S
</code>```

But I need another level of authorization: sometimes client A should send messages from B name, so message will look like:

```<code>A -> { from: B, message: ..., signiture: A signiture} -> S
</code>```

So server somehow should test if A is allowed to acts as B. Is there a way to make such logic on sertificate level with bouncycastle? I need an idea without implementation.

答: You could include a field in the certificate, that containes the names that this certificate may alias as. This only works if you use certificates that can include other fields (like X509)</p>

Body:
I have problem with design of next business logic.
I had server (S) acts as CA with some services, and many clients (A,B, ...) that registered on server. Each client has it's sertificate. Each client can sign his message so server can authorize him, ie request (pseudocode):

A -> { from: A, message: ..., signiture: A signiture} -> S

But I need another level of authorization: sometimes client A should send messages from B name, so message will look like:

A -> { from: B, message: ..., signiture: A signiture} -> S

So server somehow should test if A is allowed to acts as B. Is there a way to make such logic on sertificate level with bouncycastle? I need an idea without implementation.


问:
Woocommerce: Save all products by X times a day
I have this code which update all products. It works fine. But I need to change it.

```<code>    add_action( 'wp', 'update_products_by_x' );
function update_products_by_x(){

    $limit = 200;

    // getting all products
    $products_ids = get_posts( array(
        'post_type'        => 'product', // or ['product','product_variation'],
        'numberposts'      => $limit,
        'post_status'      => 'publish',
        'fields'           => 'ids',
        'meta_query'       => array( array(
            'key'     => '_sync_updated',
            'compare' => 'NOT EXISTS',
        ) )
    ) );

    // Loop through product Ids
    foreach ( $products_ids as $product_id ) {

        // Get the WC_Product object
        $product = wc_get_product($product_id);

        // Mark product as updated
        $product->update_meta_data( '_sync_updated', true );

        $product->save();
    }
}
</code>```

The function above marks the updated products as 'updated'. Then this code will save all the products just one time.

Question: How do change this function so that I get all products saved every time the function is executed and not just one time.

答:
Update: the function will run 5 times a day (max).

If you have many products, you can't update all products.

The following will run each time your website is browsed, and will update a defined number of products each time to avoid problems (it will run forever, util you will remove it):

```<code>add_action( 'wp', 'update_products_by_x' );
function update_products_by_x(){
    // Get next start time
    $start_time = (float) get_option('product_update_start_time');

    if ( $start_time <= time() ) {
        if ( empty($start_time) || $start_time == 0 ) {
            $start_time = time();
        }

        ## ----- SETTINGS (Below) ----- ##
        $next_time = $start_time + ( 4.8 * 60 * 60 ); // 5 times à day
        $limit     = 200; // Fix the number of products to update each time

        $offset    = (int) get_option('product_update_offset');

        // Get products
        $products_ids = get_posts( array(
            'post_type'        => 'product', // or ['product','product_variation'],
            'numberposts'      => $limit,
            'offset'           => $offset,
            'post_status'      => 'publish',
            'fields'           => 'ids',
        ) );

        $count = count($products_ids);

        if( $count > 0 ) {
            // Loop through product Ids
            foreach ( $products_ids as $product_id ) {
                // Get the WC_Product object
                $product = wc_get_product($product_id);
                $product->save();
            }
            update_option('product_update_offset', ( $count == $limit ? ( $count + $offset ) : 0 ) );
        }
        update_option('product_update_start_time', $next_time);
    }
}
</code>```

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Body:
I have this code which update all products. It works fine. But I need to change it.

    add_action( 'wp', 'update_products_by_x' );
function update_products_by_x(){

    $limit = 200;

    // getting all products
    $products_ids = get_posts( array(
        'post_type'        => 'product', // or ['product','product_variation'],
        'numberposts'      => $limit,
        'post_status'      => 'publish',
        'fields'           => 'ids',
        'meta_query'       => array( array(
            'key'     => '_sync_updated',
            'compare' => 'NOT EXISTS',
        ) )
    ) );

    // Loop through product Ids
    foreach ( $products_ids as $product_id ) {

        // Get the WC_Product object
        $product = wc_get_product($product_id);

        // Mark product as updated
        $product->update_meta_data( '_sync_updated', true );

        $product->save();
    }
}

The function above marks the updated products as 'updated'. Then this code will save all the products just one time.

Question: How do change this function so that I get all products saved every time the function is executed and not just one time.

Body:
Update: the function will run 5 times a day (max).

If you have many products, you can't update all products.

The following will run each time your website is browsed, and will update a defined number of products each time to avoid problems (it will run forever, util you will remove it):

add_action( 'wp', 'update_products_by_x' );
function update_products_by_x(){
    // Get next start time
    $start_time = (float) get_option('product_update_start_time');

    if ( $start_time <= time() ) {
        if ( empty($start_time) || $start_time == 0 ) {
            $start_time = time();
        }

        ## ----- SETTINGS (Below) ----- ##
        $next_time = $start_time + ( 4.8 * 60 * 60 ); // 5 times à day
        $limit     = 200; // Fix the number of products to update each time

        $offset    = (int) get_option('product_update_offset');

        // Get products
        $products_ids = get_posts( array(
            'post_type'        => 'product', // or ['product','product_variation'],
            'numberposts'      => $limit,
            'offset'           => $offset,
            'post_status'      => 'publish',
            'fields'           => 'ids',
        ) );

        $count = count($products_ids);

        if( $count > 0 ) {
            // Loop through product Ids
            foreach ( $products_ids as $product_id ) {
                // Get the WC_Product object
                $product = wc_get_product($product_id);
                $product->save();
            }
            update_option('product_update_offset', ( $count == $limit ? ( $count + $offset ) : 0 ) );
        }
        update_option('product_update_start_time', $next_time);
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


问:
Object initialisation - The relation of the constructor to class type and method access
I have the following code:

```<code>package testapp;

class Calculation {

    public Calculation(){}

    public void addition(int x, int y) {   }

    public void Subtraction(int x, int y) {   }
}

class My_Calculation extends Calculation {

    public My_Calculation(){}

    public void multiplication(int x, int y) {   }
}

public class TestApp {

    public static void main(String[] args) {

        int a = 20, b = 10;

        My_Calculation demo = new My_Calculation();
        demo.addition(a, b);
        demo.Subtraction(a, b);
        demo.multiplication(a, b);
        System.out.println(demo.getClass().getName());

        Calculation d = new Calculation();
        d.Subtraction(b, b);
        d.addition(b, b);
        // no multiplication
        System.out.println(d.getClass().getName());

        Calculation d2 = new My_Calculation();
        d2.Subtraction(b, b);
        d2.addition(b, b);
        // no multiplication
        System.out.println(d2.getClass().getName());
    }
}
</code>```

The output is this:

demo = testapp.My_Calculation

d = testapp.Calculation

d2 = testapp.My_Calculation

The following statement is a declaration that references variable name d2 to object type Calculation:

```<code>Calculation d2;
</code>```

The following statement is an initialisation that calls My_Calculation constructor.

```<code>Calculation d2 = new My_Calculation();
</code>```

When I run the following code, the output states that d2 is of class type My_Calculation but gives access to the methods within Calculation class.

```<code>System.out.println(d2.getClass().getName());
</code>```

Output: testapp.My_Calculation

Access: addition; subtraction

Now, my understanding tells me that if My_Calculation constructor is called I should either have:

1. access to multiplication ONLY, or

2. access to addition, subtraction and multiplication.

But, I actually get the inverse: access to addition and subtraction ONLY. Thus, I see this as counter-intuitive.

Could someone explain to me what is happening here to give me a coherent understanding of why an object of type: My_Calculation would have no access to its own methods but access to only the superclasses methods.

答:
That is because, at compile time, you only have access to methods from the static type of the object you are dealing with (that is the type of your variable) and to the ones from its superclasses, interfaces and superinterfaces. The getClass method is available because it is defined inside the Object class, and Calculation inherits from it. Hence if you want to call multiplication you have to declare your variable as My_Calculation.

At runtime however, the method that is invoked is the one from the dynamic type (the one that you assign to the variable). Thus if you override the method addition inside My_Calculation, that one will be the one invoked at runtime even if the static type is Calculation.

Body:
I have the following code:

package testapp;

class Calculation {

    public Calculation(){}

    public void addition(int x, int y) {   }

    public void Subtraction(int x, int y) {   }
}

class My_Calculation extends Calculation {

    public My_Calculation(){}

    public void multiplication(int x, int y) {   }
}

public class TestApp {

    public static void main(String[] args) {

        int a = 20, b = 10;

        My_Calculation demo = new My_Calculation();
        demo.addition(a, b);
        demo.Subtraction(a, b);
        demo.multiplication(a, b);
        System.out.println(demo.getClass().getName());

        Calculation d = new Calculation();
        d.Subtraction(b, b);
        d.addition(b, b);
        // no multiplication
        System.out.println(d.getClass().getName());

        Calculation d2 = new My_Calculation();
        d2.Subtraction(b, b);
        d2.addition(b, b);
        // no multiplication
        System.out.println(d2.getClass().getName());
    }
}

The output is this:

demo = testapp.My_Calculation

d = testapp.Calculation

d2 = testapp.My_Calculation

The following statement is a declaration that references variable name d2 to object type Calculation:

Calculation d2;

The following statement is an initialisation that calls My_Calculation constructor.

Calculation d2 = new My_Calculation();

When I run the following code, the output states that d2 is of class type My_Calculation but gives access to the methods within Calculation class.

System.out.println(d2.getClass().getName());

Output: testapp.My_Calculation

Access: addition; subtraction

Now, my understanding tells me that if My_Calculation constructor is called I should either have:

1. access to multiplication ONLY, or

2. access to addition, subtraction and multiplication.

But, I actually get the inverse: access to addition and subtraction ONLY. Thus, I see this as counter-intuitive.

Could someone explain to me what is happening here to give me a coherent understanding of why an object of type: My_Calculation would have no access to its own methods but access to only the superclasses methods.


问:
How can I remove all NSTableColumns from an NSTableView?
I am trying to implement a method to clear the NSTableView of all items AND columns. But I get a crash when I try to implement the following:</p>

```<code>- (void)clearResultData
{
    [resultArray removeAllObjects];
    NSArray *tableCols = [resultTableView tableColumns];
    if ([tableCols count] > 0)
    {
        id object;
        NSEnumerator *e = [tableCols objectEnumerator];
        while (object = [e nextObject])
        {
            NSTableColumn *col = (NSTableColumn*)object;
            [resultTableView removeTableColumn:col];
        }
    }
    [resultTableView reloadData];
}
</code>```

答:
Here is a Swift implementation:</p>

```<code>tableView.tableColumns.forEach({tableView.removeTableColumn($0)})
</code>```

Body:
I am trying to implement a method to clear the NSTableView of all items AND columns. But I get a crash when I try to implement the following:

- (void)clearResultData
{
    [resultArray removeAllObjects];
    NSArray *tableCols = [resultTableView tableColumns];
    if ([tableCols count] > 0)
    {
        id object;
        NSEnumerator *e = [tableCols objectEnumerator];
        while (object = [e nextObject])
        {
            NSTableColumn *col = (NSTableColumn*)object;
            [resultTableView removeTableColumn:col];
        }
    }
    [resultTableView reloadData];
}

Body:
Here is a Swift implementation:

tableView.tableColumns.forEach({tableView.removeTableColumn($0)})


问:
Memory Allocation in Dynamic Linked List of Structs
What's the difference in allocating memory with Malloc or Calloc in this example?

With Calloc the memory breaks, but with Malloc is fine!

My example is similar to (but with many values):

If the code is wrong, how should I do it?

```<code>typedef struct {
    int ID, age;
} person;

typedef struct {
    person *person;
    struct NO *next;
} NO;

...   // with calloc, the memory breaks
      // with  (NO*)malloc(sizeof(NO))  it´s fine

NO *p1, *px1, *px2;

px2 = (NO*)calloc(1, sizeof(NO));
p1 = px2;
px2->person->ID = 1; px2->person->age = 30;
px2->next = NULL;
px1 = px2;

px2 = (NO*)calloc(1, sizeof(NO));
px2->person->ID = 2; px2->person->age = 20;
px2->next = NULL;
px1->next = px2;
</code>```

...

答:
What's the difference in allocating memory with Malloc or Calloc in this example?

Provided that a and b are both positive and a * b does not overflow, the difference between calloc(a, b) and malloc(a * b) is only that calloc initializes the allocated memory to all-bits-zero.  Nothing else.

With Calloc the memory breaks, but with Malloc is fine!

Your program is faulty regardless of whether you use calloc() or malloc(), whether it breaks noisily or not.  You allocate memory for a NO, but then you dereference its person pointer without first assigning it to point to a valid object.  The result is undefined regardless of which allocation function you use.

Body:
What's the difference in allocating memory with Malloc or Calloc in this example?

With Calloc the memory breaks, but with Malloc is fine!

My example is similar to (but with many values):

If the code is wrong, how should I do it?

typedef struct {
    int ID, age;
} person;

typedef struct {
    person *person;
    struct NO *next;
} NO;

...   // with calloc, the memory breaks
      // with  (NO*)malloc(sizeof(NO))  it´s fine

NO *p1, *px1, *px2;

px2 = (NO*)calloc(1, sizeof(NO));
p1 = px2;
px2->person->ID = 1; px2->person->age = 30;
px2->next = NULL;
px1 = px2;

px2 = (NO*)calloc(1, sizeof(NO));
px2->person->ID = 2; px2->person->age = 20;
px2->next = NULL;
px1->next = px2;

...