问:
Another if statement to execute the goal function
I am making a matchmaking system where 2 players with the same weight will be matched. My target is when i have a nofight the player should not be matched with the entry ID. (More explanation below)

NOTE: my noFight is based on player's entryID.

const source = [
  {
    entryID: 1,
    entryName: "player1",
    weight: 1900,
    noFight: 2&3, //Will not be matched with entryID: 2 & 3

  },
  {
    entryID: 2,
    entryName: "player2",
    weight: 1900,
   noFight: 1&3&4, //Will not be matched with entryID: 1 & 2 & 3
  },
  {
    entryID: 3,
    entryName: "player3",
    weight: 1900,
    noFight: 1&2&4, //Will not be matched with entryID: 1 & 2 & 4
  },
    {
    entryID: 4,
    entryName: "player4",
    weight: 1900,
    noFight: 2&3&4, //Will not be matched with entryID: 2 & 3 & 4

  },

];

function combine(
  data = [],
  different = 0,
  maxGroupSize = 2,
  sortedStatement = (a, b) => a.weight - b.weight
) {
  const sortedData = [...data].sort(sortedStatement); // "weight" must be in ascending order

  const dataGroups = sortedData.reduce((acc, item) => {
    const findedAccItem = acc.find(
      (accItem) =>
        accItem.length < maxGroupSize && // if the array is not filled
        accItem[0].weight + different >= item.weight && // and if the minimum is in the acceptable range
        !accItem.find((obj) => obj.entryName === item.entryName /* || obj.entryID === item.nofight */) // I think i need to add more statement here. I have tried  obj.entryID === item.nofight but it is not working.
    );
    if (findedAccItem) {
      findedAccItem.push(item);
    } else {
      acc.push([item]);
    }
    return acc;
  }, []);

  const namedDataGroups = dataGroups.reduce((acc, item, index) => {
    // added an index as a prefix because the keys can match
    const key = [index, ...item.map((item) => item.weight)].join("_");
    acc[key] = item;
    return acc;
  }, {});

  return namedDataGroups;
}

// default example
console.log("Example #1: ", combine(source));```
</div>
</div>
</p>
<p>We can see the result on the snippet that <code>entryID: 1 & entryID: 2</code> has been matched. Same with  <code>entryID: 3 & entryID: 4</code>.</p>
<p>Now, if I achieve the goal of nofight. The result would be like this:</p>
```Example #1:  {
    "0_1900_1900": [
      {
        "entryID": 1,
        "entryName": "player1",
        "weight": 1900,
        "noFight": 2&3,
      },
      {
        "entryID": 4,
        "entryName": "player4",
        "weight": 1900,
        "noFight": 2&3&4,
      }
    ],

  }
```

Only entryID: 1 & entryID: 4 has been matched.

Any help will be appreciated. Thank you

答:
This might be an issue on my end, but I've never seen the syntax noFight: 2&3 used in this context, so my first step was changing this to arrays instead like so noFight: [2,3].

Once that's done all you need to do is check if the noFight array contains the current fighter being checked. And finally, when setting up the final data group you'll also need to check that the groups contain two fighters. Because of the way the reduce in the previous section works, you'll end up with an array that also contains single players who didn't get a match. You could probably push this logic somewhere inside the reduce but it's convoluted enough as is and this does the job.

Here's the updated code with comments on the changes.

const source = [
  {
    entryID: 1,
    entryName: "player1",
    weight: 1900,
    noFight: [2,3], // changed these to arrays
  },
  {
    entryID: 2,
    entryName: "player2",
    weight: 1900,
   noFight: [1,3,4],
  },
  {
    entryID: 3,
    entryName: "player3",
    weight: 1900,
    noFight: [1,2,4],
  },
    {
    entryID: 4,
    entryName: "player4",
    weight: 1900,
    noFight: [2,3,4],
  },
    { // added a new player that will fight anyone to test the logic
    entryID: 5,
    entryName: "player5",
    weight: 1900,
    noFight: [],
  },
];

function combine(
  data = [],
  different = 0,
  maxGroupSize = 2,
  sortedStatement = (a, b) => a.weight - b.weight
) {
  const sortedData = [...data].sort(sortedStatement);

  const dataGroups = sortedData.reduce((acc, item) => {
    const findedAccItem = acc.find(
      (accItem) =>
        accItem.length < maxGroupSize &&
        accItem[0].weight + different >= item.weight &&
        !accItem.find((obj) => obj.entryName === item.entryName || item.noFight.includes(obj.entryID)) // here we check if the fighter is in the noFight array or not
    );

    if (findedAccItem) {
      findedAccItem.push(item);
    } else {
      acc.push([item]);
    }

    return acc;
  }, []);

  const namedDataGroups = dataGroups.reduce((acc, item, index) => {
    if (item.length > 1) { // and finally we check that there are in fact two fighters in the grouping; without this you'll end up with  fighters that didn't get a match in the array as a result of how the reduce above works
      const key = [index, ...item.map((item) => item.weight)].join("_");
      acc[key] = item;
    }
    return acc;
  }, {});

  return namedDataGroups;
}

console.log("Example #1: ", combine(source));```

EDIT: A quick final thought on preference. Personally, I would remove the first reduce altogether and opt for traversing the array myself. I know you would lose some performance but the current method is incredibly difficult to read. That's just my 2c of course, but it would make life so much easier if you need to make changes in the future.

Body:
I am making a matchmaking system where 2 players with the same weight will be matched. My target is when i have a nofight the player should not be matched with the entry ID. (More explanation below)

NOTE: my noFight is based on player's entryID.

const source = [
  {
    entryID: 1,
    entryName: "player1",
    weight: 1900,
    noFight: 2&3, //Will not be matched with entryID: 2 & 3

  },
  {
    entryID: 2,
    entryName: "player2",
    weight: 1900,
   noFight: 1&3&4, //Will not be matched with entryID: 1 & 2 & 3
  },
  {
    entryID: 3,
    entryName: "player3",
    weight: 1900,
    noFight: 1&2&4, //Will not be matched with entryID: 1 & 2 & 4
  },
    {
    entryID: 4,
    entryName: "player4",
    weight: 1900,
    noFight: 2&3&4, //Will not be matched with entryID: 2 & 3 & 4

  },

];

function combine(
  data = [],
  different = 0,
  maxGroupSize = 2,
  sortedStatement = (a, b) => a.weight - b.weight
) {
  const sortedData = [...data].sort(sortedStatement); // "weight" must be in ascending order

  const dataGroups = sortedData.reduce((acc, item) => {
    const findedAccItem = acc.find(
      (accItem) =>
        accItem.length < maxGroupSize && // if the array is not filled
        accItem[0].weight + different >= item.weight && // and if the minimum is in the acceptable range
        !accItem.find((obj) => obj.entryName === item.entryName /* || obj.entryID === item.nofight */) // I think i need to add more statement here. I have tried  obj.entryID === item.nofight but it is not working.
    );
    if (findedAccItem) {
      findedAccItem.push(item);
    } else {
      acc.push([item]);
    }
    return acc;
  }, []);

  const namedDataGroups = dataGroups.reduce((acc, item, index) => {
    // added an index as a prefix because the keys can match
    const key = [index, ...item.map((item) => item.weight)].join("_");
    acc[key] = item;
    return acc;
  }, {});

  return namedDataGroups;
}

// default example
console.log("Example #1: ", combine(source));

We can see the result on the snippet that entryID: 1 & entryID: 2 has been matched. Same with  entryID: 3 & entryID: 4.

Now, if I achieve the goal of nofight. The result would be like this:

Example #1:  {
    "0_1900_1900": [
      {
        "entryID": 1,
        "entryName": "player1",
        "weight": 1900,
        "noFight": 2&3,
      },
      {
        "entryID": 4,
        "entryName": "player4",
        "weight": 1900,
        "noFight": 2&3&4,
      }
    ],

  }

Only entryID: 1 & entryID: 4 has been matched.

Any help will be appreciated. Thank you

Body:
This might be an issue on my end, but I've never seen the syntax noFight: 2&3 used in this context, so my first step was changing this to arrays instead like so noFight: [2,3].

Once that's done all you need to do is check if the noFight array contains the current fighter being checked. And finally, when setting up the final data group you'll also need to check that the groups contain two fighters. Because of the way the reduce in the previous section works, you'll end up with an array that also contains single players who didn't get a match. You could probably push this logic somewhere inside the reduce but it's convoluted enough as is and this does the job.

Here's the updated code with comments on the changes.

const source = [
  {
    entryID: 1,
    entryName: "player1",
    weight: 1900,
    noFight: [2,3], // changed these to arrays
  },
  {
    entryID: 2,
    entryName: "player2",
    weight: 1900,
   noFight: [1,3,4],
  },
  {
    entryID: 3,
    entryName: "player3",
    weight: 1900,
    noFight: [1,2,4],
  },
    {
    entryID: 4,
    entryName: "player4",
    weight: 1900,
    noFight: [2,3,4],
  },
    { // added a new player that will fight anyone to test the logic
    entryID: 5,
    entryName: "player5",
    weight: 1900,
    noFight: [],
  },
];

function combine(
  data = [],
  different = 0,
  maxGroupSize = 2,
  sortedStatement = (a, b) => a.weight - b.weight
) {
  const sortedData = [...data].sort(sortedStatement);

  const dataGroups = sortedData.reduce((acc, item) => {
    const findedAccItem = acc.find(
      (accItem) =>
        accItem.length < maxGroupSize &&
        accItem[0].weight + different >= item.weight &&
        !accItem.find((obj) => obj.entryName === item.entryName || item.noFight.includes(obj.entryID)) // here we check if the fighter is in the noFight array or not
    );

    if (findedAccItem) {
      findedAccItem.push(item);
    } else {
      acc.push([item]);
    }

    return acc;
  }, []);

  const namedDataGroups = dataGroups.reduce((acc, item, index) => {
    if (item.length > 1) { // and finally we check that there are in fact two fighters in the grouping; without this you'll end up with  fighters that didn't get a match in the array as a result of how the reduce above works
      const key = [index, ...item.map((item) => item.weight)].join("_");
      acc[key] = item;
    }
    return acc;
  }, {});

  return namedDataGroups;
}

console.log("Example #1: ", combine(source));

EDIT: A quick final thought on preference. Personally, I would remove the first reduce altogether and opt for traversing the array myself. I know you would lose some performance but the current method is incredibly difficult to read. That's just my 2c of course, but it would make life so much easier if you need to make changes in the future.


来源: stackexchange

问:
Tensorflow 2.0 Tensor Manipulation
wanted to reshape and combine two tensor in the tensorflow :

```<code>a = [[1, 3, 5],
     [7, 9, 11]]
</code>```

a.shape = (2, 3)

