问:
@react-native-firebase/auth: app not authorized Error in signInWithPhoneNumber
I am trying to set up a react-native project with firebase to signInWithPhoneNumber functionality. I am receiving an error:

NativeFirebaseError: [auth/app-not-authorized] This app is not authorized to use Firebase Authentication. Please verify that the correct package name and SHA-1 are configured in the Firebase Console. [ App validation failed. Is app running on a physical device? ]

My Function call is as follows:

```<code>import auth from '@react-native-firebase/auth';

Screen Class
....
getOtp = async () => {

....
auth()
      .signInWithPhoneNumber(`+91${phonenumber}`)
      .then(confirmResult =>
      ....
}
</code>```

I have tried all the setup instructions for the Firebase connection.

The Steps I have tried are:

I have the same package name in the react-native android project and firebase console.

Added the SHA1 from signingReport to Firebase Console.

Copied the google-services.json to android/app Folder.

Linked the Firebase to Android Studio via Google Analytics.

Giving Dummy Mobile Number for Testing works and has no issue but not with actual mobile number.
In android studio debugger, I am getting error issue displaying:

```<code>I/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzaq@8b3312c

D/Auth: signInWithPhoneNumber:verification:failed
</code>```

package details in package.json:

```<code>    "@react-native-firebase/app": "^6.3.3",
    "@react-native-firebase/auth": "^6.3.3",
    "@react-native-firebase/firestore": "^6.3.3",
    "@react-native-firebase/functions": "^6.3.3",
    "@react-native-firebase/messaging": "^6.3.3",
    "@react-native-firebase/storage": "^6.3.3",
    "react": "^16.12.0",
    "react-native": "^0.61.5",
</code>```

config in build.gradle(app):

```<code>...
dependencies {
    implementation "com.google.firebase:firebase-auth:19.2.0"
    //implementation "com.google.firebase:firebase-messaging"
    implementation "com.google.firebase:firebase-storage:17.0.0"
    implementation "com.google.firebase:firebase-firestore:17.1.5"
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
    implementation 'com.android.support:multidex:1.0.3'

    implementation 'org.webkit:android-jsc:+'
    implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.0'
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:0.61.5"  // From node_modules
    implementation "com.google.android.gms:play-services-base:17.1.0"
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation "com.google.firebase:firebase-core:17.2.2"

}
...
</code>```

config in build.gradle(projectname):

```<code>...
buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        // googlePlayServicesVersion = "16.1.0"
        androidMapsUtilsVersion = "0.5+"
    }
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
    dependencies {
        classpath('com.android.tools.build:gradle:3.5.3')
        classpath 'com.google.gms:google-services:4.3.3'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
...
</code>```

答:
I think in order to prevent abuse the firebase phone authentication wont work in emulator. It only works with real device.

But if you want it for testing purpose then you should add use some testing phone number in firebase console that will work in emulator.

Go to your firebase console -> Authentication -> SIGN-IN Method -> Phone and check the "Phone numbers for testing (optional)" field.

Body:
I am trying to set up a react-native project with firebase to signInWithPhoneNumber functionality. I am receiving an error:

NativeFirebaseError: [auth/app-not-authorized] This app is not authorized to use Firebase Authentication. Please verify that the correct package name and SHA-1 are configured in the Firebase Console. [ App validation failed. Is app running on a physical device? ]

My Function call is as follows:

import auth from '@react-native-firebase/auth';

Screen Class
....
getOtp = async () => {

....
auth()
      .signInWithPhoneNumber(`+91${phonenumber}`)
      .then(confirmResult =>
      ....
}

I have tried all the setup instructions for the Firebase connection.

The Steps I have tried are:

I have the same package name in the react-native android project and firebase console.

Added the SHA1 from signingReport to Firebase Console.

Copied the google-services.json to android/app Folder.

Linked the Firebase to Android Studio via Google Analytics.

Giving Dummy Mobile Number for Testing works and has no issue but not with actual mobile number.
In android studio debugger, I am getting error issue displaying:

I/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzaq@8b3312c

D/Auth: signInWithPhoneNumber:verification:failed

package details in package.json:

    "@react-native-firebase/app": "^6.3.3",
    "@react-native-firebase/auth": "^6.3.3",
    "@react-native-firebase/firestore": "^6.3.3",
    "@react-native-firebase/functions": "^6.3.3",
    "@react-native-firebase/messaging": "^6.3.3",
    "@react-native-firebase/storage": "^6.3.3",
    "react": "^16.12.0",
    "react-native": "^0.61.5",

config in build.gradle(app):

...
dependencies {
    implementation "com.google.firebase:firebase-auth:19.2.0"
    //implementation "com.google.firebase:firebase-messaging"
    implementation "com.google.firebase:firebase-storage:17.0.0"
    implementation "com.google.firebase:firebase-firestore:17.1.5"
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
    implementation 'com.android.support:multidex:1.0.3'

    implementation 'org.webkit:android-jsc:+'
    implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.0'
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:0.61.5"  // From node_modules
    implementation "com.google.android.gms:play-services-base:17.1.0"
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation "com.google.firebase:firebase-core:17.2.2"

}
...

config in build.gradle(projectname):

...
buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        // googlePlayServicesVersion = "16.1.0"
        androidMapsUtilsVersion = "0.5+"
    }
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
    dependencies {
        classpath('com.android.tools.build:gradle:3.5.3')
        classpath 'com.google.gms:google-services:4.3.3'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
...


来源: stackexchange

问:
how to delete nan in df from row without losing the whole row?
G'day, how can I drop the nan values without losing the whole row?
This is how my df looks like.

I have tried the pandasdf = schule.dropna()  But this deleted everything in the rows.

But I have to keep the values, because at the end, I want them to go upwards.

答:
As per your problem statement, you want to give less priority to nan values and bring the non-nan values to the top.</p>

```<code>import numpy as np
import pandas as pd
import functools

def drop_and_roll(col, na_position='last', fillvalue=np.nan):
    result = np.full(len(col), fillvalue, dtype=col.dtype)
    mask = col.notnull()
    N = mask.sum()
    if na_position == 'last':
        result[:N] = col.loc[mask]
    elif na_position == 'first':
        result[-N:] = col.loc[mask]
    else:
        raise ValueError('na_position {!r} unrecognized'.format(na_position))
    return result

df = pd.read_table('data', sep='\s{2,}')

print(df.apply(functools.partial(drop_and_roll, fillvalue='')))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
As per your problem statement, you want to give less priority to nan values and bring the non-nan values to the top.

import numpy as np
import pandas as pd
import functools

def drop_and_roll(col, na_position='last', fillvalue=np.nan):
    result = np.full(len(col), fillvalue, dtype=col.dtype)
    mask = col.notnull()
    N = mask.sum()
    if na_position == 'last':
        result[:N] = col.loc[mask]
    elif na_position == 'first':
        result[-N:] = col.loc[mask]
    else:
        raise ValueError('na_position {!r} unrecognized'.format(na_position))
    return result

df = pd.read_table('data', sep='\s{2,}')

print(df.apply(functools.partial(drop_and_roll, fillvalue='')))


问:
Regular Expression in .NET
I am new to .NET regular expressions.

My regular expression below alerted too many ) at run time. I don't know how to handle the ()

```<code>input = "Get_MyAppList()";
Match match = Regex.Match(input, @"Get_([A-Za-z0-9\-]+)\()$", RegexOptions.IgnoreCase);
</code>```

答:
You forgot to escape the last ) (just before the $):

```<code>@"Get_([A-Za-z0-9\-]+)\(\)$"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Regular Expression in .NET

Body:
I am new to .NET regular expressions.

My regular expression below alerted too many ) at run time. I don't know how to handle the ()

input = "Get_MyAppList()";
Match match = Regex.Match(input, @"Get_([A-Za-z0-9\-]+)\()$", RegexOptions.IgnoreCase);

Body:
You forgot to escape the last ) (just before the $):

@"Get_([A-Za-z0-9\-]+)\(\)$"


问:
Sum up a number until it becomes 1 digit JS
Before you mark duplicate note that it isn't. Others didn't look for the exact same thing as me.

What is the most compact possible way to sum up a number in javascript until there is only one digit left. For example: You input 5678 then the script adds it together (5+6+7+8) and gets 26, but since its more than 1 digit it adds it again and gets 2+6=8.

Is there anyway to do this with a number of any size? And how compact can the script get?

答:
I did it like this: </p>

```<code>function sumOfID(__id){
  var arr_str = Array.from(__id)
  var arr = arr_str.map((t)=>{return parseInt(t)})
  function digSum(__arr){
   return __arr.reduce((a,b)=>{return a + b})
  }
   return digSum(arr)%9 || 9
 }
</code>```

<p>Note :
The trick here is to use mod9 because the modulo 9 of any multiple digit number is its total sum until it becomes a single digit number. </p>

Body:
I did it like this:

function sumOfID(__id){
  var arr_str = Array.from(__id)
  var arr = arr_str.map((t)=>{return parseInt(t)})
  function digSum(__arr){
   return __arr.reduce((a,b)=>{return a + b})
  }
   return digSum(arr)%9 || 9
 }

Note :
The trick here is to use mod9 because the modulo 9 of any multiple digit number is its total sum until it becomes a single digit number.


