问:
Error when launching app with firebase cloud messaging
I am trying to integrate firebase cloud messaging into my app inorder to send notifications to users. When trying to start up the app, I am getting the following error:

```<code>    *** First throw call stack:
(0x1e024927c 0x1df4239f8 0x1e01534b0 0x102a31268 0x102995540 0x1029956f8 0x20cb84088 0x20cb83944 0x102995878 0x1dfc9a8e0)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

This happens here:

```<code>    [NSException raise:NSInternalInconsistencyException
</code>```

in FIRAuth.m.

```<code>  [NSException raise:NSInternalInconsistencyException
                format:@"The default FIRApp instance must be configured before the default FIRAuth"
                       @"instance can be initialized. One way to ensure that is to call "
                       @"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) in the App "
                       @"Delegate's `application:didFinishLaunchingWithOptions:` "
                       @"(`application(_:didFinishLaunchingWithOptions:)` in Swift)."];
</code>```

This is what most of my app delegate looks like:

```<code>      let currentUser = Auth.auth().currentUser!.uid

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()
        Messaging.messaging().delegate = self as! MessagingDelegate

//        InstanceID.instanceID().instanceID { (result, error) in
//            if let error = error {
//                print("Error fetching remote instange ID: \(error)")
//            } else if let result = result {
//                print("Remote instance ID token: \(result.token)")
//                let ref = Database.database().reference()
//                ref.child("UsersFireTokens").child(self.currentUser).child("token").setValue(result.token)
//            }
//        }

        return true
    }

    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        if #available(iOS 10.0, *) {//for notif's
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self as! UNUserNotificationCenterDelegate

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
        InstanceID.instanceID().instanceID { (result, error) in
            if error == nil {
                print("InstanceID token: \(result)")
//                let ref = Database.database().reference()
//                ref.child("UsersFireTokens").child(self.currentUser).child("token").setValue(result!)
            } else {
                print(error, ": Error in getting token for Fire")
            }
        }
//        if let refreshedToken = InstanceID.instanceID().token() {
//            print("InstanceID token: \(refreshedToken)")
//        }
    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")

        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
        // TODO: If necessary send token to application server.
        let ref = Database.database().reference()
        ref.child("UsersFireTokens").child(self.currentUser).child("token").setValue(dataDict["token"]!)
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }

    // MARK: - MessagingDelegate

    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print(fcmToken, ": fcmToken")
        let ref = Database.database().reference()
        ref.child("UsersFireTokens").child(self.currentUser).child("token").setValue(fcmToken)

    }
</code>```

What is happening and how can i fix this error?

I was trying to follow the instructions here...

答:
You can't have this line

```<code>let currentUser = Auth.auth().currentUser!.uid
</code>```

outside a function - It will be called when the App Delegate is initialised, which is before didFinishLaunching is called - This means that Auth.auth() is being initialised before calling FireBaseApp.configure() as the exception said.

I would suggest:

```<code>var currentUser: String?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()
    Messaging.messaging().delegate = self as! MessagingDelegate

    self.currentUser = Auth.auth().currentUser?.uid

    return true
}
</code>```

Body:
I am trying to integrate firebase cloud messaging into my app inorder to send notifications to users. When trying to start up the app, I am getting the following error:

    *** First throw call stack:
(0x1e024927c 0x1df4239f8 0x1e01534b0 0x102a31268 0x102995540 0x1029956f8 0x20cb84088 0x20cb83944 0x102995878 0x1dfc9a8e0)
libc++abi.dylib: terminating with uncaught exception of type NSException

This happens here:

    [NSException raise:NSInternalInconsistencyException

in FIRAuth.m.

  [NSException raise:NSInternalInconsistencyException
                format:@"The default FIRApp instance must be configured before the default FIRAuth"
                       @"instance can be initialized. One way to ensure that is to call "
                       @"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) in the App "
                       @"Delegate's `application:didFinishLaunchingWithOptions:` "
                       @"(`application(_:didFinishLaunchingWithOptions:)` in Swift)."];

This is what most of my app delegate looks like:

      let currentUser = Auth.auth().currentUser!.uid

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()
        Messaging.messaging().delegate = self as! MessagingDelegate

//        InstanceID.instanceID().instanceID { (result, error) in
//            if let error = error {
//                print("Error fetching remote instange ID: \(error)")
//            } else if let result = result {
//                print("Remote instance ID token: \(result.token)")
//                let ref = Database.database().reference()
//                ref.child("UsersFireTokens").child(self.currentUser).child("token").setValue(result.token)
//            }
//        }

        return true
    }

    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        if #available(iOS 10.0, *) {//for notif's
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self as! UNUserNotificationCenterDelegate

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
        InstanceID.instanceID().instanceID { (result, error) in
            if error == nil {
                print("InstanceID token: \(result)")
//                let ref = Database.database().reference()
//                ref.child("UsersFireTokens").child(self.currentUser).child("token").setValue(result!)
            } else {
                print(error, ": Error in getting token for Fire")
            }
        }
//        if let refreshedToken = InstanceID.instanceID().token() {
//            print("InstanceID token: \(refreshedToken)")
//        }
    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")

        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
        // TODO: If necessary send token to application server.
        let ref = Database.database().reference()
        ref.child("UsersFireTokens").child(self.currentUser).child("token").setValue(dataDict["token"]!)
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }

    // MARK: - MessagingDelegate

    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print(fcmToken, ": fcmToken")
        let ref = Database.database().reference()
        ref.child("UsersFireTokens").child(self.currentUser).child("token").setValue(fcmToken)

    }

What is happening and how can i fix this error?

I was trying to follow the instructions here...

Body:
You can't have this line

let currentUser = Auth.auth().currentUser!.uid

outside a function - It will be called when the App Delegate is initialised, which is before didFinishLaunching is called - This means that Auth.auth() is being initialised before calling FireBaseApp.configure() as the exception said.

I would suggest:

var currentUser: String?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()
    Messaging.messaging().delegate = self as! MessagingDelegate

    self.currentUser = Auth.auth().currentUser?.uid

    return true
}


来源: stackexchange

问:
Reduce sum of digits recursively down to one digit number
How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion?  I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:

```<code>class sum_of_digits
{

    static int sum_of_digit(int n)
    {
        if (n == 0)
            return 0;
        return (n % 10 + sum_of_digit(n / 10));
    }

    public static void main(String args[])
    {
        int num = 12345;
        int result = sum_of_digit(num);
        System.out.println("Sum of digits in " +
                           num + " is " + result);
    }
}
</code>```

This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.

答:
do you think it is possible to make it work without an additional
  method?

Why can't we just let the recursion do the work for us and simply say:

```<code>static int sum_of_digit(int n)
{
    if (n < 10)
        return n;

    return sum_of_digit(n % 10 + sum_of_digit(n / 10));
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion?  I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:

class sum_of_digits
{

    static int sum_of_digit(int n)
    {
        if (n == 0)
            return 0;
        return (n % 10 + sum_of_digit(n / 10));
    }

    public static void main(String args[])
    {
        int num = 12345;
        int result = sum_of_digit(num);
        System.out.println("Sum of digits in " +
                           num + " is " + result);
    }
}

This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.

Body:
do you think it is possible to make it work without an additional
  method?

Why can't we just let the recursion do the work for us and simply say:

static int sum_of_digit(int n)
{
    if (n < 10)
        return n;

    return sum_of_digit(n % 10 + sum_of_digit(n / 10));
}


答:
With AWK, please try the following:</p>

```<code>awk -F, '
FNR==1 {next}       # skip the header line
{
    if ($2 != prevcol2) {           # insert newline when SOReference changes
        nl = FNR<=2 ? "" : "\n"     # suppress the newline in the 1st line
        printf("%sWOH~1.0~~%stest~~~ORD~~~~\n", nl, $2)
    }
    printf("WOL~~~%s~~~~~~~~%s~~~~~~~~~~~~~~~~~~~~~\n", $4, $5)
    prevcol2 = $2
}' file.csv
</code>```

Title: Converting CSV file to multiline text file

Body:
I have file which looks like following:

C_DocType_ID,SOReference,DocumentNo,ProductValue,Quantity,LineDescription,C_Tax_ID,TaxAmt

1000000,1904093563U,1904093563U,5210-1,1,0,1000000,0
1000000,1904093563U,1904093563U,6511,2,0,1000000,0
1000000,1904093563U,1904093563U,5001,1,0,1000000,0
1000000,1904083291U,1904083291U,5310,4,0,1000000,0
1000000,1904083291U,1904083291U,5311,3,0,1000000,0
1000000,1904083291U,1904083291U,6101,6,0,1000000,0
1000000,1904083291U,1904083291U,6102,1,0,1000000,0
1000000,1904083291U,1904083291U,6106,6,0,1000000,0

I need to convert it to text file which looks like this:

WOH~1.0~~1904093563Utest~~~ORD~~~~
WOL~~~5210-1~~~~~~~~1~~~~~~~~~~~~~~~~~~~~~
WOL~~~6511~~~~~~~~2~~~~~~~~~~~~~~~~~~~~~
WOL~~~5001~~~~~~~~1~~~~~~~~~~~~~~~~~~~~~

WOH~1.0~~1904083291Utest~~~ORD~~~~~~
WOL~~~5310~~~~~~~~4~~~~~~~~~~~~~~~~~~~~~
WOL~~~5311~~~~~~~~3~~~~~~~~~~~~~~~~~~~~~
WOL~~~6101~~~~~~~~6~~~~~~~~~~~~~~~~~~~~~
WOL~~~6102~~~~~~~~1~~~~~~~~~~~~~~~~~~~~~
WOL~~~6106~~~~~~~~6~~~~~~~~~~~~~~~~~~~~~

The output file has header record and line item record. Header Record contains the SOReference and some hardcoded fields and the Line Item record contains the Product Value and Quantity associated to that SOReference . In the input file we have 2 unique SOReferences thats why the the output file contains 2 header record and their associated line items record.

Need something being done as a command line (awk/sed)? since I have a series of files like this one which need to be converted to text.

Body:
With AWK, please try the following:

awk -F, '
FNR==1 {next}       # skip the header line
{
    if ($2 != prevcol2) {           # insert newline when SOReference changes
        nl = FNR<=2 ? "" : "\n"     # suppress the newline in the 1st line
        printf("%sWOH~1.0~~%stest~~~ORD~~~~\n", nl, $2)
    }
    printf("WOL~~~%s~~~~~~~~%s~~~~~~~~~~~~~~~~~~~~~\n", $4, $5)
    prevcol2 = $2
}' file.csv


问:
Enable Sound button in Notification Channel
In MI Note 5 Pro which has latest MI UI 10.0 with Oreo, so when I try to send push notification by default sound is disable, so i am not able to enable sound programmatically when I am creating a channel for that.

In other Oreo devices notification sound is coming but in MI custom Oreo OS Sound is by default disable

Let me show my code for notification :

```<code>    var intent = Intent(mContext, HomeActivity::class.java)
    intent.putExtra(Constants.EXTRA_FROM_NOTIFICATION, true)
    var pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    var uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

    var mBuilder = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
            .setContentTitle(mContext.getString(R.string.app_name))
            .setContentText(mFirstContactName + " : " + mListChatWindow[0].message)
            .setPriority(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) NotificationManager.IMPORTANCE_HIGH else Notification.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .setSound(uri)
            .setSmallIcon(R.drawable.ic_app_icon)
            .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
            .setVibrate(longArrayOf(0, 100, 1000, 300))
            .setAutoCancel(true)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        var channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH)
        channel.description = "NOTIFICATION_DESCRIPTION"
        channel.lightColor = Color.LTGRAY
        channel.enableVibration(true)
        channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC

        val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build()
        channel.setSound(uri, attributes)
        var notificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }

    var notificationManager = NotificationManagerCompat.from(mContext)
    notificationManager.notify(NOTIFICATION_CHAT_ID, mBuilder.build())
</code>```

I am also set channel.setSound(uri, attributes) in cannel but sound not coming

Here is the screenshot of Notification channel see there sound icon is disabled, how to enable?

Plz help

答:
I had similar problem in MIUI Global 10.1 with oreo but it was only while using custom sound and not like yours, default sound. Any way let me explain how I solve it and hope it may solve yours.

First thing to consider is where the registration of notification channel is executed. It must be executed in Application.onCreate so that the channel is created even before the notification arrives. I was doing it in onMessageReceived.

Second as I said it was working for default notification sound and not for custom one, I inserted below code while creating notification channel and it worked.

```<code>NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID);

    if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
        notificationBuilder.setDefaults(Notification.DEFAULT_SOUND); // This line did the magic for me.

        Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound_notification_plucky);
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();

        CharSequence name = "MyChild";
        String description = "All MyChild messages";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        notificationChannel.setDescription(description);
        notificationChannel.enableVibration(true);
        notificationChannel.setSound(sound, audioAttributes);

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
    }
</code>```

Body:
In MI Note 5 Pro which has latest MI UI 10.0 with Oreo, so when I try to send push notification by default sound is disable, so i am not able to enable sound programmatically when I am creating a channel for that.

In other Oreo devices notification sound is coming but in MI custom Oreo OS Sound is by default disable

Let me show my code for notification :

    var intent = Intent(mContext, HomeActivity::class.java)
    intent.putExtra(Constants.EXTRA_FROM_NOTIFICATION, true)
    var pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    var uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

    var mBuilder = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
            .setContentTitle(mContext.getString(R.string.app_name))
            .setContentText(mFirstContactName + " : " + mListChatWindow[0].message)
            .setPriority(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) NotificationManager.IMPORTANCE_HIGH else Notification.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .setSound(uri)
            .setSmallIcon(R.drawable.ic_app_icon)
            .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
            .setVibrate(longArrayOf(0, 100, 1000, 300))
            .setAutoCancel(true)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        var channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH)
        channel.description = "NOTIFICATION_DESCRIPTION"
        channel.lightColor = Color.LTGRAY
        channel.enableVibration(true)
        channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC

        val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build()
        channel.setSound(uri, attributes)
        var notificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }

    var notificationManager = NotificationManagerCompat.from(mContext)
    notificationManager.notify(NOTIFICATION_CHAT_ID, mBuilder.build())