```<code>b = [[2, 2, 6],
     [8, 10, 12]]
</code>```

b.shape = (2, 3)

c = combine(a, b)

result of c should be :

```<code>c = [[[[1, 2], [3, 2], [5, 6]],
[[7, 8], [9, 10], [11, 12]]]]
</code>```

c.shape = (1, 2, 3, 2)

I need to convert a and b into c?

PS : Needed some tensor manipulation function in use like tf.concat, tf.reshape, looping is too slow to handle huge data. Numpy is also an option.

ContentLicense: CC BY-SA 4.0

Title: Tensorflow 2.0 Tensor Manipulation

Body:
wanted to reshape and combine two tensor in the tensorflow :

a = [[1, 3, 5],
     [7, 9, 11]]

a.shape = (2, 3)

b = [[2, 2, 6],
     [8, 10, 12]]

b.shape = (2, 3)

c = combine(a, b)

result of c should be :

c = [[[[1, 2], [3, 2], [5, 6]],
[[7, 8], [9, 10], [11, 12]]]]

c.shape = (1, 2, 3, 2)

I need to convert a and b into c?

PS : Needed some tensor manipulation function in use like tf.concat, tf.reshape, looping is too slow to handle huge data. Numpy is also an option.

Body:
You can try tf.stack and tf.expand_dims:

import tensorflow as tf

a = tf.constant([[1, 3, 5],
                [7, 9, 11]])

b = tf.constant([[2, 2, 6],
                  [8, 10, 12]])

c = tf.expand_dims(tf.stack([a, b], axis=-1), axis=0)

tf.Tensor(
[[[[ 1  2]
   [ 3  2]
   [ 5  6]]

  [[ 7  8]
   [ 9 10]
   [11 12]]]], shape=(1, 2, 3, 2), dtype=int32)

Or tf.stack and tf.newaxis

c = tf.stack([a, b], axis=-1)[tf.newaxis,...]

tf.Tensor(
[[[[ 1  2]
   [ 3  2]
   [ 5  6]]

  [[ 7  8]
   [ 9 10]
   [11 12]]]], shape=(1, 2, 3, 2), dtype=int32)


问:
Merging data in pandas
I have two pandas dataframes.

The first dataframe contains data recorded in millisecond intervals.

```<code>Time                  Price

1643669589971         145.77
1643669589977         145.78
1643669589984         145.79
</code>```

The second dataframe contains data recorded in 1 minute intervals.

```<code>Time                  Price

1643669589971         145.77
1643669649971         146.33
1643669709971         147.02
</code>```

I would like to map the equivalent last_minute data in the millisecond data like this.

```<code>Time                  Price        last_minute_time       last_minute_price

1643669589971         145.77       1643669589971          145.77
1643669589977         145.78       1643669589971          145.77
1643669589984         145.79       1643669589971          145.77
</code>```

Is there any easier way to do this in pandas?

Thanks

Title: Merging data in pandas

Body:
I have two pandas dataframes.

The first dataframe contains data recorded in millisecond intervals.

Time                  Price

1643669589971         145.77
1643669589977         145.78
1643669589984         145.79

The second dataframe contains data recorded in 1 minute intervals.

Time                  Price

1643669589971         145.77
1643669649971         146.33
1643669709971         147.02

I would like to map the equivalent last_minute data in the millisecond data like this.

Time                  Price        last_minute_time       last_minute_price

1643669589971         145.77       1643669589971          145.77
1643669589977         145.78       1643669589971          145.77
1643669589984         145.79       1643669589971          145.77

Is there any easier way to do this in pandas?

Thanks

Body:
Use merge_asof with DataFrame.add_prefix:

df = pd.merge_asof(df1,
                   df2.add_prefix('last_minute_'),
                   left_on='Time',
                   right_on='last_minute_Time')
print (df)
            Time   Price  last_minute_Time  last_minute_Price
0  1643669589971  145.77     1643669589971             145.77
1  1643669589977  145.78     1643669589971             145.77
2  1643669589984  145.79     1643669589971             145.77


问:
Learning about Computer Vision
I am really intrigued by the field of computer vision and the potential it has. Are there any examples (preferably implemented in .NET) which I can study along with a reference book?</p>

答:
I recommend Open Computer Vision Library. It's much spoken of and looks promising. It even has an O'Reilly accompanying book :)

The Open Computer Vision Library has >
  500 algorithms, documentation and
  sample code for real time computer
  vision. Tutorial documentation is in
  O'Reilly Book

OwnerDisplayName: Ali Kazmi

ContentLicense: CC BY-SA 2.5

Title: Learning about Computer Vision

LastEditorDisplayName: Gortok

OwnerDisplayName: dmondark


问:
LINQ vs context.entity.Where()
Are these two blocks exactly the same? Does one have any advantage over the other?</p>

```<code>        using (var context = new TRANSITEntities())
        {
            var result = context.Table1.Where(c => c.UserCode == "123");
        }

        using (var context = new TRANSITEntities())
        {
            var result = from c in context.Table1
                         where c.UserCode == "123"
                         select c;
        }
</code>```

答:
If you are trying to select from different tables then it is different.

But if the tables are same then it is just the representation different.

There is no difference it is just the preference which way you like to code.

All the linq queries are converted to Lambda before creating the sql representation.

ContentLicense: CC BY-SA 3.0

Title: LINQ vs context.entity.Where()

Body:
Are these two blocks exactly the same? Does one have any advantage over the other?

        using (var context = new TRANSITEntities())
        {
            var result = context.Table1.Where(c => c.UserCode == "123");
        }

        using (var context = new TRANSITEntities())
        {
            var result = from c in context.Table1
                         where c.UserCode == "123"
                         select c;
        }


问:
Missing compileSdkVersion for google mobile ads
```<code>defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.example.ringit2"
    minSdkVersion 21
    targetSdkVersion 30
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}
</code>```

Here is what I found on my build.gradle and I can't find compileSdkVersion which I have to change to at least 28 in order for google mobile ads to operate.

After I added google_mobile_ads: ^1.1.0 on pubspec.yaml and imported the package to the main.dart, The app opens as I run the simulator but shuts down right away. Console shows me this message and it is stuck just like this forever.

```<code>Launching lib\main.dart on SM G950N in debug mode...
Running Gradle task 'assembleDebug'...
√  Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
</code>```

Please note that my ext.kotlin_version is '1.6.10' because people have recommended to upgrade it

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
</code>```

Also changed the distributionUrl...

Not sure why google mobile ads package is so hard to use even just to start but what should I change to use it?

答: I am also using kotlin version '1.6.10' and compilesdk version is inside android>app>build.gradle

Body:
defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.example.ringit2"
    minSdkVersion 21
    targetSdkVersion 30
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

Here is what I found on my build.gradle and I can't find compileSdkVersion which I have to change to at least 28 in order for google mobile ads to operate.

After I added google_mobile_ads: ^1.1.0 on pubspec.yaml and imported the package to the main.dart, The app opens as I run the simulator but shuts down right away. Console shows me this message and it is stuck just like this forever.

Launching lib\main.dart on SM G950N in debug mode...
Running Gradle task 'assembleDebug'...
√  Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...

Please note that my ext.kotlin_version is '1.6.10' because people have recommended to upgrade it

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip

Also changed the distributionUrl...

Not sure why google mobile ads package is so hard to use even just to start but what should I change to use it?


问:
How to Retrieve downloaded file to play React-native
I'm using react-native-fetch-blob to download the File .
The File is residing at RNFS.DocumentDirectoryPath + fileExtension;
eq: RNFS.DocumentDirectoryPath /myMusic.mp3;

the downloaded file is located at

```<code>/data/user/0/com.myproject/files/myMusic.mp3
</code>```

and As per react-native-sound it is asking to place the files under raw folder.
when I follow the below code using react-native-fs, Its Playing !!!!

downloadFileAndPlay()
    {
        console.log('Download');

        const downloadDest = RNFS.DocumentDirectoryPath + '/sample.mp3';
        const ret = RNFS.downloadFile(
            {
                fromUrl: 'http://www.julien-gustin.be/files/sample.mp3',
                toFile: downloadDest
            }
        );
        ret.promise.then(res => {
            console.log(res);
            // Load the sound file 'whoosh.mp3' from the app bundle
            // See notes below about preloading sounds within initialization code below.
            console.log(downloadDest);
            var whoosh = new Sound(downloadDest, '', (error) => {
                if (error) {
                    console.log('failed to load the sound', error);
                    return;
                }
                // loaded successfully
                console.log('duration in seconds: ' + whoosh.getDuration() + 'number of channels: ' + whoosh.getNumberOfChannels());

                if(whoosh.isLoaded()){
                    console.log('LOADED');
                }else{
                    console.log('NOT LOADED');
                }

                // Play the sound with an onEnd callback
                whoosh.play((success) => {
                    if (success) {
                        console.log('successfully finished playing');
                    } else {
                        console.log('playback failed due to audio decoding errors');
                    }
                });
            });

        }).catch(err => {
            console.log(err);
        });
    }
```

in both places I'am using the same Directory path . But in our case its not playing ..
How can I retrieve the downloaded file and play While I am calling this file from another component?

答:
This works for me, but with react-native-video

<Video
    source={{ uri: "file://" + RNFS.DocumentDirectoryPath + "/Claymore-OP01-NCBD.mp4" }} />
