问:
Performing operations across typescript objects by key
In typescript, I have two objects with matching keys, and the values are of type number[][], for example:

```<code>const A = {
    "X": [ [100, 20], [200, 35], [300, 30] ],
    "Y": [ [400, 20], [500, 15], [600, 25] ],
    "Z": [ [700, 30], [800, 35], [900, 40] ]
}

const B = {
    "X": [ [100, 2], [200, 3], [300, 2] ],
    "Y": [ [400, 1], [500, 3], [600, 2] ],
    "Z": [ [700, 3], [800, 3], [900, 2], [1000, 4 ]
}

</code>```

I would like a function which is able to match the keys in each of the objects, merge the values based on the first entry in the inner arrays, and then finally perform an operation on the 2nd entry in the arrays, for example multiply the values.

The desired output would be a third object in the same format as A and B, like so:

```<code>C = A * B

const C = {
    "X": [ [100, 40], [200, 105], [300, 60] ],
    "Y": [ [400, 20], [500, 45], [600, 50] ],
    "Z": [ [700, 90], [800, 105], [900, 160] ]
}
</code>```

Note that since the value of "1000" only appears in B, it is not included in C

This is my attempt so far:

```<code>C =  Object.keys(A).reduce((o,key)  => ({ ...o, [key]: A.key[1]*B.key[1]}), {})
</code>```

However, I am getting the error message "Cannot read properties of undefined (reading '1')"

Any help here would be greatly appreciated!

答:
typescript

type Pair<K, V> = [K, V];
type IndexableOf<T> = { [key: string]: T };

function calculate_product(a: IndexableOf<Pair<number, number>[]>, b: IndexableOf<Pair<number, number>[]>): IndexableOf<Pair<number, number>[]> {

  const product: IndexableOf<Pair<number, number>[]> = {};

  Object.keys(a).forEach(key => {
    product[key] =
      pairise(a[key], b[key])
        .map(pair => multiply_pairized(pair))
  });
  return product;

  function multiply_pairs(pair1: Pair<number, number>, pair2: Pair<number, number>): Pair<number, number> {
    return [pair1[0], pair1[1] * (isNaN(pair2[1]) ? 1 : pair2[1])];
  }

  function pairise(arrayOfPairs1: Pair<number, number>[], arrayOfPairs2: Pair<number, number>[]): Pair<Pair<number, number>, Pair<number, number>>[] {
    return arrayOfPairs1.map((pair: Pair<number, number>, index: number) => [pair, arrayOfPairs2[index] || []]);
  }

  function multiply_pairized(pair: Pair<Pair<number, number>, Pair<number, number>>) {
    return multiply_pairs(pair[0], pair[1]);
  }
}

const a: IndexableOf<Pair<number, number>[]> = {
  "X": [[100, 20], [200, 35], [300, 30]],
  "Y": [[400, 20], [500, 15], [600, 25]],
  "Z": [[700, 30], [800, 35], [900, 40]]
};

const b: IndexableOf<Pair<number, number>[]> = {
  "X": [[100, 2], [200, 3], [300, 2]],
  "Y": [[400, 1], [500, 3], [600, 2]],
  "Z": [[700, 3], [800, 3], [900, 2], [1000, 4]]
};

// console.log(calculate_product(a, a));
// console.log(calculate_product(b, b));
console.log(calculate_product(a, b));
```
<hr />
<h2><em><strong>Illustration: Javascript Code</strong></em></h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function calculate_product(a, b) {
  const product = {};
  Object.keys(a).forEach(key => {
    product[key] =
      pairise(a[key], b[key])
      .map(pair => multiply_pairized(pair));
  });
  return product;

  function multiply_pairs(pair1, pair2) {
    return [pair1[0], pair1[1] * (isNaN(pair2[1]) ? 1 : pair2[1])];
  }

  function pairise(arrayOfPairs1, arrayOfPairs2) {
    return arrayOfPairs1.map((pair, index) => [pair, arrayOfPairs2[index] || []]);
  }

  function multiply_pairized(pair) {
    return multiply_pairs(pair[0], pair[1]);
  }
}

const a = {
  "X": [
    [100, 20],
    [200, 35],
    [300, 30]
  ],
  "Y": [
    [400, 20],
    [500, 15],
    [600, 25]
  ],
  "Z": [
    [700, 30],
    [800, 35],
    [900, 40]
  ]
};

const b = {
  "X": [
    [100, 2],
    [200, 3],
    [300, 2]
  ],
  "Y": [
    [400, 1],
    [500, 3],
    [600, 2]
  ],
  "Z": [
    [700, 3],
    [800, 3],
    [900, 2],
    [1000, 4]
  ]
};

// console.log(calculate_product(a, a));
// console.log(calculate_product(b, b));
console.log(calculate_product(a, b));</code>```

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

Body:
In typescript, I have two objects with matching keys, and the values are of type number[][], for example:

const A = {
    "X": [ [100, 20], [200, 35], [300, 30] ],
    "Y": [ [400, 20], [500, 15], [600, 25] ],
    "Z": [ [700, 30], [800, 35], [900, 40] ]
}

const B = {
    "X": [ [100, 2], [200, 3], [300, 2] ],
    "Y": [ [400, 1], [500, 3], [600, 2] ],
    "Z": [ [700, 3], [800, 3], [900, 2], [1000, 4 ]
}

I would like a function which is able to match the keys in each of the objects, merge the values based on the first entry in the inner arrays, and then finally perform an operation on the 2nd entry in the arrays, for example multiply the values.

The desired output would be a third object in the same format as A and B, like so:

C = A * B

const C = {
    "X": [ [100, 40], [200, 105], [300, 60] ],
    "Y": [ [400, 20], [500, 45], [600, 50] ],
    "Z": [ [700, 90], [800, 105], [900, 160] ]
}

Note that since the value of "1000" only appears in B, it is not included in C

This is my attempt so far:

C =  Object.keys(A).reduce((o,key)  => ({ ...o, [key]: A.key[1]*B.key[1]}), {})

However, I am getting the error message "Cannot read properties of undefined (reading '1')"

Any help here would be greatly appreciated!

Body:
typescript

type Pair<K, V> = [K, V];
type IndexableOf<T> = { [key: string]: T };

function calculate_product(a: IndexableOf<Pair<number, number>[]>, b: IndexableOf<Pair<number, number>[]>): IndexableOf<Pair<number, number>[]> {

  const product: IndexableOf<Pair<number, number>[]> = {};

  Object.keys(a).forEach(key => {
    product[key] =
      pairise(a[key], b[key])
        .map(pair => multiply_pairized(pair))
  });
  return product;

  function multiply_pairs(pair1: Pair<number, number>, pair2: Pair<number, number>): Pair<number, number> {
    return [pair1[0], pair1[1] * (isNaN(pair2[1]) ? 1 : pair2[1])];
  }

  function pairise(arrayOfPairs1: Pair<number, number>[], arrayOfPairs2: Pair<number, number>[]): Pair<Pair<number, number>, Pair<number, number>>[] {
    return arrayOfPairs1.map((pair: Pair<number, number>, index: number) => [pair, arrayOfPairs2[index] || []]);
  }

  function multiply_pairized(pair: Pair<Pair<number, number>, Pair<number, number>>) {
    return multiply_pairs(pair[0], pair[1]);
  }
}

const a: IndexableOf<Pair<number, number>[]> = {
  "X": [[100, 20], [200, 35], [300, 30]],
  "Y": [[400, 20], [500, 15], [600, 25]],
  "Z": [[700, 30], [800, 35], [900, 40]]
};

const b: IndexableOf<Pair<number, number>[]> = {
  "X": [[100, 2], [200, 3], [300, 2]],
  "Y": [[400, 1], [500, 3], [600, 2]],
  "Z": [[700, 3], [800, 3], [900, 2], [1000, 4]]
};

// console.log(calculate_product(a, a));
// console.log(calculate_product(b, b));
console.log(calculate_product(a, b));

Illustration: Javascript Code

function calculate_product(a, b) {
  const product = {};
  Object.keys(a).forEach(key => {
    product[key] =
      pairise(a[key], b[key])
      .map(pair => multiply_pairized(pair));
  });
  return product;

  function multiply_pairs(pair1, pair2) {
    return [pair1[0], pair1[1] * (isNaN(pair2[1]) ? 1 : pair2[1])];
  }

  function pairise(arrayOfPairs1, arrayOfPairs2) {
    return arrayOfPairs1.map((pair, index) => [pair, arrayOfPairs2[index] || []]);
  }

  function multiply_pairized(pair) {
    return multiply_pairs(pair[0], pair[1]);
  }
}

const a = {
  "X": [
    [100, 20],
    [200, 35],
    [300, 30]
  ],
  "Y": [
    [400, 20],
    [500, 15],
    [600, 25]
  ],
  "Z": [
    [700, 30],
    [800, 35],
    [900, 40]
  ]
};

const b = {
  "X": [
    [100, 2],
    [200, 3],
    [300, 2]
  ],
  "Y": [
    [400, 1],
    [500, 3],
    [600, 2]
  ],
  "Z": [
    [700, 3],
    [800, 3],
    [900, 2],
    [1000, 4]
  ]
};

// console.log(calculate_product(a, a));
// console.log(calculate_product(b, b));
console.log(calculate_product(a, b));

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET


来源: stackexchange

问:
Flutter: How to get values of a checkbox and put in a variable
I'm currently stuck on a code in flutter.

So, I have a checkbox and I want that everytime I click the checkbox the value of that checkbox will be save in an array variable and if I click it again the value will be removed in the array variable, so in that way I can call that array variable and save it in the database.

This is what I have so far.

My code:

```<code>Map<String, bool> values = {
'Food': false,
'Materials': false,
};

Widget build(BuildContext context) {
return Scaffold(
  appBar: new AppBar(title: new Text('CheckboxListTile demo')),
  body:  new ListView(
    children: values.keys.map((String key) {
      return new CheckboxListTile(
        title: new Text(key),
        value: values[key],
        onChanged: (bool value) {
          setState(() {
            values[key] = value;
          });
          print(key);
         },
       );
      }).toList(),
     ),
   );
  }
 }
</code>```

My UI:

答:
```<code>//calling in main funtion

void main(){

runApp(GridCheck1());

}

//code

import 'package:flutter/material.dart';

class GridCheck1 extends StatelessWidget{

  @override

  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('List Checkbox Demo'),
        ),
        body: MyGridCheckDemo(),
      ),
    );

  }
}

class MyGridCheckDemo extends StatefulWidget {
  @override
  _MyGridCheckState createState() => _MyGridCheckState();
}

class _MyGridCheckState extends State<MyGridCheckDemo> {
  var selectedItem;
  bool selecteValue = false;

  List<GridCheckModel> checkBoxListTileModel = GridCheckModel.getUsers();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blueGrey,
        centerTitle: true,
        title:  Text(
          'CheckBox ListTile Demo',
          style: TextStyle(color: Colors.black),
        ),
      ),
      body: Column(
        children: [
          Container(
padding: EdgeInsets.symmetric(horizontal: 15,vertical: 10),
            child: Text('Selected Item: ${selectedItem}'+ ', ' + ' Selected Value: ${selecteValue}', style: TextStyle(fontSize: 20, fontWeight: FontWeight.normal),),

          ),
        Expanded(
            child: GridView.builder(

                shrinkWrap: true,

                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 4.0,
                  mainAxisSpacing: 4.0,
                ),
                itemCount: 12,

                itemBuilder: (BuildContext context, int index) {

                  return Card(

                    elevation: 20,

                    color: Colors.orange,

                    child: Container(

                      padding: EdgeInsets.all(10.0),

                      child: Column(

                        children: <Widget>[

                          CheckboxListTile(
                            //checkColor: Colors.indigo,
                              tileColor: Colors.greenAccent,
                              controlAffinity: ListTileControlAffinity.trailing,
                              activeColor: Colors.pink[300],
                              dense: true,

                              //font change
                              title: Text(

                                checkBoxListTileModel[index].title,

                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  letterSpacing: 0.5,
                                ),
                              ),
                              value: checkBoxListTileModel[index].isCheck,

                              onChanged: (bool? newValue) {
                                //itemChange(newValue!, index);
                                setState(() {
                                  checkBoxListTileModel[index].isCheck = newValue!;
                                  if(checkBoxListTileModel[index].isCheck) {
                                    selectedItem = checkBoxListTileModel[index].title;
                                    selecteValue =  checkBoxListTileModel[index].isCheck;
                                  }
                                  else{
                                    selectedItem = '';
                                    selecteValue = checkBoxListTileModel[index].isCheck!;
                                  }
                                });
                              }
                              ),
                        ],
                      ),
                    ),
                  );
                }
            ),
          )
        ],
      ),
    );
  }

  void itemChange(bool val, int index) {
    setState(() {
      checkBoxListTileModel[index].isCheck = val;
    });
  }
}
class GridCheckModel {
  int userId;
  String title;
  bool isCheck;

  GridCheckModel({required this.userId, required this.title, required this.isCheck});

  static List<GridCheckModel> getUsers() {
    return <GridCheckModel>[

      GridCheckModel(
          userId: 1,
          title: "Android",
          isCheck: false),
      GridCheckModel(
          userId: 2,
          title: "Flutter",
          isCheck: false),
      GridCheckModel(
          userId: 3,
          title: "IOS",
          isCheck: false),
      GridCheckModel(
          userId: 4,
          title: "PHP",
          isCheck: false),
      GridCheckModel(
          userId: 5,
          title: "Node",
          isCheck: false),
      GridCheckModel(
          userId: 6,
          title: "c#",
          isCheck: false),
      GridCheckModel(
          userId: 7,
          title: "C",
          isCheck: false),
      GridCheckModel(
          userId: 8,
          title: "C++",
          isCheck: false),
      GridCheckModel(
          userId: 9,
          title: "React",
          isCheck: false),
      GridCheckModel(
          userId: 10,
          title: "Ruby",
          isCheck: false),
      GridCheckModel(
          userId: 11,
          title: ".Net",
          isCheck: false),
      GridCheckModel(
          userId: 12,
          title: "Cobol",
          isCheck: false),
    ];
  }
}
</code>```

output:

enter image description here

ContentLicense: CC BY-SA 4.0

Body:
I'm currently stuck on a code in flutter.

So, I have a checkbox and I want that everytime I click the checkbox the value of that checkbox will be save in an array variable and if I click it again the value will be removed in the array variable, so in that way I can call that array variable and save it in the database.

This is what I have so far.

My code:

Map<String, bool> values = {
'Food': false,
'Materials': false,
};

Widget build(BuildContext context) {
return Scaffold(
  appBar: new AppBar(title: new Text('CheckboxListTile demo')),
  body:  new ListView(
    children: values.keys.map((String key) {
      return new CheckboxListTile(
        title: new Text(key),
        value: values[key],
        onChanged: (bool value) {
          setState(() {
            values[key] = value;
          });
          print(key);
         },
       );
      }).toList(),
     ),
   );
  }
 }