问:
WebSocket TLS certificate setup fun
I'm trying to setup a WebSocket over TLS.

For that end I'm going by the directions on page 81 in the following book.

https://www.amazon.com/WebSocket-Client-Server-Communications-Andrew-Lombardi/dp/1449369278/ref=sr_1_1?keywords=websocket&qid=1581782142&sr=8-1

I setup the server code as they say in the book.
All good there, but there is some problem with the certificates.

According to the book I am supposed to take four steps in setting up the certificates

```<code>1. Generate a 2048 bit key.
openssl genrsa -des -passout pass:x -out server.pass.key 2048

2. Generate a passphrase free key.
openssl rsa -passin pass:x -in server.pass.key -out server.key

3. Generate csr from the private key.
openssl req -new -key server.key -out server.csr

4. Generate the certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
</code>```

When I run step 1 I get error

```<code>"UI_set_result:result too small .."
</code>```

For which the fix is here.

He basically says to run the following snipped instead of step 1.

```<code>openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out server.key
</code>```

It looks like he is skipping the .pass part. For which step 2 is taken. So I am unsure if I should take that step or not, after the fix.

I run those four steps, then in server.js i have:

```<code>var connection={
    ssl:true,
    port:port_number_here,
    ssl_key:'server.key',
    ssl_cert:'server.crt'
    }

//..
var processRequest=function(req,res){
    res.writeHead(200);
    res.end("Hi!\n");
    //console.log('connecting');
    };

var app=null;
app = httpsServ.createServer({
    key: fs.readFileSync(connection.ssl_key),
    cert:fs.readFileSync(connection.ssl_cert)
    },processRequest).listen(connection.port);

var wss = new WebSocketServer({server:app});

var clients=[];
var client_number=0;
wss.on('connection', function(cclient_socket){
    console.log('Estabished Connection with client.');
    }
</code>```

Then I start the server with:

```<code>node server.js
</code>```

But when I run the client code via Firefox I get error:

```<code>Firefox can’t establish a connection to the server at wss://somedomain:someportnumber/.
</code>```

And in Chromium I get error:

```<code>(index):9 WebSocket connection to 'wss://thedomain.org:theportnumber/'
failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID
</code>```

I am unsure how to proceed from here.
I would guess I somehow didn't make the certificates correctly but the error doesn't give me much to work with.

Any help would be appreciated.

p.s. I tried implementing the following directions, to no avail.

https://stackoverflow.com/a/41366949/322537

Also, I have a suspicion the Chromium error "ERR_CERT_AUTHORITY_INVALID" is a key thing here. I googled it and found
https://www.guildcafe.com/fix-net-err_cert_authority_invalid-error.html
it has to do with the certificate authority. which is just me. I'm still stranded though for I don't know how to fix it.

答:
It looks to me like you use a self-signed server certificate. You have to tell your client -- your Chromium instance--to trust that key before it will use a websocket to connect to the server you are developing.  You can sweet-talk your browser into accepting an incorrectly signed https webpage connection, but not a websocket connection.

In Chromium's case you actually need to tell your machine's OS (not the server machine, but rather the machine where you run Chromium). Please look up those instructions for your OS. You're looking up "trust self-signed certificate in Chrome on Ubuntu" or ".. on MacOS" or "...on Windows" or whatever.

Firefox has its own UI for that purpose. You can read about that too. It might be a quicker route to success for you.

Then there's Let's Encrypt, with which you can make a trusted certificate for free. For a tutorial, check this out. https://itnext.io/node-express-letsencrypt-generate-a-free-ssl-certificate-and-run-an-https-server-in-5-minutes-a730fbe528ca

Are we having fun yet?  Are we?  Are we?

Title: WebSocket TLS certificate setup fun

Body:
I'm trying to setup a WebSocket over TLS.

For that end I'm going by the directions on page 81 in the following book.

https://www.amazon.com/WebSocket-Client-Server-Communications-Andrew-Lombardi/dp/1449369278/ref=sr_1_1?keywords=websocket&qid=1581782142&sr=8-1

I setup the server code as they say in the book.
All good there, but there is some problem with the certificates.

According to the book I am supposed to take four steps in setting up the certificates

1. Generate a 2048 bit key.
openssl genrsa -des -passout pass:x -out server.pass.key 2048

2. Generate a passphrase free key.
openssl rsa -passin pass:x -in server.pass.key -out server.key

3. Generate csr from the private key.
openssl req -new -key server.key -out server.csr

4. Generate the certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

When I run step 1 I get error

"UI_set_result:result too small .."

For which the fix is here.

He basically says to run the following snipped instead of step 1.

openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out server.key

It looks like he is skipping the .pass part. For which step 2 is taken. So I am unsure if I should take that step or not, after the fix.

I run those four steps, then in server.js i have:

var connection={
    ssl:true,
    port:port_number_here,
    ssl_key:'server.key',
    ssl_cert:'server.crt'
    }

//..
var processRequest=function(req,res){
    res.writeHead(200);
    res.end("Hi!\n");
    //console.log('connecting');
    };

var app=null;
app = httpsServ.createServer({
    key: fs.readFileSync(connection.ssl_key),
    cert:fs.readFileSync(connection.ssl_cert)
    },processRequest).listen(connection.port);

var wss = new WebSocketServer({server:app});