```

so basically, add the schema before the path:

file://somepath.mp3

Body:
I'm using react-native-fetch-blob to download the File .
The File is residing at RNFS.DocumentDirectoryPath + fileExtension;
eq: RNFS.DocumentDirectoryPath /myMusic.mp3;

the downloaded file is located at

/data/user/0/com.myproject/files/myMusic.mp3

and As per react-native-sound it is asking to place the files under raw folder.
when I follow the below code using react-native-fs, Its Playing !!!!

downloadFileAndPlay()
    {
        console.log('Download');

        const downloadDest = RNFS.DocumentDirectoryPath + '/sample.mp3';
        const ret = RNFS.downloadFile(
            {
                fromUrl: 'http://www.julien-gustin.be/files/sample.mp3',
                toFile: downloadDest
            }
        );
        ret.promise.then(res => {
            console.log(res);
            // Load the sound file 'whoosh.mp3' from the app bundle
            // See notes below about preloading sounds within initialization code below.
            console.log(downloadDest);
            var whoosh = new Sound(downloadDest, '', (error) => {
                if (error) {
                    console.log('failed to load the sound', error);
                    return;
                }
                // loaded successfully
                console.log('duration in seconds: ' + whoosh.getDuration() + 'number of channels: ' + whoosh.getNumberOfChannels());

                if(whoosh.isLoaded()){
                    console.log('LOADED');
                }else{
                    console.log('NOT LOADED');
                }

                // Play the sound with an onEnd callback
                whoosh.play((success) => {
                    if (success) {
                        console.log('successfully finished playing');
                    } else {
                        console.log('playback failed due to audio decoding errors');
                    }
                });
            });

        }).catch(err => {
            console.log(err);
        });
    }

in both places I'am using the same Directory path . But in our case its not playing ..
How can I retrieve the downloaded file and play While I am calling this file from another component?

Body:
This works for me, but with react-native-video

<Video
    source={{ uri: "file://" + RNFS.DocumentDirectoryPath + "/Claymore-OP01-NCBD.mp4" }} />

so basically, add the schema before the path:

file://somepath.mp3


问:
gcloud crashed HTTPSConnectionPool
gcloud auth login not coming back to terminal on macos:

ERROR: gcloud crashed (ConnectionError):

HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x105347130>:

Failed to establish a new connection: [Errno 60] Operation timed out'))

gcloud auth login working fine on my other PC windows bash terminal with same Wifi.

Given read & write permissions to everyone of folder google-cloud-sdk

答: I tried both browser and no-browser options, but kept getting the problem. To resolve this, I connected my corporate VPN and the problem was solved.</p>

Title: gcloud crashed HTTPSConnectionPool


问:
Java API for xml type with JDBCthin driver
I have been trying to access an xmlType column-table from my java application the whole day and all I found is functions oracle.xdb.XMLType. But sadly I can't use those functions since almost all start with the basig getOPAQUE function wich is not supported by thin driver. And I can not use oci driver in my application. So my question is if u can help me with a java api to access xmlType data from Oracle database table with a connection of JDBC thing driver connection.
Regards.</p>

答: Take a look at this thread. It specifically states that its not supported by the thin driver , but then suggests some workarounds.</p>


问:
How to XOR two strings using Python?
If I have:

```<code>cipher_text1 =  "3b101c091d53320c000910"
cipher_text2 = "071d154502010a04000419"
</code>```

How do I XOR the two cipher texts using Python to get:

```<code>cipher_text1_XOR_cipher_text2 = "3c0d094c1f523808000d09"
</code>```

Thanks

答:
Start with the int() function, which allows you to specify a base in which to interpret a string to be converted to a numeric value.  The default base the function assumes is 10, but 16 works too and is what's appropriate for the strings you have.  So you convert your two strings to numeric values with int(), and then perform the XOR on those values.  Then, you apply the hex() function to the result convert it to a hex string. Finally, since you asked for a result without Ox at the front, you apply the appropriate slice to chop off the first two characters of what hex() returns:

```<code>cipher_text1 = "3b101c091d53320c000910"
cipher_text2 = "071d154502010a04000419"

cipher_text1_XOR_cipher_text2 = hex(int(cipher_text1, 16) ^ int(cipher_text2, 16))[2:]

print(cipher_text1_XOR_cipher_text2)
</code>```

Result:

```<code>3c0d094c1f523808000d09
</code>```

Title: How to XOR two strings using Python?

Body:
If I have:

cipher_text1 =  "3b101c091d53320c000910"
cipher_text2 = "071d154502010a04000419"

How do I XOR the two cipher texts using Python to get:

cipher_text1_XOR_cipher_text2 = "3c0d094c1f523808000d09"

Thanks

Body:
Start with the int() function, which allows you to specify a base in which to interpret a string to be converted to a numeric value.  The default base the function assumes is 10, but 16 works too and is what's appropriate for the strings you have.  So you convert your two strings to numeric values with int(), and then perform the XOR on those values.  Then, you apply the hex() function to the result convert it to a hex string. Finally, since you asked for a result without Ox at the front, you apply the appropriate slice to chop off the first two characters of what hex() returns:

cipher_text1 = "3b101c091d53320c000910"
cipher_text2 = "071d154502010a04000419"

cipher_text1_XOR_cipher_text2 = hex(int(cipher_text1, 16) ^ int(cipher_text2, 16))[2:]

print(cipher_text1_XOR_cipher_text2)

Result:

3c0d094c1f523808000d09


问:
How to select a particular field from javascript array
I have an array object in javascript. I would to select a particular field from all the rows of the object.

I have an object like

```<code>var sample = {
[Name:"a",Age:1],
[Name:"b",Age:2],
[Name:"c",Age:3]
}
</code>```

I would like to get an output of only Names as ["a","b","c"] without looping over sample object.

How can I select one or two fields using jlinq? or any other plugin?

Thanks a lot.

答:
```<code>let names = [];
this.dtoArray.forEach(arr => names.push(arr.name));
</code>```

Body:
I have an array object in javascript. I would to select a particular field from all the rows of the object.

I have an object like

var sample = {
[Name:"a",Age:1],
[Name:"b",Age:2],
[Name:"c",Age:3]
}

I would like to get an output of only Names as ["a","b","c"] without looping over sample object.

How can I select one or two fields using jlinq? or any other plugin?

Thanks a lot.


问:
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>

答:
You mean something like:

```<code>catch(MyException e){
    e.printStackTrace();
    throw e;
}
</code>```

?

Body:
You mean something like:

catch(MyException e){
    e.printStackTrace();
    throw e;
}

?


问:
Flex box column not equal width with flex: 1
Hi I am trying to make flex columns equal width but it doesn't seem to be working with flex: 1.

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.17/tailwind.min.css" rel="stylesheet" />

Box 1

Box 1 Flexbox 00000000

Box 2

Box 2 Flexbox 0

Box 3

Box 4 Flexbox 000

```

I want it to be the size of the flex col with the widest content.

答:
This is the solution I come to

If an element has flex: 1 , this means the size of all of the other elements will have the same width as their content, but the element with flex: 1 will have the remaining full space given to it.

Soln

You can use grid grid-cols-{n} to equally distribute a row into n number of columns . I had shared the code below .

    <link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.17/tailwind.min.css" rel="stylesheet" />

Box 1

Box 1 Flexbox 00000000

Box 2

Box 2 Flexbox 0

Box 3

Box 4 Flexbox 000

```

For more info refer the docs here

Body:
Hi I am trying to make flex columns equal width but it doesn't seem to be working with flex: 1.

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.17/tailwind.min.css" rel="stylesheet" />

Box 1

Box 1 Flexbox 00000000

Box 2

Box 2 Flexbox 0

Box 3

Box 4 Flexbox 000

I want it to be the size of the flex col with the widest content.

Body:
This is the solution I come to

If an element has flex: 1 , this means the size of all of the other elements will have the same width as their content, but the element with flex: 1 will have the remaining full space given to it.

Soln

You can use grid grid-cols-{n} to equally distribute a row into n number of columns . I had shared the code below .

    <link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.17/tailwind.min.css" rel="stylesheet" />

    <section class="flex flex-wrap w-full justify-center items-center content-center mt-20 lg:mt-0 min-h-85 fade fadeout">

      <div class="grid grid-cols-3 w-full md:w-1/3 max-w-md items-center bg-red-100">
        <div class="bg-red-100"></div>
        <div class="py-12 flex-1 bg-red-200 text-center">
          <h4 class="font-semibold tracking-widest text-xs">Box 1</h4>
          <p>Box 1 Flexbox 00000000</p>
        </div>
        <div class="bg-red-100"></div>
      </div>

      <div class="grid grid-cols-3 w-full md:w-1/3 max-w-md items-center bg-blue-100">
      <div class="bg-blue-100"></div>
        <div class="py-12 flex-1 bg-blue-200 text-center">
          <h4 class="font-semibold tracking-widest text-xs">Box 2</h4>
          <p>Box 2 Flexbox 0</p>
        </div>
        <div class="bg-blue-100"></div>
      </div>

      <div class="grid grid-cols-3 w-full md:w-1/3 max-w-md items-center bg-green-100">
      <div class="bg-green-100"></div>
        <div class="py-12 flex-1 bg-green-200 text-center">
          <h4 class="font-semibold tracking-widest text-xs">Box 3</h4>
          <p>Box 4 Flexbox 000</p>
        </div>
        <div class="bg-green-100"></div>
      </div>

    </section>

For more info refer the docs here


问:
Finding children of a GtkWidget
I need to be able to explore a GTK GUI's structure programmatically. I have the GtkWidget and I want to find any children of that widget. Now I know that GtkContainer's have a function to find children and that GtkContainer is derived from GtkWidget.

Is there anyway I can check if a widget is a GtkContainer and then perform the cast? If not, is there any other way I can discover the GtkWidget's that are children of the one I have?

答:
A different approach is needed if using GTK4 as GtkContainer no longer exists. See migration guide

A simple function traversing the widget heirarchy:

```<code>void print_widget_names(GtkWidget* parent, int level) {
  for (int i=0; i < level; i++) {
    g_print("    ");
  }
  level++;
  g_print("%s\n", gtk_widget_get_name(GTK_WIDGET(parent)));
  GtkWidget *widget = gtk_widget_get_first_child(GTK_WIDGET(parent));
  GtkWidget *next;
  if (widget != NULL) {
    print_widget_names(widget, level);
    while ((next = gtk_widget_get_next_sibling(widget)) != NULL) {
      widget = next;
      print_widget_names(widget, level);
    }
  }
}
</code>```

Title: Finding children of a GtkWidget

Body:
A different approach is needed if using GTK4 as GtkContainer no longer exists. See migration guide

A simple function traversing the widget heirarchy:

void print_widget_names(GtkWidget* parent, int level) {
  for (int i=0; i < level; i++) {
    g_print("    ");
  }
  level++;
  g_print("%s\n", gtk_widget_get_name(GTK_WIDGET(parent)));
  GtkWidget *widget = gtk_widget_get_first_child(GTK_WIDGET(parent));
  GtkWidget *next;
  if (widget != NULL) {
    print_widget_names(widget, level);
    while ((next = gtk_widget_get_next_sibling(widget)) != NULL) {
      widget = next;
      print_widget_names(widget, level);
    }
  }
}


问:
Faced this error while using React-Hook-Form and YupResolver: Attempted import error: 'set' is not exported from 'react-hook-form' (imported as 'o')
I'm developing an app using Capacitor, Ionic, React and recently I faced the following error, while using React Hook Form and YupResolver for the first time:

When I try to run the project, I get this error:

```<code>Failed to compile
./node_modules/@hookform/resolvers/dist/resolvers.module.js
Attempted import error: 'set' is not exported from 'react-hook-form' (imported as 'o').
</code>```

I want to create and validate a form for changing Password, submitting the new Password to an external API /change-password. The form will be like below:

```<code>Actual Password: ...
New Password: ...
Confirm new Password: ...