My UI:

Body:
//calling in main funtion

void main(){

runApp(GridCheck1());

}

//code

import 'package:flutter/material.dart';

class GridCheck1 extends StatelessWidget{

  @override

  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('List Checkbox Demo'),
        ),
        body: MyGridCheckDemo(),
      ),
    );

  }
}

class MyGridCheckDemo extends StatefulWidget {
  @override
  _MyGridCheckState createState() => _MyGridCheckState();
}

class _MyGridCheckState extends State<MyGridCheckDemo> {
  var selectedItem;
  bool selecteValue = false;

  List<GridCheckModel> checkBoxListTileModel = GridCheckModel.getUsers();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blueGrey,
        centerTitle: true,
        title:  Text(
          'CheckBox ListTile Demo',
          style: TextStyle(color: Colors.black),
        ),
      ),
      body: Column(
        children: [
          Container(
padding: EdgeInsets.symmetric(horizontal: 15,vertical: 10),
            child: Text('Selected Item: ${selectedItem}'+ ', ' + ' Selected Value: ${selecteValue}', style: TextStyle(fontSize: 20, fontWeight: FontWeight.normal),),

          ),
        Expanded(
            child: GridView.builder(

                shrinkWrap: true,

                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 4.0,
                  mainAxisSpacing: 4.0,
                ),
                itemCount: 12,

                itemBuilder: (BuildContext context, int index) {

                  return Card(

                    elevation: 20,

                    color: Colors.orange,

                    child: Container(

                      padding: EdgeInsets.all(10.0),

                      child: Column(

                        children: <Widget>[

                          CheckboxListTile(
                            //checkColor: Colors.indigo,
                              tileColor: Colors.greenAccent,
                              controlAffinity: ListTileControlAffinity.trailing,
                              activeColor: Colors.pink[300],
                              dense: true,

                              //font change
                              title: Text(

                                checkBoxListTileModel[index].title,

                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  letterSpacing: 0.5,
                                ),
                              ),
                              value: checkBoxListTileModel[index].isCheck,

                              onChanged: (bool? newValue) {
                                //itemChange(newValue!, index);
                                setState(() {
                                  checkBoxListTileModel[index].isCheck = newValue!;
                                  if(checkBoxListTileModel[index].isCheck) {
                                    selectedItem = checkBoxListTileModel[index].title;
                                    selecteValue =  checkBoxListTileModel[index].isCheck;
                                  }
                                  else{
                                    selectedItem = '';
                                    selecteValue = checkBoxListTileModel[index].isCheck!;
                                  }
                                });
                              }
                              ),
                        ],
                      ),
                    ),
                  );
                }
            ),
          )
        ],
      ),
    );
  }

  void itemChange(bool val, int index) {
    setState(() {
      checkBoxListTileModel[index].isCheck = val;
    });
  }
}
class GridCheckModel {
  int userId;
  String title;
  bool isCheck;

  GridCheckModel({required this.userId, required this.title, required this.isCheck});

  static List<GridCheckModel> getUsers() {
    return <GridCheckModel>[

      GridCheckModel(
          userId: 1,
          title: "Android",
          isCheck: false),
      GridCheckModel(
          userId: 2,
          title: "Flutter",
          isCheck: false),
      GridCheckModel(
          userId: 3,
          title: "IOS",
          isCheck: false),
      GridCheckModel(
          userId: 4,
          title: "PHP",
          isCheck: false),
      GridCheckModel(
          userId: 5,
          title: "Node",
          isCheck: false),
      GridCheckModel(
          userId: 6,
          title: "c#",
          isCheck: false),
      GridCheckModel(
          userId: 7,
          title: "C",
          isCheck: false),
      GridCheckModel(
          userId: 8,
          title: "C++",
          isCheck: false),
      GridCheckModel(
          userId: 9,
          title: "React",
          isCheck: false),
      GridCheckModel(
          userId: 10,
          title: "Ruby",
          isCheck: false),
      GridCheckModel(
          userId: 11,
          title: ".Net",
          isCheck: false),
      GridCheckModel(
          userId: 12,
          title: "Cobol",
          isCheck: false),
    ];
  }
}

output:

enter image description here


问:
How should I access attributes of union types in typscript?
What is the correct way to access attributes of a union type that is not present on all of the types? I seem to always get a typescript "property ... does not exist on type..." error, even if I do a check to make sure the attribute exists (see example below)

```<code>interface Car {
  wheels: 4,
  spareWheels: 1,
}

interface Bicycle {
  wheels: 2,
}

type Vehicle = Car | Bicycle

getWheelCount(vehicle: Vehicle): number => {
   return vehicle.spareWheels ? vehicle.spareWheels + vehicle.wheels : vehicle.wheels
}
</code>```

The documentation (https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types ) has a solution to use 'typeof', but that doesn't work for custom types.

答:
You can use in operator like this:

```<code>interface Car {
  wheels: 4;
  spareWheels: 1;
}

interface Bicycle {
  wheels: 2;
}

type Vehicle = Car | Bicycle;

const getWheelCount = (vehicle: Vehicle): number => {
  return "spareWheels" in vehicle // using `in` operator
    ? vehicle.spareWheels + vehicle.wheels
    : vehicle.wheels;
};
</code>```

Body:
What is the correct way to access attributes of a union type that is not present on all of the types? I seem to always get a typescript "property ... does not exist on type..." error, even if I do a check to make sure the attribute exists (see example below)

interface Car {
  wheels: 4,
  spareWheels: 1,
}

interface Bicycle {
  wheels: 2,
}

type Vehicle = Car | Bicycle