var clients=[];
var client_number=0;
wss.on('connection', function(cclient_socket){
    console.log('Estabished Connection with client.');
    }

Then I start the server with:

node server.js

But when I run the client code via Firefox I get error:

Firefox can’t establish a connection to the server at wss://somedomain:someportnumber/.

And in Chromium I get error:

(index):9 WebSocket connection to 'wss://thedomain.org:theportnumber/'
failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID

I am unsure how to proceed from here.
I would guess I somehow didn't make the certificates correctly but the error doesn't give me much to work with.

Any help would be appreciated.

p.s. I tried implementing the following directions, to no avail.

https://stackoverflow.com/a/41366949/322537

Also, I have a suspicion the Chromium error "ERR_CERT_AUTHORITY_INVALID" is a key thing here. I googled it and found
https://www.guildcafe.com/fix-net-err_cert_authority_invalid-error.html
it has to do with the certificate authority. which is just me. I'm still stranded though for I don't know how to fix it.


问:
How to lift the 100 user cap for OAuth to Google API for verified apps
Does anyone know why my app would have a 100 user cap, even though the Verification Status is "Published"? It says "the user cap will be in place until the app is verified by Google", but this is already the case. I would appreciate any insight.

答:
The 100 users cap is a quota limit for unverified scope requests, it is applied when the application tries to obtain access to scopes that have not been approved for the project during the app verification process, see this. Since you're seeing this quota being actively used you should check whether the scopes requested by your application match the ones you submitted in the app verification status. In case there is a mismatch you would need to update the requested scopes and go through the verification process once again. Optionally you might also request a OAuth quota increase with this support form, but bear in mind there's no approval guarantee.

Finally, as Pievis pointed out this kind of inquiries would be better handled by Google Cloud Support team as they have the necessary information about your project to address your questions from end to end.


问:
Django Create Class From Multiple Functions
I have several functions in my utils.py file that my views use to calculate trade stats. Below I added just 3 but there are 8 and soon there will be several more. The way I currently have it set up works but it's very inefficient. You can see each function starts from the beginning and calls other functions that set similar variables.

What is the proper way to turn this into a class?

Is this even the right approach?

utils.py | multiple functions

```<code>def max_amount_function (pk):
    trade = get_object_or_404(Trade, pk=pk)
    entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")
    max_amount_function = entries_buy.aggregate(max_amount_function=Sum('amount'))['max_amount_function']
    if max_amount_function is None:
        return 0
    else:
        return max_amount_function

def fees_function (pk):
    trade = get_object_or_404(Trade, pk=pk)
    entries = Entry.objects.filter(trade=trade)
    fees_function = entries.aggregate(fees_function=Sum('fee'))['fees_function']
    return fees_function

def entry_cpu_function (pk):
    if max_amount_function(pk) > 0:
        trade = get_object_or_404(Trade, pk=pk)
        entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")
        entry_cpu_function = entries_buy.annotate(
            s=F('amount') * F('price')
        ).aggregate(
            entry_cpu_function=ExpressionWrapper(
                Sum(
                    Cast('s', output_field=models.FloatField())
                ) / Sum('amount'),
                output_field=models.FloatField()
            )
        )['entry_cpu_function']
        return entry_cpu_function
    else:
        return 0
</code>```

utils.py | one class

```<code>class TradeStats:
    trade = get_object_or_404(Trade)
    entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")

    def __init__(self):
        pass

    def max_amount_functio(pk):
        pass

    def fees_function(pk):
        pass

    def entry_cpu_function(self):
        pass
</code>```

Edit added models.py as it may be relevant for the entries since it's a different class.

models.py

```<code>class Trade(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    status = models.CharField(max_length=2, choices=STATUS_CHOICES, default='op')
    broker = models.ForeignKey(Broker, on_delete=models.CASCADE, blank=True, null=True)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE, null=True)
    ...

class Entry(models.Model):

    ENTRY = 'entry'
    EXIT = 'exit'
    ENTRY_TYPE_CHOICES = [
        (ENTRY, 'Entry'),
        (EXIT, 'Exit'),

    trade = models.ForeignKey(Trade, on_delete=models.CASCADE)
    amount = models.FloatField(null=True)
    price = models.FloatField(null=True, blank=True)
    entry_type = models.CharField(max_length=5, choices=ENTRY_TYPE_CHOICES, default=ENTRY)
    ...
</code>```

答:
Rockstar already posted the best solution in this context - you're working on a Django model and all your code depends on a specific model instance, so adding those features as methods in your Trade model is the very obvuous solution.

This being said, the question by itself (how do I turn a bunch of function relying on the same variables into a class) can also do with a more generic answer that apply to other contexts as well:

First, you want to fix this class definition so trades and entries_buy are instance attributes, not class attributes - else they will be initialised only once at module import time and you will end up with stale data. For this to work you will also need to add the pk param to your class initializer:

```<code>class TradeStats:
    def __init__(self, pk):
        self.trade = get_object_or_404(Trade, pk=pk)
        self.entries_buy = Entry.objects.filter(trade=self.trade, entry_type="entry")
</code>```

Then you want to add self as first param to all your methods (else the current instance can't be passed - and remove the now useless 'pk' param:

```<code>def max_amount_function(self):
    pass

def fees_function(self):
    pass

def entry_cpu_function(self):
    pass
</code>```

Now you can backport your methods implementations, replacing the relevant parts with accesses to self.trade and self.entries_buy, ie:

```<code>def max_amount_function(self):
    result = self.entries_buy.aggregate(max_amount_function=Sum('amount'))['max_amount_function']
    return 0 if result is None else result
</code>```

etc...

Also, "xxx_yyy_function" is a very poor naming. As a general rule, you want to use nouns for objects (variables, values, class names, etc), and verbs for functions or methods, so one would expect something like get_max_amount, get_fees etc.

Finally, given your question (and what you second snippet looks like), I strongly suggest you spend some time on the official Python tutorial - the part about classes of course but you may learn a lot of otherwise useful things doing the whole tutorial.

Body:
I have several functions in my utils.py file that my views use to calculate trade stats. Below I added just 3 but there are 8 and soon there will be several more. The way I currently have it set up works but it's very inefficient. You can see each function starts from the beginning and calls other functions that set similar variables.

What is the proper way to turn this into a class?

Is this even the right approach?

utils.py | multiple functions

def max_amount_function (pk):
    trade = get_object_or_404(Trade, pk=pk)
    entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")
    max_amount_function = entries_buy.aggregate(max_amount_function=Sum('amount'))['max_amount_function']
    if max_amount_function is None:
        return 0
    else:
        return max_amount_function

def fees_function (pk):
    trade = get_object_or_404(Trade, pk=pk)
    entries = Entry.objects.filter(trade=trade)
    fees_function = entries.aggregate(fees_function=Sum('fee'))['fees_function']
    return fees_function

def entry_cpu_function (pk):
    if max_amount_function(pk) > 0:
        trade = get_object_or_404(Trade, pk=pk)
        entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")
        entry_cpu_function = entries_buy.annotate(
            s=F('amount') * F('price')
        ).aggregate(
            entry_cpu_function=ExpressionWrapper(
                Sum(
                    Cast('s', output_field=models.FloatField())
                ) / Sum('amount'),
                output_field=models.FloatField()
            )
        )['entry_cpu_function']
        return entry_cpu_function
    else:
        return 0

utils.py | one class

class TradeStats:
    trade = get_object_or_404(Trade)
    entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")

    def __init__(self):
        pass

    def max_amount_functio(pk):
        pass

    def fees_function(pk):
        pass

    def entry_cpu_function(self):
        pass

Edit added models.py as it may be relevant for the entries since it's a different class.

models.py

class Trade(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    status = models.CharField(max_length=2, choices=STATUS_CHOICES, default='op')
    broker = models.ForeignKey(Broker, on_delete=models.CASCADE, blank=True, null=True)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE, null=True)
    ...

class Entry(models.Model):

    ENTRY = 'entry'
    EXIT = 'exit'
    ENTRY_TYPE_CHOICES = [
        (ENTRY, 'Entry'),
        (EXIT, 'Exit'),

    trade = models.ForeignKey(Trade, on_delete=models.CASCADE)
    amount = models.FloatField(null=True)
    price = models.FloatField(null=True, blank=True)
    entry_type = models.CharField(max_length=5, choices=ENTRY_TYPE_CHOICES, default=ENTRY)
    ...

Body:
Rockstar already posted the best solution in this context - you're working on a Django model and all your code depends on a specific model instance, so adding those features as methods in your Trade model is the very obvuous solution.

This being said, the question by itself (how do I turn a bunch of function relying on the same variables into a class) can also do with a more generic answer that apply to other contexts as well:

First, you want to fix this class definition so trades and entries_buy are instance attributes, not class attributes - else they will be initialised only once at module import time and you will end up with stale data. For this to work you will also need to add the pk param to your class initializer:

class TradeStats:
    def __init__(self, pk):
        self.trade = get_object_or_404(Trade, pk=pk)
        self.entries_buy = Entry.objects.filter(trade=self.trade, entry_type="entry")

Then you want to add self as first param to all your methods (else the current instance can't be passed - and remove the now useless 'pk' param:

def max_amount_function(self):
    pass

def fees_function(self):
    pass

def entry_cpu_function(self):
    pass

Now you can backport your methods implementations, replacing the relevant parts with accesses to self.trade and self.entries_buy, ie:

def max_amount_function(self):
    result = self.entries_buy.aggregate(max_amount_function=Sum('amount'))['max_amount_function']
    return 0 if result is None else result

etc...

Also, "xxx_yyy_function" is a very poor naming. As a general rule, you want to use nouns for objects (variables, values, class names, etc), and verbs for functions or methods, so one would expect something like get_max_amount, get_fees etc.

Finally, given your question (and what you second snippet looks like), I strongly suggest you spend some time on the official Python tutorial - the part about classes of course but you may learn a lot of otherwise useful things doing the whole tutorial.


问:
Ranking newer items fairly?
Using StackOverflow itself as an example, if you had any such system where entries were voted and viewed in order of rank based on this, how do you compensate to sort newer entries fairly? That is, if ten bad answers are given and upvoted, how do you make sure people see the new entry that might be better, but hasn't had time to gather votes or even been seen all the way at the bottom?</p>

答: You should decrease actual the rank of older posts proportional to their age relative to the newest post.  The actual rank would be derived from the moderated rank, this time based rank, and any other custom modifiers. Update when each new post is made. You should leave it up to the user to turn this feature on, though.</p>

OwnerDisplayName: ironfroggy

ContentLicense: CC BY-SA 2.5

Title: Ranking newer items fairly?

LastEditorDisplayName: Pete Kirkham

OwnerDisplayName: John Ellinwood


问:
Is a binding target required to be a DP or is it enough to implement INotifyPropertyChanged?
My question is in the title. I read that a binding target must be a DP but a reply I got from a moderator on the WPF forum seemed to indicate that it was sufficient for my class to implement INotifyPropertyChanged in order to designate it as a binding target. </p>

答:
Targets of data bindings are required to be dependency properties. WPF data binding sources do not have to be dependency properties. Obviously there must exist some kind of mechanism for the source object to notify the outside world when the bound property has changed. For that you have to implement the INotifyPropertyChanged interface and has an event named PropertyChanged, which identifies the particular event that's changed with a string.

for more please have a look at this links

http://msdn.microsoft.com/en-us/library/ms522664.aspx

http://www.charlespetzold.com/blog/2006/03/210946.html


问:
CSS not finding JavaFX rules
I am currently trying to style my JavaFX project with CSS, and each time I try to implement a property, it says "no rule for ___ found!". I have tried -fx-font-family: and -fx-background-color:.

I am using Eclipse 2019-09.

EDIT: Minimal Reproductive Example: application.css in a JavaFX project in Eclipse 2019-09

.label {
    -fx-font-family: Helvetica;
}

Shows the message "no rule for -fx-font-family found!" and underlines the -fx-font-family line in yellow.

答:
I had the same issue. Auto-completion was not working in JavaFx-Projects' css files.

I am using: openJDK12.0.2 and openjfx-sdk-11

The Problem is that e(fx)clipse requires this file in the build path.
/.p2/pool/plugins/org.eclipse.fx.ide.css.jfx8_3.5.0.201907240300.jar

Earlier versions automatically added a JavaFX-Library (which included this jar) to your JavaFX-Project.

For using openjfx-sdk-11 you need to define a User Library anyways. I called it JavaFX11. Add all the JavaFX.*.jars there and also the **org.eclipse.fx.ide.css.jfx8_3.5.0.201907240300.jar.

Having a modularised project, you need to rename the file to some name, where the module system can derive a module name from. Ergo:
org.eclipse.fx.ide.css.jfx8.jar

Now, auto-completion should work for all JavaFX-Projects where you used the JavaFX11-User-Library again!

Hope that helps.
Johannes

Title: CSS not finding JavaFX rules


问:
Odoo: one2many field still adds record even though i raise error if zero stock on it
so the idea is when i change the product, it checks on the stock available on the current branch, if none, it raises error that there are no stock

expected behavior: an error is raised when no stock is available on selected product and the record won't be added to tree view if no stock available

current behavior: the error is raised when no stock is available on selected product yet the record still gets added to the one2many tree view

code below

```<code># -*- coding: utf-8 -*-
from docutils.nodes import line

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError

class CustomTransRequest(models.Model):
    _name = 'custom.trans.request'
    _description = 'Transfer Request'
    user_id = fields.Many2one('res.users', string='Salesperson', default=lambda self: self.env.user)
    branch_from_id = fields.Many2one('custom.branch', string="From", required=True)
    branch_to_id = fields.Many2one('custom.branch', string="To", required=True)
    product_ids = fields.One2many(comodel_name="custom.trans.line", inverse_name="request_id", string="Products",
                                  required=False, )
class CustomTransLine(models.Model):
    _name = 'custom.trans.line'
    _description = 'Transfer Request Line'

    branch_from_id = fields.Many2one(comodel_name="custom.branch", string="Branch", )
    request_id = fields.Many2one("custom.trans.request", string="Request ID", )
    product_id = fields.Many2one("custom.product", string="Product", required=True, )
    qty = fields.Integer(string="Qty")

    @api.onchange('product_id')
    def onchange_product(self):
        if self.product_id:
            for rec in self:
                selected_lines = rec.env['custom.branch.line'].search(
                    ['&', ('product_id', '=', rec.product_id.id), ('branch_id', '=', rec.branch_from_id.id)]).mapped(
                    'qty')
                if not selected_lines:
                    raise ValidationError(
                        _('Current branch has ZERO stock on this product, Please select an available Product'))
</code>```

答:
If you don't want record into one2many field, set product_id=False. And return validation dictionary.

Try with following code.

```<code>@api.onchange('product_id')
def onchange_product(self):
    if self.product_id:
        res = {}
        selected_lines = rec.env['custom.branch.line'].search(
            ['&',
             ('product_id', '=', self.product_id.id),
             ('branch_id', '=', self.branch_from_id.id)]).mapped('qty')
        if not selected_lines:
            self.product_id = False
            res['warning'] = {'title': _('ValidationError'),
                              'message': _(
                                      'Current branch has ZERO stock on this product, '
                                      'Please select an available Product')}
            return res
</code>```

Body:
so the idea is when i change the product, it checks on the stock available on the current branch, if none, it raises error that there are no stock

expected behavior: an error is raised when no stock is available on selected product and the record won't be added to tree view if no stock available

current behavior: the error is raised when no stock is available on selected product yet the record still gets added to the one2many tree view

code below

# -*- coding: utf-8 -*-
from docutils.nodes import line

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError

class CustomTransRequest(models.Model):
    _name = 'custom.trans.request'
    _description = 'Transfer Request'
    user_id = fields.Many2one('res.users', string='Salesperson', default=lambda self: self.env.user)
    branch_from_id = fields.Many2one('custom.branch', string="From", required=True)
    branch_to_id = fields.Many2one('custom.branch', string="To", required=True)
    product_ids = fields.One2many(comodel_name="custom.trans.line", inverse_name="request_id", string="Products",
                                  required=False, )
class CustomTransLine(models.Model):
    _name = 'custom.trans.line'
    _description = 'Transfer Request Line'

    branch_from_id = fields.Many2one(comodel_name="custom.branch", string="Branch", )
    request_id = fields.Many2one("custom.trans.request", string="Request ID", )
    product_id = fields.Many2one("custom.product", string="Product", required=True, )
    qty = fields.Integer(string="Qty")

    @api.onchange('product_id')
    def onchange_product(self):
        if self.product_id:
            for rec in self:
                selected_lines = rec.env['custom.branch.line'].search(
                    ['&', ('product_id', '=', rec.product_id.id), ('branch_id', '=', rec.branch_from_id.id)]).mapped(
                    'qty')
                if not selected_lines:
                    raise ValidationError(
                        _('Current branch has ZERO stock on this product, Please select an available Product'))

Body:
If you don't want record into one2many field, set product_id=False. And return validation dictionary.

Try with following code.

@api.onchange('product_id')
def onchange_product(self):
    if self.product_id:
        res = {}
        selected_lines = rec.env['custom.branch.line'].search(
            ['&',
             ('product_id', '=', self.product_id.id),
             ('branch_id', '=', self.branch_from_id.id)]).mapped('qty')
        if not selected_lines:
            self.product_id = False
            res['warning'] = {'title': _('ValidationError'),
                              'message': _(
                                      'Current branch has ZERO stock on this product, '
                                      'Please select an available Product')}
            return res


问:
How to pass variables as parameters to an Aspect
```<code>@Component("taskCreateListener")
public class TaskCreateListener implements FlowableEventListener {

@LogMethod
    @DetermineCaseTypeOfWork
    @Override
    public void onEvent(FlowableEvent event) {

///Do stuff that results in variables I want to pass to aspect
//For example, get ids and details and set to variables that I want to pass to insertThing() method once onEvent(FlowableEvent event) is finished executing
//ex:
//String procInstId = "abc1234";
//String type = "case1";
}

</code>```

I need the onEvent to fully complete and then get local variables set in onEvent(FlowableEvent event) passed into my aspect insertThing() method:

```<code>@Aspect
@Component
public class DetermineCaseTypeOfWork {

@Transactional
@After(@annotation(path goes here))
public void insertThing() {
    //Do something here with the variables passed in from doSomething method
//if(procInstId.equals("abc1234") && type.equals("case1")) {
//do something
} else if(//other id and type) {
//do something else
} else {
//do something else
}
}
</code>```

I can't modify the onEvent(FlowableEvent event) method to return something and the onEvent(FlowableEvent event) method has to fully complete first, so how would I go about passing parameters into insertThing()?

答:
According your question, there is no possibility to change signature of the onEvent() method, which should be handled by an aspect. You could try to create a ThreadLocal based container class which is initialized in aspect before calling onEvent() and assessed after finishing onEvent(). But that approach requires you to be able to edit onEvent() code (but do not requires change its returning type). Here are some details:

```<code>public class VariableContextHolder {

/**
 * ThreadLocal with map storing variables
 */
private final ThreadLocal<Map<String, Object>> threadlocal = new ThreadLocal<>();

private static VariableContextHolder instance;

private VariableContextHolder () {

}

public final static VariableContextHolder getInstance() {
    if (instance == null) {
        instance = new VariableContextHolder ();
    }
    return instance;
}

public Map<String, Object>get() {
    return threadlocal.get();
}

public void set(Map<String, Object>map) {
    threadlocal.set(map);
}

public void clear() {
    threadlocal.remove();
}
}
</code>```

Aspect class:

```<code>@Aspect()
public class DetermineCaseTypeOfWork {

@Transactional
@Around(@annotation("path goes here"))
public void insertThing(ProceedingJoinPoint joinPoint) throws Throwable {

// save initialized map to threadlocal
VariableContextHolder.getInstance().set(new HashMap<>());

// method onEvent() will be called
joinPoint.proceed();

// retrieve map from threadlocal
Map<String, Object> variablesMap = VariableContextHolder.getInstance().get();

// get variables by names and handle them
String procInstId = variablesMap.get("procInstId");

// clear threadlocal after using it
VariableContextHolder.getInstance().clear();
}

}
</code>```

Changes needed to be done in onEvent() method:

```<code>public void onEvent(FlowableEvent event) {

    // retrieve map from threadlocal
    Map<String, Object> variablesMap = VariableContextHolder.getInstance().get();
    String procInstId = "abc1234";
    String type = "case1";
    // save variables to map
    variablesMap.put("procInstId", procInstId);
    variablesMap.put("type", type);
}
</code>```

Body:
@Component("taskCreateListener")
public class TaskCreateListener implements FlowableEventListener {

@LogMethod
    @DetermineCaseTypeOfWork
    @Override
    public void onEvent(FlowableEvent event) {

///Do stuff that results in variables I want to pass to aspect
//For example, get ids and details and set to variables that I want to pass to insertThing() method once onEvent(FlowableEvent event) is finished executing
//ex:
//String procInstId = "abc1234";
//String type = "case1";
}

I need the onEvent to fully complete and then get local variables set in onEvent(FlowableEvent event) passed into my aspect insertThing() method:

@Aspect
@Component
public class DetermineCaseTypeOfWork {

@Transactional
@After(@annotation(path goes here))
public void insertThing() {
    //Do something here with the variables passed in from doSomething method
//if(procInstId.equals("abc1234") && type.equals("case1")) {
//do something
} else if(//other id and type) {
//do something else
} else {
//do something else
}
}

I can't modify the onEvent(FlowableEvent event) method to return something and the onEvent(FlowableEvent event) method has to fully complete first, so how would I go about passing parameters into insertThing()?

Body:
According your question, there is no possibility to change signature of the onEvent() method, which should be handled by an aspect. You could try to create a ThreadLocal based container class which is initialized in aspect before calling onEvent() and assessed after finishing onEvent(). But that approach requires you to be able to edit onEvent() code (but do not requires change its returning type). Here are some details:

public class VariableContextHolder {

/**
 * ThreadLocal with map storing variables
 */
private final ThreadLocal<Map<String, Object>> threadlocal = new ThreadLocal<>();

private static VariableContextHolder instance;

private VariableContextHolder () {

}

public final static VariableContextHolder getInstance() {
    if (instance == null) {
        instance = new VariableContextHolder ();
    }
    return instance;
}

public Map<String, Object>get() {
    return threadlocal.get();
}

public void set(Map<String, Object>map) {
    threadlocal.set(map);
}

public void clear() {
    threadlocal.remove();
}
}

Aspect class:

@Aspect()
public class DetermineCaseTypeOfWork {

@Transactional
@Around(@annotation("path goes here"))
public void insertThing(ProceedingJoinPoint joinPoint) throws Throwable {

// save initialized map to threadlocal
VariableContextHolder.getInstance().set(new HashMap<>());

// method onEvent() will be called
joinPoint.proceed();

// retrieve map from threadlocal
Map<String, Object> variablesMap = VariableContextHolder.getInstance().get();

// get variables by names and handle them
String procInstId = variablesMap.get("procInstId");

// clear threadlocal after using it
VariableContextHolder.getInstance().clear();
}

}

Changes needed to be done in onEvent() method:

public void onEvent(FlowableEvent event) {

    // retrieve map from threadlocal
    Map<String, Object> variablesMap = VariableContextHolder.getInstance().get();
    String procInstId = "abc1234";
    String type = "case1";
    // save variables to map
    variablesMap.put("procInstId", procInstId);
    variablesMap.put("type", type);
}


问:
Concatenate chars to form String in java
Is there a way to concatenate char to form a String in Java?

Example:

```<code>String str;
Char a, b, c;
a = 'i';
b = 'c';
c = 'e';

str = a + b + c; // thus str = "ice";
</code>```

答:
If the size of the string is fixed, you might find easier to use an array of chars.
If you have to do this a lot, it will be a tiny bit faster too.

```<code>char[] chars = new char[3];
chars[0] = 'i';
chars[1] = 'c';
chars[2] = 'e';
return new String(chars);
</code>```

Also, I noticed in your original question, you use the Char class.
If your chars are not nullable, it is better to use the lowercase char type.

Body:
Is there a way to concatenate char to form a String in Java?

Example:

String str;
Char a, b, c;
a = 'i';
b = 'c';
c = 'e';

str = a + b + c; // thus str = "ice";

Body:
If the size of the string is fixed, you might find easier to use an array of chars.
If you have to do this a lot, it will be a tiny bit faster too.

char[] chars = new char[3];
chars[0] = 'i';
chars[1] = 'c';
chars[2] = 'e';
return new String(chars);

Also, I noticed in your original question, you use the Char class.
If your chars are not nullable, it is better to use the lowercase char type.


问:
Flutter DropdownButton NoSuchMethodError: The getter value was called on null
I'm trying to populate a dropdown button in my flutter app with data coming from my restful api. However i get the error above.

Here is my model;

```<code>class SavingsCategory extends Equatable{
    final int id;
    final String name;

   SavingsCategory({
     @required this.id,
     @required this.name
   });

 @override
 List<Object> get props => [name, id];

}
</code>```

My repository fetching the data

```<code>  @override
  Future<List<SavingsCategory>> getSavingsCategory()
 async {
var token = await tokenRepository.getToken();

final response = await http.get(
  '$baseUrl/user/savings-category',
  headers: {HttpHeaders.authorizationHeader: 'Bearer $token'},
  );

  if (response.statusCode == 200) {
     var data = json.decode(response.body);

    List<SavingsCategory> categoryList = data['savingsCategory'].map<SavingsCategory>((json) {
        return SavingsCategory.fromJson(json);
    }).toList();
    return categoryList;
  } else {
    throw new Exception("Couldn't get any saving categories");
  }

}
</code>```

My bloc code

```<code>class SavingsCategoryBloc {
    final repository = SavingsRepository();
    final _savingsCategories = PublishSubject<List<SavingsCategory>>();

    Stream<List<SavingsCategory>> get savingsCategories => _savingsCategories.stream;

   fetchSavingsCategories() async {
  final categories = await repository.getSavingsCategory();
  _savingsCategories.sink.add(categories);
  }

  dispose(){
  _savingsCategories.close();
}

}
</code>```

Finally my widget

```<code>class _StartSavingPageState extends State<StartSavingPage> {
    final SavingsCategoryBloc bloc = SavingsCategoryBloc();

    @override
    void initState() {
    bloc.fetchSavingsCategories();
    super.initState();
 }

 @override
 Widget build(BuildContext context) {
 ....
     Container(
                      padding: EdgeInsets.symmetric(
                          horizontal: 15.0, vertical: 10.0),
                      child: StreamBuilder<List<SavingsCategory>>(

                          stream: bloc.savingsCategories,
                          builder: (context, snapshot) {
                            if (!snapshot.hasData) {
                              return DropdownButton<String>(

                                items: [
                                  DropdownMenuItem<String>(
                                    child: Text('No Savings Category'),
                                    value: '',
                                  ),
                                ],
                                onChanged: (String value) {
                                  setState(() {

                                  });
                                },
                                isExpanded: true,
                                hint: Text(
                                  'SAVING FOR?',
                                  style: TextStyle(
                                      fontSize: 15.0, color: Colors.grey),
                                ),
                              );
                            }
                            return DropdownButton(
                              value: category,
                              items: snapshot.data.map((category) {
                                DropdownMenuItem(
                                  child: Text('${category.name}'),
                                  value: category.id,
                                );
                              }).toList(),
                              onChanged: (value) {
                                setState(() {
                                  category = value;
                                });
                              },

                              isExpanded: true,
                              hint: Text(
                                'SAVING FOR?',
                                style: TextStyle(
                                    fontSize: 15.0, color: Colors.grey),
                              ),
                            );

                          }),
                    ),
    }
}
</code>```

How can i fix this error? I know the data fetching works just fine. I'm definitely missing something in my widget. Any help would be appreciated.

答:
The DropdownButton value must in item values or must be null.</p>

```<code>DropdownButton(
  value: categoryId,
  items: snapshot.data.map((category) {
    DropdownMenuItem(
      child: Text('${category.name}'),
      value: category.id,
    );
  }).toList(),
  onChanged: (value) {
    setState(() {
      categoryId = value;
    });
  },

  isExpanded: true,
  hint: Text(
    'SAVING FOR?',
    style: TextStyle(
        fontSize: 15.0, color: Colors.grey),
  ),
);
</code>```

Body:
I'm trying to populate a dropdown button in my flutter app with data coming from my restful api. However i get the error above.

Here is my model;

class SavingsCategory extends Equatable{
    final int id;
    final String name;

   SavingsCategory({
     @required this.id,
     @required this.name
   });

 @override
 List<Object> get props => [name, id];

}

My repository fetching the data

  @override
  Future<List<SavingsCategory>> getSavingsCategory()
 async {
var token = await tokenRepository.getToken();

final response = await http.get(
  '$baseUrl/user/savings-category',
  headers: {HttpHeaders.authorizationHeader: 'Bearer $token'},
  );

  if (response.statusCode == 200) {
     var data = json.decode(response.body);

    List<SavingsCategory> categoryList = data['savingsCategory'].map<SavingsCategory>((json) {
        return SavingsCategory.fromJson(json);
    }).toList();
    return categoryList;
  } else {
    throw new Exception("Couldn't get any saving categories");
  }

}

My bloc code

class SavingsCategoryBloc {
    final repository = SavingsRepository();
    final _savingsCategories = PublishSubject<List<SavingsCategory>>();

    Stream<List<SavingsCategory>> get savingsCategories => _savingsCategories.stream;

   fetchSavingsCategories() async {
  final categories = await repository.getSavingsCategory();
  _savingsCategories.sink.add(categories);
  }

  dispose(){
  _savingsCategories.close();
}

}

Finally my widget

class _StartSavingPageState extends State<StartSavingPage> {
    final SavingsCategoryBloc bloc = SavingsCategoryBloc();

    @override
    void initState() {
    bloc.fetchSavingsCategories();
    super.initState();
 }

 @override
 Widget build(BuildContext context) {
 ....
     Container(
                      padding: EdgeInsets.symmetric(
                          horizontal: 15.0, vertical: 10.0),
                      child: StreamBuilder<List<SavingsCategory>>(

                          stream: bloc.savingsCategories,
                          builder: (context, snapshot) {
                            if (!snapshot.hasData) {
                              return DropdownButton<String>(

                                items: [
                                  DropdownMenuItem<String>(
                                    child: Text('No Savings Category'),
                                    value: '',
                                  ),
                                ],
                                onChanged: (String value) {
                                  setState(() {

                                  });
                                },
                                isExpanded: true,
                                hint: Text(
                                  'SAVING FOR?',
                                  style: TextStyle(
                                      fontSize: 15.0, color: Colors.grey),
                                ),
                              );
                            }
                            return DropdownButton(
                              value: category,
                              items: snapshot.data.map((category) {
                                DropdownMenuItem(
                                  child: Text('${category.name}'),
                                  value: category.id,
                                );
                              }).toList(),
                              onChanged: (value) {
                                setState(() {
                                  category = value;
                                });
                              },

                              isExpanded: true,
                              hint: Text(
                                'SAVING FOR?',
                                style: TextStyle(
                                    fontSize: 15.0, color: Colors.grey),
                              ),
                            );

                          }),
                    ),
    }
}

How can i fix this error? I know the data fetching works just fine. I'm definitely missing something in my widget. Any help would be appreciated.

Body:
The DropdownButton value must in item values or must be null.

DropdownButton(
  value: categoryId,
  items: snapshot.data.map((category) {
    DropdownMenuItem(
      child: Text('${category.name}'),
      value: category.id,
    );
  }).toList(),
  onChanged: (value) {
    setState(() {
      categoryId = value;
    });
  },

  isExpanded: true,
  hint: Text(
    'SAVING FOR?',
    style: TextStyle(
        fontSize: 15.0, color: Colors.grey),
  ),
);


问:
passing unknown class as parameter and trying to run function on it
Using C#, lets say I have these classes:

```<code>classZero
classOne
classTwo
</code>```

class classZero and classOne have a public function named "Hello()".

how can i creat a new function (in any class) that takes a unknown class as a paramenter and then run the function "Hello" on this unknown class, if it exists?

in sebdo code this would look something like this:

```<code>function runHelloIfPossible(anyclass aclass):
   if aclass contains function Hello:
      aclass.Hello()
</code>```

if in my case the anyclass argument where any of classZero or classOne the function Hello would run.

答:
You can use type pattern matching with switch statement for that (it's available from C# 7)

public void RunHelloIfPossible(object anyObject)
{
    switch (anyObject)
    {
        case classZero zero:
            zero.Hello();
            break;
        case classOne one:
            one.Hello();
            break;
    }
}
```

<p>Example of the usage</p>

<pre class="lang-cs prettyprint-override"><code>RunHelloIfPossible(new classOne());
</code>```

If both classes implement the same interface (lets say IHello) or base class, the code above can be simplified to

if (anyObject is IHello hello)
{
    hello.Hello();
}
```

Body:
Using C#, lets say I have these classes:

classZero
classOne
classTwo

class classZero and classOne have a public function named "Hello()".

how can i creat a new function (in any class) that takes a unknown class as a paramenter and then run the function "Hello" on this unknown class, if it exists?

in sebdo code this would look something like this:

function runHelloIfPossible(anyclass aclass):
   if aclass contains function Hello:
      aclass.Hello()

if in my case the anyclass argument where any of classZero or classOne the function Hello would run.

Body:
You can use type pattern matching with switch statement for that (it's available from C# 7)

public void RunHelloIfPossible(object anyObject)
{
    switch (anyObject)
    {
        case classZero zero:
            zero.Hello();
            break;
        case classOne one:
            one.Hello();
            break;
    }
}

Example of the usage

RunHelloIfPossible(new classOne());

If both classes implement the same interface (lets say IHello) or base class, the code above can be simplified to

if (anyObject is IHello hello)
{
    hello.Hello();
}


问:
Headless Browser for Python (Javascript support REQUIRED!)
I need a headless browser which is fairly easy to use (I am still fairly new to Python and programming in general) which will allow me to navigate to a page, log into a form that requires Javascript, and then scrape the resulting web page by searching for results matching certain criteria, clicking check boxes, and clicking to download files. All of this requires Javascript.

I hear a headless browser is what I want - requirements/preferences are that I be able to run it from Python, and preferably that the resultant script will be compilable by py2exe (I am writing this program for other users).

So far Windmill looks like it MIGHT be what I want, but I am not sure.

Any ideas appreciated!

答:
I use webkit as a headless browser in Python via pyqt / pyside:

http://www.riverbankcomputing.co.uk/software/pyqt/download

http://developer.qt.nokia.com/wiki/Category:LanguageBindings::PySide::Downloads

I particularly like webkit because it is simple to setup. For Ubuntu you just use: sudo apt-get install python-qt4

Here is an example script:

http://webscraping.com/blog/Scraping-JavaScript-webpages-with-webkit/


问:
How to convert to camel casing after a symbol?
```<code>Input #2: profile.Address.AddressLine1
Result: profile.address.addressLine1

Input #2: MyName
Result: myName
</code>```

<hr>

```<code>using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputText = "profile.Business.AddressLine1"; //profile.business.addressLine1
            //string inputText = "MyName"; //myName
            string result = null;

            if (inputText.Contains('.'))
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);

                //Loop to find period symbol
                //make the next character after the period symbol lowercase
            }
            else
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);
            }
        }
    }
}
</code>```

答:
Try below:

```<code>var input = "profile.Business.AddressLine1";
var result = string.Join(".",
         input.Split('.')
         .Select(x => string.IsNullOrEmpty(x)
               ? "" : Char.ToLower(x.First()) + x.Substring(1)));