I am also set channel.setSound(uri, attributes) in cannel but sound not coming

Here is the screenshot of Notification channel see there sound icon is disabled, how to enable?

Plz help

Body:
I had similar problem in MIUI Global 10.1 with oreo but it was only while using custom sound and not like yours, default sound. Any way let me explain how I solve it and hope it may solve yours.

First thing to consider is where the registration of notification channel is executed. It must be executed in Application.onCreate so that the channel is created even before the notification arrives. I was doing it in onMessageReceived.

Second as I said it was working for default notification sound and not for custom one, I inserted below code while creating notification channel and it worked.

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID);

    if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
        notificationBuilder.setDefaults(Notification.DEFAULT_SOUND); // This line did the magic for me.

        Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound_notification_plucky);
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();

        CharSequence name = "MyChild";
        String description = "All MyChild messages";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        notificationChannel.setDescription(description);
        notificationChannel.enableVibration(true);
        notificationChannel.setSound(sound, audioAttributes);

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
    }


问:
how to add elements within a array structured object in javascript
I have this structure of javascript object

```<code>var propertiesObject = {
 dataFormat: 'json',
 dataSource: {
    build: {
        caption: "Some caption"

        }, categories: [
        {
        category:[
            {"label":"January"},
            {"ADD NEW HERE DYNAMICALLY"}
        ]
      }
    ],
    dataset: [
        {
            seriesname: "ISB",
            data: [
             {
                 "value": "10000",
                 {"ADD NEW HERE DYNAMICALLY"}
             }
            ]
        },
        {"ADD NEW HERE DYNAMICALLY"}
    ]
} }
</code>```

and I want to add new element dynamically in  "category" and "dataset", then  after all dynamic data added I will stringify it to json.

my problem is how can I achieve this?

I'm really confused with the several solutions i found and it's not the outcome i need.

thank you for any help.

答:
Use that child array as the way you use normal arrays.

```<code>// push directly to array
propertiesObject.category.push(new element);
</code>```

About array push: https://www.w3schools.com/jsref/jsref_push.asp

Body:
I have this structure of javascript object

var propertiesObject = {
 dataFormat: 'json',
 dataSource: {
    build: {
        caption: "Some caption"

        }, categories: [
        {
        category:[
            {"label":"January"},
            {"ADD NEW HERE DYNAMICALLY"}
        ]
      }
    ],
    dataset: [
        {
            seriesname: "ISB",
            data: [
             {
                 "value": "10000",
                 {"ADD NEW HERE DYNAMICALLY"}
             }
            ]
        },
        {"ADD NEW HERE DYNAMICALLY"}
    ]
} }

and I want to add new element dynamically in  "category" and "dataset", then  after all dynamic data added I will stringify it to json.

my problem is how can I achieve this?

I'm really confused with the several solutions i found and it's not the outcome i need.

thank you for any help.

Body:
Use that child array as the way you use normal arrays.

// push directly to array
propertiesObject.category.push(new element);

About array push: https://www.w3schools.com/jsref/jsref_push.asp


问:
Write N/A or " - " on empty cells if one cell of the same row is written
What I am trying to do is this;

