问:
Paste From Clipboard Like MS Word
I appreciate if any one help me to tell me how to (paste from clipbord like MS Word) What I mean is if I selected a part of wep page contents text and picture, how to pate this contents from clipboard as it copped or formated.

this is my code

```<code>Private Sub Past_TxtBx_From_Cliboard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Try
        RCSN.DetectUrls = True
        Me.Cursor = Cursors.WaitCursor
        Clipboard.GetDataObject()
        If My.Computer.Clipboard.ContainsData(DataFormats.Html) Then
            Clipboard.GetText(TextDataFormat.Html)
        ElseIf (Clipboard.ContainsText(TextDataFormat.Html)) Then
            Clipboard.GetText(TextDataFormat.Html)
        ElseIf (Clipboard.ContainsText(TextDataFormat.Text)) Then
            Clipboard.GetText(TextDataFormat.Text)
        ElseIf My.Computer.Clipboard.ContainsImage() Then
            Clipboard.GetImage()
        End If
        RCSN.Paste()
        RCSN.Select()
    Catch ex As Exception
        ShowMsg(ex.Message & CurrentStickInfo(), "InfoSysMe (Stick Note)", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2, MessageBoxOptions.ServiceNotification, False)
    Finally
        Me.Cursor = Cursors.Default
        'RCSN.DetectUrls = False
    End Try
End Sub
</code>```

Title: Paste From Clipboard Like MS Word

Body:
I appreciate if any one help me to tell me how to (paste from clipbord like MS Word) What I mean is if I selected a part of wep page contents text and picture, how to pate this contents from clipboard as it copped or formated.

this is my code

Private Sub Past_TxtBx_From_Cliboard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Try
        RCSN.DetectUrls = True
        Me.Cursor = Cursors.WaitCursor
        Clipboard.GetDataObject()
        If My.Computer.Clipboard.ContainsData(DataFormats.Html) Then
            Clipboard.GetText(TextDataFormat.Html)
        ElseIf (Clipboard.ContainsText(TextDataFormat.Html)) Then
            Clipboard.GetText(TextDataFormat.Html)
        ElseIf (Clipboard.ContainsText(TextDataFormat.Text)) Then
            Clipboard.GetText(TextDataFormat.Text)
        ElseIf My.Computer.Clipboard.ContainsImage() Then
            Clipboard.GetImage()
        End If
        RCSN.Paste()
        RCSN.Select()
    Catch ex As Exception
        ShowMsg(ex.Message & CurrentStickInfo(), "InfoSysMe (Stick Note)", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2, MessageBoxOptions.ServiceNotification, False)
    Finally
        Me.Cursor = Cursors.Default
        'RCSN.DetectUrls = False
    End Try
End Sub


来源: stackexchange

问:
C# dotnet MongoDB UpdateMany command using linq (abstracted db access)

My Problem

I'm using an abstracted database layer between my app and mongodb.
I need to update an entire collection (UpdateMany). Could be 2 records, could be 200 million.
For this reason, I'm having trouble executing an abstracted UpdateMany, specifically, when either the Filter, or Update expressions include more than one value or property.

I can update one field, based on a single field in the filter, but i require multiple in both.