</code>```

Steps to solve your issue:

Split your input string using ..

Change your first letter of each word to lower and concatenate rest of the string.

Again join array with .

Try it online

Inputs:

```<code>var input = "profile.Business.AddressLine1";
var test = "Test..Test";
</code>```

Output:

```<code>profile.business.addressLine1
test..test
</code>```

Body:
Input #2: profile.Address.AddressLine1
Result: profile.address.addressLine1

Input #2: MyName
Result: myName

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputText = "profile.Business.AddressLine1"; //profile.business.addressLine1
            //string inputText = "MyName"; //myName
            string result = null;

            if (inputText.Contains('.'))
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);

                //Loop to find period symbol
                //make the next character after the period symbol lowercase
            }
            else
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);
            }
        }
    }
}

Body:
Try below:

var input = "profile.Business.AddressLine1";
var result = string.Join(".",
         input.Split('.')
         .Select(x => string.IsNullOrEmpty(x)
               ? "" : Char.ToLower(x.First()) + x.Substring(1)));

Steps to solve your issue:

Split your input string using ..

Change your first letter of each word to lower and concatenate rest of the string.

Again join array with .

Try it online

Inputs:

var input = "profile.Business.AddressLine1";
var test = "Test..Test";

Output:

profile.business.addressLine1
test..test


问:
What is the SQL query to show another date format?
I have two MySQL database tabels (named 'accounts' and 'events') with some columns like events.date. This column has a 'date' format. It shows the date as i.e. '2020-02-17'. Now I want to show some data from this combined tables with a query and I want to convert the date formate to DD-MM-YYYY instead of YYYY-MM-DD. I've tried some things but I got errors.

Queries I've tried:

```<code>SELECT events.id, convert(varchar, events.date, 105), events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date