I have a table with 8 columns.
What I am trying to do is when I write something in one of the first 4 columns in the same row the other 3 should return me with the value "N/A" or " - ", or something like that. (Or even better with an error message saying I can't write on them since one of the other is written).

The same with the other rows in the table.

Here is the table:

table

I've tried with IF(OR(ISBLACK( etc. but it wasn't working.

So if i write something on cell B3, the other cells (C3,D3,E3) will have to be empty, the same as if i write something on cell C3, the other cells(B3,D3,E3) should be empty.

答:
You could do this using formulas, with each column have a formula that checks the other columns. For example, B3 would have:

=IF(OR(C3<>"",D3<>"",E3<>""),"Do not use","")

But the problem with formulas in data entry spaces is they get overwritten when users enter data. If the user changes their mind and deletes the value they entered, you don't get the formula back and warning won't reappear when they enter data elsewhere.

Instead, you can use conditional formatting to change the colour of cells without values after a value gets entered:

Select B1:E16 (starting from B1 is important, as relative conditional formatting depends on which cell is active within the selection)

Create a new Custom Formatting rule based on a formula: =AND(COUNTA($B3:$E3)>0,B3="")

Set the format to make the background gray

This doesn't stop users entering data in more than cell. You may want to put in another additional conditional formatting rule to set cells red if there is more than 1 value entered.


问:
Using map function instead of for loop
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23":
Number of words =

What am I doing wrong here?

```<code>def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', numwords)
</code>```

答:
after:

```<code>numwords = map(wordcount, lines)
</code>```

numwords is a list of None the same length as lines as wordcount returns None

```<code>for line in lines:
    words = line.split()
    numwords += len(words)
</code>```

would be better and more pythonic

ContentLicense: CC BY-SA 3.0

Title: Using map function instead of for loop

Body:
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23":
Number of words =

What am I doing wrong here?

def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', numwords)

Body:
after:

numwords = map(wordcount, lines)

numwords is a list of None the same length as lines as wordcount returns None

for line in lines:
    words = line.split()
    numwords += len(words)

would be better and more pythonic


问:
How do I increase a variable until a number is reached in JavaScript, leaving all other spaces blank?
I need numbers on a PDF in Adobe Acrobat Pro DC to continue to 30, but in various positions across the PDF pages. Rather than rearrange over and over again (and yet more in the future), I'd rather have a form with autofill boxes extending into the spaces beyond where I need them (think blank monthly calendar spread, filling in those numbers) where I input "1" in one of the boxes and it increases until it gets to 30, leaving the rest of the boxes blank.

What I need help with is getting the numbers to stop there.

Someone else gave me this to get the numbers to increase like I needed:

```<code>if (this.getField("Box1").valueAsString!="") event.value =
  Number(this.getField("Box1").valueAsString)+1;
</code>```

Line break added by editor to reduce scrolling.

Where this is assigned to the one named Box2. That part works beautifully! What I can't figure out is how to tell the numbers to stop at 30. Again, I'm brand spanking new, so I don't really know what I'm doing to begin with.

Some other guys I talked to suggested doing a Date field, but I'm not experienced enough to make the chain of numbers continue and stop where I need them to. That's way beyond me, though I did try with that, too. I'll work up to that one day, but for now I wanted to know if there's a way to code it to stop at a given number, instead.

答:
It sounds like you just need to test if the new event.value will be more than 30 or not:

```<code>var stringVal = this.getField("Box1").valueAsString;
if (stringVal !== '') {
  var numVal = Number(stringVal);
  if (numVal < 30) {
    event.value = numVal + 1;
  }
}
</code>```

Body:
I need numbers on a PDF in Adobe Acrobat Pro DC to continue to 30, but in various positions across the PDF pages. Rather than rearrange over and over again (and yet more in the future), I'd rather have a form with autofill boxes extending into the spaces beyond where I need them (think blank monthly calendar spread, filling in those numbers) where I input "1" in one of the boxes and it increases until it gets to 30, leaving the rest of the boxes blank.

What I need help with is getting the numbers to stop there.

Someone else gave me this to get the numbers to increase like I needed:

if (this.getField("Box1").valueAsString!="") event.value =
  Number(this.getField("Box1").valueAsString)+1;

Line break added by editor to reduce scrolling.

Where this is assigned to the one named Box2. That part works beautifully! What I can't figure out is how to tell the numbers to stop at 30. Again, I'm brand spanking new, so I don't really know what I'm doing to begin with.

Some other guys I talked to suggested doing a Date field, but I'm not experienced enough to make the chain of numbers continue and stop where I need them to. That's way beyond me, though I did try with that, too. I'll work up to that one day, but for now I wanted to know if there's a way to code it to stop at a given number, instead.

Body:
It sounds like you just need to test if the new event.value will be more than 30 or not:

var stringVal = this.getField("Box1").valueAsString;
if (stringVal !== '') {
  var numVal = Number(stringVal);
  if (numVal < 30) {
    event.value = numVal + 1;
  }
}


问:
fixed element is lost when it is on top of another absolute
I have an arrow for the navigation that is fixed, its operation is correct, until it passes over an absolute element with a sliding animation to the left, at that moment my "fixed" arrow goes along with the animation, it is lost from the screen.

I have two absolute divs in a relative container, when the user scrolls up to that position the two divs move out of the screen, left and right respectively. When the animation is triggered, my navigation arrow falls with it.

```<code>//this is my scss

/*******
 ARROW
********/

@import '../../scss/variables';

.arrow{
display: block;
position: fixed;
 right: 15px;
 bottom: 15px;
  svg{
    fill: #fff;
    width:50px;
  }
}
.my_bounce {
  animation-name: my_bounce;
  animation-duration: 2s;
  animation-direction: alternate;
  animation-iteration-count: infinite;
}

/***********
BOXES
************/
.about_cont{
  background: url('../../images/about-movil.jpg') top center;
  background-size: cover;
  display: flex;
  height: 100vh;
  position: relative;
}
.about_boxes{
  display: flex;
  width: 50vw;
  align-items: center;
  font-family: 'Panton';
  position: absolute;
  height: 100vh;;
}
#about_box_1{
  justify-content: flex-end;
  background: $sec;
  left: 0;
  p{
    font-size: 2.5rem;
  }
}
#about_box_2{
  color: #fff;
  background: $prim;
  right: 0;
 p{
   font-size: 2.5rem;
  }
}
</code>```

Does anyone have any idea what is wrong?

答: Without Html file we can not tell about that code.Html file matter with css file </p>

Body:
I have an arrow for the navigation that is fixed, its operation is correct, until it passes over an absolute element with a sliding animation to the left, at that moment my "fixed" arrow goes along with the animation, it is lost from the screen.

I have two absolute divs in a relative container, when the user scrolls up to that position the two divs move out of the screen, left and right respectively. When the animation is triggered, my navigation arrow falls with it.

//this is my scss

/*******
 ARROW
********/

@import '../../scss/variables';

.arrow{
display: block;
position: fixed;
 right: 15px;
 bottom: 15px;
  svg{
    fill: #fff;
    width:50px;
  }
}
.my_bounce {
  animation-name: my_bounce;
  animation-duration: 2s;
  animation-direction: alternate;
  animation-iteration-count: infinite;
}

/***********
BOXES
************/
.about_cont{
  background: url('../../images/about-movil.jpg') top center;
  background-size: cover;
  display: flex;
  height: 100vh;
  position: relative;
}
.about_boxes{
  display: flex;
  width: 50vw;
  align-items: center;
  font-family: 'Panton';
  position: absolute;
  height: 100vh;;
}
#about_box_1{
  justify-content: flex-end;
  background: $sec;
  left: 0;
  p{
    font-size: 2.5rem;
  }
}
#about_box_2{
  color: #fff;
  background: $prim;
  right: 0;
 p{
   font-size: 2.5rem;
  }
}

Does anyone have any idea what is wrong?


问:
How can one get user's home directory using C++17 std::filesystem?
I need to obtain the current user's home directory and then append to it paths to other directories. Since the app is cross-platform then the approach should take this into consideration. I have been looking for a solution without success. Is there a way to get current user's home directory using C++17 std::filesystem?</p>

答:
No.

The only special directories you are handed is a directory suitable for temporary files, and the current directory.

You'll have to write a OS specific wrapper for getting the home directory.  I, personally, think that is a bad idea: rather, you should have "user app settings" directory function, "user document'" directory function, etc (as determined by your application needs).  Where those directories are compared to the home directory vary on a OS by OS basis.

In my experience, also having an API for storing a "registry-like property set" is a good idea (a string-string map with serialization code on the values, for example).  It can map to plists on macOS, registry on windows, and something else on linux.


问:
How to prevent a literal type in TypeScript
Let's say I have a class like this which wraps over a value:

```<code>class Data<T> {
  constructor(public val: T){}

  set(newVal: T) {
    this.val = newVal;
  }
}

const a = new Data('hello');
a.set('world');
// typeof a --> Primitive<string>
</code>```

So far so good, but now I want to restrict it to only one of a set of types, let's say the primitives:

```<code>type Primitives = boolean|string|number|null|undefined;

class PrimitiveData<T extends Primitives> {
  constructor(public val: T){}

  set(newVal: T) {
    this.val = newVal;
  }
}

const b = new PrimitiveData('hello');
b.set('world'); // Error :(
</code>```

Playground link

That last line fails because b is a Primitive<'hello'> not a Primitive<string>, and so set will only take the literal 'hello' as a value, which clearly isn't what I'm after.

What am I doing wrong here? Without resorting to explicitly widening the types myself (eg: new Primitive<string>('hello')) is there anything I can do?

答:
TypeScript intentionally infers literal types just about everywhere, but usually widens those types except in a few circumstances.  One is when you have a type parameter which extends one of the widened types.  The heuristic is that if you're asking for T extends string you might care to keep the exact literal.  This is still true with unions, like T extends Primitives, so you get this behavior.

We can use conditional types to force (unions of) string, number, and boolean literals to widen to (unions of) string, number, and boolean:

```<code>type WidenLiterals<T> =
  T extends boolean ? boolean :
  T extends string ? string :
  T extends number ? number :
  T;

type WString = WidenLiterals<"hello"> // string
type WNumber = WidenLiterals<123> // number
type WBooleanOrUndefined = WidenLiterals<true | undefined> // boolean | undefined
</code>```

Now this is great, and one way you might want to proceed is to use WidenLiterals<T> in place of T everywhere inside PrimitiveData:

```<code>class PrimitiveDataTest<T extends Primitives> {
  constructor(public val: WidenLiterals<T>){}
  set(newVal: WidenLiterals<T>) {
    this.val = newVal;
  }
}

const bTest = new PrimitiveDataTest("hello"); // PrimitiveDataTest<"hello">
bTest.set("world"); // okay
</code>```

And that works as far as it goes. bTest is of type PrimitiveDataTest<"hello">, but the actual type of val is string and you can use it as such.  Unfortunately, you get this undesirable behavior:

```<code>let aTest = new PrimitiveDataTest("goodbye"); // PrimitiveDataTest<"goodbye">
aTest = bTest; // error!
// PrimitiveDataTest<"hello"> not assignable to PrimitiveDataTest<"goodbye">.
// Type '"hello"' is not assignable to type '"goodbye"'.
</code>```

This seems to be due to a bug in TypeScript where conditional types are not being checked properly.  The types PrimitiveDataTest<"hello"> and PrimitiveDataTest<"goodbye"> are each structurally identical to each other and to PrimitiveDataTest<string>, so the types should be mutually assignable.  That they are not is a bug which may or may not get addressed in the near future (maybe some fixes are set for TS3.5 or TS3.6?)

If that's okay then you can probably stop there.

Otherwise, you might consider this implementation, instead. Define an unconstrained version like Data<T>:

```<code>class Data<T> {
  constructor(public val: T) {}
  set(newVal: T) {
    this.val = newVal;
  }
}
</code>```

And then define the type and value PrimitiveData as related to Data like this:

```<code>interface PrimitiveData<T extends Primitives> extends Data<T> {}
const PrimitiveData = Data as new <T extends Primitives>(
  val: T
) => PrimitiveData<WidenLiterals<T>>;
</code>```

The pair of type and value named PrimitiveData acts like a generic class where T is constrained to Primitives, but when you call the constructor the resulting instance is of the widened type:

```<code>const b = new PrimitiveData("hello"); // PrimitiveData<string>
b.set("world"); // okay
let a = new PrimitiveData("goodbye"); // PrimitiveData<string>
a = b; // okay
</code>```

That might be easier for users of PrimitiveData to work with, although the implementation of PrimitiveData does require a bit of hoop jumping.

Okay, hope that helps you move forward.  Good luck!

Link to code

Body:
Let's say I have a class like this which wraps over a value:

class Data<T> {
  constructor(public val: T){}

  set(newVal: T) {
    this.val = newVal;
  }
}

const a = new Data('hello');
a.set('world');
// typeof a --> Primitive<string>

So far so good, but now I want to restrict it to only one of a set of types, let's say the primitives:

type Primitives = boolean|string|number|null|undefined;

class PrimitiveData<T extends Primitives> {
  constructor(public val: T){}

  set(newVal: T) {
    this.val = newVal;
  }
}

const b = new PrimitiveData('hello');
b.set('world'); // Error :(

<a href="http://www.typescriptlang.org/play/index.html#src=class%20Data%3CT%3E%20%7B%0A%20%20constructor(public%20val%3A%20T)%7B%7D%0A%0A%20%20set(newVal%3A%20T)%20%7B%0A%20%20%20%20this.val%20%3D%20newVal%3B%0A%20%20%7D%0A%7D%0A%0Aconst%20a%20%3D%20new%20Data('hello')%3B%0Aa.set('world')%3B%0A%0A%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%0A%0Atype%20Primitives%20%3D%20boolean%7Cstring%7Cnumber%7Cnull%7Cundefined%3B%0A%0Aclass%20PrimitiveData%3CT%20extends%20Primitives%3E%20%7B%0A%20%20constructor(public%20val%3A%20T)%7B%7D%0A%0A%20%20set(newVal%3A%20T)%20%7B%0A%20%20%20%20this.val%20%3D%20newVal%3B%0A%20%20%7D%0A%7D%0A%0Aconst%20b%20%3D%20new%20PrimitiveData('hello')%3B%0Ab.set('world')%3B%20%2F%2F%20Error%20%3A(%0A" rel="noreferrer">Playground link