getWheelCount(vehicle: Vehicle): number => {
   return vehicle.spareWheels ? vehicle.spareWheels + vehicle.wheels : vehicle.wheels
}

The documentation (https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types ) has a solution to use 'typeof', but that doesn't work for custom types.

Body:
You can use in operator like this:

interface Car {
  wheels: 4;
  spareWheels: 1;
}

interface Bicycle {
  wheels: 2;
}

type Vehicle = Car | Bicycle;

const getWheelCount = (vehicle: Vehicle): number => {
  return "spareWheels" in vehicle // using `in` operator
    ? vehicle.spareWheels + vehicle.wheels
    : vehicle.wheels;
};


问:
What is the difference between Web App Bot and Azure Bot

Bot Framework SDK documentation says that Web App Bot is deprecated. But there is no information  about the difference between development with Azure Bot and (deprecated) Web App Bot. What exact changes should be done if we migrate form one service (Web App Bot) to another (Azure Bot)?

答:
In regards of other contributor's answer, I think main concept and
queries has not explained accordingly, so I felt it requires more
explanation in addition to clear the OP's main concern.

Questions: But there is no information about the difference between development with Azure Bot and (deprecated) Web App Bot.

The Bot Service behind Azure Bot and Web App Bot/Bot Channels Registration is the same; the change is in how the resources are
created that you use in your bot such as web apps, language
understanding, and more.

Rather than the one size fits all templates that the Web App Bot used,
Bot Framework Composer can be used to create resources for the Bot
with much more flexibility than the Web App Bot templates allowed.

Bot Channels Registration and Azure Bot are basically the same
capabilities renamed. The UX is slightly different in the Azure Portal
to help customers connect to the Bot Framework Composer.

Its clearly documented here in the official document you can get here

Questions: What exact changes should be done if we migrate form one service (Web App Bot) to another (Azure Bot)?

Currently migration from Web App BottoAzure Bot isn't supported.
If your Web App Bot isn't being used in production, you can delete
your old Web App Bot resource and reuse the bot name and app ID in a
new bot resource (after some time for the old record to get deleted).
The new Azure Bot is designed around creating your bot using
Composer, Bot Framework SDK, and so the gains from such a migration
would be minimal. You can get the official explanation here

Note:

Now you might be wondering, what about your existing Web app bot. Your bot and other resources will continue to work without any problem and you don't need to migrate your old web app bot in this aspect.

One question may arise,then why its been depricated or no longer be used?

The answer would be, Functionally though Azure Bot, Web App Bot, and
Bot Channels Registration all utilize the Bot Service in the same way
"under the hood". The Azure Bot path is easier, and more
configurable for developers in comparison of Web app bot

Hope above explanation will redeem your concern.


问:
Overwrite Local Notifications
I have a method that activates a local notification.

```<code>UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
    return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];

// Notification details
localNotif.alertBody = [mainTitle text];
// Set the action button
localNotif.alertAction = @"View";

localNotif.soundName = UILocalNotificationDefaultSoundName;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
</code>```

The problem is that if you call several times the method, do not overwrite the localNotif, but it adds another. How do I delete the old every time?

Thanks!

答:
Save the local notification object (say in an ivar), and do:

```<code>[[UIApplication sharedApplication] cancelLocalNotification:previousNotification];
</code>```

You can also clear all local notifications with cancelAllLocalNotifications.

ContentLicense: CC BY-SA 3.0

Title: Overwrite Local Notifications

Body:
I have a method that activates a local notification.

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
    return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];

// Notification details
localNotif.alertBody = [mainTitle text];
// Set the action button
localNotif.alertAction = @"View";

localNotif.soundName = UILocalNotificationDefaultSoundName;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];

The problem is that if you call several times the method, do not overwrite the localNotif, but it adds another. How do I delete the old every time?

Thanks!

Body:
Save the local notification object (say in an ivar), and do:

[[UIApplication sharedApplication] cancelLocalNotification:previousNotification];

You can also clear all local notifications with cancelAllLocalNotifications.


问:
Django: aggregate if all boolean model fields is True
```<code>from django.db import models

class Car(models.model):
    sold = models.BooleanField(default=False)
</code>```

I can detemine if all cars were sold by making two queries:

```<code>sold_count = Car.objects.filter(sold=True).count()
all_count = Car.objects.count()

are_all_sold = (all_count - sold_count) == 0
</code>```

Since this operation is very frequent on my app, I am wondering if it is possible to do it in just one DB query? e.g. using Aggregation or Query Expressions, etc.

just an update, I can get the stats on how many were sold & unsold by one single query:

```<code>Car.objects.values("sold").annotate(count=Count("sold"))
<QuerySet [{'sold': False, 'count': 1}, {'sold': True, 'count': 9}]>
</code>```

答:
Yes. You can do that by using Model Manager.

in model.py:

```<code>from django.db import models

class CarManager(models.Manager):
    def are_all_sold_or_not(self):
        sold_count = Car.objects.filter(sold=True).count()
        all_count = Car.objects.count()
        return all_count == sold_count

class Car(models.model):
    sold = models.BooleanField(default=False)
    objects = CarManager()

</code>```

in views.py

```<code>
def myview(request):
  .....
  .
  are_all_sold = Car.objects.are_all_sold_or_not()
  .
  .

</code>```

You can read more about Model Manager in the documentation:
https://docs.djangoproject.com/en/4.0/topics/db/managers/

Body:
from django.db import models

class Car(models.model):
    sold = models.BooleanField(default=False)

I can detemine if all cars were sold by making two queries:

sold_count = Car.objects.filter(sold=True).count()
all_count = Car.objects.count()

are_all_sold = (all_count - sold_count) == 0

Since this operation is very frequent on my app, I am wondering if it is possible to do it in just one DB query? e.g. using Aggregation or Query Expressions, etc.

just an update, I can get the stats on how many were sold & unsold by one single query:

Car.objects.values("sold").annotate(count=Count("sold"))
<QuerySet [{'sold': False, 'count': 1}, {'sold': True, 'count': 9}]>

Body:
Yes. You can do that by using Model Manager.

in model.py:

from django.db import models

class CarManager(models.Manager):
    def are_all_sold_or_not(self):
        sold_count = Car.objects.filter(sold=True).count()
        all_count = Car.objects.count()
        return all_count == sold_count

class Car(models.model):
    sold = models.BooleanField(default=False)
    objects = CarManager()

in views.py

def myview(request):
  .....
  .
  are_all_sold = Car.objects.are_all_sold_or_not()
  .
  .

You can read more about Model Manager in the documentation:
https://docs.djangoproject.com/en/4.0/topics/db/managers/


问:
How do I create an array of objects?
I only know Java, and I am learning how to do c++ right now. I currently have an object called "node". I want to make an array of those elements in a different class, and I have to perform many operations on this array. Because of this, I am trying to declare a global array variable that gets initialized in my constructor. In Java, this would've been done by

```<code>ObjectName[] variableName = new ObjectName[size];
</code>```

but I am not sure how to do it in c++. I've tried declaring it similar to how I declared the other global arrays, with

```<code>Node* nodes;
</code>```

and then in my constructor:

```<code>nodes = new Node[size]
</code>```

but I got a bunch of compiler errors. How am I supposed to do this? This is only my second week of coding in c++, so try to keep answers basic.

答:
How do I create an array of objects?

Given a type named ObjectName, you can define an array variable with name variableName and a compile time constant size size like this:

```<code>ObjectName variableName[size]{};
</code>```

Title: How do I create an array of objects?

Body:
I only know Java, and I am learning how to do c++ right now. I currently have an object called "node". I want to make an array of those elements in a different class, and I have to perform many operations on this array. Because of this, I am trying to declare a global array variable that gets initialized in my constructor. In Java, this would've been done by

ObjectName[] variableName = new ObjectName[size];

but I am not sure how to do it in c++. I've tried declaring it similar to how I declared the other global arrays, with

Node* nodes;

and then in my constructor:

nodes = new Node[size]

but I got a bunch of compiler errors. How am I supposed to do this? This is only my second week of coding in c++, so try to keep answers basic.

Body:
How do I create an array of objects?

Given a type named ObjectName, you can define an array variable with name variableName and a compile time constant size size like this:

ObjectName variableName[size]{};


问:
Duplicated iframe-request-id in url when login to a Azure hosted app which have AAD authentication using Cypress
When I try to login to a Azure hosted app using Cypress I get below in the url. Does this mean that backend code have a redirection loop. Please help if anyone have any idea about this.

答:
The iframe-request-id is not something that is added by Cypress, this is behavior that is being done my microsoft when run through Cypress. Likely it is not expecting to be run within an iframe in the manner that Cypress runs it.

I would suggest looking into other ways to test the login through your application as explained in this doc: https://on.cypress.io/best-practices#Visiting-external-sites.

For more information you can refer this github discussion


问:
Error in installing request module in Python
I am facing some errors while installing requests module in python 3.10 version.
enter image description hereI am attaching screenshot of the errors.</p>

答:
You can try any one of these commands:

"pip install requests"

"python -m pip install requests"

Or go to this official python packages page to check how you can install the requests library.
https://pypi.org/project/requests/


问:
How to change background color and font color on selection in mAngular material toggle button
I am facing one issue. I need to change the background color and its font color when user will select the toggle button using Angular material. I am explaining my code below.

```<code> <div class="btn-group">
            <mat-button-toggle-group #group="matButtonToggleGroup" [value]="selectedVal" (change)="onValChange(group.value)" color="primary">
              <mat-button-toggle value="option1" style="border-right: none;width:127px">
                Option 1
              </mat-button-toggle>
              <mat-button-toggle value="option2" style="border-right: none;width:127px">
                Option 2
              </mat-button-toggle>
            </mat-button-toggle-group>
          </div>
</code>```

The css code is given below.

```<code>:host .mat-button-toggle-group{
    border-radius: 20px !important;
    height: 40px !important;
    align-items: center !important;
    margin-top: 5px !important;
    padding: 0 5px !important;
    z-index: 3 !important;
    color: #017cad !important;
}
:host .mat-button-toggle-checked {
    background-color: #017cad !important;
    color: #f5f5f6;
}
</code>```

As per my code the view looks like below.

When I am selecting any one button it looks like below.

If we see the above view then the some part of background is not filled with the color and also the text color I need to change to white after selection. The right view should looks like below.