Submit
</code>```

The component:

```<code>import {
  IonContent,
  IonPage,
  IonItem,
  IonLabel,
  IonButton,
  IonInput,
  IonRow,
  IonAlert,
  IonGrid,
  IonCol,
} from "@ionic/react";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import axios from "axios";

 // form validation rules
  const validationSchema = yup.object().shape({
    password: yup
      .string()
      .min(8, "Password must be at least 8 characters")
      .required("Password is required"),
    newPassword: yup
      .string()
      .min(8, "Password must be at least 8 characters")
      .required("New Password is required"),
    confirmPassword: yup
      .string()
      .oneOf([yup.ref("newPassword"), null], "Passwords must match")
      .required("Confirm Password is required"),
  });

const ChangePassword: React.FC = () => {

//get the actual password from React Contenxt
  const {
    password,
    setPassword,
    alertMessage,
    setAlertMessage,
  } = React.useContext(AuthContext);

  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  // functions to build form returned by useForm() hook
  const { register, handleSubmit, errors } = useForm({
    resolver: yupResolver(validationSchema),
  });

  const onSubmit = () => {
    const data = {
      oldPassword: password,
      newPassword: newPassword,
      sourceId: 1,
    };

    axios
      .post("change-password", data)
      .then((response) => {
        return response.data;
      });
  };

  return (
    <React.Fragment>
      <IonPage className="ion-page" id="main-content">
        <IonContent className="ion-padding">
          <IonGrid>
            <h3>Change Password</h3>

            <form onSubmit={handleSubmit(onSubmit)}>
              <IonItem>
                <IonLabel position="floating">Actual Password</IonLabel>
                <IonInput
                  name="password"
                  type="password"
                  value={password}
                  ref={register}
                  className={`form-control ${
                    errors.password ? "is-invalid" : ""
                  }`}
                  onIonChange={(e) => setPassword(e.detail.value!)}
                ></IonInput>
                <div className="invalid-feedback">
                  {errors.password?.message}
                </div>
              </IonItem>

              <IonItem>
                <IonLabel position="floating">New Password</IonLabel>
                <IonInput
                  name="newPassword"
                  type="password"
                  value={newPassword}
                  ref={register}
                  className={`form-control ${
                    errors.newPassword ? "is-invalid" : ""
                  }`}
                  onIonChange={(e) => setNewPassword(e.detail.value!)}
                ></IonInput>
                <div className="invalid-feedback">
                  {errors.newPassword?.message}
                </div>
              </IonItem>

              <IonItem>
                <IonLabel position="floating">
                  Cofirm New Password
                </IonLabel>
                <IonInput
                  name="confirmPassword"
                  type="password"
                  value={confirmPassword}
                  ref={register}
                  className={`form-control ${
                    errors.confirmPassword ? "is-invalid" : ""
                  }`}
                  onIonChange={(e) => setConfirmPassword(e.detail.value!)}
                ></IonInput>
                <div className="invalid-feedback">
                  {errors.confirmPassword?.message}
                </div>
              </IonItem>

              <IonButton type="submit">
                Submit
              </IonButton>
            </form>
          </IonGrid>
        </IonContent>
      </IonPage>
    </React.Fragment>
  );
};

export default ChangePassword;
</code>```
```<code>@hookform/resolvers@2.4.0
yup@0.32.9
react-hook-form@6.15.6
</code>```

Any help would be really appreciated. Thanks!

答:
I am using "react-hook-form": "^7.25.1" version and i was importing as

import { yupResolver } from "@hookform/resolvers";    Instaed of

you can import as shown below (it's working for me)

import { yupResolver } from '@hookform/resolvers/yup';

Body:
I'm developing an app using Capacitor, Ionic, React and recently I faced the following error, while using React Hook Form and YupResolver for the first time:

When I try to run the project, I get this error:

Failed to compile
./node_modules/@hookform/resolvers/dist/resolvers.module.js
Attempted import error: 'set' is not exported from 'react-hook-form' (imported as 'o').

I want to create and validate a form for changing Password, submitting the new Password to an external API /change-password. The form will be like below:

Actual Password: ...
New Password: ...
Confirm new Password: ...

Submit

The component:

import {
  IonContent,
  IonPage,
  IonItem,
  IonLabel,
  IonButton,
  IonInput,
  IonRow,
  IonAlert,
  IonGrid,
  IonCol,
} from "@ionic/react";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import axios from "axios";

 // form validation rules
  const validationSchema = yup.object().shape({
    password: yup
      .string()
      .min(8, "Password must be at least 8 characters")
      .required("Password is required"),
    newPassword: yup
      .string()
      .min(8, "Password must be at least 8 characters")
      .required("New Password is required"),
    confirmPassword: yup
      .string()
      .oneOf([yup.ref("newPassword"), null], "Passwords must match")
      .required("Confirm Password is required"),
  });

const ChangePassword: React.FC = () => {

//get the actual password from React Contenxt
  const {
    password,
    setPassword,
    alertMessage,
    setAlertMessage,
  } = React.useContext(AuthContext);

  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  // functions to build form returned by useForm() hook
  const { register, handleSubmit, errors } = useForm({
    resolver: yupResolver(validationSchema),
  });

  const onSubmit = () => {
    const data = {
      oldPassword: password,
      newPassword: newPassword,
      sourceId: 1,
    };

    axios
      .post("change-password", data)
      .then((response) => {
        return response.data;
      });
  };

  return (
    <React.Fragment>
      <IonPage className="ion-page" id="main-content">
        <IonContent className="ion-padding">
          <IonGrid>

Change Password

            <form onSubmit={handleSubmit(onSubmit)}>
              <IonItem>
                <IonLabel position="floating">Actual Password</IonLabel>
                <IonInput
                  name="password"
                  type="password"
                  value={password}
                  ref={register}
                  className={`form-control ${
                    errors.password ? "is-invalid" : ""
                  }`}
                  onIonChange={(e) => setPassword(e.detail.value!)}
                ></IonInput>

                  {errors.password?.message}

              </IonItem>

              <IonItem>
                <IonLabel position="floating">New Password</IonLabel>
                <IonInput
                  name="newPassword"
                  type="password"
                  value={newPassword}
                  ref={register}
                  className={`form-control ${
                    errors.newPassword ? "is-invalid" : ""
                  }`}
                  onIonChange={(e) => setNewPassword(e.detail.value!)}
                ></IonInput>

                  {errors.newPassword?.message}

              </IonItem>

              <IonItem>
                <IonLabel position="floating">
                  Cofirm New Password
                </IonLabel>
                <IonInput
                  name="confirmPassword"
                  type="password"
                  value={confirmPassword}
                  ref={register}
                  className={`form-control ${
                    errors.confirmPassword ? "is-invalid" : ""
                  }`}
                  onIonChange={(e) => setConfirmPassword(e.detail.value!)}
                ></IonInput>

                  {errors.confirmPassword?.message}

              </IonItem>

              <IonButton type="submit">
                Submit
              </IonButton>
            </form>
          </IonGrid>
        </IonContent>
      </IonPage>
    </React.Fragment>
  );
};

export default ChangePassword;

@hookform/resolvers@2.4.0
yup@0.32.9
react-hook-form@6.15.6

Any help would be really appreciated. Thanks!


问:
How do I create a single list of object pairs from two lists in C#?
I have two lists of objects. List A and List B. I need to create List C which combines List A and List B into pairs. For example:</p>

```<code>List A
object a1
object a2
object a3

List B
object b1
object b2
object b3

List C (creates pairs)
object c1 (object a1, object b1)
object c2 (object a2, object b2)
object c3 (object a3, object b3)
</code>```

答:
I would suggest to use a List of tupples

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

Body:
I have two lists of objects. List A and List B. I need to create List C which combines List A and List B into pairs. For example:

List A
object a1
object a2
object a3

List B
object b1
object b2
object b3

List C (creates pairs)
object c1 (object a1, object b1)
object c2 (object a2, object b2)
object c3 (object a3, object b3)


问:
Merge R data frames with differing lengths
There are three data sets

Parent Category:

```<code>ID
Ants
Cow
Dog
Hen
Tiger
</code>```

df1:

```<code>ID     Number1
Ants    6
Dog     2
Hen     7
</code>```

df2:

```<code>ID     Number2
Ants    5
Cow     7
Tiger   3
</code>```

The final data (df3) should look like this:

```<code>ID      Number1  Number2
Ants       6        5
Cow        0        7
Dog        2        0
Hen        7        0
Tiger      0        3
</code>```

Is there any direct way to achieve this in R. I can do it in a manual way where I try to find out the missing values and then input it in each row and assign it to 0 and then arrange it in ascending order. Lastly I will merge the two data frames into one. But can we make a function that can do all this for us, with even more than two datasets.

I found a solution,  here

but this is taking to much of time to run and showing the error
Error: cannot allocate a vector of size 46.0 MB

答:
You can use full_join from dplyr :

```<code>full_join(df1, df2, "ID") %>% replace_NA(0)
</code>```

For your data :

```<code>library(dplyr)
library(collapse)

df1 <- data.frame(ID = c("Ants", "Dog", "Hen"), Number1 = c(6,2,7))
df2 <- data.frame(ID = c("Ants", "Cow", "Tiger"), Number2 = c(5,7,3))

full_join(df1, df2, "ID") %>% replace_NA(0) %>% arrange(ID)
</code>```

Body:
There are three data sets

Parent Category:

ID
Ants
Cow
Dog
Hen
Tiger

df1:

ID     Number1
Ants    6
Dog     2
Hen     7

df2:

ID     Number2
Ants    5
Cow     7
Tiger   3

The final data (df3) should look like this:

ID      Number1  Number2
Ants       6        5
Cow        0        7
Dog        2        0
Hen        7        0
Tiger      0        3

Is there any direct way to achieve this in R. I can do it in a manual way where I try to find out the missing values and then input it in each row and assign it to 0 and then arrange it in ascending order. Lastly I will merge the two data frames into one. But can we make a function that can do all this for us, with even more than two datasets.

I found a solution,  here

but this is taking to much of time to run and showing the error
Error: cannot allocate a vector of size 46.0 MB

Body:
You can use full_join from dplyr :

full_join(df1, df2, "ID") %>% replace_NA(0)

For your data :

library(dplyr)
library(collapse)

df1 <- data.frame(ID = c("Ants", "Dog", "Hen"), Number1 = c(6,2,7))
df2 <- data.frame(ID = c("Ants", "Cow", "Tiger"), Number2 = c(5,7,3))

full_join(df1, df2, "ID") %>% replace_NA(0) %>% arrange(ID)


问:
RxJS - Combine multiple observables and emit any value
I know how to combine observables and fetch the result when all observables emit at least one value (combineLatest, forkJoin, etc.).

But how can I emit a value when one of many observables emits a value?

For example:

```<code>const adModelChangedObs$ = this.editAdService.adModelChanged; // Angular subject one
const refreshPreviewClickedObs$ = this.editAdService.refreshPreviewClick // Angular subject two