That last line fails because b is a Primitive<'hello'> not a Primitive<string>, and so set will only take the literal 'hello' as a value, which clearly isn't what I'm after.

What am I doing wrong here? Without resorting to explicitly widening the types myself (eg: new Primitive<string>('hello')) is there anything I can do?

Body:
TypeScript intentionally infers literal types just about everywhere, but usually widens those types except in a few circumstances.  One is when you have a type parameter which extends one of the widened types.  The heuristic is that if you're asking for T extends string you might care to keep the exact literal.  This is still true with unions, like T extends Primitives, so you get this behavior.

We can use conditional types to force (unions of) string, number, and boolean literals to widen to (unions of) string, number, and boolean:

type WidenLiterals<T> =
  T extends boolean ? boolean :
  T extends string ? string :
  T extends number ? number :
  T;

type WString = WidenLiterals<"hello"> // string
type WNumber = WidenLiterals<123> // number
type WBooleanOrUndefined = WidenLiterals<true | undefined> // boolean | undefined

Now this is great, and one way you might want to proceed is to use WidenLiterals<T> in place of T everywhere inside PrimitiveData:

class PrimitiveDataTest<T extends Primitives> {
  constructor(public val: WidenLiterals<T>){}
  set(newVal: WidenLiterals<T>) {
    this.val = newVal;
  }
}

const bTest = new PrimitiveDataTest("hello"); // PrimitiveDataTest<"hello">
bTest.set("world"); // okay

And that works as far as it goes. bTest is of type PrimitiveDataTest<"hello">, but the actual type of val is string and you can use it as such.  Unfortunately, you get this undesirable behavior:

let aTest = new PrimitiveDataTest("goodbye"); // PrimitiveDataTest<"goodbye">
aTest = bTest; // error!
// PrimitiveDataTest<"hello"> not assignable to PrimitiveDataTest<"goodbye">.
// Type '"hello"' is not assignable to type '"goodbye"'.

This seems to be due to a bug in TypeScript where conditional types are not being checked properly.  The types PrimitiveDataTest<"hello"> and PrimitiveDataTest<"goodbye"> are each structurally identical to each other and to PrimitiveDataTest<string>, so the types should be mutually assignable.  That they are not is a bug which may or may not get addressed in the near future (maybe some fixes are set for TS3.5 or TS3.6?)

If that's okay then you can probably stop there.

Otherwise, you might consider this implementation, instead. Define an unconstrained version like Data<T>:

class Data<T> {
  constructor(public val: T) {}
  set(newVal: T) {
    this.val = newVal;
  }
}

And then define the type and value PrimitiveData as related to Data like this:

interface PrimitiveData<T extends Primitives> extends Data<T> {}
const PrimitiveData = Data as new <T extends Primitives>(
  val: T
) => PrimitiveData<WidenLiterals<T>>;

The pair of type and value named PrimitiveData acts like a generic class where T is constrained to Primitives, but when you call the constructor the resulting instance is of the widened type:

const b = new PrimitiveData("hello"); // PrimitiveData<string>
b.set("world"); // okay
let a = new PrimitiveData("goodbye"); // PrimitiveData<string>
a = b; // okay

That might be easier for users of PrimitiveData to work with, although the implementation of PrimitiveData does require a bit of hoop jumping.

Okay, hope that helps you move forward.  Good luck!

<a href="https://typescript-play.js.org/#code/C4TwDgpgBA6glgEwgOwDJ2BATgQwDYDOAPACoB8UAvFCVBAB6bIIFQBGA9h3hDsgFBQoAfnZcefQVABcNOoxQsoBYFjjIA5iOWr1W2bQZMlyAK4BbNtm1nL1gwG5+-UJFgBlXZqqxEKdJi4hEQARAAWEHh4HCFkDlAA9Ak6apou4NAwAHIWVlg+8EhoGNj4xACMAEwAzHGJybZ56W4wAELivMgA8lgAqswQAGbqEAgFfsWBZUSqptAAPlCmA8PIo3VJYtydUIvLSKujzq7QAApq5hhwAG4QrNSc23zzKqka843YH6ZR8-tDIwQTn4AGM8DgCKxznBLsAbhAACI4YA4Eh3YCkeTGKEXK63AgUADeUhBHGQr1MIOAHCwAAowKY2Hg4CCoNd8LJCv4SkFiOQAJSEgC+UgIEGAtLWAHcAGoc3xFAKlYICqDEoRCYBhOAEAB07LwPmlcrwTiEIpFoLJKnYaJt1GlUGhsPhSJRdol4Ui0RC-Pim2deMRyNR6NCESiMTI-DYHt1Ys9UppeAQvv9yQ4AGscCBnJsGCCIGBgFAtTr+DwS6H7VBHYG4bc3dXPRouAg2CAIGn6k7cQ3g+6wyFWxx253Yvxmz5Y+j03QsFgaQBCKD8AN910hj3h71R2scKuQuAaZA4JnQam9mFBpvb4dtjtdsi6tfJEgZKAAci9kZCn6gOr7oeBDHqe56lhwpYft+I5jl2n4vs4YIQqwTakESJLWrMVI0vSjLMqyBoGPyaoikICaShAsryiQJHqhqZZ6gaRpUSaZpQBazjqIEgw4IWV4uo2IaYkYig4te-YEliYlQGh5CkVa5IlvWm4oj4TZQBCtZUVAIkKMw4mCXcZC0lIRE0PwJGUBQKlCSiRBcpMyp8mQcRIVh7AsVKAk3iGtI-j6fo9rZA44EQrx6NGbDxuK-lJlgKbdpsWY5hW4qaV5Pn9k2-mwY+SXJCFaERZo0Y4NOc4pSAQA" rel="noreferrer">Link to code


问:
Will TOP always return the same rows
I have written some code to move data into an archive table, 1000 rows at a time (SQL Server 2008 R2):

```<code>-- archive data
while (@QuitLoop = 0)
begin
 begin transaction

  insert into MyTransactionTable (...)
  select top 1000 * from MyTransactionTable where DateOfSale < @ArchiveCutOffDate

  delete top 1000 from MyTransactionTable where DateOfSale < @ArchiveCutOffDate

  if (@@rowcount = 0) select @QuitLoop = 1
 commit transaction
end
</code>```

Will top always returns the same 1000 rows?

So the rows being inserted into the archive table are the same as the rows being deleted form the transaction table.

答:
As you are using them no, they will not be guaranteed to return the same rows.

Why? Because you don't specify an order by clause. It'll just be whatever 1000 records the engine decides are the 'top' ones that time around.

Also note that it's possible even if you specify an order by that you still wouldn't get the same 1000 rows... if your order by is not selective enough that on the border of the 1000th item is a specific, definable order.

For example; if there are 1002 items with the same sorted value at the top, you don't know which 2 would not be included.

Title: Will TOP always return the same rows

Body:
I have written some code to move data into an archive table, 1000 rows at a time (SQL Server 2008 R2):

-- archive data
while (@QuitLoop = 0)
begin
 begin transaction

  insert into MyTransactionTable (...)
  select top 1000 * from MyTransactionTable where DateOfSale < @ArchiveCutOffDate

  delete top 1000 from MyTransactionTable where DateOfSale < @ArchiveCutOffDate

  if (@@rowcount = 0) select @QuitLoop = 1
 commit transaction
end

Will top always returns the same 1000 rows?

So the rows being inserted into the archive table are the same as the rows being deleted form the transaction table.


问:
React-native command not found in Terminal
I keep encountering the "command not found" error when trying to create a new react native project. I've looked through past questions on this topic and they all say to change the PATH, which doesn't seem to work for me.

I tried installing and uninstalling react-native-cli. I've checked and changed the PATH. Nothing works.

```<code>Davids-MBP-2:~ David$ brew -v
Homebrew >=1.7.1 (shallow or no git repository)
Homebrew/homebrew-core (no git repository)
Davids-MBP-2:~ David$ watchman -v
4.9.0
Davids-MBP-2:~ David$ node -v
v11.13.0
Davids-MBP-2:~ David$ npm install -g react-native-cli
/Users/David/.npm-global/bin/react-native -> /Users/David/.npm-global/lib/node_modules/react-native-cli/index.js
+ react-native-cli@2.0.1
updated 1 package in 1.392s
Davids-MBP-2:~ David$ react-native init hello
-bash: react-native: command not found
Davids-MBP-2:~ David$
</code>```

I installed node, homebrew, watchman, and finally react-native. The first three work, but react doesn't.

答:
I'll first describe the setup on my system.

Check first where brew install node installed your node_modules.

```<code>$ npm root -g
/usr/local/lib/node_modules
</code>```

Next, check that the installed scripts/commands are in a corresponding bin folder:

```<code>$ ls -l /usr/local/bin | grep react-native
... react-native -> ../lib/node_modules/react-native-cli/index.js
</code>```

Next, make sure that the bin folder is in your $PATH.

```<code>$ echo $PATH
...:/usr/local/bin:...
</code>```

Finally, persist the path to that bin folder by adding it to PATH in your ~/.bash_profile.

```<code>$ cat ~/.bash_profile
...
export PATH=$PATH:/usr/local/bin
...
$ source ~/.bash_profile
</code>```

(I am not sure if your Terminal env need you to do source ~/.bash_profile every time you open a new Terminal session.)

Now, from your comment, it seems you have your node_modules installed in a non-standard folder.

this is the output of npm root -g: /Users/David/.npm-global/lib/node_modules

Try doing the same steps I mentioned above:

Look for the corresponding bin folder (maybe in /Users/David/.npm-global/bin/?)

Add the bin folder to your PATH

Persist the modified PATH by putting it in your ~/.bash_profile.

If you can't find the bin/react-native, try these:

```<code>$ find /Users/David/ -name "react-native" -type l
$ find /usr/local/bin -name "react-native" -type l
</code>```

Those commands may take a long time, but it should return something like this:

```<code>$ find /usr/local/bin -name "react-native" -type l
/usr/local/bin/react-native
</code>```

Once you've found the path to react-native bin, it should just be a matter of adding it your PATH and persisting it.

Body:
I keep encountering the "command not found" error when trying to create a new react native project. I've looked through past questions on this topic and they all say to change the PATH, which doesn't seem to work for me.

I tried installing and uninstalling react-native-cli. I've checked and changed the PATH. Nothing works.

Davids-MBP-2:~ David$ brew -v
Homebrew >=1.7.1 (shallow or no git repository)
Homebrew/homebrew-core (no git repository)
Davids-MBP-2:~ David$ watchman -v
4.9.0
Davids-MBP-2:~ David$ node -v
v11.13.0
Davids-MBP-2:~ David$ npm install -g react-native-cli
/Users/David/.npm-global/bin/react-native -> /Users/David/.npm-global/lib/node_modules/react-native-cli/index.js
+ react-native-cli@2.0.1
updated 1 package in 1.392s
Davids-MBP-2:~ David$ react-native init hello
-bash: react-native: command not found
Davids-MBP-2:~ David$

I installed node, homebrew, watchman, and finally react-native. The first three work, but react doesn't.

Body:
I'll first describe the setup on my system.

Check first where brew install node installed your node_modules.

$ npm root -g
/usr/local/lib/node_modules

Next, check that the installed scripts/commands are in a corresponding bin folder:

$ ls -l /usr/local/bin | grep react-native
... react-native -> ../lib/node_modules/react-native-cli/index.js

Next, make sure that the bin folder is in your $PATH.

$ echo $PATH
...:/usr/local/bin:...

Finally, persist the path to that bin folder by adding it to PATH in your ~/.bash_profile.

$ cat ~/.bash_profile
...
export PATH=$PATH:/usr/local/bin
...
$ source ~/.bash_profile

(I am not sure if your Terminal env need you to do source ~/.bash_profile every time you open a new Terminal session.)

Now, from your comment, it seems you have your node_modules installed in a non-standard folder.

this is the output of npm root -g: /Users/David/.npm-global/lib/node_modules

Try doing the same steps I mentioned above:

Look for the corresponding bin folder (maybe in /Users/David/.npm-global/bin/?)

Add the bin folder to your PATH

Persist the modified PATH by putting it in your ~/.bash_profile.

If you can't find the bin/react-native, try these:

$ find /Users/David/ -name "react-native" -type l
$ find /usr/local/bin -name "react-native" -type l

Those commands may take a long time, but it should return something like this:

$ find /usr/local/bin -name "react-native" -type l
/usr/local/bin/react-native

Once you've found the path to react-native bin, it should just be a matter of adding it your PATH and persisting it.


问:
Problems adding new AdMob to android app
I am trying to add the new AdMob ads to my first application, I managed to arrange the code in the correct way but I have to problems:

First problem is my ad ID ca-app-pub-61413779example is getting multiple errors like: ca cannot be resolved to a variable, ba cannot be resolved to a variable, the literal
61413779 of type int is out of range.

The second problem is R.id.mainLayout, which is mainLayout, I don't get it.

```<code> protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_basic_screen);

     // Create the adView
        adView = new AdView(this, AdSize.BANNER, ca-app-pub-61413779example);

        // Lookup your LinearLayout assuming it's been given
        // the attribute android:id="@+id/mainLayout"
        LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);

        // Add the adView to it
        layout.addView(adView);
        adView.loadAd(new AdRequest());

        // Initiate a generic request to load it with an ad
        adView.loadAd(new AdRequest());
</code>```

答:
This maybe a different answer to what you are looking for, but I would highly recommend using SMART_BANNER Over BANNER. look here at The table that list the standard banner sizes:

https://developers.google.com/admob/android/banner

Banner: size 320x50 only
Smart Banner: size change to Screen width x 32|50|90

Here is an example on how to do it:

-Layout

```<code>  <android.support.constraint.ConstraintLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       xmlns:tools="http://schemas.android.com/tools"
       android:id="@+id/main_r"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:context="com.example.adexample">

    <RelativeLayout
        android:id="@+id/adView_test"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

 </android.support.constraint.ConstraintLayout>
</code>```

-Activity:

```<code>  public class MainActivity extends AppCompatActivity {

      private AdView adView;
      private AdRequest adRequest;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

     MobileAds.initialize(this, "YOUR_ADMOB_APP_ID");
     admobCall();

  }

 // Function to Set Ads for Main Layout
 private void admobCall(){

    // Set the RelativeLayout id to the view
    View adContainer = findViewById(R.id.adView_test);
    adView = new AdView(this);
    adView.setAdSize(AdSize.SMART_BANNER);

    //Real Admob Main Activity Banner
    adView.setAdUnitId(getString(R"YOUR_ADMOB_AD_ID"));

   // Test google ID for Banner
   // adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

   ((RelativeLayout)adContainer).addView(adView);

   // This Request will bulid the ADs as a Test
   //adRequest = new AdRequest.Builder()
   //.addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();

  // This Request Will bulid the ADs as Real
  adRequest = new AdRequest.Builder().build();

  adView.loadAd(adRequest);

 }
</code>```

Also be sure to add "google()" to the project-level build.gradle, and
this implementation to dependencies

```<code>implementation 'com.google.android.gms:play-services-ads:17.2.1'
</code>```

Check the Implementation instructions site just to be sure you are not missing something:

https://developers.google.com/admob/android/quick-start

Hope this was helpful :)

Body:
I am trying to add the new AdMob ads to my first application, I managed to arrange the code in the correct way but I have to problems:

First problem is my ad ID ca-app-pub-61413779example is getting multiple errors like: ca cannot be resolved to a variable, ba cannot be resolved to a variable, the literal
61413779 of type int is out of range.

The second problem is R.id.mainLayout, which is mainLayout, I don't get it.

 protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_basic_screen);

     // Create the adView
        adView = new AdView(this, AdSize.BANNER, ca-app-pub-61413779example);

        // Lookup your LinearLayout assuming it's been given
        // the attribute android:id="@+id/mainLayout"
        LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);

        // Add the adView to it
        layout.addView(adView);
        adView.loadAd(new AdRequest());

        // Initiate a generic request to load it with an ad
        adView.loadAd(new AdRequest());

Body:
This maybe a different answer to what you are looking for, but I would highly recommend using SMART_BANNER Over BANNER. look here at The table that list the standard banner sizes:

https://developers.google.com/admob/android/banner

Banner: size 320x50 only
Smart Banner: size change to Screen width x 32|50|90

Here is an example on how to do it:

-Layout

  <android.support.constraint.ConstraintLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       xmlns:tools="http://schemas.android.com/tools"
       android:id="@+id/main_r"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:context="com.example.adexample">

    <RelativeLayout
        android:id="@+id/adView_test"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

 </android.support.constraint.ConstraintLayout>

-Activity:

  public class MainActivity extends AppCompatActivity {

      private AdView adView;
      private AdRequest adRequest;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

     MobileAds.initialize(this, "YOUR_ADMOB_APP_ID");
     admobCall();

  }

 // Function to Set Ads for Main Layout
 private void admobCall(){

    // Set the RelativeLayout id to the view
    View adContainer = findViewById(R.id.adView_test);
    adView = new AdView(this);
    adView.setAdSize(AdSize.SMART_BANNER);

    //Real Admob Main Activity Banner
    adView.setAdUnitId(getString(R"YOUR_ADMOB_AD_ID"));

   // Test google ID for Banner
   // adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

   ((RelativeLayout)adContainer).addView(adView);

   // This Request will bulid the ADs as a Test
   //adRequest = new AdRequest.Builder()
   //.addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();

  // This Request Will bulid the ADs as Real
  adRequest = new AdRequest.Builder().build();

  adView.loadAd(adRequest);

 }

Also be sure to add "google()" to the project-level build.gradle, and
this implementation to dependencies

implementation 'com.google.android.gms:play-services-ads:17.2.1'

Check the Implementation instructions site just to be sure you are not missing something:

https://developers.google.com/admob/android/quick-start

Hope this was helpful :)


问:
Groupby - count of pandas df with duplicate values
I am trying to perform a groupby count of a pandas df with duplicate values. I'm hoping to return the unduplicated values only. For the intended output, I only want to determine the count of values between Val_A and Val_B. The returned column can be labelled anything as I will rename it. For the purposes of this question, I'll label it Val_X

```<code>d = ({
    'Date' : ['1/2/18','1/2/18','1/2/18','1/2/18','1/2/18','1/2/18'],
    'Val_A' : [1,1,2,2,1,1],
    'Val_B' : ['X','X','X','X','Y','Y'],
    })

df = pd.DataFrame(data=d)

df1 = pd.pivot_table(df, index=['Date'],values=['Val_A','Val_B'],aggfunc= 'count')
</code>```

Output:

```<code>            Val_A  Val_B
    Date
    1/2/18      6      6
</code>```

Intended Output:

```<code>            Val_X
    Date
    1/2/18      3
</code>```

答:
In principle, you get it through

```<code>df1 = pd.pivot_table(df.drop_duplicates(), index=['Date'],values=['Val_A','Val_B'],aggfunc= 'count')
</code>```

However, your example numbers are not the same.

```<code>df.drop_duplicates()

     Date  Val_A Val_B
0  1/2/18      1     X
2  1/2/18      2     X
4  2/2/18      1     Y
6  2/2/18      2     Y
</code>```

Body:
I am trying to perform a groupby count of a pandas df with duplicate values. I'm hoping to return the unduplicated values only. For the intended output, I only want to determine the count of values between Val_A and Val_B. The returned column can be labelled anything as I will rename it. For the purposes of this question, I'll label it Val_X

d = ({
    'Date' : ['1/2/18','1/2/18','1/2/18','1/2/18','1/2/18','1/2/18'],
    'Val_A' : [1,1,2,2,1,1],
    'Val_B' : ['X','X','X','X','Y','Y'],
    })

df = pd.DataFrame(data=d)

df1 = pd.pivot_table(df, index=['Date'],values=['Val_A','Val_B'],aggfunc= 'count')

Output:

            Val_A  Val_B
    Date
    1/2/18      6      6

Intended Output:

            Val_X
    Date
    1/2/18      3

Body:
In principle, you get it through

df1 = pd.pivot_table(df.drop_duplicates(), index=['Date'],values=['Val_A','Val_B'],aggfunc= 'count')