SELECT events.id, convert(date(4), events.date, 20), events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date
</code>```

This query works well but shows me the wrong date format:

```<code>SELECT events.id, events.date, events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date
</code>```

Can you please help me? Many thanks in advance!

答:
use FORMAT function

To get DD-MM-YYYY use

```<code>SELECT FORMAT (getdate(), 'dd-MM-yyyy ')
</code>```

read more here: https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2012/hh213505(v=sql.110)

Body:
I have two MySQL database tabels (named 'accounts' and 'events') with some columns like events.date. This column has a 'date' format. It shows the date as i.e. '2020-02-17'. Now I want to show some data from this combined tables with a query and I want to convert the date formate to DD-MM-YYYY instead of YYYY-MM-DD. I've tried some things but I got errors.

Queries I've tried:

SELECT events.id, convert(varchar, events.date, 105), events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date

SELECT events.id, convert(date(4), events.date, 20), events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date

This query works well but shows me the wrong date format:

SELECT events.id, events.date, events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date

Can you please help me? Many thanks in advance!

Body:
use FORMAT function

To get DD-MM-YYYY use

SELECT FORMAT (getdate(), 'dd-MM-yyyy ')

read more here: https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2012/hh213505(v=sql.110)


问:
Wicket 8: How to prevent sendRedirect after writing to response stream?
I have a form which downloads a PDF file to the user at the end of onSubmit().

```<code>   @Override
   protected void onSubmit() {
       if (some error condition) {
          getPage().error("Form invalid for some reason");
          return;
       }
       byte[] bytes = ...;
       WebResponse response = getWebResponse();
       response.setContentType("application/pdf");
       response.setStatus(200);
       response.setAttachmentHeader("file.pdf"));
       response.write(bytes));
   }