I need like above image the angular material toggle button should visible. Please help me to resolve this issue.

答: I would suggest using themes. With material theming you can extract whichever individual palettes you need from the theme and apply the backgrounds default-contrast color to the text color to achieve optimal contrast with light or dark colors. https://stackoverflow.com/a/48159346/15439733</p>

Body:
I am facing one issue. I need to change the background color and its font color when user will select the toggle button using Angular material. I am explaining my code below.

            <mat-button-toggle-group #group="matButtonToggleGroup" [value]="selectedVal" (change)="onValChange(group.value)" color="primary">
              <mat-button-toggle value="option1" style="border-right: none;width:127px">
                Option 1
              </mat-button-toggle>
              <mat-button-toggle value="option2" style="border-right: none;width:127px">
                Option 2
              </mat-button-toggle>
            </mat-button-toggle-group>

The css code is given below.

:host .mat-button-toggle-group{
    border-radius: 20px !important;
    height: 40px !important;
    align-items: center !important;
    margin-top: 5px !important;
    padding: 0 5px !important;
    z-index: 3 !important;
    color: #017cad !important;
}
:host .mat-button-toggle-checked {
    background-color: #017cad !important;
    color: #f5f5f6;
}

As per my code the view looks like below.

When I am selecting any one button it looks like below.

If we see the above view then the some part of background is not filled with the color and also the text color I need to change to white after selection. The right view should looks like below.

I need like above image the angular material toggle button should visible. Please help me to resolve this issue.


问:
Passing IConfiguration to constructor using Reflection
I'm trying to use C# Reflection to create an instance, my constructor is receiving two parameters:

ILogger

IConfiguration

I created the ILogger and passed it to the constructor it's working fine, but the IConfiguration is not working because the object of IConfiguration is returning ConfigurationRoot object

class code:

```<code>public class Weekly
    {
        public Guid SessionId { get; set; }
        private readonly ILogger<Weekly> _logger;
        private readonly IConfiguration _configuration;
        public Weekly(ILogger<Weekly> ilogger, IConfiguration configuration)
        {
            _logger = ilogger;
            _configuration = configuration;
            SessionId = Guid.NewGuid();
            Console.WriteLine("Weekly inestance created with id: " + SessionId.ToString());
            _logger.LogInformation("Weekly inestance created with id: " + SessionId.ToString());
        }
        public void Report()
        {
            Console.WriteLine("Weekly report called");
            _logger.LogInformation("Weekly report called");
        }
    }
</code>```

creating object :

```<code>    foreach (ConstructorInfo constructor in constructors)
                {
                    ParameterInfo[] parameters = constructor.GetParameters();
                    if (parameters.Count() > 0)
                    {
                        object[] objs = new object[parameters.Count()];
                        for (int i = 0; i < parameters.Count(); i++)
                        {
                            if (typeof(ILogger).IsAssignableFrom(parameters[i].ParameterType))
                            {
                                objs[i] = _serviceProvider.GetService(typeof(ILogger<dynamic>)) as ILogger<dynamic>;
                            }
                            else if (typeof(IConfiguration).IsAssignableFrom(parameters[i].ParameterType))
                            {
                         //here i'm adding IConfiguration
                                objs[i] = _serviceProvider.GetService<IConfiguration>();
                            }
                        }
                        instance = Activator.CreateInstance(type, objs);
                    }
                    else
                    {
                        instance = Activator.CreateInstance(type);
                    }
                }
</code>```

Edit:
I'm getting the error
System.AggregateException: 'One or more errors occurred. (Constructor on type 'WeeklyReport.Weekly' not found.)'

答:
Solution:

the problem was in ILogger<Weekly> in Weekly class, I was trying to pass ILogger<dynamic> to ILogger<Weekly>

I just made a change in Weekly class :

```<code>public class Weekly
    {
        public Guid SessionId { get; set; }
        private readonly ILogger<dynamic> _logger;
        private readonly IConfiguration _configuration;
        public Weekly(ILogger<dynamic> ilogger, IConfiguration configuration)
        {
            _logger = ilogger;
            _configuration = configuration;
            SessionId = Guid.NewGuid();
            Console.WriteLine("Weekly inestance created with id: " + SessionId.ToString());
            _logger.LogInformation("Weekly inestance created with id: " + SessionId.ToString());
        }
        public void Report()
        {
            Console.WriteLine("Weekly report called");
            _logger.LogInformation("Weekly report called");
        }
    }
</code>```

and finally, it's working fine.

Body:
I'm trying to use C# Reflection to create an instance, my constructor is receiving two parameters:

ILogger

IConfiguration

I created the ILogger and passed it to the constructor it's working fine, but the IConfiguration is not working because the object of IConfiguration is returning ConfigurationRoot object

class code:

public class Weekly
    {
        public Guid SessionId { get; set; }
        private readonly ILogger<Weekly> _logger;
        private readonly IConfiguration _configuration;
        public Weekly(ILogger<Weekly> ilogger, IConfiguration configuration)
        {
            _logger = ilogger;
            _configuration = configuration;
            SessionId = Guid.NewGuid();
            Console.WriteLine("Weekly inestance created with id: " + SessionId.ToString());
            _logger.LogInformation("Weekly inestance created with id: " + SessionId.ToString());
        }
        public void Report()
        {
            Console.WriteLine("Weekly report called");
            _logger.LogInformation("Weekly report called");
        }
    }

creating object :

    foreach (ConstructorInfo constructor in constructors)
                {
                    ParameterInfo[] parameters = constructor.GetParameters();
                    if (parameters.Count() > 0)
                    {
                        object[] objs = new object[parameters.Count()];
                        for (int i = 0; i < parameters.Count(); i++)
                        {
                            if (typeof(ILogger).IsAssignableFrom(parameters[i].ParameterType))
                            {
                                objs[i] = _serviceProvider.GetService(typeof(ILogger<dynamic>)) as ILogger<dynamic>;
                            }
                            else if (typeof(IConfiguration).IsAssignableFrom(parameters[i].ParameterType))
                            {
                         //here i'm adding IConfiguration
                                objs[i] = _serviceProvider.GetService<IConfiguration>();
                            }
                        }
                        instance = Activator.CreateInstance(type, objs);
                    }
                    else
                    {
                        instance = Activator.CreateInstance(type);
                    }
                }

Edit:
I'm getting the error
System.AggregateException: 'One or more errors occurred. (Constructor on type 'WeeklyReport.Weekly' not found.)'

Body:
Solution:

the problem was in ILogger<Weekly> in Weekly class, I was trying to pass ILogger<dynamic> to ILogger<Weekly>

I just made a change in Weekly class :

public class Weekly
    {
        public Guid SessionId { get; set; }
        private readonly ILogger<dynamic> _logger;
        private readonly IConfiguration _configuration;
        public Weekly(ILogger<dynamic> ilogger, IConfiguration configuration)
        {
            _logger = ilogger;
            _configuration = configuration;
            SessionId = Guid.NewGuid();
            Console.WriteLine("Weekly inestance created with id: " + SessionId.ToString());
            _logger.LogInformation("Weekly inestance created with id: " + SessionId.ToString());
        }
        public void Report()
        {
            Console.WriteLine("Weekly report called");
            _logger.LogInformation("Weekly report called");
        }
    }

and finally, it's working fine.


问:
ASP.NET mixed windows/forms authentication problem with session objects
Weird problem here, we're running a few mixed environment web applications, that use Windows or Forms authentication depending on where the user comes from.

I'm curious how everyone else might be handling expired sessions to avoid the errors you would get from someone leaving an idle session open for too long and then trying to resume work, mainly looking for best practices on the subject.

Any suggestions or opinions would be greatly appreciated.

Thanks,

答:
I'm not sure how your authentication method affects session timeouts, the mechanism they use to get in shouldn't affect how long they can stay in.

Generally speaking, if someone does have an expired session, you can add code to check to see if their session is active. If it isn't, just redirect them to a login page, or display some other friendly text.

Basically something like:

```<code>if (Session.IsNewSession)
   Response.Redirect("login.aspx");
</code>```

OwnerDisplayName: This Mat

ContentLicense: CC BY-SA 2.5

Body:
I'm not sure how your authentication method affects session timeouts, the mechanism they use to get in shouldn't affect how long they can stay in.

Generally speaking, if someone does have an expired session, you can add code to check to see if their session is active. If it isn't, just redirect them to a login page, or display some other friendly text.

Basically something like:

if (Session.IsNewSession)
   Response.Redirect("login.aspx");

OwnerDisplayName: AaronS


问:
Postgresql, inner join or subquery or view?
I have the following tables:

```<code>user
car
dealer
user_metrics
  - user_id (FK) (required)
  - dealer_id (FK) (can be null)
  - car_id (FK) (can be null)
  - saved
  - .... other columns
</code>```

A user can save a car or a dealership, when that happens the user_metrics.saved is set to true and the related car_id or dealership_id is set (car_id and dealership_id are exclusive, only one is set for a row).

I want user A to be able to see all users that have saved the same cars / dealerships.

So, if user A has saved car 1, 2,3 and dealership 5,7, I want to get all users that have saved any of those cars / dealerships.

I thought about inner join on user_metrics, but, I am not sure how to write the entire query that would deliver on this.

What query would allow me to get all users that have saved any of the cars/dealerships a certain user has saved?

答:
If I understand as well maybe the below query solve your problem.

First should find a list of user A has been reserved after that should search which of car or dealer used by another user

with user_saved_data as (
    select um.*,
           u.name,
           ...
    from user_metrics um
             inner join user u
    on um.user_id = u.id
    where um.saved = true
      and u.id = $1 -- User id of user 'A' or any username (Or use other column for create custom condition)
)
select usd.name as current_reserved_user,
       u.name   as reserved_by_user,
       d.*,
       c.*
from user_metrics um
         inner join user u on um.user_id = u.id
         left join user_saved_data usd on usd.dealer_id notnull and usd.dealer_id = um.dealer_id
         left join user_saved_data usd on usd.car_id notnull and usd.car_id = um.car_id
         left join dealer d on um.dealer_id = d.id
         left join car c on um.car_id = c.id