However, your example numbers are not the same.

df.drop_duplicates()

     Date  Val_A Val_B
0  1/2/18      1     X
2  1/2/18      2     X
4  2/2/18      1     Y
6  2/2/18      2     Y


问:
Strange process while turning off my computer
So I was on my way to turn off my computer when unexpectedly, in the screen where you see the programs that block Windows to turn off, i saw one process with a strange name like {4593-9493-8949-9390} (not the exact same name but similar) and before i could click on the cancel button the process close.

My question here is if I should be wondering about that strange process or its just some random Windows 10 routine

答:
This very well could be a malware of sort being executed in the background. I would recommend scanning your computer with your preferred anti-virus program and then installing Process Monitor which should help you detect and analyze suspicious processes running on your computer:

Process Monitor is an advanced monitoring tool for Windows that shows real-time file system, Registry and process/thread activity. It combines the features of two legacy Sysinternals utilities, Filemon and Regmon, and adds an extensive list of enhancements including rich and non-destructive filtering, comprehensive event properties such session IDs and user names, reliable process information, full thread stacks with integrated symbol support for each operation, simultaneous logging to a file, and much more. Its uniquely powerful features will make Process Monitor a core utility in your system troubleshooting and malware hunting toolkit.


问:
Can't add Swift to PATH Linux
I'm running POP!_OS linux distro and want to run Swift on it. I found a tutorial on https://medium.com/@agavatar/open-source-swift-on-ubuntu-linux-cd00e697dff0
the problem is once I enter the line to add Swift to the PATH, I get this error:
"swift: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such file or directory"</p>

答:
It's hard to know for sure with this little information, but it seem that you're missing dependencies. try:

```<code>sudo apt-get install libcurl3 libpython2.7 libpython2.7-dev
</code>```

EDIT: Ubuntu moved from libtinfo5 to 6 a while ago, you've installed the wrong swift version. you can get swift for unbutu 1804 here: wget https://swift.org/builds/swift-4.2.1-release/ubuntu1804/swift-4.2.1-RELEASE/swift-4.2.1-RELEASE-ubuntu18.04.tar.gz

Title: Can't add Swift to PATH Linux

Body:
It's hard to know for sure with this little information, but it seem that you're missing dependencies. try:

sudo apt-get install libcurl3 libpython2.7 libpython2.7-dev

EDIT: Ubuntu moved from libtinfo5 to 6 a while ago, you've installed the wrong swift version. you can get swift for unbutu 1804 here: wget https://swift.org/builds/swift-4.2.1-release/ubuntu1804/swift-4.2.1-RELEASE/swift-4.2.1-RELEASE-ubuntu18.04.tar.gz


问:
Passing an object from one component to another using props
I am trying to pass a whole object from one component to another on button click.

I have tried using Link and Router, but I still cannot see the object inside the props of the destination component.

I am using the onClick handler handleReportIncident to pass an available object while Routing to this component. The handleReportIncident function is bound at the top.

```<code>    handleReportIncident() {
        const { trip } = this.state;
        this.props.history.push(`/app/new`)
        return (
            <div>
                <New trip={trip} />
            </div>
        )
    }

    render() {

        return (

                    <Button
                        variant="contained"
                        color="primary"
                        className={classes.toolbarButton}
                        onClick={this.handleReportIncident}
                    >
                        <AddIcon />
                        Incident
        </ Button>
)}
</code>```

Inside of New component I have :

```<code>class New extends Component {
render() {
const {trip} = this.props;
console.log("the trip is", trip);
return(
...
)
}
New.propTypes = {
    trip: PropTypes.object.isRequired,
};
</code>```

Note: I am using material UI as a theme.

The Log inside the New component is the trip is undefined.

答:
You can wrap your desired object in the state of the Link. See example below.

// Main Component  from which you want object passed

```<code>render() {

  return (
    <Link to = {{
      pathname: '/app/new',
      state: {
        trip: this.state.trip
      }
    }}>
      <AddIcon /> Incident
    </Link>
  )
}
</code>```

// New Component get desired object from this.props.location.state

```<code>class New extends Component {
render() {
const { trip } = this.props.location.state
console.log("the trip is", trip);
return(
...
)
}
New.propTypes = {
    trip: PropTypes.object.isRequired,
}
</code>```

For more info on how it works head over to this tutorial: https://tylermcginnis.com/react-router-pass-props-to-link/

Body:
I am trying to pass a whole object from one component to another on button click.

I have tried using Link and Router, but I still cannot see the object inside the props of the destination component.

I am using the onClick handler handleReportIncident to pass an available object while Routing to this component. The handleReportIncident function is bound at the top.

    handleReportIncident() {
        const { trip } = this.state;
        this.props.history.push(`/app/new`)
        return (

                <New trip={trip} />

        )
    }

    render() {

        return (

                    <Button
                        variant="contained"
                        color="primary"
                        className={classes.toolbarButton}
                        onClick={this.handleReportIncident}
                    >
                        <AddIcon />
                        Incident
        </ Button>
)}

Inside of New component I have :