I know I can can "find" data, convert that to a list, the iterate the list and "update" one by one (which is what all examples I've seen say to do - example below) but seriously... 200 million records!!!

Background

My actual application knows nothing of MongoDB. It's using IQueryable for simple queries, and abstracted Insert, Update, Delete functions for individual entities by ID.

For queries, this works well. I retrieve an IQueryable of a collection, and use LINQ to query for some data.

public class AbstractionLayer {
    public IQueryable<T> GetQueryable<T>(string collectionName) {
        return db.GetCollection<T>(collectionName).AsQueryable();
    }
}
```
<p>I know, <code>mongoCollection.AsQueryable()</code> returns an <code>IMongoQueryable</code>, but the rest of the app will only ever know about the generic <code>IQueryable</code> from System.Linq.
Then, in my service (where dbAbstraction is an AbstractionLayer), I want to create a query for:</p>
<p>Mongo shell query: <code>db.Books.find({ "Publisher": "Penguin", "Year": { $gt: 1980 }})</code></p>
<p>Which looks like this:</p>
<pre class="lang-cs prettyprint-override"><code>public MyService {
    public void DoStuff() {
        var query = dbAbstraction.GetQueryable<Book>();
        var books = query
            .Where(b => b.Publisher == "Penguin")
            .Where(b => b.Year > 1980)
            .ToList();
    }
}
</code>```

Brilliant... I can create complex queries using Linq such as Where(), sorting, Take() etc.

Similarly, I can perform an "Update" by passing in an ID, and an update "Expression" using the following abstraction function:

public class AbstractionLayer {
    public bool UpdateOne<T>(string id, Expression<Func<T, object>> updateExpr, object value)
    {
        var collection = db.GetCollection<T>(nameof(T));
        var filter = Builders<T>.Filter.Eq(o => o.Id, id);
        var update = Builders<T>.Update.Set(updateExpr, value);
        var result = collection.UpdateOne(filter, update);
        return result.IsAcknowledged && result.MatchedCount > 0;
    }
}
```
<p>And call it like this:</p>
```// Update the publisher of a single book with the given ID:
_ = dbAbstraction.UpdateOne<Book>("1234567890abcdef12345678", b => b.Publisher, "Secret Publisher");
```
<h1>Main Question:</h1>
<p>However, for Update Many, with a complex filter query, I can't create anything more complex than filtering by a single field, and updating a single field.</p>
<p>I need to do this update many via the DB, as "finding" all matching docs, converting them (<code>.ToList()</code>) to an object list then iterating them back into individual update statements could bring the system down if there's 200 million matching records in a given update.
I know Mongo can do this in the background very quickly.</p>
<p>I have this so far:</p>
<pre class="lang-cs prettyprint-override"><code>    public UpdateMany<T>(
        Expression<Func<T, object>> findExpression,
        object filterValue,
        Expression<Func<T, object>> updateExpression,
        object updateValue)
    {
        var collection = this.GetCollection<T>(nameof(T));
        var filter = Builders<T>.Filter.Eq(findExpression, filterValue);
        var update = Builders<T>.Update.Set(updateExpression, updateValue);
        _ = collection.UpdateMany(filter, update);
    }
</code>```

But, this will only do a simple filter (by one field and value only) and can only update a single field at a time.

UpdateMany<Book>(b => b.Publisher, "Penguin", b => b.Publisher, "Secret Publisher");
```
<p>But, if I want to update multiple fields, or use multiple values in the find expression, I'm stuck.</p>
<p>How, if even possible, do I specify callbacks in a way I can filter using multiple conditions, as well as update multiple values of the matched documents?</p>
<h2>Example of the required "update many" in Mongo Shell</h2>
<p>My exact updates could have many times more properties than this, but as a simple example:</p>
<p>e.g. Mongo shell query: <code>db.Books.Update({ "Publisher": "Penguin", "Year": { $gt: 1980 }}, { "Publisher": "Secret Publisher", "LastUpdatedBy": "My Username" }, { multi: true })</code>;</p>
<h1>Update</h1>
<p>Progress so far...</p>
<p>My filter definition can now be defined as a single expression by changing the interface to (ignore the async differences to original question - my actual codebase if fully async):</p>
<pre class="lang-cs prettyprint-override"><code>Task<bool> UpdateAsync<TEntity>(
        Expression<Func<TEntity, bool>> filterExpression,
        Expression<Func<TEntity, object>> updateExpression,
        object updateValue)
</code>```

Calling:

await UpdateManyAsync(
    x => x.Publisher == "Penguin" && x.Year > 1980,
    x => x.Publisher,
    "Secret Publisher");
```

So, to figure out the second half...

ContentLicense: CC BY-SA 4.0

Body:
My Problem

I'm using an abstracted database layer between my app and mongodb.
I need to update an entire collection (UpdateMany). Could be 2 records, could be 200 million.
For this reason, I'm having trouble executing an abstracted UpdateMany, specifically, when either the Filter, or Update expressions include more than one value or property.

I can update one field, based on a single field in the filter, but i require multiple in both.

I know I can can "find" data, convert that to a list, the iterate the list and "update" one by one (which is what all examples I've seen say to do - example below) but seriously... 200 million records!!!

Background

My actual application knows nothing of MongoDB. It's using IQueryable for simple queries, and abstracted Insert, Update, Delete functions for individual entities by ID.

For queries, this works well. I retrieve an IQueryable of a collection, and use LINQ to query for some data.

public class AbstractionLayer {
    public IQueryable<T> GetQueryable<T>(string collectionName) {
        return db.GetCollection<T>(collectionName).AsQueryable();
    }
}

I know, mongoCollection.AsQueryable() returns an IMongoQueryable, but the rest of the app will only ever know about the generic IQueryable from System.Linq.
Then, in my service (where dbAbstraction is an AbstractionLayer), I want to create a query for:

Mongo shell query: db.Books.find({ "Publisher": "Penguin", "Year": { $gt: 1980 }})

Which looks like this:

public MyService {
    public void DoStuff() {
        var query = dbAbstraction.GetQueryable<Book>();
        var books = query
            .Where(b => b.Publisher == "Penguin")
            .Where(b => b.Year > 1980)
            .ToList();
    }
}

Brilliant... I can create complex queries using Linq such as Where(), sorting, Take() etc.

Similarly, I can perform an "Update" by passing in an ID, and an update "Expression" using the following abstraction function:

public class AbstractionLayer {
    public bool UpdateOne<T>(string id, Expression<Func<T, object>> updateExpr, object value)
    {
        var collection = db.GetCollection<T>(nameof(T));
        var filter = Builders<T>.Filter.Eq(o => o.Id, id);
        var update = Builders<T>.Update.Set(updateExpr, value);
        var result = collection.UpdateOne(filter, update);
        return result.IsAcknowledged && result.MatchedCount > 0;
    }
}

And call it like this:

// Update the publisher of a single book with the given ID:
_ = dbAbstraction.UpdateOne<Book>("1234567890abcdef12345678", b => b.Publisher, "Secret Publisher");

Main Question:

However, for Update Many, with a complex filter query, I can't create anything more complex than filtering by a single field, and updating a single field.

I need to do this update many via the DB, as "finding" all matching docs, converting them (.ToList()) to an object list then iterating them back into individual update statements could bring the system down if there's 200 million matching records in a given update.
I know Mongo can do this in the background very quickly.

I have this so far:

    public UpdateMany<T>(
        Expression<Func<T, object>> findExpression,
        object filterValue,
        Expression<Func<T, object>> updateExpression,
        object updateValue)
    {
        var collection = this.GetCollection<T>(nameof(T));
        var filter = Builders<T>.Filter.Eq(findExpression, filterValue);
        var update = Builders<T>.Update.Set(updateExpression, updateValue);
        _ = collection.UpdateMany(filter, update);
    }

But, this will only do a simple filter (by one field and value only) and can only update a single field at a time.

UpdateMany<Book>(b => b.Publisher, "Penguin", b => b.Publisher, "Secret Publisher");

But, if I want to update multiple fields, or use multiple values in the find expression, I'm stuck.

How, if even possible, do I specify callbacks in a way I can filter using multiple conditions, as well as update multiple values of the matched documents?

Example of the required "update many" in Mongo Shell

My exact updates could have many times more properties than this, but as a simple example:

e.g. Mongo shell query: db.Books.Update({ "Publisher": "Penguin", "Year": { $gt: 1980 }}, { "Publisher": "Secret Publisher", "LastUpdatedBy": "My Username" }, { multi: true });

Update

Progress so far...

My filter definition can now be defined as a single expression by changing the interface to (ignore the async differences to original question - my actual codebase if fully async):

Task<bool> UpdateAsync<TEntity>(
        Expression<Func<TEntity, bool>> filterExpression,
        Expression<Func<TEntity, object>> updateExpression,
        object updateValue)

Calling:

await UpdateManyAsync(
    x => x.Publisher == "Penguin" && x.Year > 1980,
    x => x.Publisher,
    "Secret Publisher");

So, to figure out the second half...


问:
React Native App is crashing on Android Version 12 or later
I am using react native 64.0.3 version to develop the app. Recently I have shifted my sdk
31. I am facing this issue:

"Targeting S+ (version 31 and above) requires that one of
flag_immutable or flag_mutable be specified when creating a
PendingIntent. Strongly consider using flag_immutable, only use
flag_mutable if some functionality depends on the Pendingment being
mutable, e.g. if it needs to be used with inline replies or bubbles"

My build.gradle(android/app):

```<code>dependencies {
    implementation(project(':react-native-svg')) {
        exclude group: "com.android.support", module: "appcompat-v7"
    }
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    //noinspection GradleDynamicVersion
    // implementation('androidx.work:work-runtime:2.7.1')
    implementation "androidx.media:media:1.4.1"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'androidx.appcompat:appcompat:1.7.0-alpha01'
    implementation 'androidx.work:work-runtime-ktx:2.7.1'
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
    implementation 'com.android.support:multidex:1.0.3'
    implementation project(':react-native-view-pdf')
    implementation project(':rn-fetch-blob')
    implementation project(':react-native-ping')
    implementation project(':react-native-gesture-handler')
    implementation 'com.facebook.fresco:animated-gif:2.6.0'
    debugImplementation("com.facebook.flipper:flipper:0.176.1") {
      exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:0.176.1") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:0.176.1") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}
</code>```

Body:
I am using react native 64.0.3 version to develop the app. Recently I have shifted my sdk
31. I am facing this issue:

"Targeting S+ (version 31 and above) requires that one of
flag_immutable or flag_mutable be specified when creating a
PendingIntent. Strongly consider using flag_immutable, only use
flag_mutable if some functionality depends on the Pendingment being
mutable, e.g. if it needs to be used with inline replies or bubbles"

My build.gradle(android/app):

dependencies {
    implementation(project(':react-native-svg')) {
        exclude group: "com.android.support", module: "appcompat-v7"
    }
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    //noinspection GradleDynamicVersion
    // implementation('androidx.work:work-runtime:2.7.1')
    implementation "androidx.media:media:1.4.1"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'androidx.appcompat:appcompat:1.7.0-alpha01'
    implementation 'androidx.work:work-runtime-ktx:2.7.1'
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
    implementation 'com.android.support:multidex:1.0.3'
    implementation project(':react-native-view-pdf')
    implementation project(':rn-fetch-blob')
    implementation project(':react-native-ping')
    implementation project(':react-native-gesture-handler')
    implementation 'com.facebook.fresco:animated-gif:2.6.0'
    debugImplementation("com.facebook.flipper:flipper:0.176.1") {
      exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:0.176.1") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:0.176.1") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}


问:
Access ID of user from a given map on click of dropdown - Flutter
I had a map given below. The task is to create a dropdown with values showing in the dropdown and when selecting those values I get to store keys in a list.
On Selecting the name of the user. The ID must be selected and stored in a list.
Tried using the below approach. But it only matches with the First occurrence of the user and returns its ID.

```<code> var idOfUser = groupsController
                                            .userMap.keys
                                            .firstWhere((element) =>
                                                groupsController
                                                        .userMap[element] ==
                                                    value);
</code>```

**This is User Map ---> {1: Royal Coders, 5: Harshit Gupta, 7: Harshit Gupta, 8: Harshit Gupta, 9: Harshit Gupta, 10: Harshit Gupta, 11: Harshit Gupta, 12: Harshit Gupta, 13: Vinove Coders, 14: Value Coders, 15: Harshit Gupta, 16: Abhay Sharma, 17: SHUBHAM SINGH, 18: Abhay Sharma, 19: Abhay Sharma, 20: Abhay Sharma, 21: Abhay Sharma, 22: Abhay Sharma, 23: Abhay Sharma, 24: Test User, 25: Abhay Sharma, 26: Abhay Sharma, 27: Abhay Sharma, 28: Abhay Sharma, 29: Abhay Sharma, 30: Abhay Sharma, 31: Abhay Sharma, 32: Abhay Sharma, 33: Abh  sh, 34: Abh  sh, 35: abh vjh, 36: abhay sharma, 37: gdgb  cvh, 38: sparsh tandon, 39: sparsh tandon, 40: sparsh tandon, 41: vcghfhh bfghfh, 42: aaaddgh saddgh, 43: SHUBHAM SINGH, 44: 1 string, 45: Abhay Sharma, 46: Sparsh Vinove , 47: 1 string, 48: 1 string, 49: 1 string, 50: Harshit Gupta, 51: Harshit Gupta, 52: Harshit Gupta, 53: Harshit Gupta, 54: 1 @, 55: Harshit Gupta, 56: Harshit Gupta, 57: Harshit Gupta, 58: Harshit Gupta, 59: Harshit Gupta, 60: Harshit Gupta}

Body:
I had a map given below. The task is to create a dropdown with values showing in the dropdown and when selecting those values I get to store keys in a list.
On Selecting the name of the user. The ID must be selected and stored in a list.
Tried using the below approach. But it only matches with the First occurrence of the user and returns its ID.

 var idOfUser = groupsController
                                            .userMap.keys
                                            .firstWhere((element) =>
                                                groupsController
                                                        .userMap[element] ==
                                                    value);

**This is User Map ---> {1: Royal Coders, 5: Harshit Gupta, 7: Harshit Gupta, 8: Harshit Gupta, 9: Harshit Gupta, 10: Harshit Gupta, 11: Harshit Gupta, 12: Harshit Gupta, 13: Vinove Coders, 14: Value Coders, 15: Harshit Gupta, 16: Abhay Sharma, 17: SHUBHAM SINGH, 18: Abhay Sharma, 19: Abhay Sharma, 20: Abhay Sharma, 21: Abhay Sharma, 22: Abhay Sharma, 23: Abhay Sharma, 24: Test User, 25: Abhay Sharma, 26: Abhay Sharma, 27: Abhay Sharma, 28: Abhay Sharma, 29: Abhay Sharma, 30: Abhay Sharma, 31: Abhay Sharma, 32: Abhay Sharma, 33: Abh  sh, 34: Abh  sh, 35: abh vjh, 36: abhay sharma, 37: gdgb  cvh, 38: sparsh tandon, 39: sparsh tandon, 40: sparsh tandon, 41: vcghfhh bfghfh, 42: aaaddgh saddgh, 43: SHUBHAM SINGH, 44: 1 string, 45: Abhay Sharma, 46: Sparsh Vinove , 47: 1 string, 48: 1 string, 49: 1 string, 50: Harshit Gupta, 51: Harshit Gupta, 52: Harshit Gupta, 53: Harshit Gupta, 54: 1 @, 55: Harshit Gupta, 56: Harshit Gupta, 57: Harshit Gupta, 58: Harshit Gupta, 59: Harshit Gupta, 60: Harshit Gupta}


问:
How to improve MYSQL sort by match against rel query speed?
Below is my table schema, and a query, I am trying to search on title of the product and sort by relevance score. However, my query takes ~10 second to return results from 1 million row DB, I need ~1 second perf. Thanks

My TABLE SCHEMA:

```<code>CREATE TABLE aliexpress (
                id INT PRIMARY KEY AUTO_INCREMENT UNIQUE NOT NULL,
                `title` VARCHAR(500) NOT NULL,
                `subCatogery` VARCHAR(50) NOT NULL DEFAULT '',
                `numberSold` VARCHAR(10) NOT NULL DEFAULT '0',
                `reviewScore` FLOAT(10) NOT NULL DEFAULT '0',
                `thumbnailSource` VARCHAR(200) NOT NULL DEFAULT '',
                `productLink` VARCHAR(500) NOT NULL DEFAULT '',
                `priceCurrency` VARCHAR(100) NOT NULL DEFAULT '',
                `price` VARCHAR(50) NOT NULL DEFAULT '',
                `isFreeShip` BOOLEAN,
                `shipFromUS` BOOLEAN,
                `feedbackScore` VARCHAR(10),
                `itemAsDescribed` FLOAT(10),
                `shipSpeed`FLOAT(10),
                `communication` FLOAT(10),
                `changeDate` date NOT NULL,
                totalAvailableQuantity VARCHAR(10),
                description VARCHAR(10000),
                orders VARCHAR(10),
                images JSON,
                storeInfo JSON,
                ratings JSON,
                feedbacks JSON,
                varOptions JSON,
                varPrices JSON,
                spec JSON,
                currency VARCHAR(10),
                minOriginalPrice VARCHAR(10),
                maxOriginalPrice VARCHAR(10),
                minSalePrice VARCHAR(10),
                maxSalePrice VARCHAR(10),
                productID VARCHAR(50),
                storeID VARCHAR(100),
                JSCralwerDate date,
                isExpired VARCHAR(10),
                shippingDayMin VARCHAR(10),
                shippingDayMax VARCHAR(10),
                videoLink VARCHAR(200),
                shippingFee VARCHAR(10),
                INDEX (`subCatogery`, `price`, `isFreeShip`, `shipFromUS`, `feedbackScore`, `itemAsDescribed`, `shipSpeed`
                , reviewScore, numberSold, isExpired, productID, shippingDayMin, shippingDayMax, shippingFee),
                FULLTEXT(title)
        ) ENGINE=MyISAM DEFAULT CHARSET=UTF8MB4;

</code>```

MySQL Query:

```<code>SELECT
    base.id
FROM
    `aliexpress` base
        JOIN
    (SELECT
        `id`,
            MATCH (title) AGAINST ('+latex pants' IN BOOLEAN MODE) AS rel
    FROM
        `aliexpress`
    LIMIT 1000000) result ON base.id = result.id
ORDER BY result.rel DESC limit 1;
</code>```

This query takes ~10 seconds to execute, and aliexpress has ~1 million rows. How can I improve this query speed to ~1 second. Thanks

Body:
Below is my table schema, and a query, I am trying to search on title of the product and sort by relevance score. However, my query takes ~10 second to return results from 1 million row DB, I need ~1 second perf. Thanks

My TABLE SCHEMA:

CREATE TABLE aliexpress (
                id INT PRIMARY KEY AUTO_INCREMENT UNIQUE NOT NULL,
                `title` VARCHAR(500) NOT NULL,
                `subCatogery` VARCHAR(50) NOT NULL DEFAULT '',
                `numberSold` VARCHAR(10) NOT NULL DEFAULT '0',
                `reviewScore` FLOAT(10) NOT NULL DEFAULT '0',
                `thumbnailSource` VARCHAR(200) NOT NULL DEFAULT '',
                `productLink` VARCHAR(500) NOT NULL DEFAULT '',
                `priceCurrency` VARCHAR(100) NOT NULL DEFAULT '',
                `price` VARCHAR(50) NOT NULL DEFAULT '',
                `isFreeShip` BOOLEAN,
                `shipFromUS` BOOLEAN,
                `feedbackScore` VARCHAR(10),
                `itemAsDescribed` FLOAT(10),
                `shipSpeed`FLOAT(10),
                `communication` FLOAT(10),
                `changeDate` date NOT NULL,
                totalAvailableQuantity VARCHAR(10),
                description VARCHAR(10000),
                orders VARCHAR(10),
                images JSON,
                storeInfo JSON,
                ratings JSON,
                feedbacks JSON,
                varOptions JSON,
                varPrices JSON,
                spec JSON,
                currency VARCHAR(10),
                minOriginalPrice VARCHAR(10),
                maxOriginalPrice VARCHAR(10),
                minSalePrice VARCHAR(10),
                maxSalePrice VARCHAR(10),
                productID VARCHAR(50),
                storeID VARCHAR(100),
                JSCralwerDate date,
                isExpired VARCHAR(10),
                shippingDayMin VARCHAR(10),
                shippingDayMax VARCHAR(10),
                videoLink VARCHAR(200),
                shippingFee VARCHAR(10),
                INDEX (`subCatogery`, `price`, `isFreeShip`, `shipFromUS`, `feedbackScore`, `itemAsDescribed`, `shipSpeed`
                , reviewScore, numberSold, isExpired, productID, shippingDayMin, shippingDayMax, shippingFee),
                FULLTEXT(title)
        ) ENGINE=MyISAM DEFAULT CHARSET=UTF8MB4;

MySQL Query:

SELECT
    base.id
FROM
    `aliexpress` base
        JOIN
    (SELECT
        `id`,
            MATCH (title) AGAINST ('+latex pants' IN BOOLEAN MODE) AS rel
    FROM
        `aliexpress`
    LIMIT 1000000) result ON base.id = result.id
ORDER BY result.rel DESC limit 1;

This query takes ~10 seconds to execute, and aliexpress has ~1 million rows. How can I improve this query speed to ~1 second. Thanks


问:
Module Federation: Can a NextJS Remote work in a CRA Host?
Would it possible to use a NextJS remote in a Create React App (CRA) host app?

On the NextJS Remote, I am using @module-federation/nextjs-mf to expose a component which relies on NextJS's useRouter.

On the CRA Host, I am using craco-mf to connect to the component.

However when running the CRA Host, I am receiving the console error: Uncaught Error: Shared module next/router doesn't exist in shared scope default

Q: How can I resolve this issue? Is this even possible?

References:

A similar issue was being brought up in a thread within this discussion as well.

Update:

I am starting to think that I should create a NextJS remote and CRA remote for the same component. Q. Would this be a viable solution?


问:
How to extract the 6th value of a multi-dimensional numpy array
I've written the following code to read a CSV file and parse the data down to a numpy array.  However, I only want the 6th number from each array. I wondered if I could do it in the string spilt method before converting it to a numpy array but couldn't get anything to work.

```<code>data = pd.read_csv('pbhistory.csv')
data['date'] = pd.to_datetime(data.date, infer_datetime_format=True)
data.sort_values(by='date', ascending=True, inplace=True)
df = pd.DataFrame(data.numbers)
df2 = df['numbers'].str.split(' ', expand=True)
df3 = pd.DataFrame(df2).to_numpy()
</code>```

I get the following output:

```<code>[['17' '22' '36' '37' '52' '24']
 ['14' '22' '52' '54' '59' '04']
 ['05' '08' '29' '37' '38' '34']
 ['10' '14' '30' '40' '51' '01']
 ['07' '08' '19' '26' '36' '15']]
</code>```

What I would like is the 6th or last number from each array.  For example, 24, 04, 34, 01, and 15 from the array above.

Body:
I've written the following code to read a CSV file and parse the data down to a numpy array.  However, I only want the 6th number from each array. I wondered if I could do it in the string spilt method before converting it to a numpy array but couldn't get anything to work.

data = pd.read_csv('pbhistory.csv')
data['date'] = pd.to_datetime(data.date, infer_datetime_format=True)
data.sort_values(by='date', ascending=True, inplace=True)
df = pd.DataFrame(data.numbers)
df2 = df['numbers'].str.split(' ', expand=True)
df3 = pd.DataFrame(df2).to_numpy()

I get the following output:

[['17' '22' '36' '37' '52' '24']
 ['14' '22' '52' '54' '59' '04']
 ['05' '08' '29' '37' '38' '34']
 ['10' '14' '30' '40' '51' '01']
 ['07' '08' '19' '26' '36' '15']]

What I would like is the 6th or last number from each array.  For example, 24, 04, 34, 01, and 15 from the array above.


问:
How to create sequential (primary) id that is constrained to another id or parameter?
I am creating an Invoicing Application and I am using sequelize.

I want the invoice code (or id) to be sequential per (end-) user profile; not throughout the system/database.

For instance, let us consider 2 end-users who created 2 invoices. The first 2 distinct invoices for each end-users will be <0001> and <0002>; 4 invoices in total.

I am using MySQL where I can easily define an auto-incremental  / sequential ID as so:

```<code>module.exports = (sequelize, Sequelize) => {
const Invoice = sequelize.define("invoice", {
id: {
  type: Sequelize.INTEGER,
  primaryKey: true,
  allowNull: false,
},
userId: {
  type: DataTypes.BIGINT,
  allowNull: false,
  references: {
    model: 'user',
    key: 'id',
  },
},
contactId: {
  type: DataTypes.BIGINT,
  allowNull: false,
  references: {
    model: 'contact',
    key: 'id',
  },
},
dueDays: {
  type: DataTypes.BIGINT,
  allowNull: false,
},
subTotal: {
  type: DataTypes.DECIMAL,
  allowNull: true,
}, ...
</code>```

However, with the code above, an invoice will have a sequential/incremental id throughout the database regardless of the specific end user issuing the invoice.

What is the correct way to implement this so that the invoice ID is incremented per end user?

Should each user have its own database (a database dedicated to one end-user) accessible through one server instance?

Thanks!

Body:
I am creating an Invoicing Application and I am using sequelize.

I want the invoice code (or id) to be sequential per (end-) user profile; not throughout the system/database.

For instance, let us consider 2 end-users who created 2 invoices. The first 2 distinct invoices for each end-users will be <0001> and <0002>; 4 invoices in total.

I am using MySQL where I can easily define an auto-incremental  / sequential ID as so:

module.exports = (sequelize, Sequelize) => {
const Invoice = sequelize.define("invoice", {
id: {
  type: Sequelize.INTEGER,
  primaryKey: true,
  allowNull: false,
},
userId: {
  type: DataTypes.BIGINT,
  allowNull: false,
  references: {
    model: 'user',
    key: 'id',
  },
},
contactId: {
  type: DataTypes.BIGINT,
  allowNull: false,
  references: {
    model: 'contact',
    key: 'id',
  },
},
dueDays: {
  type: DataTypes.BIGINT,
  allowNull: false,
},
subTotal: {
  type: DataTypes.DECIMAL,
  allowNull: true,
}, ...

However, with the code above, an invoice will have a sequential/incremental id throughout the database regardless of the specific end user issuing the invoice.

What is the correct way to implement this so that the invoice ID is incremented per end user?

Should each user have its own database (a database dedicated to one end-user) accessible through one server instance?

Thanks!


问:
Django on nginx showing logs for both basic auth logged in and logged out for same device
Project setup: I have a Django app deployed on my VPS with nginx (using docker compose). The nginx has BASIC auth, so users have to login with BASIC auth in order to use the app. I also have fail2ban installed on my host machine, so if 4xx errors are returned for the same IP address multiple times, that IP address is banned.

My app is primarily used for staff members at my store, and there are at most 3 people using the app on their respective computers.

Problem: fail2ban is banning even my staff members, who should have been logged in via BASIC auth. Checking the logs, it seems that for the same IP address, there are logs for both logged in and logged out user. The logs look something like this:

(masked IP address is the staff's, who should have been logged in)

```<code>xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:00 +0900] "POST /search/ HTTP/1.1" 200 406 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:00 +0900] "POST /search/ HTTP/1.1" 200 406 Chrome/108.0.0.0
xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:11 +0900] "GET /page-one/ HTTP/1.1" 401 574 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:11 +0900] "GET /page-one/ HTTP/1.1" 200 58526 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:14 +0900] "POST /page-one/ HTTP/1.1" 302 0 Chrome/108.0.0.0
</code>```
```<code>xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:51 +0900] "GET /page-one/ HTTP/1.1" 200 58526 Chrome/108.0.0.0
xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:53 +0900] "GET /page-two/ HTTP/1.1" 401 574 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:53 +0900] "GET /page-two/ HTTP/1.1" 200 6465 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:54 +0900] "GET /page-one/ HTTP/1.1" 200 58526 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:57 +0900] "GET /page-one/ HTTP/1.1" 200 58526 Chrome/108.0.0.0
xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:58 +0900] "GET /page-three/ HTTP/1.1" 401 574 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:59 +0900] "GET /page-three/ HTTP/1.1" 200 8115 Chrome/108.0.0.0
xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:59 +0900] "GET /page-three-styles.css HTTP/1.1" 401 574 Chrome/108.0.0.0
xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:59 +0900] "GET /page-three-script.js HTTP/1.1" 401 574 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:59 +0900] "GET /page-three-styles.css HTTP/1.1" 304 0 Chrome/108.0.0.0
</code>```

The logs show that there are both requests from the logged in user staff and the logged out user - for the same IP xxx.xxx.xxx.xx.

I have confirmed with my staff that

there was only one person using the app at the time

as far as they are aware, they did not try to request the page that have returned 401

The only explanations I can come up with are that somehow Django makes requests to other pages in the background, or nginx logs out requests at random, but I'm sure there is a better explanation for this issue I am seeing.

Body:
Project setup: I have a Django app deployed on my VPS with nginx (using docker compose). The nginx has BASIC auth, so users have to login with BASIC auth in order to use the app. I also have fail2ban installed on my host machine, so if 4xx errors are returned for the same IP address multiple times, that IP address is banned.

My app is primarily used for staff members at my store, and there are at most 3 people using the app on their respective computers.

Problem: fail2ban is banning even my staff members, who should have been logged in via BASIC auth. Checking the logs, it seems that for the same IP address, there are logs for both logged in and logged out user. The logs look something like this:

(masked IP address is the staff's, who should have been logged in)

xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:00 +0900] "POST /search/ HTTP/1.1" 200 406 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:00 +0900] "POST /search/ HTTP/1.1" 200 406 Chrome/108.0.0.0
xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:11 +0900] "GET /page-one/ HTTP/1.1" 401 574 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:11 +0900] "GET /page-one/ HTTP/1.1" 200 58526 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:14 +0900] "POST /page-one/ HTTP/1.1" 302 0 Chrome/108.0.0.0

xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:51 +0900] "GET /page-one/ HTTP/1.1" 200 58526 Chrome/108.0.0.0
xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:53 +0900] "GET /page-two/ HTTP/1.1" 401 574 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:53 +0900] "GET /page-two/ HTTP/1.1" 200 6465 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:54 +0900] "GET /page-one/ HTTP/1.1" 200 58526 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:57 +0900] "GET /page-one/ HTTP/1.1" 200 58526 Chrome/108.0.0.0
xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:58 +0900] "GET /page-three/ HTTP/1.1" 401 574 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:59 +0900] "GET /page-three/ HTTP/1.1" 200 8115 Chrome/108.0.0.0
xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:59 +0900] "GET /page-three-styles.css HTTP/1.1" 401 574 Chrome/108.0.0.0
xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:59 +0900] "GET /page-three-script.js HTTP/1.1" 401 574 Chrome/108.0.0.0
xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:59 +0900] "GET /page-three-styles.css HTTP/1.1" 304 0 Chrome/108.0.0.0

The logs show that there are both requests from the logged in user staff and the logged out user - for the same IP xxx.xxx.xxx.xx.

I have confirmed with my staff that

there was only one person using the app at the time

as far as they are aware, they did not try to request the page that have returned 401

The only explanations I can come up with are that somehow Django makes requests to other pages in the background, or nginx logs out requests at random, but I'm sure there is a better explanation for this issue I am seeing.


问:
How to add Identity to your MVC project
After I added Identity to my project, I keep getting to this error message when I try to run the project

```<code>    using CandySoap.Data;
using CandySoap.DataAccess.Repository;
using CandySoap.DataAccess.Repository.IRepository;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationContext>(option => option.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionLink")));

builder.Services.AddDefaultIdentity<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationContext>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();;

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{area=Customer}/{controller=Home}/{action=Index}/{id?}");

app.Run();
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
</code>```

using Microsoft.EntityFrameworkCore;

```<code>namespace CandySoap.Data
{
    public class ApplicationContext : IdentityDbContext
    {
        public ApplicationContext(DbContextOptions<ApplicationContext> option) : base(option) { }
        public DbSet<Category> categories { get; set; }
        public DbSet<Covertype> covertypes { get; set; }
        public DbSet<Product> products { get; set; }
    }
}
</code>```

Error message:constructed (Error while validating the service descriptor 'ServiceType: CandySoap.DataAccess.Repository.IRepository.IUnitOfWork Lifetime: Scoped ImplementationType: CandySoap.DataAccess.Repository.UnitOfWork': Unable to resolve

```<code>using CandySoap.Data;
using CandySoap.DataAccess.Repository.IRepository;

namespace CandySoap.DataAccess.Repository
{
    public class UnitOfWork : IUnitOfWork
    {
        private ApplicationContext _db;

        public UnitOfWork(ApplicationContext db)
        {
            _db = db;
            Category = new CategoryRepository(_db);
            Covers = new CovertypesRepository(_db);
            Product = new ProductRepository(_db);

        }
        public ICategoryRepository Category { get; private set; }

        public ICovertypesRepository Covers { get; private set; }

        public IProductRepository Product { get; private set; }

        public void Save()
        {
            _db.SaveChanges();
        }
    }
}
</code>```

er code here

Title: How to add Identity to your MVC project

Body:
After I added Identity to my project, I keep getting to this error message when I try to run the project

    using CandySoap.Data;
using CandySoap.DataAccess.Repository;
using CandySoap.DataAccess.Repository.IRepository;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationContext>(option => option.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionLink")));

builder.Services.AddDefaultIdentity<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationContext>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();;

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{area=Customer}/{controller=Home}/{action=Index}/{id?}");

app.Run();
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

using Microsoft.EntityFrameworkCore;

namespace CandySoap.Data
{
    public class ApplicationContext : IdentityDbContext
    {
        public ApplicationContext(DbContextOptions<ApplicationContext> option) : base(option) { }
        public DbSet<Category> categories { get; set; }
        public DbSet<Covertype> covertypes { get; set; }
        public DbSet<Product> products { get; set; }
    }
}

Error message:constructed (Error while validating the service descriptor 'ServiceType: CandySoap.DataAccess.Repository.IRepository.IUnitOfWork Lifetime: Scoped ImplementationType: CandySoap.DataAccess.Repository.UnitOfWork': Unable to resolve

using CandySoap.Data;
using CandySoap.DataAccess.Repository.IRepository;

namespace CandySoap.DataAccess.Repository
{
    public class UnitOfWork : IUnitOfWork
    {
        private ApplicationContext _db;

        public UnitOfWork(ApplicationContext db)
        {
            _db = db;
            Category = new CategoryRepository(_db);
            Covers = new CovertypesRepository(_db);
            Product = new ProductRepository(_db);

        }
        public ICategoryRepository Category { get; private set; }

        public ICovertypesRepository Covers { get; private set; }

        public IProductRepository Product { get; private set; }

        public void Save()
        {
            _db.SaveChanges();
        }
    }
}

er code here


问:
How to pass parameter and get value from .ps1 in C#
I can excute the .ps1 file by the command on PowerShell

```<code>./Restart/get_parentid.ps1 -Computername "computername" -processid "processid"
</code>```

and return the value of parent id integer.

How can I use it on C# to pass the computer name and processid for getting the return value?

```<code>Process.Start(powershell.exe, filelocation, computername, processid);
</code>```

Body:
I can excute the .ps1 file by the command on PowerShell

./Restart/get_parentid.ps1 -Computername "computername" -processid "processid"

and return the value of parent id integer.

How can I use it on C# to pass the computer name and processid for getting the return value?

Process.Start(powershell.exe, filelocation, computername, processid);


问:
Understanding the regex for password validation
I was searching for Regex for passwords and came across this expression:

```<code>^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$
</code>```

I know what the quantifiers mean individually. However, I don't understand this expression.

Here, it is said that (?=.*[0-9]) means that the password must contain a single digit from 1 to 9. What I don't understand is the ?=.*   part. Can someone please help me with this? Thanks in advance!

Body:
I was searching for Regex for passwords and came across this expression:

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$

I know what the quantifiers mean individually. However, I don't understand this expression.

Here, it is said that (?=.*[0-9]) means that the password must contain a single digit from 1 to 9. What I don't understand is the ?=.*   part. Can someone please help me with this? Thanks in advance!


问:
Polygon.io : Forex Quotes, timestamp and "next_url":"n_url" next GET issue using C#
The issue is when trying to http GET information from the FOREX historical tick data in polygon.io, from https://polygon.io/docs/forex/get_v3_quotes__fxticker it works by date using the following call.

https://api.polygon.io/v3/quotes/C:EUR-USD +

?timestamp=1638802773000000000&order=asc&limit=100&sort=timestamp&apiKey=api_key_goes_here

It works on the polygon.io web site when doing a query, but from C# code it does not, it returns a single result. Using an actual date it works for the first call in C# for the limit requested, but not subsequent ones. the returns are always a single line, and it is always the same line. The last one in the date call (timestamp) below, regardless of date.

?timestamp=2020-01-05&order=asc&limit=1000&sort=timestamp&apiKey=api_key_goes_here

When using the json "next_url":"urlfrom polygonIO" returned, it fails also and returns a single line or no lines.

The code I am using is below. It should be as simple as taking the last tick returned and feeding it back in.

Does anyone have any idea where I am going wrong?

```<code>`using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;

using static PolygonIO_HistoricTickData.Program;

namespace PolygonIO_HistoricTickData
{
    internal class Program
    {
        static string baseAddress = string.Empty;
        static string apiKey = string.Empty;
        static string parameters = string.Empty;
        static string timestamp = string.Empty;

        static void Main(string[] args)
        {

        //https://api.polygon.io/v3/quotes/C:EUR-USD?timestamp=1638802773000000000&order=asc&limit=100&sort=timestamp&apiKey=ApiKeyGoesHere

            int limitCount = 100;

            apiKey = "Your Polygon.io key goes here"; // you can get one here ... https://polygon.io/docs/forex/get_v3_quotes__fxticker

            //timestamp = "2021-12-06"; // = Mon Dec 06 2021 09:59:33 GMT - 0500(Eastern Standard Time)
            timestamp = "1638802774000000000"; // = ~ Mon Dec 06 2021 09:59:33 GMT - 0500(Eastern Standard Time)

            baseAddress = "https://api.polygon.io/v3/quotes/C:EUR-USD";
            parameters = "?timestamp=" + timestamp + "&order=asc&limit=" + limitCount + "&sort=timestamp&apiKey=" + apiKey;

            bool loop = true;
            Root ThisIsTheReturn = new Root();

            Console.WriteLine("\n\n\n" + baseAddress + parameters);

            parameters = "?timestamp=" + timestamp + "&order=asc&limit=" + limitCount + "&sort=timestamp&apikey=" + apiKey;

            // loop through next
            while (loop = true || ThisIsTheReturn.next_url != string.Empty)
            {
                //string url = hopeThisWorks.next_url;
                string url = baseAddress + parameters;

                Console.WriteLine("\n\n\n" + url + "&apiKey=" + apiKey);

                string polygonIOReturn = PolygonIOHistoricTickData(baseAddress, parameters);

                Console.WriteLine("\n\n>>>>>>>>>>>>>------------->>\n\n" + polygonIOReturn);

                ThisIsTheReturn = JsonConvert.DeserializeObject<Root>(polygonIOReturn);

                timestamp = ThisIsTheReturn.results[ThisIsTheReturn.results.Count - 1].participant_timestamp.ToString();
                parameters = "?timestamp=" + timestamp + "&order=asc&limit=" + limitCount + "&sort=timestamp&apikey=" + apiKey;

            }
        }

        public static string PolygonIOHistoricTickData(string baseAddress, string parameters) // AnotherTry05
        {

            string returnthis = string.Empty;

            var handler = new HttpClientHandler() { SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls };

            ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
            HttpClient httpClient = new HttpClient(handler);

            var task = Task.Run(() =>
                httpClient.GetAsync(baseAddress + parameters).Result.Content.ReadAsStringAsync()
                );
            task.Wait();

            returnthis = task.Result;

            return returnthis;
        }

        public class Root
        {
            public List<Result> results { get; set; }
            public string status { get; set; }
            public string request_id { get; set; }
            public string next_url { get; set; }
        }

        public class Result
        {
            public int ask_exchange { get; set; }
            public double ask_price { get; set; }
            public int bid_exchange { get; set; }
            public double bid_price { get; set; }
            public Int64 participant_timestamp { get; set; }
        }
    }
}`
</code>```

Using polygon.io The is documentation lacking. after creating a testing application flaws in both the documentation and the implementation showed up. I can pull data by date but not timestamp. The big flaw in using a time stamp is it only returns a single value ...

Body:
The issue is when trying to http GET information from the FOREX historical tick data in polygon.io, from https://polygon.io/docs/forex/get_v3_quotes__fxticker it works by date using the following call.

https://api.polygon.io/v3/quotes/C:EUR-USD +

?timestamp=1638802773000000000&order=asc&limit=100&sort=timestamp&apiKey=api_key_goes_here

It works on the polygon.io web site when doing a query, but from C# code it does not, it returns a single result. Using an actual date it works for the first call in C# for the limit requested, but not subsequent ones. the returns are always a single line, and it is always the same line. The last one in the date call (timestamp) below, regardless of date.

?timestamp=2020-01-05&order=asc&limit=1000&sort=timestamp&apiKey=api_key_goes_here

When using the json "next_url":"urlfrom polygonIO" returned, it fails also and returns a single line or no lines.

The code I am using is below. It should be as simple as taking the last tick returned and feeding it back in.

Does anyone have any idea where I am going wrong?

`using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;

using static PolygonIO_HistoricTickData.Program;

namespace PolygonIO_HistoricTickData
{
    internal class Program
    {
        static string baseAddress = string.Empty;
        static string apiKey = string.Empty;
        static string parameters = string.Empty;
        static string timestamp = string.Empty;

        static void Main(string[] args)
        {

        //https://api.polygon.io/v3/quotes/C:EUR-USD?timestamp=1638802773000000000&order=asc&limit=100&sort=timestamp&apiKey=ApiKeyGoesHere

            int limitCount = 100;

            apiKey = "Your Polygon.io key goes here"; // you can get one here ... https://polygon.io/docs/forex/get_v3_quotes__fxticker

            //timestamp = "2021-12-06"; // = Mon Dec 06 2021 09:59:33 GMT - 0500(Eastern Standard Time)
            timestamp = "1638802774000000000"; // = ~ Mon Dec 06 2021 09:59:33 GMT - 0500(Eastern Standard Time)

            baseAddress = "https://api.polygon.io/v3/quotes/C:EUR-USD";
            parameters = "?timestamp=" + timestamp + "&order=asc&limit=" + limitCount + "&sort=timestamp&apiKey=" + apiKey;

            bool loop = true;
            Root ThisIsTheReturn = new Root();

            Console.WriteLine("\n\n\n" + baseAddress + parameters);

            parameters = "?timestamp=" + timestamp + "&order=asc&limit=" + limitCount + "&sort=timestamp&apikey=" + apiKey;

            // loop through next
            while (loop = true || ThisIsTheReturn.next_url != string.Empty)
            {
                //string url = hopeThisWorks.next_url;
                string url = baseAddress + parameters;

                Console.WriteLine("\n\n\n" + url + "&apiKey=" + apiKey);

                string polygonIOReturn = PolygonIOHistoricTickData(baseAddress, parameters);

                Console.WriteLine("\n\n>>>>>>>>>>>>>------------->>\n\n" + polygonIOReturn);

                ThisIsTheReturn = JsonConvert.DeserializeObject<Root>(polygonIOReturn);

                timestamp = ThisIsTheReturn.results[ThisIsTheReturn.results.Count - 1].participant_timestamp.ToString();
                parameters = "?timestamp=" + timestamp + "&order=asc&limit=" + limitCount + "&sort=timestamp&apikey=" + apiKey;

            }
        }

        public static string PolygonIOHistoricTickData(string baseAddress, string parameters) // AnotherTry05
        {

            string returnthis = string.Empty;

            var handler = new HttpClientHandler() { SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls };

            ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
            HttpClient httpClient = new HttpClient(handler);

            var task = Task.Run(() =>
                httpClient.GetAsync(baseAddress + parameters).Result.Content.ReadAsStringAsync()
                );
            task.Wait();

            returnthis = task.Result;

            return returnthis;
        }

        public class Root
        {
            public List<Result> results { get; set; }
            public string status { get; set; }
            public string request_id { get; set; }
            public string next_url { get; set; }
        }

        public class Result
        {
            public int ask_exchange { get; set; }
            public double ask_price { get; set; }
            public int bid_exchange { get; set; }
            public double bid_price { get; set; }
            public Int64 participant_timestamp { get; set; }
        }
    }
}`

Using polygon.io The is documentation lacking. after creating a testing application flaws in both the documentation and the implementation showed up. I can pull data by date but not timestamp. The big flaw in using a time stamp is it only returns a single value ...


问:
prometheus : which is the best type for network_transmit_bytes_total
There is total network transmission and I need to save on Prometheus
My requirement :

Calculation of data increments in an interval like counter

reset data when a server reset, such as gauge

Problems :
If I want to use a counter, I don't have a set method or reset method also, and it is hard to how it can figure out when it needs to reset value.

In case I want to select gauge, we can't use the  increase() method on gauge (show the wrong value in resets times)

Based on my needs, what is the best choice?


问:
Allow user to choose photos for buttons
Building a script for controlling components at the house. As an example I have 4 buttons. I am trying to figure out how I can edit the button images as a user. so the user can assign an image to a button. I have a folder of pre designed images the user can select from.
I figured out how to open a filesystem, chose a photo and place that photo into a random button but I am not really sure where to go from here or if I am even going in the right direction. I am new so, example code would be very helpful with the explanation. thanks</p>
```<code>import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
from tkinter.filedialog import askopenfilename

my_w = tk.Tk()
my_w.geometry("800x480")
my_w.title('SELECT PHOTOS')

l1 = tk.Label(my_w, text='EDIT BUTTON IMAGES')
l1.pack()
b = tk.Button(my_w, text='IMAGES', command=lambda:upload_file())
b.pack()
f1 = tk.Frame(my_w)
b1 = tk.Button(f1, text="button 1")
b2 = tk.Button(f1, text="button 2")
b3 = tk.Button(f1, text="button 3")
b4 = tk.Button(f1, text="button 4")

b1.grid(row=0, column=0, padx=5)
b2.grid(row=0, column=1, padx=5)
b3.grid(row=0, column=2, padx=5)
b4.grid(row=0, column=3, padx=5)
f1.pack(pady=30)

def upload_file():
    f_types=[('png Files', '*.png'), ('Jpg Files', '*.png')]
    filename=tk.filedialog.askopenfilename(filetypes=f_types)
    img=Image.open(filename)
    img=img.resize((100, 100))
    img=ImageTk.PhotoImage(img)
    e1=tk.Button(my_w)
    e1.pack()
    e1.image=img
    e1['image'] = img

my_w.mainloop()

</code>```

Title: Allow user to choose photos for buttons

Body:
Building a script for controlling components at the house. As an example I have 4 buttons. I am trying to figure out how I can edit the button images as a user. so the user can assign an image to a button. I have a folder of pre designed images the user can select from.
I figured out how to open a filesystem, chose a photo and place that photo into a random button but I am not really sure where to go from here or if I am even going in the right direction. I am new so, example code would be very helpful with the explanation. thanks

import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
from tkinter.filedialog import askopenfilename

my_w = tk.Tk()
my_w.geometry("800x480")
my_w.title('SELECT PHOTOS')

l1 = tk.Label(my_w, text='EDIT BUTTON IMAGES')
l1.pack()
b = tk.Button(my_w, text='IMAGES', command=lambda:upload_file())
b.pack()
f1 = tk.Frame(my_w)
b1 = tk.Button(f1, text="button 1")
b2 = tk.Button(f1, text="button 2")
b3 = tk.Button(f1, text="button 3")
b4 = tk.Button(f1, text="button 4")

b1.grid(row=0, column=0, padx=5)
b2.grid(row=0, column=1, padx=5)
b3.grid(row=0, column=2, padx=5)
b4.grid(row=0, column=3, padx=5)
f1.pack(pady=30)

def upload_file():
    f_types=[('png Files', '*.png'), ('Jpg Files', '*.png')]
    filename=tk.filedialog.askopenfilename(filetypes=f_types)
    img=Image.open(filename)
    img=img.resize((100, 100))
    img=ImageTk.PhotoImage(img)
    e1=tk.Button(my_w)
    e1.pack()
    e1.image=img
    e1['image'] = img

my_w.mainloop()


Title: How to use telegram auth key with nodejs?

Body:
I have auth_key in format like [number, number, number ... number] (its just a Buffer)

I have host and port I need to log in, I have mobile phone also.

And I need to login account through telegram API using node.js.

Eg auth key:

[
108,86,106,236,141,234,215,213,63,78,153,89,4,217,38,157,29,231,45,30,120,81,159,141,137,97,236,247,
163,66,132,87,50,252,120,152,112,119,47,172,51,205,7,98,13,51,93,222,162,255,60,163,213,46,17,206,17,
69,156,123,229,248,71,119,118,226,85,100,74,160,126,9,189,158,217,204,246,66,191,67,142,223,163,25,
152,121,150,89,255,188,102,177,203,188,254,213,28,84,159,207,88,15,87,39,116,229,208,120,174,202,182,
184,15,44,160,116,206,152,134,74,166,89,183,66,76,138,83,168,235,196,166,186,109,88,176,54,93,17,146,
232,148,201,229,178,196,60,198,120,241,243,250,65,36,205,124,92,40,215,107,74,27,23,112,164,241,250,
149,140,30,146,139,24,204,69,101,115,15,178,164,158,43,178,75,115,197,145,108,221,224,197,222,179,
210,218,137,188,152,58,129,225,157,251,125,236,57,123,162,72,27,109,533,244,133,82,7,179,15,255,190,
173,59,14,24,212,21,101,224,248,106,211,138,3,142,41,45,89,123,227,115,234,126,243,165,105,115,12,
172,221,82,61,190,178,86,203,85,251
]

I tried sending these bytes directly to server:

const buffer = new Buffer.from(this.account.auth_key);
fetch('91.108.56.157:443', {
    method: 'POST',
    body: buffer
});

Also I tried using get/post/put requests but it did not work.


问:
Typing React custom hook useOnOutsideClick
help with hook typing, I did not find a solution on the site

```<code>import { RefObject, useEffect, useRef } from 'react';
import { isEqual } from 'lodash';

const useOnOutsideClick = <T extends HTMLElement = HTMLElement>(
  $ignoredElementRefs:RefObject<T>,
  isListening:boolean,
  onOutsideClick:()=>void,
  $listeningElementRef:RefObject<T>,
) => {
  const $mouseDownTargetRef = useRef(null);
  const $ignoredElementRefsMemoized = useDeepCompareMemoize([$ignoredElementRefs].flat());

  useEffect(() => {
    const handleMouseDown = (event:MouseEventInit ) => {
      const e = event as MouseEvent
      $mouseDownTargetRef.current = e?.target;
    };

    const handleMouseUp = (event:MouseEventInit) => {
      const e = event as MouseEvent
      const isAnyIgnoredElementAncestorOfTarget = $ignoredElementRefsMemoized?.some(
        $elementRef =>
          $elementRef.current.contains($mouseDownTargetRef.current) ||
          $elementRef.current.contains(e.target),
      );
      if (e.button === 0 && !isAnyIgnoredElementAncestorOfTarget) {
        onOutsideClick();
      }
    };

    const $listeningElement = ($listeningElementRef || {}).current || document;

    if (isListening) {
      $listeningElement.addEventListener('mousedown', handleMouseDown);
      $listeningElement.addEventListener('mouseup', handleMouseUp);
    }
    return () => {
      $listeningElement.removeEventListener('mousedown', handleMouseDown);
      $listeningElement.removeEventListener('mouseup', handleMouseUp);
    };
  }, [$ignoredElementRefsMemoized, $listeningElementRef, isListening, onOutsideClick]);
};

export default useOnOutsideClick;

const useDeepCompareMemoize = <T>(value:T) => {
  const valueRef = useRef<T>();

  if (!isEqual(value, valueRef.current)) {
    valueRef.current = value;
  }
  return valueRef.current;
};

</code>```

Problem in ref

```<code>$mouseDownTargetRef.current = e?.target;

</code>```

Type 'EventTarget | null' is not assignable to type 'null'.
Type 'EventTarget' is not assignable to type 'null'.

and

```<code>$elementRef.current.contains($mouseDownTargetRef.current) ||
$elementRef.current.contains(e.target),
</code>```

Argument of type 'EventTarget | null' is not assignable to parameter of type 'Node | null'.
Type 'EventTarget' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 43 more

Body:
help with hook typing, I did not find a solution on the site

import { RefObject, useEffect, useRef } from 'react';
import { isEqual } from 'lodash';

const useOnOutsideClick = <T extends HTMLElement = HTMLElement>(
  $ignoredElementRefs:RefObject<T>,
  isListening:boolean,
  onOutsideClick:()=>void,
  $listeningElementRef:RefObject<T>,
) => {
  const $mouseDownTargetRef = useRef(null);
  const $ignoredElementRefsMemoized = useDeepCompareMemoize([$ignoredElementRefs].flat());

  useEffect(() => {
    const handleMouseDown = (event:MouseEventInit ) => {
      const e = event as MouseEvent
      $mouseDownTargetRef.current = e?.target;
    };

    const handleMouseUp = (event:MouseEventInit) => {
      const e = event as MouseEvent
      const isAnyIgnoredElementAncestorOfTarget = $ignoredElementRefsMemoized?.some(
        $elementRef =>
          $elementRef.current.contains($mouseDownTargetRef.current) ||
          $elementRef.current.contains(e.target),
      );
      if (e.button === 0 && !isAnyIgnoredElementAncestorOfTarget) {
        onOutsideClick();
      }
    };

    const $listeningElement = ($listeningElementRef || {}).current || document;

    if (isListening) {
      $listeningElement.addEventListener('mousedown', handleMouseDown);
      $listeningElement.addEventListener('mouseup', handleMouseUp);
    }
    return () => {
      $listeningElement.removeEventListener('mousedown', handleMouseDown);
      $listeningElement.removeEventListener('mouseup', handleMouseUp);
    };
  }, [$ignoredElementRefsMemoized, $listeningElementRef, isListening, onOutsideClick]);
};

export default useOnOutsideClick;

const useDeepCompareMemoize = <T>(value:T) => {
  const valueRef = useRef<T>();

  if (!isEqual(value, valueRef.current)) {
    valueRef.current = value;
  }
  return valueRef.current;
};

Problem in ref

$mouseDownTargetRef.current = e?.target;

Type 'EventTarget | null' is not assignable to type 'null'.
Type 'EventTarget' is not assignable to type 'null'.

and

$elementRef.current.contains($mouseDownTargetRef.current) ||
$elementRef.current.contains(e.target),

Argument of type 'EventTarget | null' is not assignable to parameter of type 'Node | null'.
Type 'EventTarget' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 43 more


问:
Two Phase Commit Rollback With PostgreSQL And Node.js
Suppose I have Two Database db1 and bd2

db1 has a table tb1
db2 has a table tb2

now I want to insert a row to tb2 from tb1 and after successful insertion, the row will be deleted from tb1 so how i can do it using two-phase commit rollback in Postgres with node js


问:
Is there a way to run the Datastore Emulator in Cloud Build?
I am trying to run some Go unit tests in Cloud Build each time that a PR is submitted to a particular branch on my repository. The problem is that my unit tests rely on a connection to the Datastore Emulator 1. Here is an example of how I setup the emulator before running the unit tests. I have a *_test.go file with the init function like this:

```<code>    func init() {
        // Set up port for Datastore Emulator
        err := os.Setenv("DATASTORE_EMULATOR_HOST", "localhost:8000")
        if err != nil {
            log.Fatalf("Error setting up Port for DS Emulator: %v", err)
        }

        // Check if Datastore Emulator is running on port 8000
        _, err = net.Dial("tcp", "localhost:8000")
        if err != nil {
            log.Fatalf("Please ensure you have Datastore Emulator running on port 8000 before running tests: %v", err)
        }

        dsClient, err = datastore.NewClient(ctx, mockCfg.GCP.ProjectID)
        if err != nil {
            log.Fatalf("Error creating datastore client: %v", err)
        }
        defer dsClient.Close()
    }
</code>```

Locally I run the emulator with the cloud-sdk using:

gcloud --project=dsemu beta emulators datastore start \
    --host-port 0.0.0.0:8000 \
    --no-store-on-disk \
    --use-firestore-in-datastore-mode
```
<p>The tests run fine locally, and I use the following <code>cloudbuild.yaml</code> to execute the tests in Cloud Build:</p>
```steps:
  - name: gcr.io/cloud-builders/docker
    args:
      - run
      - '-d'
      - '--network=cloudbuild'
      - '--name=dsemu'
      - google/cloud-sdk
      - gcloud
      - '--project=dsemu'
      - beta
      - emulators
      - datastore
      - start
      - '--host-port=0.0.0.0:8000'
      - '--no-store-on-disk'
      - '--use-firestore-in-datastore-mode'
  - name: jwilder/dockerize
    args:
      - dockerize
      - '-timeout=60s'
      - '-wait=tcp://dsemu:8000'
  - name: 'golang:1.19'
    env:
      - 'DATASTORE_EMULATOR_HOST=dsemu:8000'
    args:
      - go
      - test
      - ./...
  - name: gcr.io/cloud-builders/docker
    args:
      - rm
      - '--force'
      - dsemu
timeout: 600s
```

This is where the issue arises. The tests are unable to connect to the cloudbuild network to complete. The build reaches the timeout of 10m and fails. Any ideas of what could be wrong?

Body:
I am trying to run some Go unit tests in Cloud Build each time that a PR is submitted to a particular branch on my repository. The problem is that my unit tests rely on a connection to the Datastore Emulator 1. Here is an example of how I setup the emulator before running the unit tests. I have a *_test.go file with the init function like this:

    func init() {
        // Set up port for Datastore Emulator
        err := os.Setenv("DATASTORE_EMULATOR_HOST", "localhost:8000")
        if err != nil {
            log.Fatalf("Error setting up Port for DS Emulator: %v", err)
        }

        // Check if Datastore Emulator is running on port 8000
        _, err = net.Dial("tcp", "localhost:8000")
        if err != nil {
            log.Fatalf("Please ensure you have Datastore Emulator running on port 8000 before running tests: %v", err)
        }

        dsClient, err = datastore.NewClient(ctx, mockCfg.GCP.ProjectID)
        if err != nil {
            log.Fatalf("Error creating datastore client: %v", err)
        }
        defer dsClient.Close()
    }

Locally I run the emulator with the cloud-sdk using:

gcloud --project=dsemu beta emulators datastore start \
    --host-port 0.0.0.0:8000 \
    --no-store-on-disk \
    --use-firestore-in-datastore-mode

The tests run fine locally, and I use the following cloudbuild.yaml to execute the tests in Cloud Build:

steps:
  - name: gcr.io/cloud-builders/docker
    args:
      - run
      - '-d'
      - '--network=cloudbuild'
      - '--name=dsemu'
      - google/cloud-sdk
      - gcloud
      - '--project=dsemu'
      - beta
      - emulators
      - datastore
      - start
      - '--host-port=0.0.0.0:8000'
      - '--no-store-on-disk'
      - '--use-firestore-in-datastore-mode'
  - name: jwilder/dockerize
    args:
      - dockerize
      - '-timeout=60s'
      - '-wait=tcp://dsemu:8000'
  - name: 'golang:1.19'
    env:
      - 'DATASTORE_EMULATOR_HOST=dsemu:8000'
    args:
      - go
      - test
      - ./...
  - name: gcr.io/cloud-builders/docker
    args:
      - rm
      - '--force'
      - dsemu
timeout: 600s

This is where the issue arises. The tests are unable to connect to the cloudbuild network to complete. The build reaches the timeout of 10m and fails. Any ideas of what could be wrong?


问:
Calling async method in ngInit not working in Angular 14
I have a problem with calling an “async” method in “ngInit” method in angular 14
here is the method I want to call when component initialized:

```<code>async setInterfaceDatatableHeaders() {
    var bankName = await GetTranslatedValue(this.translate, "SUPPLIERMANAGEMENT.Bank”)
      .then(res => {
        return res;
      });
    var accountOwnerName = await GetTranslatedValue(this.translate, "GENERAL.AccountOwnerName”)
      .then(res => {
        return res;
      });
    var interfaceBankID = await GetTranslatedValue(this.translate, "SUPPLIERMANAGEMENT.InterfaceBankID”)
      .then(res => {
        return res;
      });
    var accountOwnerTel = await GetTranslatedValue(this.translate, "GENERAL.AccountOwnerTel”)
      .then(res => {
        return res;
      });

    this.interfaceDatatableHeaders = [
      new DataTableHeaderDTO('BankName', bankName, 'text'),
      new DataTableHeaderDTO('AccountOwnerName', accountOwnerName, 'text'),
      new DataTableHeaderDTO('InterfaceBankID', interfaceBankID, 'text'),
      new DataTableHeaderDTO('AccountOwnerTel', accountOwnerTel, 'text'),
    ]
  }
</code>```

When I call it directly in ngInit, method not calling and not working
but if I surround the method with a “setTimeout” function, it will work properly

This works :

```<code>setTimeout(async () => {
      await this.setInterfaceDatatableHeaders();
    }, 0);
</code>```

This NOT work with this way of calling, even if I set async for my “ngInit” method:

```<code>await this.setInterfaceDatatableHeaders();
</code>```

How can I fix this without using “setTimeout” in “NgInit” ???

Body:
I have a problem with calling an “async” method in “ngInit” method in angular 14
here is the method I want to call when component initialized:

async setInterfaceDatatableHeaders() {
    var bankName = await GetTranslatedValue(this.translate, "SUPPLIERMANAGEMENT.Bank”)
      .then(res => {
        return res;
      });
    var accountOwnerName = await GetTranslatedValue(this.translate, "GENERAL.AccountOwnerName”)
      .then(res => {
        return res;
      });
    var interfaceBankID = await GetTranslatedValue(this.translate, "SUPPLIERMANAGEMENT.InterfaceBankID”)
      .then(res => {
        return res;
      });
    var accountOwnerTel = await GetTranslatedValue(this.translate, "GENERAL.AccountOwnerTel”)
      .then(res => {
        return res;
      });

    this.interfaceDatatableHeaders = [
      new DataTableHeaderDTO('BankName', bankName, 'text'),
      new DataTableHeaderDTO('AccountOwnerName', accountOwnerName, 'text'),
      new DataTableHeaderDTO('InterfaceBankID', interfaceBankID, 'text'),
      new DataTableHeaderDTO('AccountOwnerTel', accountOwnerTel, 'text'),
    ]
  }

When I call it directly in ngInit, method not calling and not working
but if I surround the method with a “setTimeout” function, it will work properly

This works :

setTimeout(async () => {
      await this.setInterfaceDatatableHeaders();
    }, 0);

This NOT work with this way of calling, even if I set async for my “ngInit” method:

await this.setInterfaceDatatableHeaders();

How can I fix this without using “setTimeout” in “NgInit” ???


问:
How to revert `git subtree push`?
So I have to main project:

MyProject

and a folder which is a subtree of another repo:

MyProject/Dependency

I need to change something in the subtree folder and push the change to its own repo, so I did:

git remote add -f dependency git@DependencyPath/Dependency.git

git remote add -f dependency-fork git@DependencyPath:myname/Dependency.git

git checkout -b branch-mychange

[MADE CHANGES and commited]

git subtree push --prefix Dependency dependency-fork branch-mychange

But there's something wrong in my change, and now Github complains:

We found potential security vulnerabilities in your dependencies.

So I want to revert the push that I did earlier, even better, reset it to a state before I made the change. I can make the change directly in my fork of the dependency repo, but is there anyway to do it in MyProject repo? Furthermore, is there a way I can see what repo/branch the Dependency folder points to (as in the dependency repo)?

Thanks!

Title: How to revert `git subtree push`?


问:
I need a help to execute javascript dynamic function function (pageContext) { return (pagecontext["n2"] * pagecontext["n3"] ) } in flutter
```<code>          public func evaluateJS(functionName : String, argument : [String: Any?]) -> Any? {
    let jsFunc = self.replaceSubContextWithActualValue(key: functionName)
    let jsFunctionVal = "func = " + jsFunc
    let context = JSContext()
    _ =  context?.evaluateScript(jsFunctionVal)
    let jsFunction = context?.objectForKeyedSubscript("func")
    let result = jsFunction?.call(withArguments:[argument])
    return result?.toObject()
}
</code>```

the above code executes like above in ios

Body:
          public func evaluateJS(functionName : String, argument : [String: Any?]) -> Any? {
    let jsFunc = self.replaceSubContextWithActualValue(key: functionName)
    let jsFunctionVal = "func = " + jsFunc
    let context = JSContext()
    _ =  context?.evaluateScript(jsFunctionVal)
    let jsFunction = context?.objectForKeyedSubscript("func")
    let result = jsFunction?.call(withArguments:[argument])
    return result?.toObject()
}

the above code executes like above in ios


问:
How to update globally installed packages in nvm Windows?
I want to update:

```<code> $ npm outdated -g --depth=0
Package   Current   Wanted  Latest  Location
npm        6.12.1  6.14.18   9.2.0  global
prettier    2.8.1    2.8.2   2.8.2  global
</code>```

I followed https://stackoverflow.com/a/56806361/8001538 but node npm-cli.js update -g --force doesn't work. It gives this error:

```<code>$ node  npm-cli.js update -g --force
internal/modules/cjs/loader.js:895
    throw err;
    ^

Error: Cannot find module '../lib/utils/unsupported.js'
Require stack:
- C:\Users\sunil\AppData\Roaming\nvm\v13.1.0\node_modules\npm.old\bin\npm-cli.js
←[90m    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:892:15)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:785:27)←[39m
←[90m    at Module.require (internal/modules/cjs/loader.js:956:19)←[39m
←[90m    at require (internal/modules/cjs/helpers.js:74:18)←[39m
    at C:\Users\sunil\AppData\Roaming\nvm\v13.1.0\node_modules\←[4mnpm.old←[24m\bin\npm-cli.js:19:21
    at Object.<anonymous> (C:\Users\sunil\AppData\Roaming\nvm\v13.1.0\node_modules\←[4mnpm.old←[24m\bin\npm-cli.js:153:3)
←[90m    at Module._compile (internal/modules/cjs/loader.js:1063:30)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1103:10)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:914:32)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:822:14)←[39m {
  code: ←[32m'MODULE_NOT_FOUND'←[39m,
  requireStack: [
    ←[32m'C:\\Users\\sunil\\AppData\\Roaming\\nvm\\v13.1.0\\node_modules\\npm.old\\bin\\npm-cli.js'←[39m
  ]
}
</code>```

Body:
I want to update:

 $ npm outdated -g --depth=0
Package   Current   Wanted  Latest  Location
npm        6.12.1  6.14.18   9.2.0  global
prettier    2.8.1    2.8.2   2.8.2  global

I followed https://stackoverflow.com/a/56806361/8001538 but node npm-cli.js update -g --force doesn't work. It gives this error:

$ node  npm-cli.js update -g --force
internal/modules/cjs/loader.js:895
    throw err;
    ^

Error: Cannot find module '../lib/utils/unsupported.js'
Require stack:
- C:\Users\sunil\AppData\Roaming\nvm\v13.1.0\node_modules\npm.old\bin\npm-cli.js
←[90m    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:892:15)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:785:27)←[39m
←[90m    at Module.require (internal/modules/cjs/loader.js:956:19)←[39m
←[90m    at require (internal/modules/cjs/helpers.js:74:18)←[39m
    at C:\Users\sunil\AppData\Roaming\nvm\v13.1.0\node_modules\←[4mnpm.old←[24m\bin\npm-cli.js:19:21
    at Object.<anonymous> (C:\Users\sunil\AppData\Roaming\nvm\v13.1.0\node_modules\←[4mnpm.old←[24m\bin\npm-cli.js:153:3)
←[90m    at Module._compile (internal/modules/cjs/loader.js:1063:30)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1103:10)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:914:32)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:822:14)←[39m {
  code: ←[32m'MODULE_NOT_FOUND'←[39m,
  requireStack: [
    ←[32m'C:\\Users\\sunil\\AppData\\Roaming\\nvm\\v13.1.0\\node_modules\\npm.old\\bin\\npm-cli.js'←[39m
  ]
}


问:
How to deploy web app without sharing env file
I am deploying a node.js app on AWS Elastic Beanstalk using the following tutorial :
https://www.honeybadger.io/blog/node-elastic-beanstalk/

I do wish to use the pipeline integration with github but I see a small problem.

My node.js app use MongoDb atlas and as such have some credentials store in an .env file.
This .env file is excluded from the files on the github repository for security reason.
Thing is, connection is impossible without this file.

How can I deploy my node.js app using a pipeline on a public github repository without showing the .env file to the entire world ?

Thank you


问:
Unknown or bad timezone (2023-01-04)
I am getting this error. I am new to laravel and don't know how to solve this. Please help

this is my function in AttendaceController ;

```<code>function record(Request $req)
{
    $from = now($req->from_date);
    $to = now($req->to_date)->addDays(5);

    $studentAttendance = attendance::whereBetween('created_at', [$from, $to])->get();

    return view('user_record', ['details' => $studentAttendance]);
}
</code>```

Title: Unknown or bad timezone (2023-01-04)

Body:
I am getting this error. I am new to laravel and don't know how to solve this. Please help

this is my function in AttendaceController ;

function record(Request $req)
{
    $from = now($req->from_date);
    $to = now($req->to_date)->addDays(5);

    $studentAttendance = attendance::whereBetween('created_at', [$from, $to])->get();

    return view('user_record', ['details' => $studentAttendance]);
}


问:
Generic Entity Framework Pagination
I am trying to write a generic way to provide pagination on my Link query to my MySQL database. However this required me to have a generic way to where, as the field used may differ from table to table. The issue i am facing it that Linq can't translate my generic types. Are there a way to do this that would work with Linq?</p>
```<code>public static class PaginationExtentions {
    public static async Task<PaginationResult<T>> Pagination<T, J>(this DbSet<J> dbSet, Pagination pagination, Func<IQueryable<J>, IQueryable<T>>? select) where J : class {
        bool previousPage = false;
        bool nextPage = false;
        string startCursor = null;
        string endCursor = null;

        var property = typeof(J).GetProperty(pagination.SortBy);

        string after = pagination.After != null ? Base64Decode(pagination.After) : null;

        bool backwardMode = after != null && after.ToLower().StartsWith("prev__");
        string cursor = after != null ? after.Split("__", 2).Last() : null;

        List<J> items;
        if (cursor == null) {
            items = await (from s in dbSet
                           orderby GetPropertyValue<J, string>(s, pagination.SortBy) ascending
                           select s).Take(pagination.First)
                                    .ToListAsync();
        }
        else if (backwardMode) {
            items = await (from subject in (
                                                     from s in dbSet
                                                     where string.Compare( (string?)property.GetValue(s), cursor) < 0
                                                     orderby (string?)property.GetValue(s) descending
                                                     select s).Take(pagination.First)
                                 orderby (string?)property.GetValue(subject) ascending
                                 select subject).ToListAsync();
        }
        else {
            items = await (from s in dbSet
                           where string.Compare((string?)property.GetValue(s), cursor) > 0
                           orderby GetPropertyValue<J, string>(s, pagination.SortBy) ascending
                           select s).Take(pagination.First)
                                    .ToListAsync();
        }

        previousPage = await dbSet.Where(s => string.Compare((string?)property.GetValue(s), cursor) < 0).AnyAsync();
        nextPage = items.Count == 0 ? false : await dbSet.Where(s => string.Compare((string?)property.GetValue(s), (string?)property.GetValue(items.Last())) > 0).AnyAsync();

        var backwardsCursor = !previousPage ? null : "prev__" + cursor;
        var forwardsCursor = !nextPage ? null : items.Count > 0 ? "next__" + (string?)property.GetValue(items.Last()) : null;

        return new PaginationResult<T>() {
                                             Items = select(items.AsQueryable()).ToList(),
                                             TotalCount = await dbSet.CountAsync(),
                                             HasPreviousPage = previousPage,
                                             HasNextPage = nextPage,
                                             StartCusor = Base64Encode(backwardsCursor),
                                             EndCursor = Base64Encode(forwardsCursor)
                                         };
    }

    private static U GetPropertyValue<T, U>(T obj, string propertyName) {
        return (U)obj.GetType().GetProperty(propertyName).GetValue(obj, null);
    }

    public static string Base64Encode(string plainText) {
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
        return System.Convert.ToBase64String(plainTextBytes);
    }

    public static string Base64Decode(string base64EncodedData) {
        var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
        return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
    }
}
</code>```

Title: Generic Entity Framework Pagination

Body:
I am trying to write a generic way to provide pagination on my Link query to my MySQL database. However this required me to have a generic way to where, as the field used may differ from table to table. The issue i am facing it that Linq can't translate my generic types. Are there a way to do this that would work with Linq?

public static class PaginationExtentions {
    public static async Task<PaginationResult<T>> Pagination<T, J>(this DbSet<J> dbSet, Pagination pagination, Func<IQueryable<J>, IQueryable<T>>? select) where J : class {
        bool previousPage = false;
        bool nextPage = false;
        string startCursor = null;
        string endCursor = null;

        var property = typeof(J).GetProperty(pagination.SortBy);

        string after = pagination.After != null ? Base64Decode(pagination.After) : null;

        bool backwardMode = after != null && after.ToLower().StartsWith("prev__");
        string cursor = after != null ? after.Split("__", 2).Last() : null;

        List<J> items;
        if (cursor == null) {
            items = await (from s in dbSet
                           orderby GetPropertyValue<J, string>(s, pagination.SortBy) ascending
                           select s).Take(pagination.First)
                                    .ToListAsync();
        }
        else if (backwardMode) {
            items = await (from subject in (
                                                     from s in dbSet
                                                     where string.Compare( (string?)property.GetValue(s), cursor) < 0
                                                     orderby (string?)property.GetValue(s) descending
                                                     select s).Take(pagination.First)
                                 orderby (string?)property.GetValue(subject) ascending
                                 select subject).ToListAsync();
        }
        else {
            items = await (from s in dbSet
                           where string.Compare((string?)property.GetValue(s), cursor) > 0
                           orderby GetPropertyValue<J, string>(s, pagination.SortBy) ascending
                           select s).Take(pagination.First)
                                    .ToListAsync();
        }

        previousPage = await dbSet.Where(s => string.Compare((string?)property.GetValue(s), cursor) < 0).AnyAsync();
        nextPage = items.Count == 0 ? false : await dbSet.Where(s => string.Compare((string?)property.GetValue(s), (string?)property.GetValue(items.Last())) > 0).AnyAsync();

        var backwardsCursor = !previousPage ? null : "prev__" + cursor;
        var forwardsCursor = !nextPage ? null : items.Count > 0 ? "next__" + (string?)property.GetValue(items.Last()) : null;

        return new PaginationResult<T>() {
                                             Items = select(items.AsQueryable()).ToList(),
                                             TotalCount = await dbSet.CountAsync(),
                                             HasPreviousPage = previousPage,
                                             HasNextPage = nextPage,
                                             StartCusor = Base64Encode(backwardsCursor),
                                             EndCursor = Base64Encode(forwardsCursor)
                                         };
    }

    private static U GetPropertyValue<T, U>(T obj, string propertyName) {
        return (U)obj.GetType().GetProperty(propertyName).GetValue(obj, null);
    }

    public static string Base64Encode(string plainText) {
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
        return System.Convert.ToBase64String(plainTextBytes);
    }

    public static string Base64Decode(string base64EncodedData) {
        var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
        return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
    }
}