merge([adModelChangedObs$, refrshPreviewClickedObs$]).subscribe(() => {
     console.log('One of the two observables emitted a value');
});
</code>```

The subscribe handler is not being executed, although I tried it with many RxJS operators for far.

答:
As mentioned in the comments, the merge function should help in your case, however, you have to pass the observables as args, not as an array.

You can try it like the following:

// import { merge } from 'rxjs';

const adModelChangedObs$ = this.editAdService.adModelChanged; // Angular subject one
const refreshPreviewClickedObs$ = this.editAdService.refreshPreviewClick; // Angular subject two

merge(adModelChangedObs$, refrshPreviewClickedObs$).subscribe(() => {
  console.log('One of the two observables emitted a value');
});
```

However, if that's not working, then you need to make sure that your editAdService observables emit the value correctly.

Body:
I know how to combine observables and fetch the result when all observables emit at least one value (combineLatest, forkJoin, etc.).

But how can I emit a value when one of many observables emits a value?

For example:

const adModelChangedObs$ = this.editAdService.adModelChanged; // Angular subject one
const refreshPreviewClickedObs$ = this.editAdService.refreshPreviewClick // Angular subject two

merge([adModelChangedObs$, refrshPreviewClickedObs$]).subscribe(() => {
     console.log('One of the two observables emitted a value');
});

The subscribe handler is not being executed, although I tried it with many RxJS operators for far.

Body:
As mentioned in the comments, the merge function should help in your case, however, you have to pass the observables as args, not as an array.

You can try it like the following:

// import { merge } from 'rxjs';

const adModelChangedObs$ = this.editAdService.adModelChanged; // Angular subject one
const refreshPreviewClickedObs$ = this.editAdService.refreshPreviewClick; // Angular subject two

merge(adModelChangedObs$, refrshPreviewClickedObs$).subscribe(() => {
  console.log('One of the two observables emitted a value');
});

However, if that's not working, then you need to make sure that your editAdService observables emit the value correctly.


问:
Loading/Downloading image from URL on Swift
I'd like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I've a compilation error:

'imageWithData' is unavailable: use object construction 'UIImage(data:)'

My function:

```<code>@IBOutlet var imageView : UIImageView

override func viewDidLoad() {
    super.viewDidLoad()

    var url:NSURL = NSURL.URLWithString("http://myURL/ios8.png")
    var data:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)

    imageView.image = UIImage.imageWithData(data)// Error here
}
</code>```

In Objective-C:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:(@"http://myURL/ios8.png")];
    NSData *data = [NSData dataWithContentsOfURL:url];

    _imageView.image = [UIImage imageWithData: data];
    _labelURL.text = @"http://www.quentinroussat.fr/assets/img/iOS%20icon's%20Style/ios8.png";
 }
</code>```

Can someone please explain me why the imageWithData: doesn't work with Swift, and how can I solve the problem.

答:
```<code>class Downloader {

    class func downloadImageWithURL(url: String) -> UIImage! {

        let date = NSData(contentsOf: URL(string: url)!)
        return UIImage(data: date! as Data)
    }
}
</code>```

usage:

```<code>let img = Downloader.downloadImageWithURL(url: imageURL)
        self.imageView1.image = img
</code>```

Body:
I'd like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I've a compilation error:

'imageWithData' is unavailable: use object construction 'UIImage(data:)'

My function:

@IBOutlet var imageView : UIImageView

override func viewDidLoad() {
    super.viewDidLoad()

    var url:NSURL = NSURL.URLWithString("http://myURL/ios8.png")
    var data:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)

    imageView.image = UIImage.imageWithData(data)// Error here
}

In Objective-C:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:(@"http://myURL/ios8.png")];
    NSData *data = [NSData dataWithContentsOfURL:url];

    _imageView.image = [UIImage imageWithData: data];
    _labelURL.text = @"http://www.quentinroussat.fr/assets/img/iOS%20icon's%20Style/ios8.png";
 }

Can someone please explain me why the imageWithData: doesn't work with Swift, and how can I solve the problem.

Body:
class Downloader {

    class func downloadImageWithURL(url: String) -> UIImage! {

        let date = NSData(contentsOf: URL(string: url)!)
        return UIImage(data: date! as Data)
    }
}

usage:

let img = Downloader.downloadImageWithURL(url: imageURL)
        self.imageView1.image = img


问:
Django RF, error validating objects owner (error: Field 'id' expected a number but got .AnonymousUser )
I have a object created by a user, When other users try to access the object, it should not allow it. I expect Django to throw error as you are not authenticated
After logging out, when anonymous user try to access the object Django throw error as mentioned below.

ERROR

```<code>TypeError at /PoUserTracking/
Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x0445F160>.
</code>```

VIEWS.PY

```<code>class PoUserTracking(generics.ListAPIView):
    serializer_class = NewPoSerializer
    permission_classes = [IsAuthor]

    def get_queryset(self):
        user = self.request.user
        return Po.objects.filter(user=user)
</code>```

PERMISSIONS.PY

```<code>class IsAuthor(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):

        return obj.author == request.user
</code>```

答: just make request.user.id  //this will be solved for sure..</p>

Body:
I have a object created by a user, When other users try to access the object, it should not allow it. I expect Django to throw error as you are not authenticated
After logging out, when anonymous user try to access the object Django throw error as mentioned below.

ERROR

TypeError at /PoUserTracking/
Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x0445F160>.

VIEWS.PY

class PoUserTracking(generics.ListAPIView):
    serializer_class = NewPoSerializer
    permission_classes = [IsAuthor]

    def get_queryset(self):
        user = self.request.user
        return Po.objects.filter(user=user)

PERMISSIONS.PY

class IsAuthor(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):

        return obj.author == request.user


问:
How to prevent NetCore Web API to expose internals when Json is malformed?
When a malformed Json is sent to a NetCore Web Api method the default serializer Text.Json exposes the internal information in the error response.

DTO:

```<code>public record CreateGroupDTO(
            Guid AccountId,
            DateTime Start
           );
</code>```

Method in GroupsController (since the error is handled in the framework the code of the controller is off the point):

```<code>[HttpPost]
[Route("")]
public ActionResult<GroupDTO> CreateGroup(CreateGroupDTO createGroupDTO) {...}
</code>```

Post with malformed Guid:

```<code>{
  "accountId": "4-5717-4562-b3fc-2c963f66afa6",
  "start": "2022-02-14T12:39:59.244Z"
}
</code>```

Response Body:

```<code>    "errors": {
        "createGroupDTO": [
          "The createGroupDTO field is required."
        ],
        "$.accountId": [
          "The JSON value could not be converted to Elwis.Orders.Application.CreateGroupDTO.
          Path: $.accountId | LineNumber: 1 | BytePositionInLine: 52."
        ]
      }
</code>```

Post with malformed DateTime:

```<code>{
  "accountId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "start": "2022-02-30"
}
</code>```

Response Body:

```<code>{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-8f49393621db7dea28f797f4ee69f203-2612b8bd5fe0aa0d-00",
  "errors": {
    "createGroupDTO": [
      "The createGroupDTO field is required."
    ],
    "$.start": [
      "The JSON value could not be converted to Elwis.Orders.Application.CreateGroupDTO. Path: $.start | LineNumber: 2 | BytePositionInLine: 23."
    ]
  }
}
</code>```

For security reasons the response should not expose the FullName of the dto type. How can I make Web API prevent exposing the FullName?

I also don't understand why the error for accountId is stating the dto. It should state that the JSON value could not be converted to Guid. How can I make Web API state a more correct error message?

UPDATE:

.Net 6 has a new option AllowInputFormatterExceptionMessages, that solves the main part of the problem (ASP.NET 6.0 Docs). You can add to StartUp.cs

```<code>services.AddControllers()
   .AddJsonOptions(o => o.AllowInputFormatterExceptionMessages = false);
</code>```

Response for malformed Guid:

```<code>{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-a5036b75970685554b4cf7c87c452939-ca3293d1faef0d84-00",
  "errors": {
    "createGroupDTO": [
      "The createGroupDTO field is required."
    ],
    "$.accountId": [
      "The input was not valid."
    ]
  }
}
</code>```

It still exposes the variable name of the body parameter It still states that "The createGroupDTO field is required."! This response makes no sense since it is not a field in the Json structure and just an internal name. Is there a way to prevent this?

Update 2:

I filed an issue at GitHub. Microsoft moved "this issue to the .NET 7 Planning milestone for future evaluation / consideration. Because it's not immediately obvious that this is a bug in our framework, we would like to keep this around to collect more feedback, which can later help us determine the impact of it. We will re-evaluate this issue, during our next planning meeting(s)."

答:
In general it does not return the fullname, you need to provide the model. Or there is simple way, You can try to custom error message, I write a simple demo here.

custom error message

```<code>public class ReformatValidationProblemAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is BadRequestObjectResult badRequestObjectResult)
                if (badRequestObjectResult.Value is ValidationProblemDetails)
                {
                    context.Result = new BadRequestObjectResult("Json is malformed");
                }

            base.OnResultExecuting(context);
        }
    }