```

Body:
I have the following tables:

user
car
dealer
user_metrics
  - user_id (FK) (required)
  - dealer_id (FK) (can be null)
  - car_id (FK) (can be null)
  - saved
  - .... other columns

A user can save a car or a dealership, when that happens the user_metrics.saved is set to true and the related car_id or dealership_id is set (car_id and dealership_id are exclusive, only one is set for a row).

I want user A to be able to see all users that have saved the same cars / dealerships.

So, if user A has saved car 1, 2,3 and dealership 5,7, I want to get all users that have saved any of those cars / dealerships.

I thought about inner join on user_metrics, but, I am not sure how to write the entire query that would deliver on this.

What query would allow me to get all users that have saved any of the cars/dealerships a certain user has saved?


问:
What is error for when install psycopg2==2.7.*?
pip3 install psycop2==2.7.*

I try to install Django project on a live server but when I install the package I am getting error! pip install psycopg2==2.7.*

答:
You have to install "headers" for C extension. In this case you should install libpq-dev

sudo apt install libpq-dev


问:
How do I install Rails?
I am completely new to Ruby and need to use Ruby on Rails 2.3.5 on Windows. I have downloaded the zip from GitHub here: https://github.com/rails/rails/tree/v2.3.5

There was no gem file so I tried rake in the extracted directory. It took ages and seemed to have a lot of errors, but it did eventually complete.

There was no gem file created (is this even what rake is supposed to do?). And rails is not installed (typing rails at the command prompt doesnt work).

Any ideas what I am doing wrong?

EDIT: I cannot use gem install rails -v "2.3.5" as I am behind a firewall. I think I need to install it from local files.

答:
install ruby, include gems support.
at the command line

gem install rails

Title: How do I install Rails?


问:
Connections between sub modules wrong
My codes for Alu and Mux:

```<code>module alu(input logic [31:0]srca, srcb,
          input logic [2:0] alucontrol,
          output logic zero,
          output logic [31:0]aluout);

logic [31:0] addr, subr, sltr, Andr, Orr;
assign addr = srca + srcb;
assign subr = srca - srcb;
assign sltr = (srca < srcb) ? 1 : 0;
assign Andr = srca & srcb;
assign Orr = srca | srcb;
always_comb
begin
case(alucontrol)
    3'b010: aluout = addr;
    3'b110: aluout = subr;
    3'b111: aluout = sltr;
    3'b000: aluout = Andr;
    3'b001: aluout = Orr;
    default: aluout = 32'bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
endcase
zero = (subr == 0) ?  1 : 0;
end
endmodule

module mux2#(parameter WIDTH = 8)
                (input logic [WIDTH-1:0] d0, d1,
                 input logic                 s,
                 output logic [WIDTH-1:0] y);
always_comb
begin
y = s?d1 : d0;
end
endmodule
</code>```

and their instantiation under the same top module:

```<code>alu         alu(srca, srcb, alucontrol, aluout, zero);

mux2 #(32) resmux(aluout, readdata, memtoreg, result);
</code>```

When I try to connect my 2-1Mux resmux with my alu, the aluout doesn't get connected to resmux

aluout gets suspended

I could solve this by exchanging the order of aluout and zero, but could anybody explain why this happens and how to avoid? Thanks a lot!

答:
There are a number of mechanisms for connecting ports in SystemVerilog. The mechanism you are using is positional. That means each signal connection has to go in the prescribed order that they appear in the module declaration of alu. The way your code is written, the signal zero in module top is connected to last port aluout declared in module alu.

SystemVerilog also has a by_name syntax .portname(signal). You can list all your port connections in any order that way.

```<code>alu   alu(.srca(srca), .srcb(srcb), .alucontrol(alucontrol), .alu(aluout), .zero(zero));
</code>```

When the signal name you are connecting matches the declared port name, you can just use .portname.

```<code>alu alu(.alucontrol, .aluout, .zero, .srca, .srcb);
</code>```

And finally, if all the port names match the signal names, you can use a wildcard, .* as well as list exceptions explicitly

```<code>alu alu(.*, .zero(my_zero));
</code>```

Title: Connections between sub modules wrong

Body:
My codes for Alu and Mux:

module alu(input logic [31:0]srca, srcb,
          input logic [2:0] alucontrol,
          output logic zero,
          output logic [31:0]aluout);

logic [31:0] addr, subr, sltr, Andr, Orr;
assign addr = srca + srcb;
assign subr = srca - srcb;
assign sltr = (srca < srcb) ? 1 : 0;
assign Andr = srca & srcb;
assign Orr = srca | srcb;
always_comb
begin
case(alucontrol)
    3'b010: aluout = addr;
    3'b110: aluout = subr;
    3'b111: aluout = sltr;
    3'b000: aluout = Andr;
    3'b001: aluout = Orr;
    default: aluout = 32'bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
endcase
zero = (subr == 0) ?  1 : 0;
end
endmodule

module mux2#(parameter WIDTH = 8)
                (input logic [WIDTH-1:0] d0, d1,
                 input logic                 s,
                 output logic [WIDTH-1:0] y);
always_comb
begin
y = s?d1 : d0;
end
endmodule

and their instantiation under the same top module:

alu         alu(srca, srcb, alucontrol, aluout, zero);

mux2 #(32) resmux(aluout, readdata, memtoreg, result);

When I try to connect my 2-1Mux resmux with my alu, the aluout doesn't get connected to resmux

aluout gets suspended

I could solve this by exchanging the order of aluout and zero, but could anybody explain why this happens and how to avoid? Thanks a lot!

Body:
There are a number of mechanisms for connecting ports in SystemVerilog. The mechanism you are using is positional. That means each signal connection has to go in the prescribed order that they appear in the module declaration of alu. The way your code is written, the signal zero in module top is connected to last port aluout declared in module alu.

SystemVerilog also has a by_name syntax .portname(signal). You can list all your port connections in any order that way.

alu   alu(.srca(srca), .srcb(srcb), .alucontrol(alucontrol), .alu(aluout), .zero(zero));

When the signal name you are connecting matches the declared port name, you can just use .portname.

alu alu(.alucontrol, .aluout, .zero, .srca, .srcb);

And finally, if all the port names match the signal names, you can use a wildcard, .* as well as list exceptions explicitly

alu alu(.*, .zero(my_zero));


问:
Could not find path in schema while using arrayfilters in mongoose
This is my shema in mongoose

```<code>import {Schema, model} from 'mongoose'

const EmployeeSchema = new Schema({
    employeeCode: {
        type: String,
    },
    name: {
        type: String,

    },
    appraisal: {
        status: {
            type: String,
            enum: ["not started", "in progress", "completed", "not started", "self rating"],
            default: "not started"
        },
        objective_group: [{
            name: {
                type: Schema.Types.ObjectId,
                ref: "ObjectiveGroup",
                required: true
            },
            value: {
                type: Number,
            },
            objective_type: [{
                name: {
                    type: Schema.Types.ObjectId,
                    ref: "ObjectiveType",
                    required: true
                },
                value: {
                    type: Number,
                },

                objective_description: [{
                    name: {
                        type: Schema.Types.ObjectId,
                        ref: "ObjectiveDescription",
                        required: true
                    },
                    value: {
                        type: Number,
                    },
                    ratings: {
                        type: {
                            type: Schema.Types.ObjectId,
                            ref: "Ratings",

                        }
                    },

                }],
                training_recommendation: {
                    type: Schema.Types.ObjectId,
                    ref: 'TrainingRecommendation'
                },
                other_recommendation: {
                    type: Schema.Types.ObjectId,
                    ref: 'OtherRecommendation'
                },
            }],
        }],
    },
})

export default model('Employee', EmployeeSchema)
</code>```

Here is my code for the following task

```<code>const updateValue = asyncHandler(async (req: Request, res: Response) => {

    const {id, rating} = req.body

    const employee = await Employee.findOneAndUpdate({
            "_id": "6204935ebca89023952f2da9",
            "appraisal.objective_group._id": "6207ec6a8bfc1226d3f36fb1"
        },
    {
            $set: {
                "appraisal.$[objective_group].value": 1234
            }
        },
        {

            arrayFilters: [
                {
                    'objective_group._id':  new mongoose.Types.ObjectId("6207ec6a8bfc1226d3f36fb1")
                }
            ]
        }
    )
    res.status(StatusCodes.OK).json({
        employee
    });
})
</code>```

Here I am trying to update the value field in objective_group. To achieve this I am using arrayfilter. But I am getting this Error

Error: Could not find path "appraisal.0._id" in schema

When I am mongoose v6 it's showing this error. on mongoose v5 I am not getting any errors but the operation is not succeeding

There is the possibility that I am not using arrayfilters in the right way because inside objective_group I am storing objects inside the array.

I am new to StackOverflow so sorry for some mistakes

答:
You just have a slight error with the path you're providing, the error means that the path you gave resolved into a none array value.

You just need to change your update part from:

```<code>"appraisal.$[objective_group].value": 1234
</code>```

To:

```<code>"appraisal.objective_group.$[objective_group].value": 1234
</code>```

Like so:

```<code>db.collection.update({
  "_id": "6204935ebca89023952f2da9",
  "appraisal.objective_group._id": ObjectId("6207ec6a8bfc1226d3f36fb1")
},
{
  $set: {
    "appraisal.objective_group.$[group].value": 1234
  }
},
{
  arrayFilters: [
    {
      "group._id": ObjectId("6207ec6a8bfc1226d3f36fb1")
    }
  ]
})
</code>```

Mongo Playground

Body:
This is my shema in mongoose

import {Schema, model} from 'mongoose'

const EmployeeSchema = new Schema({
    employeeCode: {
        type: String,
    },
    name: {
        type: String,

    },
    appraisal: {
        status: {
            type: String,
            enum: ["not started", "in progress", "completed", "not started", "self rating"],
            default: "not started"
        },
        objective_group: [{
            name: {
                type: Schema.Types.ObjectId,
                ref: "ObjectiveGroup",
                required: true
            },
            value: {
                type: Number,
            },
            objective_type: [{
                name: {
                    type: Schema.Types.ObjectId,
                    ref: "ObjectiveType",
                    required: true
                },
                value: {
                    type: Number,
                },

                objective_description: [{
                    name: {
                        type: Schema.Types.ObjectId,
                        ref: "ObjectiveDescription",
                        required: true
                    },
                    value: {
                        type: Number,
                    },
                    ratings: {
                        type: {
                            type: Schema.Types.ObjectId,
                            ref: "Ratings",

                        }
                    },

                }],
                training_recommendation: {
                    type: Schema.Types.ObjectId,
                    ref: 'TrainingRecommendation'
                },
                other_recommendation: {
                    type: Schema.Types.ObjectId,
                    ref: 'OtherRecommendation'
                },
            }],
        }],
    },
})

export default model('Employee', EmployeeSchema)

Here is my code for the following task

const updateValue = asyncHandler(async (req: Request, res: Response) => {

    const {id, rating} = req.body

    const employee = await Employee.findOneAndUpdate({
            "_id": "6204935ebca89023952f2da9",
            "appraisal.objective_group._id": "6207ec6a8bfc1226d3f36fb1"
        },
    {
            $set: {
                "appraisal.$[objective_group].value": 1234
            }
        },
        {

            arrayFilters: [
                {
                    'objective_group._id':  new mongoose.Types.ObjectId("6207ec6a8bfc1226d3f36fb1")
                }
            ]
        }
    )
    res.status(StatusCodes.OK).json({
        employee
    });
})

Here I am trying to update the value field in objective_group. To achieve this I am using arrayfilter. But I am getting this Error

Error: Could not find path "appraisal.0._id" in schema

When I am mongoose v6 it's showing this error. on mongoose v5 I am not getting any errors but the operation is not succeeding

There is the possibility that I am not using arrayfilters in the right way because inside objective_group I am storing objects inside the array.

I am new to StackOverflow so sorry for some mistakes

Body:
You just have a slight error with the path you're providing, the error means that the path you gave resolved into a none array value.

You just need to change your update part from:

"appraisal.$[objective_group].value": 1234

To:

"appraisal.objective_group.$[objective_group].value": 1234

Like so:

db.collection.update({
  "_id": "6204935ebca89023952f2da9",
  "appraisal.objective_group._id": ObjectId("6207ec6a8bfc1226d3f36fb1")
},
{
  $set: {
    "appraisal.objective_group.$[group].value": 1234
  }
},
{
  arrayFilters: [
    {
      "group._id": ObjectId("6207ec6a8bfc1226d3f36fb1")
    }
  ]
})

Mongo Playground


问:
I'm having trouble in generating hash string in javascript
I'm trying to integrate the payment gateway in WHMCS as a module; the script does not generate the hashkey as per following format; & payment gateway returns error of information not completed; thus; reference : the following URL works fine :

Sample Code by Gateway that works 100%:  https://websol.biz/order/modules/gateways/test.php

```<code>Hashkey Generated as per following format