</code>```

When I run the code, the onSubmit correctly allows the user to download the PDF file. However, then the log file gets 19 stack traces complaining: Cannot call sendRedirect() after the response has been committed. How can I stop Wicket from calling sendRedirect after my onSubmit?

```<code>java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
    at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:488) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.wicket.protocol.http.servlet.ServletWebResponse.sendRedirect(ServletWebResponse.java:288) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.protocol.http.HeaderBufferingWebResponse.sendRedirect(HeaderBufferingWebResponse.java:117) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.handler.render.WebPageRenderer.redirectTo(WebPageRenderer.java:161) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.handler.render.WebPageRenderer.respond(WebPageRenderer.java:280) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.core.request.handler.RenderPageRequestHandler.respond(RenderPageRequestHandler.java:202) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:914) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.RequestHandlerExecutor.execute(RequestHandlerExecutor.java:65) ~[wicket-request-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:282) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:253) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:221) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:275) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:206) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:299) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_201]
</code>```

答:
Did you try this ?</p>

```<code>final AbstractResourceStreamWriter rstream = new AbstractResourceStreamWriter()
{
     @Override
     public String getContentType()
     {
          return "application/pdf";
     }

     @Override
     public void write(OutputStream out)
     {
         try  {
             out.write(bytes,0,bytes.length);
         }
         catch(IOException e) { /* ... */ }
     }
};
final ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(rstream, "my.pdf");
getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
</code>```

Body:
I have a form which downloads a PDF file to the user at the end of onSubmit().

   @Override
   protected void onSubmit() {
       if (some error condition) {
          getPage().error("Form invalid for some reason");
          return;
       }
       byte[] bytes = ...;
       WebResponse response = getWebResponse();
       response.setContentType("application/pdf");
       response.setStatus(200);
       response.setAttachmentHeader("file.pdf"));
       response.write(bytes));
   }

When I run the code, the onSubmit correctly allows the user to download the PDF file. However, then the log file gets 19 stack traces complaining: Cannot call sendRedirect() after the response has been committed. How can I stop Wicket from calling sendRedirect after my onSubmit?

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
    at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:488) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.wicket.protocol.http.servlet.ServletWebResponse.sendRedirect(ServletWebResponse.java:288) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.protocol.http.HeaderBufferingWebResponse.sendRedirect(HeaderBufferingWebResponse.java:117) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.handler.render.WebPageRenderer.redirectTo(WebPageRenderer.java:161) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.handler.render.WebPageRenderer.respond(WebPageRenderer.java:280) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.core.request.handler.RenderPageRequestHandler.respond(RenderPageRequestHandler.java:202) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:914) ~[wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.RequestHandlerExecutor.execute(RequestHandlerExecutor.java:65) ~[wicket-request-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:282) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:253) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:221) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:275) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:206) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:299) [wicket-core-8.6.1.jar:8.6.1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_201]

Body:
Did you try this ?

final AbstractResourceStreamWriter rstream = new AbstractResourceStreamWriter()
{
     @Override
     public String getContentType()
     {
          return "application/pdf";
     }

     @Override
     public void write(OutputStream out)
     {
         try  {
             out.write(bytes,0,bytes.length);
         }
         catch(IOException e) { /* ... */ }
     }
};
final ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(rstream, "my.pdf");
getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);


问:
Haskell | Exception: Non-exhaustive patterns in function myAny
I have just started learning haskell and wrote a customized code for any function.
Please suggest why does it still shows Non-exhaustive patterns error even after I have used otherwise or where I am going wrong?

Exceptiom raised :-
    Exception: main.hs:(37,1)-(40,21): Non-exhaustive patterns in function myAny

```<code>myAny :: (a -> Bool) -> [a] -> Bool
myAny f (x:xs)
  | f x == True = True
  | f x == False = myAny f xs
  | otherwise = False