</code>```

controller

```<code>[ReformatValidationProblem]
    [Route("api/[controller]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
       //........
    }
</code>```

register it in startup.cs

```<code>services.AddMvc(options =>
{
    options.Filters.Add(typeof(ReformatValidationProblemAttribute));
});
</code>```

Then you can see when Json is malformed, It just return the custom error message instead of the fullName.

Body:
When a malformed Json is sent to a NetCore Web Api method the default serializer Text.Json exposes the internal information in the error response.

DTO:

public record CreateGroupDTO(
            Guid AccountId,
            DateTime Start
           );

Method in GroupsController (since the error is handled in the framework the code of the controller is off the point):

[HttpPost]
[Route("")]
public ActionResult<GroupDTO> CreateGroup(CreateGroupDTO createGroupDTO) {...}

Post with malformed Guid:

{
  "accountId": "4-5717-4562-b3fc-2c963f66afa6",
  "start": "2022-02-14T12:39:59.244Z"
}

Response Body:

    "errors": {
        "createGroupDTO": [
          "The createGroupDTO field is required."
        ],
        "$.accountId": [
          "The JSON value could not be converted to Elwis.Orders.Application.CreateGroupDTO.
          Path: $.accountId | LineNumber: 1 | BytePositionInLine: 52."
        ]
      }

Post with malformed DateTime:

{
  "accountId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "start": "2022-02-30"
}

Response Body:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-8f49393621db7dea28f797f4ee69f203-2612b8bd5fe0aa0d-00",
  "errors": {
    "createGroupDTO": [
      "The createGroupDTO field is required."
    ],
    "$.start": [
      "The JSON value could not be converted to Elwis.Orders.Application.CreateGroupDTO. Path: $.start | LineNumber: 2 | BytePositionInLine: 23."
    ]
  }
}

For security reasons the response should not expose the FullName of the dto type. How can I make Web API prevent exposing the FullName?

I also don't understand why the error for accountId is stating the dto. It should state that the JSON value could not be converted to Guid. How can I make Web API state a more correct error message?

UPDATE:

.Net 6 has a new option AllowInputFormatterExceptionMessages, that solves the main part of the problem (ASP.NET 6.0 Docs). You can add to StartUp.cs

services.AddControllers()
   .AddJsonOptions(o => o.AllowInputFormatterExceptionMessages = false);

Response for malformed Guid:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-a5036b75970685554b4cf7c87c452939-ca3293d1faef0d84-00",
  "errors": {
    "createGroupDTO": [
      "The createGroupDTO field is required."
    ],
    "$.accountId": [
      "The input was not valid."
    ]
  }
}

It still exposes the variable name of the body parameter It still states that "The createGroupDTO field is required."! This response makes no sense since it is not a field in the Json structure and just an internal name. Is there a way to prevent this?

Update 2:

I filed an issue at GitHub. Microsoft moved "this issue to the .NET 7 Planning milestone for future evaluation / consideration. Because it's not immediately obvious that this is a bug in our framework, we would like to keep this around to collect more feedback, which can later help us determine the impact of it. We will re-evaluate this issue, during our next planning meeting(s)."

Body:
In general it does not return the fullname, you need to provide the model. Or there is simple way, You can try to custom error message, I write a simple demo here.

custom error message

public class ReformatValidationProblemAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is BadRequestObjectResult badRequestObjectResult)
                if (badRequestObjectResult.Value is ValidationProblemDetails)
                {
                    context.Result = new BadRequestObjectResult("Json is malformed");
                }

            base.OnResultExecuting(context);
        }
    }

controller

[ReformatValidationProblem]
    [Route("api/[controller]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
       //........
    }

register it in startup.cs

services.AddMvc(options =>
{
    options.Filters.Add(typeof(ReformatValidationProblemAttribute));
});

Then you can see when Json is malformed, It just return the custom error message instead of the fullName.


问:
Where i can find my pages cshtml after Deploy in NET 6
I am developing a website in asp.net mvc with NET 6 and when I deploy I cannot find anymore the cshtml pages, but a lot of folders, dll and an .exe.

The problem is that it looks like I need to update all the website each time I modify one single page.

Is there a way to put online only the modified page cshtml without deploying the entire website?

答:
1. You need add Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package.

2. You also need Copy the cshtml when you deploy.

So my .csproj  file like:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.2" />
  </ItemGroup>

  <ItemGroup>
    <ViewFiles Include="$(ProjectDir)\Views\**\*.cshtml" />
  </ItemGroup>

  <Target Name="CopyViewFilesAfterPublish" AfterTargets="Publish">
    <Copy SourceFiles="@(ViewFiles)"
      DestinationFolder="$(PublishDir)\Views\%(RecursiveDir)"
    />
  </Target>

</Project>
</code>```

Test Result:

Find cshtml file in publish file.

Test in IIS

Body:
1. You need add Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package.

2. You also need Copy the cshtml when you deploy.

So my .csproj  file like:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.2" />
  </ItemGroup>

  <ItemGroup>
    <ViewFiles Include="$(ProjectDir)\Views\**\*.cshtml" />
  </ItemGroup>

  <Target Name="CopyViewFilesAfterPublish" AfterTargets="Publish">
    <Copy SourceFiles="@(ViewFiles)"
      DestinationFolder="$(PublishDir)\Views\%(RecursiveDir)"
    />
  </Target>

</Project>

Test Result:

Find cshtml file in publish file.

Test in IIS


问:
How do I get the path of a directory where a file SQL backup is missing?
The task is to track the execution of SQL backups. One of the tracking mechanisms is to browse the directory where the backups are saved and if the file is missing, you can send an email with the full address of the directory where the file is missing. This is what I am trying to implement with Powershell script, but for some reason my script doesn't work and doesn't give me the information I need.

```<code>$list = Get-ChildItem -Path network_path_to_share -Recurse -File | Where-Object {$_.DirectoryName -like '*FULL*' -and $_.LastWriteTime -ge (Get-Date).AddDays(-6)}
$fileExists = Test-Path $list
If ($fileExists)
{
 #Do Nothing
}
Else
{
$list | Select DirectoryName
}
</code>```

Can anyone help?

答:
I suppose what you need is to test each file or path individually. You take Get-ChildItem with recurse, so it returns multiple files and stores them in $list.

If you do something like

```<code>    Foreach ($item in $list) {
$fileexists = Test-Path $item
If ($fileexists -eq $false) {
do something }
}
</code>```

You should be good to go. This would cycle through all items and does whatever you need to be done. If you compare against $false, you wouldn't need the else statement, and you could also just put "Test-Path" into the if-statement like

```<code>If (Test-Path $item -eq $false) {}
</code>```

Edit: Sorry I accidentally posted the answer before finishing it lol

Also, as stackprotector correctly points out, Get-ChildItem can only retrieve items that exist, because how should it detect missing files.

Body:
The task is to track the execution of SQL backups. One of the tracking mechanisms is to browse the directory where the backups are saved and if the file is missing, you can send an email with the full address of the directory where the file is missing. This is what I am trying to implement with Powershell script, but for some reason my script doesn't work and doesn't give me the information I need.

$list = Get-ChildItem -Path network_path_to_share -Recurse -File | Where-Object {$_.DirectoryName -like '*FULL*' -and $_.LastWriteTime -ge (Get-Date).AddDays(-6)}
$fileExists = Test-Path $list
If ($fileExists)
{
 #Do Nothing
}
Else
{
$list | Select DirectoryName
}

Can anyone help?

Body:
I suppose what you need is to test each file or path individually. You take Get-ChildItem with recurse, so it returns multiple files and stores them in $list.

If you do something like

    Foreach ($item in $list) {
$fileexists = Test-Path $item
If ($fileexists -eq $false) {
do something }
}

You should be good to go. This would cycle through all items and does whatever you need to be done. If you compare against $false, you wouldn't need the else statement, and you could also just put "Test-Path" into the if-statement like

If (Test-Path $item -eq $false) {}

Edit: Sorry I accidentally posted the answer before finishing it lol

Also, as stackprotector correctly points out, Get-ChildItem can only retrieve items that exist, because how should it detect missing files.


问:
How can I have my HTTP PUT routes treated the same way as PATCH routes?
I have an ASP.NET Core web API controller base class which can be shortened to the following:

[Route("my/route")]
public abstract class ControllerBase
{
    [HttpPut]
    [Route("")]
    public MyObject Update([FromBody] MyObject obj) => obj;

    [HttpPut]
    [Route("{*id}", Order = 1)]
    public MyObject Update([FromUri] String id, [FromBody] MyObject obj) => obj;

    [HttpPatch]
    [Route("")]
    public MyObject Patch([FromBody] JObject data) => new MyObject();

    [HttpPatch]
    [Route("{*id}", Order = 1)]
    public MyObject Patch([FromUri] String id, [FromBody] JObject data) => new MyObject();
}
```
<p>Now, imagine calls to the following four endpoints:</p>
<ol>
<li><code>PUT /my/route</code></li>
<li><code>PUT /my/route/42</code></li>
<li><code>PATCH /my/route</code></li>
<li><code>PATCH /my/route/42</code></li>
</ol>
<p>In ASP.NET (using .NET Framework), all four used to work.</p>
<p><strong>Now that the application has been switched to .NET Core and uses ASP.NET Core, calls 1 and 2, i.e. the two <code>HTTP PUT</code> calls, return <code>405/Method Not Allowed</code>.</strong> The <code>HTTP PATCH</code> calls still work as before.</p>
<p>It seems ASP.NET Core's routing behaves somewhat differently from that of ASP.NET, but why would it behave the same way for one HTTP method and differently for another?</p>
<p>After doing some digging, I found the answers to <em>HTTP Verbs PUT and DELETE: 405 Method not allowed - how to allow?</em>, where it was suggested that in ASP.NET Core, the query string parameters need to be added to the method attribute, as well. Therefore, I've tried changing my <code>PUT</code> methods as follows, but to no avail:</p>
<pre class="lang-cs prettyprint-override"><code>    [HttpPut("")]
    [Route("")]
    public MyObject Update([FromBody] MyObject obj) => obj;

    [HttpPut("{*id}", Order = 1]
    [Route("{*id}", Order = 1)]
    public MyObject Update([FromUri] String id, [FromBody] MyObject obj) => obj;
</code>```

What do I have to do to make the PUT endpoints work again, the same as the PATCH endpoints still do?

答:
The problem was the WebDAV module in IIS.

I used the Add/Remove Features function of Windows to remove it completely from my system, and once that was done, HTTP PUT calls would work again as expected.

Body:
I have an ASP.NET Core web API controller base class which can be shortened to the following:

[Route("my/route")]
public abstract class ControllerBase
{
    [HttpPut]
    [Route("")]
    public MyObject Update([FromBody] MyObject obj) => obj;

    [HttpPut]
    [Route("{*id}", Order = 1)]
    public MyObject Update([FromUri] String id, [FromBody] MyObject obj) => obj;

    [HttpPatch]
    [Route("")]
    public MyObject Patch([FromBody] JObject data) => new MyObject();

    [HttpPatch]
    [Route("{*id}", Order = 1)]
    public MyObject Patch([FromUri] String id, [FromBody] JObject data) => new MyObject();
}

Now, imagine calls to the following four endpoints:

PUT /my/route

PUT /my/route/42

PATCH /my/route

PATCH /my/route/42

In ASP.NET (using .NET Framework), all four used to work.

Now that the application has been switched to .NET Core and uses ASP.NET Core, calls 1 and 2, i.e. the two HTTP PUT calls, return 405/Method Not Allowed. The HTTP PATCH calls still work as before.

It seems ASP.NET Core's routing behaves somewhat differently from that of ASP.NET, but why would it behave the same way for one HTTP method and differently for another?

After doing some digging, I found the answers to HTTP Verbs PUT and DELETE: 405 Method not allowed - how to allow?, where it was suggested that in ASP.NET Core, the query string parameters need to be added to the method attribute, as well. Therefore, I've tried changing my PUT methods as follows, but to no avail:

    [HttpPut("")]
    [Route("")]
    public MyObject Update([FromBody] MyObject obj) => obj;

    [HttpPut("{*id}", Order = 1]
    [Route("{*id}", Order = 1)]
    public MyObject Update([FromUri] String id, [FromBody] MyObject obj) => obj;

What do I have to do to make the PUT endpoints work again, the same as the PATCH endpoints still do?


答:
We can put all dataframes into a list and use Reduce and merge from base R:

```<code>df <- Reduce(function(...) merge(..., by='ID', all.x=TRUE), list(parent, df1, df2))
df[is.na(df)] <- 0

     ID Number1 Number2
1  Ants       6       5
2   Cow       0       7
3   Dog       2       0
4   Hen       7       0
5 Tiger       0       3
</code>```

Or we can use join_all from plyr:

```<code>library(plyr)
join_all(list(parent, df1, df2), by='ID', type='left') %>%
  replace(is.na(.), 0)
</code>```

Or with purrr::reduce:

```<code>library(tidyverse)

reduce(list(parent, df1, df2), left_join, by = 'ID') %>%
  mutate(across(where(is.numeric), ~ replace_na(.x, 0)))
</code>```

Data

```<code>parent <- structure(list(ID = c("Ants", "Cow", "Dog", "Hen", "Tiger")),
                    class = "data.frame", row.names = c(NA, -5L))

df1 <- structure(list(ID = c("Ants", "Dog", "Hen"),
                      Number1 = c(6L, 2L, 7L)),
                 class = "data.frame", row.names = c(NA, -3L))

df2 <- structure(list(ID = c("Ants", "Cow", "Tiger"),
                      Number2 = c(5L, 7L, 3L)),
                 class = "data.frame", row.names = c(NA, -3L))
</code>```

Title: Merge R data frames with differing lengths

Body:
We can put all dataframes into a list and use Reduce and merge from base R:

df <- Reduce(function(...) merge(..., by='ID', all.x=TRUE), list(parent, df1, df2))
df[is.na(df)] <- 0

     ID Number1 Number2
1  Ants       6       5
2   Cow       0       7
3   Dog       2       0
4   Hen       7       0
5 Tiger       0       3

Or we can use join_all from plyr:

library(plyr)
join_all(list(parent, df1, df2), by='ID', type='left') %>%
  replace(is.na(.), 0)

Or with purrr::reduce:

library(tidyverse)

reduce(list(parent, df1, df2), left_join, by = 'ID') %>%
  mutate(across(where(is.numeric), ~ replace_na(.x, 0)))

Data

parent <- structure(list(ID = c("Ants", "Cow", "Dog", "Hen", "Tiger")),
                    class = "data.frame", row.names = c(NA, -5L))

df1 <- structure(list(ID = c("Ants", "Dog", "Hen"),
                      Number1 = c(6L, 2L, 7L)),
                 class = "data.frame", row.names = c(NA, -3L))

df2 <- structure(list(ID = c("Ants", "Cow", "Tiger"),
                      Number2 = c(5L, 7L, 3L)),
                 class = "data.frame", row.names = c(NA, -3L))


问:
copy value from one column to another if condition is met in pandas
I have a dataframe:

df =

col1
Aciton1

1
A

2
B

3
C

1
C

I want to edit df, such that when the value of col1 is bigger than 1 , take the value from Action1.

So I will get:

col1
Aciton1
Previous_Aciton

1
A
Initial Action

2
B
A

3
C
B

1
C
Initial Action

答:
If there are no negative and 0 values and each group starting by 1 is possible use DataFrameGroupBy.shift:

```<code>df['Previsou_Aciton'] = df.groupby(df['col1'].eq(1).cumsum())['Aciton1'].shift(fill_value='Initail Action')
print (df)
   col1 Aciton1 Previsou_Aciton
0     1       A  Initail Action
1     2       B               A
2     3       C               B
3     1       C  Initail Action
</code>```

Body:
If there are no negative and 0 values and each group starting by 1 is possible use DataFrameGroupBy.shift:

df['Previsou_Aciton'] = df.groupby(df['col1'].eq(1).cumsum())['Aciton1'].shift(fill_value='Initail Action')
print (df)
   col1 Aciton1 Previsou_Aciton
0     1       A  Initail Action
1     2       B               A
2     3       C               B
3     1       C  Initail Action


问:
TypeError: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x048C7E90>

```<code>Cannot cast AnonymousUser to int.
Are you trying to use it in place of User?
</code>```

I am unsure how to adjust my code to stop generating this error when i make a post request to my url.  I have attached code for my serializers, views and models.

```<code>class ActivitySessionSerializer(serializers.Serializer):
    activity_name = serializers.CharField(min_length=1, max_length=100)

    def create(self, validated_data):
        activity, created = Activity.objects.get_or_create(name=validated_data['activity_name'],
        owner=self.context['request'].user)

        return ActivitySession.objects.create(activity=activity, start_time=datetime.datetime.now())

class StartSessionView(generics.CreateAPIView):
    serializer_class = serializers.ActivitySessionSerializer

    User = get_user_model()

    class ActivityType(models.Model):
        name = models.CharField(max_length=100)
        user = models.ForeignKey(User, on_delete=models.CASCADE)

    class Activity(models.Model):
        name = models.CharField(max_length=100)
        owner = models.ForeignKey(User, on_delete=models.CASCADE)
        activity_type = models.ForeignKey(ActivityType, on_delete=models.CASCADE, null=True, blank=True)

    class ActivitySession(models.Model):
        activity = models.ForeignKey(Activity, on_delete=models.CASCADE)
        start_time = models.DateTimeField()
        end_time = models.DateTimeField()

    urlpatterns = [
        path('starting_session/', views.StartSessionView.as_view()),
    ]
</code>```

I believe i solved it by changing line

```<code>Activity.objects.get_or_create(name=validated_data['activity_name'],
        owner=self.context['request'].user)
</code>```

to

```<code>Activity.objects.get_or_create(name=validated_data['activity_name'],
        owner=self.context['request'].user.id)
</code>```

I had to add id field specifically instead of the total user object

答: just need to add request.user.id /// this will solve for sure..</p>

Body:
Cannot cast AnonymousUser to int.
Are you trying to use it in place of User?

I am unsure how to adjust my code to stop generating this error when i make a post request to my url.  I have attached code for my serializers, views and models.

class ActivitySessionSerializer(serializers.Serializer):
    activity_name = serializers.CharField(min_length=1, max_length=100)

    def create(self, validated_data):
        activity, created = Activity.objects.get_or_create(name=validated_data['activity_name'],
        owner=self.context['request'].user)

        return ActivitySession.objects.create(activity=activity, start_time=datetime.datetime.now())

class StartSessionView(generics.CreateAPIView):
    serializer_class = serializers.ActivitySessionSerializer

    User = get_user_model()

    class ActivityType(models.Model):
        name = models.CharField(max_length=100)
        user = models.ForeignKey(User, on_delete=models.CASCADE)

    class Activity(models.Model):
        name = models.CharField(max_length=100)
        owner = models.ForeignKey(User, on_delete=models.CASCADE)
        activity_type = models.ForeignKey(ActivityType, on_delete=models.CASCADE, null=True, blank=True)

    class ActivitySession(models.Model):
        activity = models.ForeignKey(Activity, on_delete=models.CASCADE)
        start_time = models.DateTimeField()
        end_time = models.DateTimeField()

    urlpatterns = [
        path('starting_session/', views.StartSessionView.as_view()),
    ]

I believe i solved it by changing line

Activity.objects.get_or_create(name=validated_data['activity_name'],
        owner=self.context['request'].user)

to

Activity.objects.get_or_create(name=validated_data['activity_name'],
        owner=self.context['request'].user.id)

I had to add id field specifically instead of the total user object


问:
Is this possible in SQL? Min and Max Dates On a Total. Where it changes in between Dates
I am trying to figure out how to write a query that will give me the correct historical data between dates. But only using sql. I know it is possible coding a loop, but I'm not sure if this is possible in a SQL query. Dates: DD/MM/YYYY

An Example of Data

ID
Points
DATE

1
10
01/01/2018

1
20
02/01/2019

1
25
03/01/2020

1
10
04/01/2021

With a simple query

```<code>SELECT ID, Points, MIN(Date), MAX(Date)
FROM table
GROUP BY ID,POINTS
</code>```

The Min date for 10 points would be 01/01/2018, and the Max Date would be 04/01/2021. Which would be wrong in this instance. As It should be:

ID
Points
Min DATE
Max DATE

1
10
01/01/2018
01/01/2019

1
20
02/01/2019
02/01/2020

1
25
03/01/2020
03/01/2021

1
10
04/01/2021
04/01/2021

I was thinking of using LAG, but need some ideas here. What I haven't told you is there is a record per day. So I would need to group until a change of points. This is to create a view from the data that I already have.

答:
*** See my other answer, as I don't think this answer is correct after reexamining the OPs question. Leaving ths answer in place, in case it has any value.

As I understand the problem consecutive daily values with the same value for a given ID may be ignored. This can be done by examining the prior value using the LAG() function and excluding records where the current value is unchanged from the prior.

From the remaining records, the LEAD() function can be used to look ahead to the next included record to extract the date where this value is superseded. Max Date is then calculated as one day prior.

Below is an example that includes expanded test data to cover multiple IDs and repeated Points values.

```<code>DECLARE @Data TABLE (Id INT, Points INT, Date DATE)
INSERT @Data
VALUES
    (1, 10, '2018-01-01'), -- Start
    (1, 20, '2019-01-02'), -- Updated
    (1, 25, '2020-01-03'), -- Updated
    (1, 10, '2021-01-04'), -- Updated
    (2, 10, '2022-01-01'), -- Start
    (2, 20, '2022-02-01'), -- Updated
    (2, 20, '2022-03-01'), -- No change
    (2, 20, '2022-04-01'), -- No change
    (2, 20, '2022-05-01'), -- No change
    (2, 25, '2022-06-01'), -- Updated
    (2, 25, '2022-07-01'), -- No change
    (2, 20, '2022-08-01'), -- Updated
    (2, 25, '2022-09-08'), -- Updated
    (2, 10, '2022-10-09'), -- Updated
    (3, 10, '2022-01-01'), -- Start
    (3, 10, '2022-01-02'), -- No change
    (3, 20, '2022-01-03'), -- Updated
    (3, 20, '2022-01-04'), -- No change
    (3, 20, '2022-01-05'), -- No change
    (3, 10, '2022-01-06'), -- Updated
    (3, 10, '2022-01-07'); -- No change

WITH CTE AS (
    SELECT *, PriorPoints = LAG(Points) OVER (PARTITION BY Id ORDER BY Date)
    FROM @Data
)
SELECT ID, Points, MinDate = Date,
    MaxDate = DATEADD(day, -1, (LEAD(Date) OVER (PARTITION BY Id ORDER BY Date)))
FROM CTE
WHERE (PriorPoints <> Points OR PriorPoints IS NULL) -- Exclude unchanged
ORDER BY Id, Date
</code>```

Results:

ID
Points
MinDate
MaxDate

1
10
2018-01-01
2019-01-01

1
20
2019-01-02
2020-01-02

1
25
2020-01-03
2021-01-03

1
10
2021-01-04
null

2
10
2022-01-01
2022-01-31

2
20
2022-02-01
2022-05-31

2
25
2022-06-01
2022-07-31

2
20
2022-08-01
2022-09-07

2
25
2022-09-08
2022-10-08

2
10
2022-10-09
null

3
10
2022-01-01
2022-01-02

3
20
2022-01-03
2022-01-05

3
10
2022-01-06
null

db<>fiddle

For the last value for a given ID, the calculated MaxDate is NULL indicating no upper bound to the date range. If you really want MaxDate = MinDate for this case, you can add ISNULL( ..., Date).

Body:
I am trying to figure out how to write a query that will give me the correct historical data between dates. But only using sql. I know it is possible coding a loop, but I'm not sure if this is possible in a SQL query. Dates: DD/MM/YYYY

An Example of Data

ID
Points
DATE

1
10
01/01/2018

1
20
02/01/2019

1
25
03/01/2020

1
10
04/01/2021

With a simple query

SELECT ID, Points, MIN(Date), MAX(Date)
FROM table
GROUP BY ID,POINTS

The Min date for 10 points would be 01/01/2018, and the Max Date would be 04/01/2021. Which would be wrong in this instance. As It should be:

ID
Points
Min DATE
Max DATE

1
10
01/01/2018
01/01/2019

1
20
02/01/2019
02/01/2020

1
25
03/01/2020
03/01/2021

1
10
04/01/2021
04/01/2021

I was thinking of using LAG, but need some ideas here. What I haven't told you is there is a record per day. So I would need to group until a change of points. This is to create a view from the data that I already have.

Body:
*** See my other answer, as I don't think this answer is correct after reexamining the OPs question. Leaving ths answer in place, in case it has any value.

As I understand the problem consecutive daily values with the same value for a given ID may be ignored. This can be done by examining the prior value using the LAG() function and excluding records where the current value is unchanged from the prior.

From the remaining records, the LEAD() function can be used to look ahead to the next included record to extract the date where this value is superseded. Max Date is then calculated as one day prior.

Below is an example that includes expanded test data to cover multiple IDs and repeated Points values.

DECLARE @Data TABLE (Id INT, Points INT, Date DATE)
INSERT @Data
VALUES
    (1, 10, '2018-01-01'), -- Start
    (1, 20, '2019-01-02'), -- Updated
    (1, 25, '2020-01-03'), -- Updated
    (1, 10, '2021-01-04'), -- Updated
    (2, 10, '2022-01-01'), -- Start
    (2, 20, '2022-02-01'), -- Updated
    (2, 20, '2022-03-01'), -- No change
    (2, 20, '2022-04-01'), -- No change
    (2, 20, '2022-05-01'), -- No change
    (2, 25, '2022-06-01'), -- Updated
    (2, 25, '2022-07-01'), -- No change
    (2, 20, '2022-08-01'), -- Updated
    (2, 25, '2022-09-08'), -- Updated
    (2, 10, '2022-10-09'), -- Updated
    (3, 10, '2022-01-01'), -- Start
    (3, 10, '2022-01-02'), -- No change
    (3, 20, '2022-01-03'), -- Updated
    (3, 20, '2022-01-04'), -- No change
    (3, 20, '2022-01-05'), -- No change
    (3, 10, '2022-01-06'), -- Updated
    (3, 10, '2022-01-07'); -- No change

WITH CTE AS (
    SELECT *, PriorPoints = LAG(Points) OVER (PARTITION BY Id ORDER BY Date)
    FROM @Data
)
SELECT ID, Points, MinDate = Date,
    MaxDate = DATEADD(day, -1, (LEAD(Date) OVER (PARTITION BY Id ORDER BY Date)))
FROM CTE
WHERE (PriorPoints <> Points OR PriorPoints IS NULL) -- Exclude unchanged
ORDER BY Id, Date

Results:

ID
Points
MinDate
MaxDate

1
10
2018-01-01
2019-01-01

1
20
2019-01-02
2020-01-02

1
25
2020-01-03
2021-01-03

1
10
2021-01-04
null

2
10
2022-01-01
2022-01-31

2
20
2022-02-01
2022-05-31

2
25
2022-06-01
2022-07-31

2
20
2022-08-01
2022-09-07

2
25
2022-09-08
2022-10-08

2
10
2022-10-09
null

3
10
2022-01-01
2022-01-02

3
20
2022-01-03
2022-01-05

3
10
2022-01-06
null

db<>fiddle

For the last value for a given ID, the calculated MaxDate is NULL indicating no upper bound to the date range. If you really want MaxDate = MinDate for this case, you can add ISNULL( ..., Date).


问:
Real state project data structure suggestion
I am working in a real state project (linux, drupal, php 5, mysql) and I need to pull data in from the local mls sytem.

What data structure should I use IDX or RETS? (and why?)

Thank you

答:
Technically, IDX is an NAR policy and not a technology.  RETS is a protocol for sharing property listing data over the net.

When then term is misused and not relating to the NAR policy, IDX is meant to use a limited set of data generally useful for advertising purposes only.  RETS, when misused in a similar matter, may mean the full feed of data.


问:
Get last datetime from from weekday() index in Python
I would like to get the most recent datetime of a weekday() index in Python. How could I do this?

Example:
Let's say today is Wednesday 02/09 (weekday index 2). Input 0 would give me datetime of last Tuesday, which is 02/07. 3 would give me datetime of last Thursday, which would be 02/03.

答:
To my understanding, weekday() only gives n'th day of the week based on a time instance.

So, ideally, the best way to get most recent weekday would be date.today().weekday().


问:
get Solana transaction status using Rust
I'm trying to get Solana transaction status using Rust. You can get the transaction status using explorer.solana.com, but I want to get it via code.

There is the get_signature_status function in the Rust SDK: https://github.com/solana-labs/solana/blob/master/client/src/rpc_client.rs#L1119

The function above expect a signature object: https://docs.rs/solana-sdk/0.16.2/src/solana_sdk/signature.rs.html#25

So I tried using it:

```<code>let sig_s = String::from("...");
let sig: Signature = Signature(sig_s.as_bytes());
let stat = self.client.get_signature_status(&sig);
println!("{:?}", stat);
</code>```

But I get an error of: "constructor is not visible here due to private fields"

I'm trying to understand if there is another way to create Signature object, I guess there should be a way to create Signature object and get its status.

答:
First of all, you linked to a massively outdated version of the docs (v0.16.2, the latest is v1.9.6). See https://docs.rs/solana-sdk for the latest version.

In the latest version, Signature implements FromStr so you can do the following:

```<code>let sig = Signature::from_str(sig_s).unwrap();
</code>```

And that'll get you a Signature you can use.

Body:
I'm trying to get Solana transaction status using Rust. You can get the transaction status using explorer.solana.com, but I want to get it via code.

There is the get_signature_status function in the Rust SDK: https://github.com/solana-labs/solana/blob/master/client/src/rpc_client.rs#L1119

The function above expect a signature object: https://docs.rs/solana-sdk/0.16.2/src/solana_sdk/signature.rs.html#25

So I tried using it:

let sig_s = String::from("...");
let sig: Signature = Signature(sig_s.as_bytes());
let stat = self.client.get_signature_status(&sig);
println!("{:?}", stat);

But I get an error of: "constructor is not visible here due to private fields"

I'm trying to understand if there is another way to create Signature object, I guess there should be a way to create Signature object and get its status.

Body:
First of all, you linked to a massively outdated version of the docs (v0.16.2, the latest is v1.9.6). See https://docs.rs/solana-sdk for the latest version.

In the latest version, Signature implements FromStr so you can do the following:

let sig = Signature::from_str(sig_s).unwrap();

And that'll get you a Signature you can use.


问:
Build Succeeded, but no .lib file gets created
I inherited a substantial amount of code, including a visual studio project that is supposed to (as best as I can tell) build a .lib file.  Visual studio says "... Generating Code... Creating Library... Creating browse information file...", and at the end, it says the build succeeded.  In the release/debug folder, it has a bunch of .obj files, but it doesn't have a .lib file.  What could I be missing?

Thanks!

答:
Sometimes when you break you head in a new project why .lib is not created - it can be some "past games" issue.
I was creating a new .dll but before I decided to use #define with __declspec(dllexport)/__declspec(dllimport) I tried to play with .def
After removing .def file it probably left some misconfiguration in the project file and it wasn't creating .lib file...
Till I decided to just remove the project completly and recreate - and walla, works perfectly!</p>


问:
Java calculate hex representation of a SHA-1 digest of a String
I'm storing the user password on the db as a sha1 hash.

Unfortunately I'm getting strange answers.

I'm storing the string as this:

```<code>MessageDigest cript = MessageDigest.getInstance("SHA-1");
              cript.reset();
              cript.update(userPass.getBytes("utf8"));
              this.password = new String(cript.digest());
</code>```

I wanted something like this -->

aff --> "0c05aa56405c447e6678b7f3127febde5c3a9238"

rather than

aff --> �V@\D~fx����:�8

答:
In java 17 HexFormat is introduced.

It allows you to write:

var cript = MessageDigest.getInstance("sha1");
var hexformat = HexFormat.of();
this.password = hexformat.formatHex(cript.digest(userPass.getBytes(StandardCharsets.UTF_8)))
```

Body:
I'm storing the user password on the db as a sha1 hash.

Unfortunately I'm getting strange answers.

I'm storing the string as this:

MessageDigest cript = MessageDigest.getInstance("SHA-1");
              cript.reset();
              cript.update(userPass.getBytes("utf8"));
              this.password = new String(cript.digest());

I wanted something like this -->

aff --> "0c05aa56405c447e6678b7f3127febde5c3a9238"

rather than

aff --> �V@\D~fx����:�8


问:
Container Creation Fails with Jib after upgrading to 2.7.0.Final
The container creation fails with the message
"Error": "OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/deployments/run-java.sh": stat /deployments/run-java.sh: no such file or directory: unknown",

The whole process works fine when I change the Quarkus version from 2.7.0.Final to 2.6.3.Final.

I am using jib to generate the image. Please let me know if I am missing anything.

答:
This is due to the change in base image that went in with Quarkus 2.7. See the relevant entry in the migration guide.
The new base image does not contain the /deployments/run-java.sh shell script.

You can go back to the base image used in previous Quarkus versions using quarkus.jib.base-jvm-image=fabric8/java-alpine-openjdk11-jre

If one needs to add their own startup script, then script can be added to the created container image as described here. Additionally the quarkus.jib.entry-point needs to be set to the path of the startup script.