99yv9hbw88&1000&TBANK&billRef&Description of transaction&EN&MC10761&9x19xxy1uv&RETL&https://websol.biz/&PKR&20200802112944
&20200803112944&T20200802112944&1.1&1&2&3&4&5
</code>```

My Module Code:

```<code><?php
/**
 * WHMCS Jazzcash Payment Gateway Module
 *
 * Payment Gateway modules allow you to integrate payment solutions with the
 * WHMCS platform.
 *
 * This sample file demonstrates how a payment gateway module for WHMCS should
 * be structured and all supported functionality it can contain.
 *
 * Within the module itself, all functions must be prefixed with the module
 * filename, followed by an underscore, and then the function name. For this
 * example file, the filename is "jazzcash" and therefore all functions
 * begin "jazzcash_".
 *
 * If your module or third party API does not support a given function, you
 * should not define that function within your module. Only the _config
 * function is required.
 *
 * For more information, please refer to the online documentation.
 *
 * @see https://developers.whmcs.com/payment-gateways/
 *
 * @copyright Copyright (c) WHMCS Limited 2017
 * @license http://www.whmcs.com/license/ WHMCS Eula
 */

if (!defined("WHMCS")) {
    die("This file cannot be accessed directly");
}

/**
 * Define module related meta data.
 *
 * Values returned here are used to determine module related capabilities and
 * settings.
 *
 * @see https://developers.whmcs.com/payment-gateways/meta-data-params/
 *
 * @return array
 */
function jazzcash_MetaData()
{
    return array(
        'DisplayName' => 'JazzCash Payment Gateway Module',
        'APIVersion' => '1.1', // Use API Version 1.1
        'DisableLocalCredtCardInput' => false,
        'TokenisedStorage' => false,
    );
}

/**
 * Define gateway configuration options.
 *
 * The fields you define here determine the configuration options that are
 * presented to administrator users when activating and configuring your
 * payment gateway module for use.
 *
 * Supported field types include:
 * * text
 * * password
 * * yesno
 * * dropdown
 * * radio
 * * textarea
 *
 * Examples of each field type and their possible configuration parameters are
 * provided in the sample function below.
 *
 * @return array
 */
function jazzcash_config()
{
    return array(
        // the friendly display name for a payment gateway should be
        // defined here for backwards compatibility
         'FriendlyName' => array(
            'Type' => 'System',
            'Value' => 'JazzCash',
        ),
        // a text field type allows for single line text input
        'merchantID' => array(
            'FriendlyName' => 'Merchant ID',
            'Type' => 'text',
            'Size' => '25',
            'Default' => '',
            'Description' => 'Enter your Merchant ID here',
        ),
        // a password field type allows for masked text input
        'salt' => array(
            'FriendlyName' => 'Integerity Salt',
            'Type' => 'text',
            'Size' => '25',
            'Default' => '',
            'Description' => 'Enter Integerity Salt key here',
        ),
        'password' => array(
            'FriendlyName' => 'Integerity Password',
            'Type' => 'password',
            'Size' => '25',
            'Default' => '',
            'Description' => 'Enter Integerity Password here',
        ),
        /*'securehash' => array(
            'FriendlyName' => 'SecureHash',
            'Type' => 'text',
            'Size' => '255',
            'Default' => '',
            'Description' => 'Enter SecureHash here',
        ),*/
    );
}

/**
 * Payment link.
 *
 * Required by third party payment gateway modules only.
 *
 * Defines the HTML output displayed on an invoice. Typically consists of an
 * HTML form that will take the user to the payment gateway endpoint.
 *
 * @param array $params Payment Gateway Module Parameters
 *
 * @see https://developers.whmcs.com/payment-gateways/third-party-gateway/
 *
 * @return string
 */
function jazzcash_link($params)
{

    // Gateway Configuration Parameters
    $merchantID = $params['merchantID'];
    $moduleDisplayName = $params['name'];
    $password = $params['password'];
    $salt = $params['salt'];
    //$securehash = $params['securehash'];

    // Invoice Parameters
    $invoiceId = $params['invoiceid'];
    $invoicenum = $params['invoicenum'];
    $dueDate = $params['dueDate'];
    $description = $params["description"];
    $amount = $params['amount'];
    $currencyCode = $params['currency'];

    // System Parameters
    $companyName = $params['companyname'];
    $systemUrl = $params['systemurl'];
    $returnUrl = $params['returnurl'];
    $langPayNow = $params['langpaynow'];
    $moduleName = $params['paymentmethod'];
    $whmcsVersion = $params['whmcsVersion'];

    $url = 'https://sandbox.jazzcash.com.pk/CustomerPortal/transactionmanagement/merchantform/';

    $postfields = array();
    $postfields['pp_Version'] = '1.1';

    //DD -Direct Debit
    //MIGS - Card Payment
    //MWALLET - Mobile Voucher
    //OTC - Voucher Payment

    $postfields['pp_TxnType'] = '';
    $postfields['pp_Language'] = 'EN';
    $postfields['pp_MerchantID'] = $merchantID;
    $postfields['pp_SubMerchantID'] = '';
    $postfields['pp_Password'] = $password;
    $postfields['pp_BankID'] = 'TBANK';
    $postfields['pp_ProductID'] = 'RETL';

    //generate the referenec number
    $postfields['pp_TxnRefNo'] = 'T'. $invoicenum . '' . rand(1111111111 , 9999999999) ;

    $postfields['pp_Amount'] = str_replace('.' , '' ,$amount);
    $postfields['pp_TxnCurrency'] = 'PKR';

    //Generate it Like 20180523111537 - yyyyMMddHHmmss
    $postfields['pp_TxnDateTime'] = date('YmdHis');

    $postfields['pp_BillReference'] = $invoiceId;
    $postfields['pp_Description'] = $description;

    //Generate The Time Like: 20180524111537
    $postfields['pp_TxnExpiryDateTime'] = date('YmdHis' , strtotime(date('YmdHis'). ' + 2 days'));

    //$postfields['callback_url'] = $systemUrl . '/modules/gateways/callback/' . $moduleName . '.php';
    $postfields['pp_ReturnURL'] = $returnUrl;
    //$postfields['pp_ReturnURL'] = urlencode('http://hosting.kayecommerce.net/viewinvoice.php');

    //pp_SecureHash
    //$securehash;
    $postfields['pp_SecureHash'] = '';
    $postfields['ppmpf_1'] = '1';
    $postfields['ppmpf_2'] = '2';
    $postfields['ppmpf_3'] = '3';
    $postfields['ppmpf_4'] = '4';
    $postfields['ppmpf_5'] = '5';

    ?>

                    <script>
                                            function submitForm() {

                                                CalculateHash();
                                                var IntegritySalt = document.getElementById("salt").innerText;
                                                var hash = CryptoJS.HmacSHA256(document.getElementById("hashValuesString").value, IntegritySalt);
                                                document.getElementsByName("pp_SecureHash")[0].value = hash + '';

                                                console.log('string: ' + hashString);
                                                console.log('hash: ' + document.getElementsByName("pp_SecureHash")[0].value);

                                                document.jsform.submit();
                                            }

                                        </script>
                                        <script src="https://sandbox.jazzcash.com.pk/Sandbox/Scripts/hmac-sha256.js"></script>

    <?php

    $htmlOutput = '

                                        <div class="jsformWrapper">';
                       $htmlOutput .= '<form name="jsform" method="post" action="' . $url . '">' ;

    foreach ($postfields as $k => $v) {
        $htmlOutput .= '<input type="text" name="' . $k . '" value="'.$v.'">' ;
    }

    $htmlOutput .= '<button type="button" class="text-center" onclick="submitForm()">' . $langPayNow . '</button><!--<input type="submit" onclick="submitForm()" value="' . $langPayNow . '" />-->';
    $htmlOutput .= '</form>';

                                        $htmlOutput .= '<label id="salt" style="display:none;">'.$salt.'</label>
                                            <br><br>
                                            <div class="formFielWrapper">

                                                <input type="hidden" id="hashValuesString" value="">
                                                <br><br>
                                            </div>

                                        </div>';

    ?>

                  <script>
                                            function CalculateHash() {
                                                var IntegritySalt = document.getElementById("salt").innerText;
                                                hashString = '';

                                                hashString += IntegritySalt + '&';

                                                if (document.getElementsByName("pp_Amount")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_Amount")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_BankID")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_BankID")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_BillReference")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_BillReference")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_Description")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_Description")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_Language")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_Language")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_MerchantID")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_MerchantID")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_Password")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_Password")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_ProductID")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_ProductID")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_ReturnURL")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_ReturnURL")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_SubMerchantID")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_SubMerchantID")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_TxnCurrency")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_TxnCurrency")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_TxnDateTime")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_TxnDateTime")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_TxnExpiryDateTime")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_TxnExpiryDateTime")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_TxnRefNo")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_TxnRefNo")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_TxnType")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_TxnType")[0].value + '&';
                                                }
                                                if (document.getElementsByName("pp_Version")[0].value != '') {
                                                    hashString += document.getElementsByName("pp_Version")[0].value + '&';
                                                }
                                                if (document.getElementsByName("ppmpf_1")[0].value != '') {
                                                    hashString += document.getElementsByName("ppmpf_1")[0].value + '&';
                                                }
                                                if (document.getElementsByName("ppmpf_2")[0].value != '') {
                                                    hashString += document.getElementsByName("ppmpf_2")[0].value + '&';
                                                }
                                                if (document.getElementsByName("ppmpf_3")[0].value != '') {
                                                    hashString += document.getElementsByName("ppmpf_3")[0].value + '&';
                                                }
                                                if (document.getElementsByName("ppmpf_4")[0].value != '') {
                                                    hashString += document.getElementsByName("ppmpf_4")[0].value + '&';
                                                }
                                                if (document.getElementsByName("ppmpf_5")[0].value != '') {
                                                    hashString += document.getElementsByName("ppmpf_5")[0].value + '&';
                                                }

                                                hashString = hashString.slice(0, -1);
                                                document.getElementById("hashValuesString").value = hashString;
                                            }

                                        </script>

    <?php

    return $htmlOutput;

}
?>