</code>```

答:
You forgot to implement a clause for the empty list. Since you perform recursion, if none of the elements match, it will eventually call myAny with the empty list. In that case you need to return False:

```<code>myAny :: (a -> Bool) -> [a] -> Bool
<b>myAny _ [] = False</b>
myAny f (x:xs)
  | f x == True = True
  | f x == False = myAny f xs
  | otherwise = False</code>```

Note that it however makes no sense to perform two checks with f x, if it is not True, it is False, so the otherwise case will normally never occcur:

```<code>myAny :: (a -> Bool) -> [a] -> Bool
myAny _ [] = False
myAny f (x:xs)
  | f x = True
  | otherwise = myAny f xs</code>```

We can further simplify this with (||) :: Bool -> Bool -> Bool to:

```<code>myAny :: (a -> Bool) -> [a] -> Bool
myAny _ [] = False
myAny f (x:xs) = <b>f x ||</b> myAny f xs</code>```

or use a foldr pattern:

```<code>myAny :: Foldable f => (a -> Bool) -> f a -> Bool
myAny f = foldr ((||) . f) False</code>```

OwnerDisplayName: Sidharath Khanna

Body:
I have just started learning haskell and wrote a customized code for any function.
Please suggest why does it still shows Non-exhaustive patterns error even after I have used otherwise or where I am going wrong?

Exceptiom raised :-
    Exception: main.hs:(37,1)-(40,21): Non-exhaustive patterns in function myAny

myAny :: (a -> Bool) -> [a] -> Bool
myAny f (x:xs)
  | f x == True = True
  | f x == False = myAny f xs
  | otherwise = False

Body:
You forgot to implement a clause for the empty list. Since you perform recursion, if none of the elements match, it will eventually call myAny with the empty list. In that case you need to return False:

myAny :: (a -> Bool) -> [a] -> Bool
myAny _ [] = False
myAny f (x:xs)
  | f x == True = True
  | f x == False = myAny f xs
  | otherwise = False

Note that it however makes no sense to perform two checks with f x, if it is not True, it is False, so the otherwise case will normally never occcur:

myAny :: (a -> Bool) -> [a] -> Bool
myAny _ [] = False
myAny f (x:xs)
  | f x = True
  | otherwise = myAny f xs

We can further simplify this with (||) :: Bool -> Bool -> Bool to:

myAny :: (a -> Bool) -> [a] -> Bool
myAny _ [] = False
myAny f (x:xs) = f x || myAny f xs

or use a foldr pattern:

myAny :: Foldable f => (a -> Bool) -> f a -> Bool
myAny f = foldr ((||) . f) False


问:
Sharing object between child and fork process node js
I'm working on child process using fork. but got totally confused on few things

```<code>• will it (process)pass app object instance eg:- let app = express(); using IPC
</code>```

I m trying to explain my senario, first I have server.js where I initialize (starting point) server and other file is my task.js from where I am doing heavy task like reading a big file data and sending data back to other server. For send I had require authorization from that server whose logic is present in main.js and  if any error occur I'm send email with few detail to client. Below provide code for email and authorization in main.js

```<code> Let task = require('./task.js')
app.sendEmail = function (message, emailinfo, attachment){
 // my email logic
  }
app.auth= function(host,port)
 // Authorization logic
}
 New task(app).run()
</code>```

In task.js (sample code)

```<code>Class Task {
  constructor(app){
    this.app =app
  }
  run(){
    fs.readfile('myfile',function(err,data){

  if(err){ let msg =err;
  let clientinf; clientinf.to = "client email";
  clientinf.cc = " other user in CC";
  this.app.sendEmail(msg, clientinf, attach);
  }else{
    let host='other server url';
    let port='port';
    this.app.auth(host,port);
 }
 })
  }
}
</code>```

I want to run task.js  in one more thread . note cluster and worker(because I m using node 10.19 so not confident that worker works properly) I don't want to use . It is possible to use folk or spawn to share data between each other. If not how I can achieve my requirement using thread?

答:
Here are two solutions. The first is using the Worker class from the worker_threads module but since you don't want to update the node version the second solution is using fork function from child_process module. They do pretty much the same thing to be honest I can't tell which is better but the worker_threads solution is more recent.

Solution 1:

```<code>const { Worker } = require('worker_threads')
const task_script = path.join(__dirname, "./task.js")
 const obj = {data:"data"}
 const worker = new Worker(task_script, {
                workerData: JSON.stringify(obj)
              })
 worker.on("error", (err) => console.log(err))
 worker.on("exit", () => console.log("exit"))
 worker.on("message", (data) => {
                console.log(data)
                res.send(data)
  })
</code>```

and you have to change the task.js code slightly.Here it is

```<code>const { parentPort, workerData, isMainThread } = require('worker_threads')

class Task {
  constructor(app){
    this.app = app
  }
  run(){
if (!isMainThread) {
  console.log("workerData: ", workerData) //you have worker data here
  fs.readfile('myfile',function(err,data){

  if(err){ let msg = err;
  let clientinf; clientinf.to = "client email";
  clientinf.cc = " other user in CC";
  this.app.sendEmail(msg, clientinf, attach);
  parentPort.postMessage(msg) //use can send message to parent like this
  } else {
    let host='other server url';
    let port='port';
    this.app.auth(host,port);
     }
   })
  }
 }
}
</code>```

And here is the second solution

```<code>const { fork } = require('child_process');

const forked = fork('task.js');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
});