class New extends Component {
render() {
const {trip} = this.props;
console.log("the trip is", trip);
return(
...
)
}
New.propTypes = {
    trip: PropTypes.object.isRequired,
};

Note: I am using material UI as a theme.

The Log inside the New component is the trip is undefined.

Body:
You can wrap your desired object in the state of the Link. See example below.

// Main Component  from which you want object passed

render() {

  return (
    <Link to = {{
      pathname: '/app/new',
      state: {
        trip: this.state.trip
      }
    }}>
      <AddIcon /> Incident
    </Link>
  )
}

// New Component get desired object from this.props.location.state

class New extends Component {
render() {
const { trip } = this.props.location.state
console.log("the trip is", trip);
return(
...
)
}
New.propTypes = {
    trip: PropTypes.object.isRequired,
}

For more info on how it works head over to this tutorial: https://tylermcginnis.com/react-router-pass-props-to-link/


问:
if(rs.next()) always not working and go to else
I work on an exame system with user login, admin login, etc.
When I check if the entered username (for example)
it doesn't return if it is already in the database
and creates it again!

```<code>try{
  //  Class.forName("com.mysql.jdbc.Driver");
    Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/big_project_3","root","");
    //imporrrrrrrrrrrrrrrrrrrrrrrtant
    String selectquery = "select count(*)from uesrs where username='" + username + "'and password='" + password + "'";
    Statement stat=con.createStatement();
    System.out.println(selectquery);
    ResultSet rs=stat.executeQuery(selectquery);
    System.out.println(rs.next());
    if(rs.next()==true){
        infoMessage("Already registered ","Welcom");
    }
    else{
        String insertQuery = "insert into uesrs values(null,'" + username_new_student.getText() + "','" + password_new_student.getText() + "','" + First_name_new_student.getText()+"')";

        stat.executeUpdate(insertQuery);
        infoMessage("info is inserted ","Alert!!!!!");
        dispose();
        user_login ul=new user_login();
        ul.setLocationRelativeTo(null);
        ul.setVisible(true);
    }
}
catch (Exception ex) {
    System.out.println(ex);
}
</code>```

答:
Once you call rs.next() inside System.out.println () it will move the  pointer forward. Then when you call rs.next() inside if condition there will be no more results to show.

```<code>try{
  //  Class.forName("com.mysql.jdbc.Driver");
    Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/big_project_3","root","");
    //imporrrrrrrrrrrrrrrrrrrrrrrtant
    String selectquery="select count(*)from uesrs where username='"+username+"'and password='"+password+"'";
    Statement stat=con.createStatement();
    System.out.println(selectquery);
    ResultSet rs=stat.executeQuery(selectquery);

    if(rs.next() ){
        infoMessage("Already registered ","Welcom");
    }
    else{
        String insertQuery="insert into uesrs values(null,'"+username_new_student.getText()+"','"+password_new_student.getText()+"','"+First_name_new_student.getText()+"')";

     stat.executeUpdate(insertQuery);
     infoMessage("info is inserted ","Alert!!!!!");
    dispose();
    user_login ul=new user_login();
    ul.setLocationRelativeTo(null);
    ul.setVisible(true);

    }

}

catch (Exception ex) {
    System.out.println(ex);
}
</code>```

Body:
I work on an exame system with user login, admin login, etc.
When I check if the entered username (for example)
it doesn't return if it is already in the database
and creates it again!

try{
  //  Class.forName("com.mysql.jdbc.Driver");
    Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/big_project_3","root","");
    //imporrrrrrrrrrrrrrrrrrrrrrrtant
    String selectquery = "select count(*)from uesrs where username='" + username + "'and password='" + password + "'";
    Statement stat=con.createStatement();
    System.out.println(selectquery);
    ResultSet rs=stat.executeQuery(selectquery);
    System.out.println(rs.next());
    if(rs.next()==true){
        infoMessage("Already registered ","Welcom");
    }
    else{
        String insertQuery = "insert into uesrs values(null,'" + username_new_student.getText() + "','" + password_new_student.getText() + "','" + First_name_new_student.getText()+"')";

        stat.executeUpdate(insertQuery);
        infoMessage("info is inserted ","Alert!!!!!");
        dispose();
        user_login ul=new user_login();
        ul.setLocationRelativeTo(null);
        ul.setVisible(true);
    }
}
catch (Exception ex) {
    System.out.println(ex);
}

Body:
Once you call rs.next() inside System.out.println () it will move the  pointer forward. Then when you call rs.next() inside if condition there will be no more results to show.

try{
  //  Class.forName("com.mysql.jdbc.Driver");
    Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/big_project_3","root","");
    //imporrrrrrrrrrrrrrrrrrrrrrrtant
    String selectquery="select count(*)from uesrs where username='"+username+"'and password='"+password+"'";
    Statement stat=con.createStatement();
    System.out.println(selectquery);
    ResultSet rs=stat.executeQuery(selectquery);

    if(rs.next() ){
        infoMessage("Already registered ","Welcom");
    }
    else{
        String insertQuery="insert into uesrs values(null,'"+username_new_student.getText()+"','"+password_new_student.getText()+"','"+First_name_new_student.getText()+"')";

     stat.executeUpdate(insertQuery);
     infoMessage("info is inserted ","Alert!!!!!");
    dispose();
    user_login ul=new user_login();
    ul.setLocationRelativeTo(null);
    ul.setVisible(true);

    }

}

catch (Exception ex) {
    System.out.println(ex);
}


答:
Solution for small exponents

A well known property of modular exponentiation estabilishes that:

x^n mod m = (x mod m)^n mod m

Thus, for large bases with small exponents, you can use the following code:

```<code>makelist(A, N, K, M, L) :-
    A>0, N>0, K>0, M>0,
    K1 is N + K,
    findall(X, (between(N,K1,E), X is (A mod M)^I mod M), L).
</code>```

Here are some solutions found with this code:

```<code>?- makelist(10,2,1,10000,L).
L = [100, 1000].

?- makelist(2,6,10,100,L).
L = [64, 28, 56, 12, 24, 48, 96, 92, 84|...].

?- makelist(12345678,3,8,100,L).
L = [52, 56, 68, 4, 12, 36, 8, 24, 72].

?- makelist(2,3000,5,7,L).
L = [1, 2, 4, 1, 2, 4].

?- makelist(2,555000,5,17,L).
L = [1, 2, 4, 8, 16, 15].

?- makelist(2,3000000,5,21,L).
L = [1, 2, 4, 8, 16, 11].
</code>```

Note that, without using such property, we cannot compute the answer for large bases with large exponents:

```<code>?- X is 142857^98765432 mod 100.
ERROR: Stack limit (0.5Gb) exceeded

?- X is (142857 mod 100)^98765432 mod 100.
X = 1.
</code>```

Solution for large exponents

However, for large exponents, this code turns out to be very inefficient. For example:

```<code>?- time(makelist(142857,98765432,9,100,L)).
% 47 inferences, 115.328 CPU in -544348879559065600.000 seconds (?% CPU, 0 Lips)
L = [1, 57, 49, 93, 1, 57, 49, 93, 1|...].
</code>```

So, a best approach for a large exponent n is to use the following definition:

if n = 0, then x^n = 1

else if n = 1, then x^n = x

else if n is even, then x^n = (x^2)^(n/2)

else if n is odd, then x^n = x*(x^2)^floor(n/2)

With this definition, we can compute x^n by using only O(lg n) multiplications. Based on it, we can define the following predicates:

```<code>fast_pow(X, N, M, P) :-
    (   N < 32
    ->  P is (X mod M)^N mod M
    ;   (   X1 is (X mod M)^2 mod M,
            N1 is N//2,
            fast_pow(X1, N1, M, P1),
            (   N mod 2 =:= 0
            ->  P is P1
            ;   P is (X mod M)*P1  mod M ) ) ).

fast_makelist(A, N, K, M, L) :-
    A>0, N>0, K>0, M>0,
    K1 is N + K,
    findall(P, (between(N,K1,E), fast_pow(A,E,M,P)), L).
</code>```

Now, we have:

```<code>?- time(fast_makelist(142857,98765432,9,100,L)).
% 1,704 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
L = [1, 57, 49, 93, 1, 57, 49, 93, 1|...].
</code>```

Title: Prolog - make list

Body:
Given the argument makelist(A,N,K,M,L) :- , should expand ,and it should return true if A,N,K,M,L>0 Integer numbers with M>=2 and L list :

[A^N mod M , A^(N+1) mod M , A^(N+2) mod M , ... , A*(N+K) mod M]

Expected results :

| ?- makelist(10,2,1,10000,L).
L = [100,1000]
| ?- makelist(2,6,10,100,L).
L = [64,28,56,12,24,48,96,92,84,68,36]
| ?- makelist(12345678,3,8,100,L).
L = [52,56,68,4,12,36,8,24,72]
| ?- makelist(2,3000,5,7,L).
L = [1,2,4,1,2,4]
| ?- makelist(2,555000,5,17,L).
L = [1,2,4,8,16,15]
| ?- makelist(2,3000000,5,21,L).
L = [1,2,4,8,16,11]
| ?- makelist(142857,98765432,9,100,L).
L = [1,57,49,93,1,57,49,93,1,57]

i thought a starting would be implementing the K element of exponent (N+K) by taking the numbers from 0 to K

bet(N, M, K) :- N =< M, K = N.
bet(N, M, K) :- N < M, N1 is N+1, bet(N1, M, K).

makelist(A,N,K,M,L) :- bet(0,K,(N+K)),

Body:
Solution for small exponents

A well known property of modular exponentiation estabilishes that:

x^n mod m = (x mod m)^n mod m

Thus, for large bases with small exponents, you can use the following code:

makelist(A, N, K, M, L) :-
    A>0, N>0, K>0, M>0,
    K1 is N + K,
    findall(X, (between(N,K1,E), X is (A mod M)^I mod M), L).

Here are some solutions found with this code:

?- makelist(10,2,1,10000,L).
L = [100, 1000].

?- makelist(2,6,10,100,L).
L = [64, 28, 56, 12, 24, 48, 96, 92, 84|...].

?- makelist(12345678,3,8,100,L).
L = [52, 56, 68, 4, 12, 36, 8, 24, 72].

?- makelist(2,3000,5,7,L).
L = [1, 2, 4, 1, 2, 4].

?- makelist(2,555000,5,17,L).
L = [1, 2, 4, 8, 16, 15].

?- makelist(2,3000000,5,21,L).
L = [1, 2, 4, 8, 16, 11].

Note that, without using such property, we cannot compute the answer for large bases with large exponents:

?- X is 142857^98765432 mod 100.
ERROR: Stack limit (0.5Gb) exceeded

?- X is (142857 mod 100)^98765432 mod 100.
X = 1.

Solution for large exponents

However, for large exponents, this code turns out to be very inefficient. For example:

?- time(makelist(142857,98765432,9,100,L)).
% 47 inferences, 115.328 CPU in -544348879559065600.000 seconds (?% CPU, 0 Lips)
L = [1, 57, 49, 93, 1, 57, 49, 93, 1|...].

So, a best approach for a large exponent n is to use the following definition:

if n = 0, then x^n = 1

else if n = 1, then x^n = x

else if n is even, then x^n = (x^2)^(n/2)

else if n is odd, then x^n = x*(x^2)^floor(n/2)

With this definition, we can compute x^n by using only O(lg n) multiplications. Based on it, we can define the following predicates:

fast_pow(X, N, M, P) :-
    (   N < 32
    ->  P is (X mod M)^N mod M
    ;   (   X1 is (X mod M)^2 mod M,
            N1 is N//2,
            fast_pow(X1, N1, M, P1),
            (   N mod 2 =:= 0
            ->  P is P1
            ;   P is (X mod M)*P1  mod M ) ) ).

fast_makelist(A, N, K, M, L) :-
    A>0, N>0, K>0, M>0,
    K1 is N + K,
    findall(P, (between(N,K1,E), fast_pow(A,E,M,P)), L).

Now, we have:

?- time(fast_makelist(142857,98765432,9,100,L)).
% 1,704 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
L = [1, 57, 49, 93, 1, 57, 49, 93, 1|...].


问:
B2C OpenID Connect with Azure AD
I am trying to connect Azure AD to B2C via open ID connect. Using a MSAL JS i am able to successfully login to Azure AD and local B2C users.

However when a user is created in B2C portal (from Azure AD) the mail fields are missing e.g. name & email

looking through the ID token from the Azure AD there are no values returned for email or name.

答:
You cannot create an Azure AD B2C user, e.g. federated from another Azure AD tenant to the Azure AD B2C tenant, using the Azure AD B2C portal. You must create this user using either an Azure AD B2C flow/policy or the Azure AD Graph API.

When you invite an Azure AD user from another Azure AD tenant to the Azure AD B2C tenant, they are added as a guest user, e.g. so that they can co-manage the Azure AD B2C tenant.

Title: B2C OpenID Connect with Azure AD


问:
How to set up performance logging in SeleniumWebdriver with Chrome
Background - trying to get ChromeDriver to log so that I can start using Lighthouse.

I'm trying to get a C# Selenium.Webdriver equivalent of this

```<code>DesiredCapabilities cap = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

Map<String, Object> perfLogPrefs = new HashMap<String, Object>();
perfLogPrefs.put("traceCategories", "browser,devtools.timeline,devtools"); // comma-separated trace categories
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("perfLoggingPrefs", perfLogPrefs);
caps.setCapability(ChromeOptions.CAPABILITY, options);

RemoteWebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:9515"), cap);
</code>```

I can't figure out the right combination. Anyone know what the correct recipe is, or have an example, or both?

My attempt

```<code>var chromeOptions = new Dictionary<string, object>();
List<string> args = new List<string>();
foreach (string ma in myArgs)   //yes, myArgs is created beforehand
                    args.Add(ma);
chromeOptions.Add("args", args);

var options = new Dictionary<string, object>();
var loggingPrefs = new Dictionary<string, object>();
loggingPrefs.Add("PERFORMANCE", "ALL" );

var perfLoggingPrefs = new Dictionary<string, object>();
perfLoggingPrefs.Add("enableNetwork", true);
perfLoggingPrefs.Add("enablePage", true);
perfLoggingPrefs.Add("traceCategories", "toplevel,disabled-by-default-devtools.timeline.frame,blink.console,disabled-by-default-devtools.timeline,benchmark");

options.Add("chromeOptions", chromeOptions);
options.Add("loggingPrefs", loggingPrefs);
options.Add("perfLoggingPrefs", perfLoggingPrefs);

var capabilities = new DesiredCapabilities(options);
Driver = new RemoteWebDriver(new Uri("http://localhost:9515"), capabilities);
</code>```

Result: No logging

答:
This worked on my end for local

```<code>ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.SetLoggingPreference("performance", LogLevel.All);
Instance = new ChromeDriver(chromeOptions);
</code>```

and for remote

```<code>ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.SetLoggingPreference("performance", LogLevel.All);
desiredCapabilities = chromeOptions.ToCapabilities() as DesiredCapabilities;
desiredCapabilities?.SetCapability(CapabilityType.BrowserName, settings.Name.ToLower());
desiredCapabilities?.SetCapability(CapabilityType.Version, settings.Version);
desiredCapabilities?.SetCapability(CapabilityType.Platform, GetPlatform(settings.Platform));
</code>```

to get the logs

```<code>var logs = Instance.Manage().Logs.GetLog("performance");
</code>```

Body:
Background - trying to get ChromeDriver to log so that I can start using Lighthouse.

I'm trying to get a C# Selenium.Webdriver equivalent of this

DesiredCapabilities cap = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

Map<String, Object> perfLogPrefs = new HashMap<String, Object>();
perfLogPrefs.put("traceCategories", "browser,devtools.timeline,devtools"); // comma-separated trace categories
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("perfLoggingPrefs", perfLogPrefs);
caps.setCapability(ChromeOptions.CAPABILITY, options);

RemoteWebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:9515"), cap);

I can't figure out the right combination. Anyone know what the correct recipe is, or have an example, or both?

My attempt

var chromeOptions = new Dictionary<string, object>();
List<string> args = new List<string>();
foreach (string ma in myArgs)   //yes, myArgs is created beforehand
                    args.Add(ma);
chromeOptions.Add("args", args);

var options = new Dictionary<string, object>();
var loggingPrefs = new Dictionary<string, object>();
loggingPrefs.Add("PERFORMANCE", "ALL" );

var perfLoggingPrefs = new Dictionary<string, object>();
perfLoggingPrefs.Add("enableNetwork", true);
perfLoggingPrefs.Add("enablePage", true);
perfLoggingPrefs.Add("traceCategories", "toplevel,disabled-by-default-devtools.timeline.frame,blink.console,disabled-by-default-devtools.timeline,benchmark");

options.Add("chromeOptions", chromeOptions);
options.Add("loggingPrefs", loggingPrefs);
options.Add("perfLoggingPrefs", perfLoggingPrefs);

var capabilities = new DesiredCapabilities(options);
Driver = new RemoteWebDriver(new Uri("http://localhost:9515"), capabilities);

Result: No logging

Body:
This worked on my end for local

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.SetLoggingPreference("performance", LogLevel.All);
Instance = new ChromeDriver(chromeOptions);

and for remote

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.SetLoggingPreference("performance", LogLevel.All);
desiredCapabilities = chromeOptions.ToCapabilities() as DesiredCapabilities;
desiredCapabilities?.SetCapability(CapabilityType.BrowserName, settings.Name.ToLower());
desiredCapabilities?.SetCapability(CapabilityType.Version, settings.Version);
desiredCapabilities?.SetCapability(CapabilityType.Platform, GetPlatform(settings.Platform));

to get the logs

var logs = Instance.Manage().Logs.GetLog("performance");


答:
Drop duplicates and pass on Val_B as values,</p>

```<code>pd.pivot_table(df.drop_duplicates(), index=['Date'],values=['Val_B'],aggfunc= 'count')

        Val_B
Date
1/2/18  3
</code>```

Title: Groupby - count of pandas df with duplicate values

Body:
Drop duplicates and pass on Val_B as values,

pd.pivot_table(df.drop_duplicates(), index=['Date'],values=['Val_B'],aggfunc= 'count')