<?php

/**
 * Refund transaction.
 *
 * Called when a refund is requested for a previously successful transaction.
 *
 * @param array $params Payment Gateway Module Parameters
 *
 * @see https://developers.whmcs.com/payment-gateways/refunds/
 *
 * @return array Transaction response status
 */
function jazzcash_refund($params)
{
    return true;
}

/**
 * Cancel subscription.
 *
 * If the payment gateway creates subscriptions and stores the subscription
 * ID in tblhosting.subscriptionid, this function is called upon cancellation
 * or request by an admin user.
 *
 * @param array $params Payment Gateway Module Parameters
 *
 * @see https://developers.whmcs.com/payment-gateways/subscription-management/
 *
 * @return array Transaction response status
 */
function jazzcash_cancelSubscription($params)
{
    return true;
}

?>
</code>```

Generate the following Hashkey:

```<code>ad12f44e5e7dfd135d204b6e31229e3b13232a180493f26e61a15251333899a8
</code>```

答:
Why not you try in PHP, its very Easy and Clean way in PHP, Here is my code,</p>
```<code>    ksort($postfields); //Sort in Assendig order
    $str = $integrity_salt;  //Your Seceret key to add
    foreach($postfields as $key => $value)
    {
        if(!empty($value) && $value != 'undefined' && $value != null && $value != '' && $value)
        {
            $str .=  "&".$value;
        }
    }

    $pp_SecureHash = hash_hmac('sha256', $str, $integrity_salt);
</code>```

Body:
I'm trying to integrate the payment gateway in WHMCS as a module; the script does not generate the hashkey as per following format; & payment gateway returns error of information not completed; thus; reference : the following URL works fine :

Sample Code by Gateway that works 100%:  https://websol.biz/order/modules/gateways/test.php

Hashkey Generated as per following format

99yv9hbw88&1000&TBANK&billRef&Description of transaction&EN&MC10761&9x19xxy1uv&RETL&https://websol.biz/&PKR&20200802112944
&20200803112944&T20200802112944&1.1&1&2&3&4&5

My Module Code:

<?php
/**
 * WHMCS Jazzcash Payment Gateway Module
 *
 * Payment Gateway modules allow you to integrate payment solutions with the
 * WHMCS platform.
 *
 * This sample file demonstrates how a payment gateway module for WHMCS should
 * be structured and all supported functionality it can contain.
 *
 * Within the module itself, all functions must be prefixed with the module
 * filename, followed by an underscore, and then the function name. For this
 * example file, the filename is "jazzcash" and therefore all functions
 * begin "jazzcash_".
 *
 * If your module or third party API does not support a given function, you
 * should not define that function within your module. Only the _config
 * function is required.
 *
 * For more information, please refer to the online documentation.
 *
 * @see https://developers.whmcs.com/payment-gateways/
 *
 * @copyright Copyright (c) WHMCS Limited 2017
 * @license http://www.whmcs.com/license/ WHMCS Eula
 */

if (!defined("WHMCS")) {
    die("This file cannot be accessed directly");
}

/**
 * Define module related meta data.
 *
 * Values returned here are used to determine module related capabilities and
 * settings.
 *
 * @see https://developers.whmcs.com/payment-gateways/meta-data-params/
 *
 * @return array
 */
function jazzcash_MetaData()
{
    return array(
        'DisplayName' => 'JazzCash Payment Gateway Module',
        'APIVersion' => '1.1', // Use API Version 1.1
        'DisableLocalCredtCardInput' => false,
        'TokenisedStorage' => false,
    );
}

/**
 * Define gateway configuration options.
 *
 * The fields you define here determine the configuration options that are
 * presented to administrator users when activating and configuring your
 * payment gateway module for use.
 *
 * Supported field types include:
 * * text
 * * password
 * * yesno
 * * dropdown
 * * radio
 * * textarea
 *
 * Examples of each field type and their possible configuration parameters are
 * provided in the sample function below.
 *
 * @return array
 */
function jazzcash_config()
{
    return array(
        // the friendly display name for a payment gateway should be
        // defined here for backwards compatibility
         'FriendlyName' => array(
            'Type' => 'System',
            'Value' => 'JazzCash',
        ),
        // a text field type allows for single line text input
        'merchantID' => array(
            'FriendlyName' => 'Merchant ID',
            'Type' => 'text',
            'Size' => '25',
            'Default' => '',
            'Description' => 'Enter your Merchant ID here',
        ),
        // a password field type allows for masked text input
        'salt' => array(
            'FriendlyName' => 'Integerity Salt',
            'Type' => 'text',
            'Size' => '25',
            'Default' => '',
            'Description' => 'Enter Integerity Salt key here',
        ),
        'password' => array(
            'FriendlyName' => 'Integerity Password',
            'Type' => 'password',
            'Size' => '25',
            'Default' => '',
            'Description' => 'Enter Integerity Password here',
        ),
        /*'securehash' => array(
            'FriendlyName' => 'SecureHash',
            'Type' => 'text',
            'Size' => '255',
            'Default' => '',
            'Description' => 'Enter SecureHash here',
        ),*/
    );
}

/**
 * Payment link.
 *
 * Required by third party payment gateway modules only.
 *
 * Defines the HTML output displayed on an invoice. Typically consists of an
 * HTML form that will take the user to the payment gateway endpoint.
 *
 * @param array $params Payment Gateway Module Parameters
 *
 * @see https://developers.whmcs.com/payment-gateways/third-party-gateway/
 *
 * @return string
 */
function jazzcash_link($params)
{

    // Gateway Configuration Parameters
    $merchantID = $params['merchantID'];
    $moduleDisplayName = $params['name'];
    $password = $params['password'];
    $salt = $params['salt'];
    //$securehash = $params['securehash'];

    // Invoice Parameters
    $invoiceId = $params['invoiceid'];
    $invoicenum = $params['invoicenum'];
    $dueDate = $params['dueDate'];
    $description = $params["description"];
    $amount = $params['amount'];
    $currencyCode = $params['currency'];

    // System Parameters
    $companyName = $params['companyname'];
    $systemUrl = $params['systemurl'];
    $returnUrl = $params['returnurl'];
    $langPayNow = $params['langpaynow'];
    $moduleName = $params['paymentmethod'];
    $whmcsVersion = $params['whmcsVersion'];

    $url = 'https://sandbox.jazzcash.com.pk/CustomerPortal/transactionmanagement/merchantform/';

    $postfields = array();
    $postfields['pp_Version'] = '1.1';

    //DD -Direct Debit
    //MIGS - Card Payment
    //MWALLET - Mobile Voucher
    //OTC - Voucher Payment

    $postfields['pp_TxnType'] = '';
    $postfields['pp_Language'] = 'EN';
    $postfields['pp_MerchantID'] = $merchantID;
    $postfields['pp_SubMerchantID'] = '';
    $postfields['pp_Password'] = $password;
    $postfields['pp_BankID'] = 'TBANK';
    $postfields['pp_ProductID'] = 'RETL';

    //generate the referenec number
    $postfields['pp_TxnRefNo'] = 'T'. $invoicenum . '' . rand(1111111111 , 9999999999) ;

    $postfields['pp_Amount'] = str_replace('.' , '' ,$amount);
    $postfields['pp_TxnCurrency'] = 'PKR';

    //Generate it Like 20180523111537 - yyyyMMddHHmmss
    $postfields['pp_TxnDateTime'] = date('YmdHis');

    $postfields['pp_BillReference'] = $invoiceId;
    $postfields['pp_Description'] = $description;

    //Generate The Time Like: 20180524111537
    $postfields['pp_TxnExpiryDateTime'] = date('YmdHis' , strtotime(date('YmdHis'). ' + 2 days'));

    //$postfields['callback_url'] = $systemUrl . '/modules/gateways/callback/' . $moduleName . '.php';
    $postfields['pp_ReturnURL'] = $returnUrl;
    //$postfields['pp_ReturnURL'] = urlencode('http://hosting.kayecommerce.net/viewinvoice.php');

    //pp_SecureHash
    //$securehash;
    $postfields['pp_SecureHash'] = '';
    $postfields['ppmpf_1'] = '1';
    $postfields['ppmpf_2'] = '2';
    $postfields['ppmpf_3'] = '3';
    $postfields['ppmpf_4'] = '4';
    $postfields['ppmpf_5'] = '5';

    ?>

    <?php

    $htmlOutput = '

';
                       $htmlOutput .= '<form name="jsform" method="post" action="' . $url . '">' ;

    foreach ($postfields as $k => $v) {
        $htmlOutput .= '<input type="text" name="' . $k . '" value="'.$v.'">' ;
    }

    $htmlOutput .= '<button type="button" class="text-center" onclick="submitForm()">' . $langPayNow . '</button>';
    $htmlOutput .= '</form>';

                                        $htmlOutput .= ''.$salt.'

                                                <input type="hidden" id="hashValuesString" value="">

';

    ?>

    <?php

    return $htmlOutput;

}
?>

<?php

/**
 * Refund transaction.
 *
 * Called when a refund is requested for a previously successful transaction.
 *
 * @param array $params Payment Gateway Module Parameters
 *
 * @see https://developers.whmcs.com/payment-gateways/refunds/
 *
 * @return array Transaction response status
 */
function jazzcash_refund($params)
{
    return true;
}

/**
 * Cancel subscription.
 *
 * If the payment gateway creates subscriptions and stores the subscription
 * ID in tblhosting.subscriptionid, this function is called upon cancellation
 * or request by an admin user.
 *
 * @param array $params Payment Gateway Module Parameters
 *
 * @see https://developers.whmcs.com/payment-gateways/subscription-management/
 *
 * @return array Transaction response status
 */
function jazzcash_cancelSubscription($params)
{
    return true;
}

?>

Generate the following Hashkey:

ad12f44e5e7dfd135d204b6e31229e3b13232a180493f26e61a15251333899a8

Body:
Why not you try in PHP, its very Easy and Clean way in PHP, Here is my code,

    ksort($postfields); //Sort in Assendig order
    $str = $integrity_salt;  //Your Seceret key to add
    foreach($postfields as $key => $value)
    {
        if(!empty($value) && $value != 'undefined' && $value != null && $value != '' && $value)
        {
            $str .=  "&".$value;
        }
    }

    $pp_SecureHash = hash_hmac('sha256', $str, $integrity_salt);


问:
Angular Ivy strictTemplates Argument of type 'Event' is not assignable to parameter of type 'InputEvent'
I really don't understand what's
the problem is with this code

```<code><input #quantity type="number" matInput formControlName="quantity" (input)="onQuantity($event, i)" placeholder="Quantity"/>