forked.send({ hello: 'world' });
</code>```

and the taks.js way of sending and recieving data with this method

```<code>class Task {
  constructor(app){
    this.app = app
  }
  run(){
  //receive
  process.on('message', (msg) => {
    console.log('Message from parent:', msg);
  });
  fs.readfile('myfile',function(err,data){

  if(err){ let msg = err;
  let clientinf; clientinf.to = "client email";
  clientinf.cc = " other user in CC";
  this.app.sendEmail(msg, clientinf, attach);
   process.send(msg); //send method
  } else {
    let host='other server url';
    let port='port';
    this.app.auth(host,port);
     }
   })
  }
}
</code>```

Body:
I'm working on child process using fork. but got totally confused on few things

• will it (process)pass app object instance eg:- let app = express(); using IPC

I m trying to explain my senario, first I have server.js where I initialize (starting point) server and other file is my task.js from where I am doing heavy task like reading a big file data and sending data back to other server. For send I had require authorization from that server whose logic is present in main.js and  if any error occur I'm send email with few detail to client. Below provide code for email and authorization in main.js

 Let task = require('./task.js')
app.sendEmail = function (message, emailinfo, attachment){
 // my email logic
  }
app.auth= function(host,port)
 // Authorization logic
}
 New task(app).run()

In task.js (sample code)

Class Task {
  constructor(app){
    this.app =app
  }
  run(){
    fs.readfile('myfile',function(err,data){

  if(err){ let msg =err;
  let clientinf; clientinf.to = "client email";
  clientinf.cc = " other user in CC";
  this.app.sendEmail(msg, clientinf, attach);
  }else{
    let host='other server url';
    let port='port';
    this.app.auth(host,port);
 }
 })
  }
}

I want to run task.js  in one more thread . note cluster and worker(because I m using node 10.19 so not confident that worker works properly) I don't want to use . It is possible to use folk or spawn to share data between each other. If not how I can achieve my requirement using thread?

Body:
Here are two solutions. The first is using the Worker class from the worker_threads module but since you don't want to update the node version the second solution is using fork function from child_process module. They do pretty much the same thing to be honest I can't tell which is better but the worker_threads solution is more recent.

Solution 1:

const { Worker } = require('worker_threads')
const task_script = path.join(__dirname, "./task.js")
 const obj = {data:"data"}
 const worker = new Worker(task_script, {
                workerData: JSON.stringify(obj)
              })
 worker.on("error", (err) => console.log(err))
 worker.on("exit", () => console.log("exit"))
 worker.on("message", (data) => {
                console.log(data)
                res.send(data)
  })

and you have to change the task.js code slightly.Here it is

const { parentPort, workerData, isMainThread } = require('worker_threads')

class Task {
  constructor(app){
    this.app = app
  }
  run(){
if (!isMainThread) {
  console.log("workerData: ", workerData) //you have worker data here
  fs.readfile('myfile',function(err,data){

  if(err){ let msg = err;
  let clientinf; clientinf.to = "client email";
  clientinf.cc = " other user in CC";
  this.app.sendEmail(msg, clientinf, attach);
  parentPort.postMessage(msg) //use can send message to parent like this
  } else {
    let host='other server url';
    let port='port';
    this.app.auth(host,port);
     }
   })
  }
 }
}

And here is the second solution

const { fork } = require('child_process');

const forked = fork('task.js');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
});

forked.send({ hello: 'world' });

and the taks.js way of sending and recieving data with this method

class Task {
  constructor(app){
    this.app = app
  }
  run(){
  //receive
  process.on('message', (msg) => {
    console.log('Message from parent:', msg);
  });
  fs.readfile('myfile',function(err,data){

  if(err){ let msg = err;
  let clientinf; clientinf.to = "client email";
  clientinf.cc = " other user in CC";
  this.app.sendEmail(msg, clientinf, attach);
   process.send(msg); //send method
  } else {
    let host='other server url';
    let port='port';
    this.app.auth(host,port);
     }
   })
  }
}


问:
Apply CSS on a Specific SharePoint Ribbon Bar Button?
Is there a way to simply hide a particular SharePoint ribbon bar button?   I've see the CSS code for hiding the entire ribbon bar, but I only want to hide 1 button on it (the check-in button).  I've tried referencing it several ways, such as:

```<code>a#Ribbon.DocLibListForm.Edit.Commit.CheckIn-Large { display: none; !important }

ms-cui-ctl-large#Ribbon.DocLibListForm.Edit.Commit.CheckIn-Large { display: none; !important }

a.ms-cui-ctl-large#Ribbon.DocLibListForm.Edit.Commit.CheckIn-Large { display: none; !important }
</code>```

It's possible that my CSS is just all wrong, or perhaps I'm going about it the wrong way.  How can I hide this element?

答:
It would be really helpful if you could post the part of the html you need help with.

However your css isn't using the important rule properly, the !important needs to be before the ; something like this:

You also need to separate with a space any child elements you are referencing, the first example needs to be written like this:

```<code>a#Ribbon .DocLibListForm .Edit .Commit .CheckIn-Large {
     display: none !important;
}
</code>```

It could be re written like this:

```<code>a#Ribbon .DocLibListForm .CheckIn-Large {
     display: none !important;
}
</code>```

Given that only 1 element is named .CheckIn-Large that is a child element of .DocLibListForm

For these kind of issues you can use the IE developer bar (or firebug if you use firefox), it should come bundled with ie8+ which can help you with this sort of things, letting you edit the css in real time.

I  would advise against using the !important rule because it modifies the way that CSS normally operates.

{edit}

since dots are part of your ID, you can try this:

```<code>#Ribbon.DocLibListForm.Edit.Commit.CheckIn-Large {
     display: none !important;
}
</code>```

However without actual HTML code, it is still hard to tell, maybe you can paste the part that's giving you issues on pastebin.

Body:
Is there a way to simply hide a particular SharePoint ribbon bar button?   I've see the CSS code for hiding the entire ribbon bar, but I only want to hide 1 button on it (the check-in button).  I've tried referencing it several ways, such as:

a#Ribbon.DocLibListForm.Edit.Commit.CheckIn-Large { display: none; !important }

ms-cui-ctl-large#Ribbon.DocLibListForm.Edit.Commit.CheckIn-Large { display: none; !important }

a.ms-cui-ctl-large#Ribbon.DocLibListForm.Edit.Commit.CheckIn-Large { display: none; !important }

It's possible that my CSS is just all wrong, or perhaps I'm going about it the wrong way.  How can I hide this element?

Body:
It would be really helpful if you could post the part of the html you need help with.

However your css isn't using the important rule properly, the !important needs to be before the ; something like this:

You also need to separate with a space any child elements you are referencing, the first example needs to be written like this:

a#Ribbon .DocLibListForm .Edit .Commit .CheckIn-Large {
     display: none !important;
}

It could be re written like this:

a#Ribbon .DocLibListForm .CheckIn-Large {
     display: none !important;
}

Given that only 1 element is named .CheckIn-Large that is a child element of .DocLibListForm

For these kind of issues you can use the IE developer bar (or firebug if you use firefox), it should come bundled with ie8+ which can help you with this sort of things, letting you edit the css in real time.

I  would advise against using the !important rule because it modifies the way that CSS normally operates.

{edit}

since dots are part of your ID, you can try this:

#Ribbon.DocLibListForm.Edit.Commit.CheckIn-Large {
     display: none !important;
}

However without actual HTML code, it is still hard to tell, maybe you can paste the part that's giving you issues on pastebin.


问:
Find all occurrences of a key in nested dictionaries and lists
I have a dictionary like this:

```<code>{
    "id": "abcde",
    "key1": "blah",
    "key2": "blah blah",
    "nestedlist": [
        {
            "id": "qwerty",
            "nestednestedlist": [
                {
                    "id": "xyz",
                    "keyA": "blah blah blah"
                },
                {
                    "id": "fghi",
                    "keyZ": "blah blah blah"
                }
            ],
            "anothernestednestedlist": [
                {
                    "id": "asdf",
                    "keyQ": "blah blah"
                },
                {
                    "id": "yuiop",
                    "keyW": "blah"
                }
            ]
        }
    ]
}
</code>```

Basically a dictionary with nested lists, dictionaries, and strings, of arbitrary depth.

What is the best way of traversing this to extract the values of every "id" key? I want to achieve the equivalent of an XPath query like "//id". The value of "id" is always a string.

So from my example, the output I need is basically:

```<code>["abcde", "qwerty", "xyz", "fghi", "asdf", "yuiop"]
</code>```

Order is not important.

答:
Following up on @hexerei software's answer and
 @bruno-bronosky's comment, if you want to iterate over a list/set of keys:

```<code>def gen_dict_extract(var, keys):
   for key in keys:
      if hasattr(var, 'items'):
         for k, v in var.items():
            if k == key:
               yield v
            if isinstance(v, dict):
               for result in gen_dict_extract([key], v):
                  yield result
            elif isinstance(v, list):
               for d in v:
                  for result in gen_dict_extract([key], d):
                     yield result
</code>```

Note that I'm passing a list with a single element ([key]}, instead of the string key.

Body:
I have a dictionary like this:

{
    "id": "abcde",
    "key1": "blah",
    "key2": "blah blah",
    "nestedlist": [
        {
            "id": "qwerty",
            "nestednestedlist": [
                {
                    "id": "xyz",
                    "keyA": "blah blah blah"
                },
                {
                    "id": "fghi",
                    "keyZ": "blah blah blah"
                }
            ],
            "anothernestednestedlist": [
                {
                    "id": "asdf",
                    "keyQ": "blah blah"
                },
                {
                    "id": "yuiop",
                    "keyW": "blah"
                }
            ]
        }
    ]
}

Basically a dictionary with nested lists, dictionaries, and strings, of arbitrary depth.

What is the best way of traversing this to extract the values of every "id" key? I want to achieve the equivalent of an XPath query like "//id". The value of "id" is always a string.

So from my example, the output I need is basically:

["abcde", "qwerty", "xyz", "fghi", "asdf", "yuiop"]

Order is not important.

Body:
Following up on @hexerei software's answer and
 @bruno-bronosky's comment, if you want to iterate over a list/set of keys:

def gen_dict_extract(var, keys):
   for key in keys:
      if hasattr(var, 'items'):
         for k, v in var.items():
            if k == key:
               yield v
            if isinstance(v, dict):
               for result in gen_dict_extract([key], v):
                  yield result
            elif isinstance(v, list):
               for d in v:
                  for result in gen_dict_extract([key], d):
                     yield result

Note that I'm passing a list with a single element ([key]}, instead of the string key.