        Val_B
Date
1/2/18  3


问:
TypeError: unhashable type: 'set' in HTTP GET Request
I am trying to execute the below python function to check the status of an invoice from an external API:

```<code>def getInvoice(inv_id):
    response = requests.get("https://api.example.com/invoices/"+str(inv_id)+"?access_token=123456789").json()
    return response

print(getInvoice("5b5f60384b3f"))
</code>```

When I try to call the function, I keep receiving the following error:

```<code> Traceback (most recent call last):
  File "C:\Users\user\Desktop\app\db.py", line 82, in <module>
    print(getInvoice("5b5f60384b3f"))
  File "C:\Users\user\Desktop\app\db.py", line 79, in getInvoice
    response = requests.get("https://api.example.com/invoices/"+str(inv_id)+"?access_token=123456789").json()
TypeError: unhashable type: 'set'
[Finished in 3.0s]
</code>```

I don't understand why this keeps happening, or where the 'set' is? Any help is much appreciated.

答:
Looks like your url is not returning json response. I suggest you to dubug the code by reading the response as text and check what it really contains.</p>

```<code>import urllib.request

contents = urllib.request.urlopen("https://api.example.com/invoices/"+str(inv_id)+"?access_token=123456789").read()

print(contents);
</code>```

Body:
I am trying to execute the below python function to check the status of an invoice from an external API:

def getInvoice(inv_id):
    response = requests.get("https://api.example.com/invoices/"+str(inv_id)+"?access_token=123456789").json()
    return response

print(getInvoice("5b5f60384b3f"))

When I try to call the function, I keep receiving the following error:

 Traceback (most recent call last):
  File "C:\Users\user\Desktop\app\db.py", line 82, in <module>
    print(getInvoice("5b5f60384b3f"))
  File "C:\Users\user\Desktop\app\db.py", line 79, in getInvoice
    response = requests.get("https://api.example.com/invoices/"+str(inv_id)+"?access_token=123456789").json()
TypeError: unhashable type: 'set'
[Finished in 3.0s]

I don't understand why this keeps happening, or where the 'set' is? Any help is much appreciated.

Body:
Looks like your url is not returning json response. I suggest you to dubug the code by reading the response as text and check what it really contains.

import urllib.request

contents = urllib.request.urlopen("https://api.example.com/invoices/"+str(inv_id)+"?access_token=123456789").read()

print(contents);


答:
If I understand you correctly, you want to return the unique combinations in columns Val_A and Val_B for each group in Date:

```<code>df.groupby(['Date', 'Val_A', 'Val_B']).size().reset_index()

     Date  Val_A Val_B  0
0  1/2/18      1     X  2
1  1/2/18      1     Y  2
2  1/2/18      2     X  2
</code>```

If you want the size:

```<code>g = df.groupby(['Date', 'Val_A', 'Val_B'])

len(g)

# Out
3
</code>```

Body:
If I understand you correctly, you want to return the unique combinations in columns Val_A and Val_B for each group in Date:

df.groupby(['Date', 'Val_A', 'Val_B']).size().reset_index()

     Date  Val_A Val_B  0
0  1/2/18      1     X  2
1  1/2/18      1     Y  2
2  1/2/18      2     X  2

If you want the size:

g = df.groupby(['Date', 'Val_A', 'Val_B'])

len(g)

# Out
3


问:
Getting uid of a firestore reference field in React
```<code>this.props.firebase.referenceListItems()
</code>```

I'm iterating over the referenceListItems, and trying to get a reference field. The current document in the loop is called referenceListItem.

Example document in the referenceListItems collections:

```<code>created: April 30, 2019 at 12:41:41 AM UTC+2 (timestamp)
name: "Name"
referenceList:
  0: /referenceLists/YzBh0E3pQGB65us1BpVP
</code>```

How do I access the uid part of the reference field?

referenceListItem.referenceList[0] doesn't return a string.

答:
It's difficult to tell what exactly you're working with.  Maybe some custom data, I don't know.  referenceListItem isn't the name of something provided natively by Firestore.  Perhaps you are using some layer of abstraction around the Firestore SDK.  So, since it's not clear what you have here, I'll just take a guess at what's going on.

It sounds like you may have stored a DocumentReference type object in an array in a document in Firestore, and you're trying to read it back out.  If you query for that document, the resulting DocumentSnapshot will contain array field with DocumentReference type objects.

If you have a DocumentReference object in hand, and you want to get the ID of the document that it's reference, you can simply use its id property to get that string.  So maybe referenceListItem.referenceList[0].id will be what you're looking for.

Body:
this.props.firebase.referenceListItems()

I'm iterating over the referenceListItems, and trying to get a reference field. The current document in the loop is called referenceListItem.

Example document in the referenceListItems collections:

created: April 30, 2019 at 12:41:41 AM UTC+2 (timestamp)
name: "Name"
referenceList:
  0: /referenceLists/YzBh0E3pQGB65us1BpVP

How do I access the uid part of the reference field?

referenceListItem.referenceList[0] doesn't return a string.


问:
How to use distinct in relations query in Laravel
I have a Laravel ORM query that I join 2-3 relation together like below :

$data = AccommodationRoom::with('accommodation.city',
    'accommodation.accommodationFacilities', 'accommodation.gallery')
    ->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    })
    ->whereHas('accommodation', function ($query) use ($searchCity) {
        $query->where('city_id', $searchCity);
    })
    ->limit(10)->get();

return response()->json($data, 200);
```

On the room model, I check if the capacity model has a date and where the city id is what the user gives to the hotels (accommodation). The problem is that when I get the result, I get repeated hotels for each room. For one search I might get ten hotels the same, so I want to make the accommodations unique and show one result (room) per accommodation.

答:
Try to chain the distinct method.

I.e:

```<code>$data = AccommodationRoom::with('accommodation.city',
    'accommodation.accommodationFacilities', 'accommodation.gallery')
    ->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    })
    ->whereHas('accommodation', function ($query) use ($searchCity) {
        $query->where('city_id', $searchCity);
    })
    ->distinct('VALUE_FOR_HOTEL_HERE')->limit(10)->get();

return response()->json($data, 200);
</code>```

Body:
I have a Laravel ORM query that I join 2-3 relation together like below :

$data = AccommodationRoom::with('accommodation.city',
    'accommodation.accommodationFacilities', 'accommodation.gallery')
    ->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    })
    ->whereHas('accommodation', function ($query) use ($searchCity) {
        $query->where('city_id', $searchCity);
    })
    ->limit(10)->get();

return response()->json($data, 200);

On the room model, I check if the capacity model has a date and where the city id is what the user gives to the hotels (accommodation). The problem is that when I get the result, I get repeated hotels for each room. For one search I might get ten hotels the same, so I want to make the accommodations unique and show one result (room) per accommodation.

Body:
Try to chain the distinct method.

I.e:

$data = AccommodationRoom::with('accommodation.city',
    'accommodation.accommodationFacilities', 'accommodation.gallery')
    ->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    })
    ->whereHas('accommodation', function ($query) use ($searchCity) {
        $query->where('city_id', $searchCity);
    })
    ->distinct('VALUE_FOR_HOTEL_HERE')->limit(10)->get();

return response()->json($data, 200);


问:
Enforce field uniqueness to parent in many-to-one relation
I have a Table model which is many-to-one with a Restaurant model. Is there a way to have a field reference_label in the Table model that must be unique per restaurant, but not across different restaurants?

In short, I want to enforce reference_label uniqueness for tables with the same foreign key.

I know I can just use the Table's id, but I want each restaurant to be able to customize how they label their tables.

答:
You can use unique_together:

```<code>class Restaurant(models.Model):
    ...

class Table(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    reference_label = models.CharField(max_length=20)
    ...
    class Meta:
        unique_together = ['restaurant', 'reference_label']
</code>```

Body:
You can use unique_together:

class Restaurant(models.Model):
    ...

class Table(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    reference_label = models.CharField(max_length=20)
    ...
    class Meta:
        unique_together = ['restaurant', 'reference_label']