onQuantity(event: InputEvent, i: number) {
    if (!this.totals[i]) {
      this.totals[i] = { price: '0', quantity: 1 };
    }
    let value = (event.target as HTMLInputElement).value;
    value = value ? value : '0';
    this.totals[i].quantity = parseInt(value, 10);
  }
</code>```

The compiler get an error
Argument of type 'Event' is not assignable to parameter of type 'InputEvent'.
and if I use

```<code>onQuantity(event: Event, i: number)
</code>```

I get
Type 'Event' is missing the following properties from type 'InputEvent': data, inputType, isComposing, detail, and 2 more.

so I don't known what way to turn :(
Can anyone help me, please?

UPDATE

I have worked it out with

```<code>(input)="onQuantity(quantity.value, i)"
</code>```

https://angular.io/guide/user-input

答: use (input)="onQuantity($any($event), i)" in html template</p>

Body:
I really don't understand what's
the problem is with this code

<input #quantity type="number" matInput formControlName="quantity" (input)="onQuantity($event, i)" placeholder="Quantity"/>

onQuantity(event: InputEvent, i: number) {
    if (!this.totals[i]) {
      this.totals[i] = { price: '0', quantity: 1 };
    }
    let value = (event.target as HTMLInputElement).value;
    value = value ? value : '0';
    this.totals[i].quantity = parseInt(value, 10);
  }

The compiler get an error
Argument of type 'Event' is not assignable to parameter of type 'InputEvent'.
and if I use

onQuantity(event: Event, i: number)

I get
Type 'Event' is missing the following properties from type 'InputEvent': data, inputType, isComposing, detail, and 2 more.

so I don't known what way to turn :(
Can anyone help me, please?

UPDATE

I have worked it out with

(input)="onQuantity(quantity.value, i)"

https://angular.io/guide/user-input


问:
java - automatically printing stack traces for uncaught exceptions
Is there a way to have java print a stack trace to console for all uncaught exceptions like in many IDEs, other than overwriting the uncaught exception handler in the thread/threadgroup?</p>

答: I'm not sure I understand your question. What you describe is already the default behavior of most if not all JVMs: a thread that gets hit by an uncaught exception will print the stack trace and exit. If you want it to do something different, then the uncaught exception handler is the way to do it.</p>


问:
How to access user added metadata in pyspark?
I create a dataframe and added some metadata to a column in it

```<code>import pandas as pd
from pyspark.sql.functions import col

from pyspark.sql import column

df = spark.createDataFrame(pd.DataFrame({'a':[1,2,3],'b':[4,5,6]}))

df=df.withColumn('a',col('a').alias('a',metadata={'numClasses':2}))
</code>```

How can I access the metadata added to the column a?
I tried looking at df.schema but it does not get updated with the metadata

答:
Try the following way.</p>
```<code>print(df.schema['a'].metadata['numClasses'])
</code>```

Body:
I create a dataframe and added some metadata to a column in it

import pandas as pd
from pyspark.sql.functions import col

from pyspark.sql import column

df = spark.createDataFrame(pd.DataFrame({'a':[1,2,3],'b':[4,5,6]}))

df=df.withColumn('a',col('a').alias('a',metadata={'numClasses':2}))

How can I access the metadata added to the column a?
I tried looking at df.schema but it does not get updated with the metadata

Body:
Try the following way.

print(df.schema['a'].metadata['numClasses'])


问:
Is it possible to set quality in Image Intervention for WebP images?
I want to convert jpg to webp and set the quality to 50 (as an example). But the Image Intervention only supports the quality parameter only for jpg files.

quality (optional)

Define the quality of the encoded image optionally.
Data ranging from 0 (poor quality, small file) to 100 (best quality,
big file). Quality is only applied if you're encoding JPG format since
PNG compression is lossless and does not affect image quality.
Default: 90.

Is there any workaround?

答:
As specified in docs: https://image.intervention.io/v2/api/encode
You can encode the image in given format and given image quality.

```<code>$webp = Image::make('public/foo.png')->encode('webp', 75);
</code>```

I did this today and worked as expected. Try to encode both qualities 80 and 100 and you will note the size difference, also a quality difference if you set it under 80

Body:
As specified in docs: https://image.intervention.io/v2/api/encode
You can encode the image in given format and given image quality.

$webp = Image::make('public/foo.png')->encode('webp', 75);

I did this today and worked as expected. Try to encode both qualities 80 and 100 and you will note the size difference, also a quality difference if you set it under 80


问:
Custom php.ini file not working in VPS hosting
I've tried going through Network Solutions tech support but didn't get it resolved ("You need to talk to Signature Support, which is $50").
I'm running some sites off of a Net Sol VPS account and need to change the upload_max_filesize setting (which is apparently set to a paltry 2MB by default) for the php server. I've added:

```<code>upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 6000
</code>```

to the /httpdocs/cgi-bin/php.ini file (per NS's instructions), and then restarted apache, but when I run a phpinfo on that domain, the settings are not applied. It still says "2M" for the upload max.

I also tried adding this to the server root at /cgi-bin/php.ini as well, to no effect.

There is no /cgi-bin/.php/php.coalesced.ini file that I can see.

Any ideas? I'm losing my mind with this.

答:
You can't just litter PHP.ini files around and expect PHP to load them. If it's not been told to look for one in that cgi-bin directory, the file will just get ignored.

Check the phpinfo() output - the first section will tell you exactly what .ini files were located/parsed, and their location. e.g. on my home server:

```<code>Configuration File (php.ini) Path   /etc/php5/apache2
Loaded Configuration File   /etc/php5/apache2/php.ini
Scan this dir for additional .ini files     /etc/php5/apache2/conf.d
Additional .ini files parsed    /etc/php5/apache2/conf.d/curl.ini, /etc/php5/apache2/conf.d/gmp.ini, /etc/php5/apache2/conf.d/mysql.ini, /etc/php5/apache2/conf.d/mysqli.ini, /etc/php5/apache2/conf.d/pdo.ini, /etc/php5/apache2/conf.d/pdo_mysql.ini
</code>```

if your cgi-bin .ini file isn't listed, then PHP is NOT looking in that directory.

Body:
I've tried going through Network Solutions tech support but didn't get it resolved ("You need to talk to Signature Support, which is $50").
I'm running some sites off of a Net Sol VPS account and need to change the upload_max_filesize setting (which is apparently set to a paltry 2MB by default) for the php server. I've added:

upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 6000

to the /httpdocs/cgi-bin/php.ini file (per NS's instructions), and then restarted apache, but when I run a phpinfo on that domain, the settings are not applied. It still says "2M" for the upload max.

I also tried adding this to the server root at /cgi-bin/php.ini as well, to no effect.

There is no /cgi-bin/.php/php.coalesced.ini file that I can see.

Any ideas? I'm losing my mind with this.

Body:
You can't just litter PHP.ini files around and expect PHP to load them. If it's not been told to look for one in that cgi-bin directory, the file will just get ignored.

Check the phpinfo() output - the first section will tell you exactly what .ini files were located/parsed, and their location. e.g. on my home server:

Configuration File (php.ini) Path   /etc/php5/apache2
Loaded Configuration File   /etc/php5/apache2/php.ini
Scan this dir for additional .ini files     /etc/php5/apache2/conf.d
Additional .ini files parsed    /etc/php5/apache2/conf.d/curl.ini, /etc/php5/apache2/conf.d/gmp.ini, /etc/php5/apache2/conf.d/mysql.ini, /etc/php5/apache2/conf.d/mysqli.ini, /etc/php5/apache2/conf.d/pdo.ini, /etc/php5/apache2/conf.d/pdo_mysql.ini

if your cgi-bin .ini file isn't listed, then PHP is NOT looking in that directory.