问:
What's the best way to store access token generated from third party API in AWS
I'm currently running a script locally to generate reports using GoogleAdsManager API. Prior running the script I've created new service account key in json format as the key type together with ~/googleads.yaml.

Here's the dev guide.

However, I wanted to schedule this script on (AWS Glue).

This is the sample script and the issue I currently faced is :

How do call this method ad_manager.AdManagerClient.LoadFromStorage() from aws? I've stored the credentials (JSON and YAML) in AWS Secrets Manager

```<code>from googleads import ad_manager, oauth2
import tempfile
import _locale

_locale._getdefaultlocale = (lambda *args: ['en_US', 'UTF-8'])

ad_unit_id = XXXXXXXXXX

def generate_ad_impressions(client):
    # Initialize appropriate service.
    report_service = client.GetService("ReportService",
    version="v202108")
    # Initialize a DataDownloader.
    report_downloader = client.GetDataDownloader(version="v202108")
    # Create statement object to filter for an order.
    statement = (
        ad_manager.StatementBuilder(version="v202108")
        .Where("PARENT_AD_UNIT_ID = :id")
        .WithBindVariable("id", mbns_aa_vod_ad_unit_id)
        .Limit(None)  # No limit/offset for reports
        .Offset(None)
    )
    report_job = {
        "reportQuery": {
        "dimensions": ["DATE", "HOUR"],
        "columns": [
            "AD_SERVER_IMPRESSIONS",
        ],
        "dateRangeType": "TODAY",
        "startDate": {
            "year": "2022",
            "month": "1",
            "day": "25"
        },
        "endDate": {
            "year": "2022",
            "month": "1",
            "day": "25"
        },
        "statement": statement.ToStatement(),
      }
    }
    try:
        # Run the report and wait for it to finish.
        report_job_id = report_downloader.WaitForReport(report_job)
    except:
        print("Failed to generate report.")
        # Change to your preferred export format.
        export_format = "CSV_DUMP"
        # report_file =
        tempfile.NamedTemporaryFile(suffix=".csv.gz",
        delete=False)
    with open('ad_unit_report.csv.gz', mode='wb') as report_file:
        # Download report data.
        report_downloader.DownloadReportToFile(report_job_id,
        export_format, report_file)
        report_file.close()

    # Download report data.
    downloaded_report =
    report_downloader.DownloadReportToFile(report_job_id,
    export_format, report_file)

    report_file.close()
    print('success!')

if __name__ == '__main__':
   ad_manager_client =
   ad_manager.AdManagerClient.LoadFromStorage('path_to_yaml_file')
   generate_ad_impressions(ad_manager_client)
</code>```

答:
Solution should be something like this:

```<code>import boto3
from botocore.exceptions import ClientError
from googleads import ad_manager, oauth2
import tempfile
import _locale

_locale._getdefaultlocale = (lambda *args: ['en_US', 'UTF-8'])

ad_unit_id = XXXXXXXXXX

def get_secret():
    secret_name = "MySecret"
    region_name = "us-west-2"

    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name,
    )

    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_name
        )
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceNotFoundException':
            print("The requested secret " + secret_name + " was not found")
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            print("The request was invalid due to:", e)
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            print("The request had invalid params:", e)
        elif e.response['Error']['Code'] == 'DecryptionFailure':
            print("The requested secret can't be decrypted using the provided KMS key:", e)
        elif e.response['Error']['Code'] == 'InternalServiceError':
            print("An error occurred on service side:", e)
    else:
        # Secrets Manager decrypts the secret value using the associated KMS CMK
        # Depending on whether the secret was a string or binary, only one of these fields will be populated
        if 'SecretString' in get_secret_value_response:
            text_secret_data = get_secret_value_response['SecretString']
            return text_secret_data
        else:
            binary_secret_data = get_secret_value_response['SecretBinary']
            return binary_secret_data

def generate_ad_impressions(client):
    # Initialize appropriate service.
    report_service = client.GetService("ReportService",
    version="v202108")
    # Initialize a DataDownloader.
    report_downloader = client.GetDataDownloader(version="v202108")
    # Create statement object to filter for an order.
    statement = (
        ad_manager.StatementBuilder(version="v202108")
        .Where("PARENT_AD_UNIT_ID = :id")
        .WithBindVariable("id", mbns_aa_vod_ad_unit_id)
        .Limit(None)  # No limit/offset for reports
        .Offset(None)
    )
    report_job = {
        "reportQuery": {
        "dimensions": ["DATE", "HOUR"],
        "columns": [
            "AD_SERVER_IMPRESSIONS",
        ],
        "dateRangeType": "TODAY",
        "startDate": {
            "year": "2022",
            "month": "1",
            "day": "25"
        },
        "endDate": {
            "year": "2022",
            "month": "1",
            "day": "25"
        },
        "statement": statement.ToStatement(),
      }
    }
    try:
        # Run the report and wait for it to finish.
        report_job_id = report_downloader.WaitForReport(report_job)
    except:
        print("Failed to generate report.")
        # Change to your preferred export format.
        export_format = "CSV_DUMP"
        # report_file =
        tempfile.NamedTemporaryFile(suffix=".csv.gz",
        delete=False)
    with open('ad_unit_report.csv.gz', mode='wb') as report_file:
        # Download report data.
        report_downloader.DownloadReportToFile(report_job_id,
        export_format, report_file)
        report_file.close()

    # Download report data.
    downloaded_report =
    report_downloader.DownloadReportToFile(report_job_id,
    export_format, report_file)

    report_file.close()
    print('success!')

if __name__ == '__main__':
   ad_manager_client =
   ad_manager.AdManagerClient.LoadFromString(get_secret())
   generate_ad_impressions(ad_manager_client)

</code>```

Here the function get_secret fetches the YAML string from AWS Secrets Manager stored as MySecret in region us-west-2. The YAML string is then subsequently used to create the Google Ad Manager Client using the function LoadFromString.

Note that I have not tested this as I do not have Google API key and Id.

Body:
I'm currently running a script locally to generate reports using GoogleAdsManager API. Prior running the script I've created new service account key in json format as the key type together with ~/googleads.yaml.

Here's the dev guide.

However, I wanted to schedule this script on (AWS Glue).

This is the sample script and the issue I currently faced is :

How do call this method ad_manager.AdManagerClient.LoadFromStorage() from aws? I've stored the credentials (JSON and YAML) in AWS Secrets Manager

from googleads import ad_manager, oauth2
import tempfile
import _locale

_locale._getdefaultlocale = (lambda *args: ['en_US', 'UTF-8'])

ad_unit_id = XXXXXXXXXX

def generate_ad_impressions(client):
    # Initialize appropriate service.
    report_service = client.GetService("ReportService",
    version="v202108")
    # Initialize a DataDownloader.
    report_downloader = client.GetDataDownloader(version="v202108")
    # Create statement object to filter for an order.
    statement = (
        ad_manager.StatementBuilder(version="v202108")
        .Where("PARENT_AD_UNIT_ID = :id")
        .WithBindVariable("id", mbns_aa_vod_ad_unit_id)
        .Limit(None)  # No limit/offset for reports
        .Offset(None)
    )
    report_job = {
        "reportQuery": {
        "dimensions": ["DATE", "HOUR"],
        "columns": [
            "AD_SERVER_IMPRESSIONS",
        ],
        "dateRangeType": "TODAY",
        "startDate": {
            "year": "2022",
            "month": "1",
            "day": "25"
        },
        "endDate": {
            "year": "2022",
            "month": "1",
            "day": "25"
        },
        "statement": statement.ToStatement(),
      }
    }
    try:
        # Run the report and wait for it to finish.
        report_job_id = report_downloader.WaitForReport(report_job)
    except:
        print("Failed to generate report.")
        # Change to your preferred export format.
        export_format = "CSV_DUMP"
        # report_file =
        tempfile.NamedTemporaryFile(suffix=".csv.gz",
        delete=False)
    with open('ad_unit_report.csv.gz', mode='wb') as report_file:
        # Download report data.
        report_downloader.DownloadReportToFile(report_job_id,
        export_format, report_file)
        report_file.close()

    # Download report data.
    downloaded_report =
    report_downloader.DownloadReportToFile(report_job_id,
    export_format, report_file)

    report_file.close()
    print('success!')

if __name__ == '__main__':
   ad_manager_client =
   ad_manager.AdManagerClient.LoadFromStorage('path_to_yaml_file')
   generate_ad_impressions(ad_manager_client)

Body:
Solution should be something like this:

import boto3
from botocore.exceptions import ClientError
from googleads import ad_manager, oauth2
import tempfile
import _locale

_locale._getdefaultlocale = (lambda *args: ['en_US', 'UTF-8'])

ad_unit_id = XXXXXXXXXX

def get_secret():
    secret_name = "MySecret"
    region_name = "us-west-2"

    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name,
    )

    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_name
        )
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceNotFoundException':
            print("The requested secret " + secret_name + " was not found")
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            print("The request was invalid due to:", e)
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            print("The request had invalid params:", e)
        elif e.response['Error']['Code'] == 'DecryptionFailure':
            print("The requested secret can't be decrypted using the provided KMS key:", e)
        elif e.response['Error']['Code'] == 'InternalServiceError':
            print("An error occurred on service side:", e)
    else:
        # Secrets Manager decrypts the secret value using the associated KMS CMK
        # Depending on whether the secret was a string or binary, only one of these fields will be populated
        if 'SecretString' in get_secret_value_response:
            text_secret_data = get_secret_value_response['SecretString']
            return text_secret_data
        else:
            binary_secret_data = get_secret_value_response['SecretBinary']
            return binary_secret_data

def generate_ad_impressions(client):
    # Initialize appropriate service.
    report_service = client.GetService("ReportService",
    version="v202108")
    # Initialize a DataDownloader.
    report_downloader = client.GetDataDownloader(version="v202108")
    # Create statement object to filter for an order.
    statement = (
        ad_manager.StatementBuilder(version="v202108")
        .Where("PARENT_AD_UNIT_ID = :id")
        .WithBindVariable("id", mbns_aa_vod_ad_unit_id)
        .Limit(None)  # No limit/offset for reports
        .Offset(None)
    )
    report_job = {
        "reportQuery": {
        "dimensions": ["DATE", "HOUR"],
        "columns": [
            "AD_SERVER_IMPRESSIONS",
        ],
        "dateRangeType": "TODAY",
        "startDate": {
            "year": "2022",
            "month": "1",
            "day": "25"
        },
        "endDate": {
            "year": "2022",
            "month": "1",
            "day": "25"
        },
        "statement": statement.ToStatement(),
      }
    }
    try:
        # Run the report and wait for it to finish.
        report_job_id = report_downloader.WaitForReport(report_job)
    except:
        print("Failed to generate report.")
        # Change to your preferred export format.
        export_format = "CSV_DUMP"
        # report_file =
        tempfile.NamedTemporaryFile(suffix=".csv.gz",
        delete=False)
    with open('ad_unit_report.csv.gz', mode='wb') as report_file:
        # Download report data.
        report_downloader.DownloadReportToFile(report_job_id,
        export_format, report_file)
        report_file.close()

    # Download report data.
    downloaded_report =
    report_downloader.DownloadReportToFile(report_job_id,
    export_format, report_file)

    report_file.close()
    print('success!')

if __name__ == '__main__':
   ad_manager_client =
   ad_manager.AdManagerClient.LoadFromString(get_secret())
   generate_ad_impressions(ad_manager_client)

Here the function get_secret fetches the YAML string from AWS Secrets Manager stored as MySecret in region us-west-2. The YAML string is then subsequently used to create the Google Ad Manager Client using the function LoadFromString.

Note that I have not tested this as I do not have Google API key and Id.


来源: stackexchange

问:
Using the space next to tabs for displaying text and images
I have a QTabWidget as my 'central widget' and I would like to use the space that's left over after the tabs have been placed for displaying some text and an image (area in blue below):

I'm looking for pointers to solutions that will allow me to best make use this space; any ideas?

答:
A good suggestion from @Minh... that would provide quite a bit of flexibility. However, this answer suggested using the 'corner widget' which sounded better since I won't lose some of the given functionality of QTabWidget.

I gave it a try and it does what I wanted; within my QTabWidget class, I now have:

    # Image and text labels
    qlabel_img = QtWidgets.QLabel()
    pixmap = QtGui.QPixmap('image.png')
    qlabel_img.setPixmap(pixmap)
    qlabel_txt = QtWidgets.QLabel(f"Text under image")

    # Corner widget
    corner_widget = QtWidgets.QWidget()
    corner_layout = QtWidgets.QVBoxLayout()
    corner_layout.addWidget(qlabel_img)
    corner_layout.addWidget(qlabel_txt)
    corner_widget.setLayout(corner_layout)
    self.setCornerWidget(corner_widget)
```

and so corner_widget is displayed at the top right (right justified) of the tab widget.

ContentLicense: CC BY-SA 4.0

Body:
A good suggestion from @Minh... that would provide quite a bit of flexibility. However, this answer suggested using the 'corner widget' which sounded better since I won't lose some of the given functionality of QTabWidget.

I gave it a try and it does what I wanted; within my QTabWidget class, I now have:

    # Image and text labels
    qlabel_img = QtWidgets.QLabel()
    pixmap = QtGui.QPixmap('image.png')
    qlabel_img.setPixmap(pixmap)
    qlabel_txt = QtWidgets.QLabel(f"Text under image")

    # Corner widget
    corner_widget = QtWidgets.QWidget()
    corner_layout = QtWidgets.QVBoxLayout()
    corner_layout.addWidget(qlabel_img)
    corner_layout.addWidget(qlabel_txt)
    corner_widget.setLayout(corner_layout)
    self.setCornerWidget(corner_widget)

and so corner_widget is displayed at the top right (right justified) of the tab widget.


问:
How to add/update an attribute to an HTML element using JavaScript?
I'm trying to find a way that will add / update attribute using JavaScript.  I know I can do it with setAttribute() function but that doesn't work in IE.

答:
Obligatory jQuery solution.  Finds and sets the title attribute to foo.  Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.

```<code>$('#element').attr( 'title', 'foo' );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Obligatory jQuery solution.  Finds and sets the title attribute to foo.  Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.

$('#element').attr( 'title', 'foo' );

OwnerDisplayName: tvanfosson

ContentLicense: CC BY-SA 2.5


问:
How to change a type in an expression tree?
I have a method like this:

```<code>private bool Method_1(Expression<Func<IPerson, bool>> expression)
{
    /* Some code that will call Method_2 */
}
</code>```

In this method I want to change the IPerson type to another type. I want to call another method that looks like this:

```<code>private bool Method_2(Expression<Func<PersonData, bool>> expression)
{
    /* Some code */
}
</code>```

So, in method_1 I need to change IPerson to PersonData. How can I do this?

Edit:

When I call: Method_1(p => p.Id == 1) I want to 'save' the condition (p.Id == 1) but I want to execute this condition on another type, namely IPerson. So, I need to alter the expression or create a new expression with IPerson

答:
This is an improvement of @Rafal solution. It allows to pipeline property calls of complex objects.

```<code>//sample expression
Expression<Func<IPerson, bool>> expression = x => x.PropA.PropB.PropC == "ABC";
</code>```

Simply change the otherMember to use the type of inner.

```<code>class Visitor<T> : ExpressionVisitor
{
    ParameterExpression _parameter;

    //there must be only one instance of parameter expression for each parameter
    //there is one so one passed here
    public Visitor(ParameterExpression parameter)
    {
        _parameter = parameter;
    }

    //this method replaces original parameter with given in constructor
    protected override Expression VisitParameter(ParameterExpression node)
    {
        return _parameter;
    }

    //this one is required because PersonData does not implement IPerson and it finds
    //property in PersonData with the same name as the one referenced in expression
    //and declared on IPerson
    protected override Expression VisitMember(MemberExpression node)
    {
        //only properties are allowed if you use fields then you need to extend
        // this method to handle them
        if (node.Member.MemberType != System.Reflection.MemberTypes.Property)
            throw new NotImplementedException();

        //name of a member referenced in original expression in your
        //sample Id in mine Prop
        var memberName = node.Member.Name;

        /*Fix*/
        //visit left side of this expression p.Id this would be p
        var inner = Visit(node.Expression);
        //find property on type T (=PersonData) by name
        var otherMember = inner.Type.GetProperty(memberName);

        return Expression.Property(inner, otherMember);
    }
}
</code>```

Body:
I have a method like this:

private bool Method_1(Expression<Func<IPerson, bool>> expression)
{
    /* Some code that will call Method_2 */
}

In this method I want to change the IPerson type to another type. I want to call another method that looks like this:

private bool Method_2(Expression<Func<PersonData, bool>> expression)
{
    /* Some code */
}

So, in method_1 I need to change IPerson to PersonData. How can I do this?

Edit:

When I call: Method_1(p => p.Id == 1) I want to 'save' the condition (p.Id == 1) but I want to execute this condition on another type, namely IPerson. So, I need to alter the expression or create a new expression with IPerson

Body:
This is an improvement of @Rafal solution. It allows to pipeline property calls of complex objects.

//sample expression
Expression<Func<IPerson, bool>> expression = x => x.PropA.PropB.PropC == "ABC";

Simply change the otherMember to use the type of inner.

class Visitor<T> : ExpressionVisitor
{
    ParameterExpression _parameter;

    //there must be only one instance of parameter expression for each parameter
    //there is one so one passed here
    public Visitor(ParameterExpression parameter)
    {
        _parameter = parameter;
    }

    //this method replaces original parameter with given in constructor
    protected override Expression VisitParameter(ParameterExpression node)
    {
        return _parameter;
    }

    //this one is required because PersonData does not implement IPerson and it finds
    //property in PersonData with the same name as the one referenced in expression
    //and declared on IPerson
    protected override Expression VisitMember(MemberExpression node)
    {
        //only properties are allowed if you use fields then you need to extend
        // this method to handle them
        if (node.Member.MemberType != System.Reflection.MemberTypes.Property)
            throw new NotImplementedException();

        //name of a member referenced in original expression in your
        //sample Id in mine Prop
        var memberName = node.Member.Name;

        /*Fix*/
        //visit left side of this expression p.Id this would be p
        var inner = Visit(node.Expression);
        //find property on type T (=PersonData) by name
        var otherMember = inner.Type.GetProperty(memberName);

        return Expression.Property(inner, otherMember);
    }
}


问:
How to filter null returning method in stream?
I have a list, it has some method like getSummary(), and this method returns null in some cases. How can I filter to avoid getting the null result?

Here is my code:

```<code>List<Event> items = getEvents(sharedCalendarId, startDateTime, endDateTime, zoneId);

if (CollectionUtils.isNotEmpty(items)) {
    openingHoursDto.setBranches(items.stream()
            .collect(Collectors.groupingBy(Event::getSummary))
            .entrySet()
            .stream()
            .map(e -> {
                LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
                lBOHDto.setName(e.getKey());
                lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
                return lBOHDto;
            })
            .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
            .collect(Collectors.toList()));
    return openingHoursDto;
}
</code>```

答:
first you don't need to validate if  List<Event> items is empty or not, stream will not be processed if there are no elements..

```<code>openingHoursDto.setBranches(items.stream()
                 //filter to not only null but also empty string
                 // or use .filter(Objects::nonNull) for the whole object to be filtered
                .filter(event -> !event.getSummary().isEmpty())
                .collect(Collectors.groupingBy(Event::getSummary))
                .entrySet()
                .stream()
                ..map(this::toLBOHDto)
                .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
                .collect(Collectors.toList()));
        return openingHoursDto;

    private LibraryBranchOpeningHoursDto toLBOHDto(Event e){
        LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
        lBOHDto.setName(e.getKey());
        lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
        return lBOHDto;
    }
</code>```

it is better practice to have your mapping outside the stream operation like making it a method,
or you can have it as you have it

Body:
I have a list, it has some method like getSummary(), and this method returns null in some cases. How can I filter to avoid getting the null result?

Here is my code:

List<Event> items = getEvents(sharedCalendarId, startDateTime, endDateTime, zoneId);

if (CollectionUtils.isNotEmpty(items)) {
    openingHoursDto.setBranches(items.stream()
            .collect(Collectors.groupingBy(Event::getSummary))
            .entrySet()
            .stream()
            .map(e -> {
                LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
                lBOHDto.setName(e.getKey());
                lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
                return lBOHDto;
            })
            .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
            .collect(Collectors.toList()));
    return openingHoursDto;
}

Body:
first you don't need to validate if  List<Event> items is empty or not, stream will not be processed if there are no elements..

openingHoursDto.setBranches(items.stream()
                 //filter to not only null but also empty string
                 // or use .filter(Objects::nonNull) for the whole object to be filtered
                .filter(event -> !event.getSummary().isEmpty())
                .collect(Collectors.groupingBy(Event::getSummary))
                .entrySet()
                .stream()
                ..map(this::toLBOHDto)
                .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
                .collect(Collectors.toList()));
        return openingHoursDto;

    private LibraryBranchOpeningHoursDto toLBOHDto(Event e){
        LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
        lBOHDto.setName(e.getKey());
        lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
        return lBOHDto;
    }

it is better practice to have your mapping outside the stream operation like making it a method,
or you can have it as you have it


问:
Weird df.sort_values result - randomly leaves multiple rows empty but missing values are misplaced a row down in the wrong columns
I've run into a very weird problem when using pandas to sort my data frame using df.sort_values on my date-time column.

In some sense the code works, it does sort the rows by date, however, in doing so it cuts some of the rows in half leaving one half of the row where it should be but leaving the other half of the row empty. The other half is put in the next row down and put in the wrong columns.

It's easier to understand from the screenshots.

Pre-Sorted Data

Post-Sorted Data

It's difficult to see from the Post-Sorted date picture but not all rows are treated this way(only one isn't in the pic, second from the bottom). Some rows turn out just fine and others don't, it seems very random.

The problem code is shown below.

```<code>df = pd.read_csv('Pre-Sort.csv', low_memory=False, skiprows=0, lineterminator='\n')

df = df.sort_values(by="created")

df.to_csv('Post-Sort.csv')

</code>```

I've tried using inplace=True and ignore_index=True as well but both returned the same results.

I'm worried this is a problem with the data as I've used df.sort_values before with virtually the same data and it worked fine.

Originally, with the data that worked, I realized that for some reason two months' worth of data roughly 15% of total data vanished. The culprit was when I merged two data frames together both containing all months with df.append. For some reason, df.append would consistently skip these two months so, in the end, I merged them through the mac terminal which kept the missing months.

This is as far as I know the only major difference between the two times I tried the code. It could be a red herring though. I had to redo many of the operations from scratch, so I might have done something differently than before, so it could be that.

Also, this changes the file size from 192MB to 210.3MB which probably shouldn't happen with a sort.

I just need to sort the data so I can resample it into daily variables, so if anyone knows a way to resample without needing to sort that would work for me just as well.

答:
Solved mostly.

Problem wasn't the sorted function but a pre-existing problem with the dataset. The displacement issue was already there but was only made apparent when the data was mixed together. Still trying to figure out exactly where in the datahandling it went wrong put I think it's a delimiter issue.

So far, an equally confusing problem which I'll likely have to create another post on to fix

Body:
I've run into a very weird problem when using pandas to sort my data frame using df.sort_values on my date-time column.

In some sense the code works, it does sort the rows by date, however, in doing so it cuts some of the rows in half leaving one half of the row where it should be but leaving the other half of the row empty. The other half is put in the next row down and put in the wrong columns.

It's easier to understand from the screenshots.

Pre-Sorted Data

Post-Sorted Data

It's difficult to see from the Post-Sorted date picture but not all rows are treated this way(only one isn't in the pic, second from the bottom). Some rows turn out just fine and others don't, it seems very random.

The problem code is shown below.

df = pd.read_csv('Pre-Sort.csv', low_memory=False, skiprows=0, lineterminator='\n')

df = df.sort_values(by="created")

df.to_csv('Post-Sort.csv')

I've tried using inplace=True and ignore_index=True as well but both returned the same results.

I'm worried this is a problem with the data as I've used df.sort_values before with virtually the same data and it worked fine.

Originally, with the data that worked, I realized that for some reason two months' worth of data roughly 15% of total data vanished. The culprit was when I merged two data frames together both containing all months with df.append. For some reason, df.append would consistently skip these two months so, in the end, I merged them through the mac terminal which kept the missing months.

This is as far as I know the only major difference between the two times I tried the code. It could be a red herring though. I had to redo many of the operations from scratch, so I might have done something differently than before, so it could be that.

Also, this changes the file size from 192MB to 210.3MB which probably shouldn't happen with a sort.

I just need to sort the data so I can resample it into daily variables, so if anyone knows a way to resample without needing to sort that would work for me just as well.


问:
Pandas dataframe trading gain/loss

Dataframe

(Disregard the two index columns)

level_0
index
Year
Month
Day
Open
High
Low
Close
Volume
Length
Polarity
Sentiment_Negative
Sentiment_Neutral
Sentiment_Positive
Target_variable
Predicted

0
0
0
2020
1
19
8941.45
9164.36
8620.08
8706.25
3.42173e+10
937.167
0.0884653
0
0
1
0
0

1
1
1
2020
1
18
8927.21
9012.2
8827.33
8942.81
3.23378e+10
1177.5
0.176394
0
0
1
1
1

2
2
2
2020
1
17
8725.21
8958.12
8677.32
8929.04
3.63721e+10
1580
0.216762
0
0
1
0
0

3
3
3
2020
1
16
8812.48
8846.46
8612.1
8723.79
3.1314e+10
1336.33
0.182707
0
0
1
0
0

Description

The value of the target_variable is 1 if todays closing price is greater than yesterdays closing price

The value of the target_variable is 0 if todays closing price is less than yesterdays closing price

The predicted value is the output of my classifier.

Problem

I need to run some code that tracks how much money is gained if I invest when the classifier tells me to invest

I have started to code this

```<code>credit = 10000
for index, row in df.iterrows():
    if row["Predicted"] == 1:
        #print(row["Percentage_diff"])
        credit = credit - 100
        credit = credit + (100 * row["Percentage_diff"])
print(credit)
</code>```

The idea is that I start off with a balance of 10,000 and invest 100 every time the classifier signals to. The only problem is that when I lose 8000 credits. Is the code correct and the classifier is very poor?

Or have I made an error in the code?

答:
Solution

```<code>
df["Percentage_diff"] = (df["Close"] - df["Open"])/df["Open"]

credit = 10000
for index, row in df.iterrows():
    if row["Predicted"] == 1:
        #print(row["Percentage_diff"])
        credit = credit - 100
        credit = credit + ((100 * row["Percentage_diff"]) + 100)
print(credit)

</code>```

This was the solution thanks to Ahmed.

If I start with an original balance of 10000 every time the classifier signals to invest I invest 100 dollars at opening and withdraw at close this calculates the balance.

Title: Pandas dataframe trading gain/loss

Body:
Dataframe

(Disregard the two index columns)

level_0
index
Year
Month
Day
Open
High
Low
Close
Volume
Length
Polarity
Sentiment_Negative
Sentiment_Neutral
Sentiment_Positive
Target_variable
Predicted

0
0
0
2020
1
19
8941.45
9164.36
8620.08
8706.25
3.42173e+10
937.167
0.0884653
0
0
1
0
0

1
1
1
2020
1
18
8927.21
9012.2
8827.33
8942.81
3.23378e+10
1177.5
0.176394
0
0
1
1
1

2
2
2
2020
1
17
8725.21
8958.12
8677.32
8929.04
3.63721e+10
1580
0.216762
0
0
1
0
0

3
3
3
2020
1
16
8812.48
8846.46
8612.1
8723.79
3.1314e+10
1336.33
0.182707
0
0
1
0
0

Description

The value of the target_variable is 1 if todays closing price is greater than yesterdays closing price

The value of the target_variable is 0 if todays closing price is less than yesterdays closing price

The predicted value is the output of my classifier.

Problem

I need to run some code that tracks how much money is gained if I invest when the classifier tells me to invest

I have started to code this

credit = 10000
for index, row in df.iterrows():
    if row["Predicted"] == 1:
        #print(row["Percentage_diff"])
        credit = credit - 100
        credit = credit + (100 * row["Percentage_diff"])
print(credit)

The idea is that I start off with a balance of 10,000 and invest 100 every time the classifier signals to. The only problem is that when I lose 8000 credits. Is the code correct and the classifier is very poor?

Or have I made an error in the code?

Body:
Solution

df["Percentage_diff"] = (df["Close"] - df["Open"])/df["Open"]

credit = 10000
for index, row in df.iterrows():
    if row["Predicted"] == 1:
        #print(row["Percentage_diff"])
        credit = credit - 100
        credit = credit + ((100 * row["Percentage_diff"]) + 100)
print(credit)

This was the solution thanks to Ahmed.

If I start with an original balance of 10000 every time the classifier signals to invest I invest 100 dollars at opening and withdraw at close this calculates the balance.


问:
Multiple issues with webpack, polyfill and node modules
I am trying to build a simple react app calling a smart contract, however while running - I get multiple issues with webpack, node modules.
Most of the issues are pointing to resolve error
This react app was created with the create-react-app module.
Here are the errors

```<code>ERROR in ../node_modules/cipher-base/index.js 3:16-43

Module not found: Error: Can't resolve 'stream' in 'C:\Sandip@IBM\BlockChainDev\MultiSigWallet\node_modules\cipher-base'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
</code>```

Similarly the other errors

```<code>ERROR in ../node_modules/eth-lib/lib/bytes.js 7:193-227

Module not found: Error: Can't resolve 'crypto' in
ERROR in ../node_modules/swarm-js/node_modules/eth-lib/lib/bytes.js 9:193-227
ERROR in ../node_modules/web3-eth-accounts/lib/index.js 33:74-91

ERROR in ../node_modules/web3-providers-http/lib/index.js 30:11-26

Module not found: Error: Can't resolve 'http' in
</code>```

I am bit lost on how to resolve these dependecy errors.

Thanks

答:
If my guess is correct, you are using react-script 5.0 +
please use "react-scripts": "4.0.3",
that issue is because of webpack config.
there are several way to fix that problem but I think this way is simple solution.

Body:
I am trying to build a simple react app calling a smart contract, however while running - I get multiple issues with webpack, node modules.
Most of the issues are pointing to resolve error
This react app was created with the create-react-app module.
Here are the errors

ERROR in ../node_modules/cipher-base/index.js 3:16-43

Module not found: Error: Can't resolve 'stream' in 'C:\Sandip@IBM\BlockChainDev\MultiSigWallet\node_modules\cipher-base'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

Similarly the other errors

ERROR in ../node_modules/eth-lib/lib/bytes.js 7:193-227

Module not found: Error: Can't resolve 'crypto' in
ERROR in ../node_modules/swarm-js/node_modules/eth-lib/lib/bytes.js 9:193-227
ERROR in ../node_modules/web3-eth-accounts/lib/index.js 33:74-91

ERROR in ../node_modules/web3-providers-http/lib/index.js 30:11-26

Module not found: Error: Can't resolve 'http' in

I am bit lost on how to resolve these dependecy errors.

Thanks


问:
Passing Laravel route to vue component's Href or router-link
I'm creating a dropdown component with Vue 3 and importing it inside my Laravel 8 project. The dropdown works perfectly and looping over the categories in database as expected.

The issue is that i want when i click on a category it routes me to '/categories/$category->slug' which is defined in Laravel routes already and works if i enter it manually. But i can't find a way to say $category->slug in vue component.

Here is the component:

I tried anchor tags and inside the href '/categories/{{category.slug}}' but it doesn't work. All i need is to have an anchor tag or router-link that directs me to '/categories/$category->slug'

答:
Okay i solved it and it was pretty simple!

I simply added to data() the below code

```<code>categoryRoute: "/categories/",
</code>```

Then adjusted the href like so

```<code>:href="this.categoryRoute + category.slug"
</code>```

Body:
Okay i solved it and it was pretty simple!

I simply added to data() the below code

categoryRoute: "/categories/",

Then adjusted the href like so

:href="this.categoryRoute + category.slug"


问:
How to get image X Y coordinates and a pixel value at the indicated point by cursor with Python?
I have a gray scale image which size is (5472, 3648). How does python return the pixel value and x y cordinates of an point in the image? I want to get the values when I set the cursor and click the point in the image?</p>

答:
```<code>def print_location(event):
    print(f' location of x={event.x}, location of y ={event.y}')

your_image_object.bind("<Button-1>", print_location)
</code>```
<p>#this should print x and y co ordinate of where you click in that image</p>

Body:
def print_location(event):
    print(f' location of x={event.x}, location of y ={event.y}')

your_image_object.bind("<Button-1>", print_location)

#this should print x and y co ordinate of where you click in that image


问:
How to check if a value exists in array with .includes?
I know we can use .includes but I've been struggling to get it to work with my array. What I want is for my function to check if the value already exists and if it does to remove it from the array.

The value is a string. That value comes from an object that has .name as a property within the object.

```<code>0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}

1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go'}
</code>```

I mapped through the data and assigned each button with a value of {d.name}

I am using a button to get the value with this function below

and adding the values to 'favs'.

```<code>const favs = [];

  function checkId(e) {
    if (e.target.value !== "")

      favs.push(e.target.value);

      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
    }
</code>```

console.log
favs

```<code>[
    "3-Bit-CNC-Starter-Pack",
    "3-Bit-CNC-Starter-Pack"
]
</code>```

How can I check to see if the value already exists within the array using .includes?

答:
Just check before push:</p>
```<code>function checkId(e) {
    if (e.target.value !== ""
        && !favs.includes(e.target.value))
    {
        favs.push(e.target.value);
        // other code here
    }
}
</code>```

Body:
I know we can use .includes but I've been struggling to get it to work with my array. What I want is for my function to check if the value already exists and if it does to remove it from the array.

The value is a string. That value comes from an object that has .name as a property within the object.

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}

1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go'}

I mapped through the data and assigned each button with a value of {d.name}

I am using a button to get the value with this function below

and adding the values to 'favs'.

const favs = [];

  function checkId(e) {
    if (e.target.value !== "")

      favs.push(e.target.value);

      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
    }

console.log
favs

[
    "3-Bit-CNC-Starter-Pack",
    "3-Bit-CNC-Starter-Pack"
]

How can I check to see if the value already exists within the array using .includes?

Body:
Just check before push:

function checkId(e) {
    if (e.target.value !== ""
        && !favs.includes(e.target.value))
    {
        favs.push(e.target.value);
        // other code here
    }
}


问:
Specialize member function of class template using C++20 concepts
I want to specialize a member function of a class template as follows:

```<code>#include <concepts>

template <typename T>
struct S {
    void f();
};

template <typename T>
void S<T>::f() {
}

// (0) This is fine.
template <>
void S<int>::f() {
}

// (1) This triggers an error.
template <std::integral T>
void S<T>::f() {
}
</code>```

The specialization (0) is fine, but specializes f() only for the int type. Instead, I would like to specialize it, e.g., for any integral type, as in (1). Is this possible using C++20 concepts? Notice that std::integral is just an example and that my specific case makes use of user-defined concepts.

答:
Simply use a trailing requires-clause. The compiler will choose the most constrained function:</p>
```<code>#include <concepts>
#include <iostream>

template <typename T>
struct S {
    void f();

    void f() requires std::integral<T>;
};

template <typename T>
void S<T>::f() {
  std::cout << "general\n";
}

template <typename T>
void S<T>::f() requires std::integral<T> {
  std::cout << "constrained\n";
};

int main() {
  S<int> x;
  S<double> y;

  x.f(); // prints constrained
  y.f(); // prints general

  return 0;
}
</code>```

Body:
I want to specialize a member function of a class template as follows:

#include <concepts>

template <typename T>
struct S {
    void f();
};

template <typename T>
void S<T>::f() {
}

// (0) This is fine.
template <>
void S<int>::f() {
}

// (1) This triggers an error.
template <std::integral T>
void S<T>::f() {
}

The specialization (0) is fine, but specializes f() only for the int type. Instead, I would like to specialize it, e.g., for any integral type, as in (1). Is this possible using C++20 concepts? Notice that std::integral is just an example and that my specific case makes use of user-defined concepts.

Body:
Simply use a trailing requires-clause. The compiler will choose the most constrained function:

#include <concepts>
#include <iostream>

template <typename T>
struct S {
    void f();

    void f() requires std::integral<T>;
};

template <typename T>
void S<T>::f() {
  std::cout << "general\n";
}

template <typename T>
void S<T>::f() requires std::integral<T> {
  std::cout << "constrained\n";
};

int main() {
  S<int> x;
  S<double> y;

  x.f(); // prints constrained
  y.f(); // prints general

  return 0;
}


问:
MKMapView set region
I'm attempting to use the MKMapView.  I've succeeded in making the world map appear.  However, I can't seem to change the region:

I have a button that will perform this:

```<code>NSLog(@"%f, %f, %f, %f,
mapView.region.center.latitude,
mapView.region.center.longitude,
mapView.region.span.latitudeDelta,
mapView.region.span.longitudeDelta);
</code>```

Now, in my viewDidLoad method, I attempt to set a starting region to view:

```<code>CLLocationCoordinate2D startCoord;
startCoord.latitude = 49.0;
startCoord.longitude = -123.0;
[mapView setRegion:MKCoordinateRegionMakeWithDistance(startCoord, 200, 200) animated:YES];
</code>```

When the view does load, it shows the same world map instead of a smaller area as expected.  Immediately logging the region's attributes gives me:

0.000000, 0.001417, 0.000000, 0.000000

Moving the map around a bit, resizing and zooming doesn't change these values (except that the second one goes back to 0.000000).

It would appear to be that mapView.region does not correspond to what I'm seeing on the screen, but I'm quite certain I made the IB links correctly, I'm looking at them right now.  What could be the problem?

答:
You need to do</p>

```<code>CLLocationCoordinate2D startCoord = CLLocationCoordinate2DMake(49, -123);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:MKCoordinateRegionMakeWithDistance(startCoord, 200, 200)];
[mapView setRegion:adjustedRegion animated:YES];
</code>```

Title: MKMapView set region

Body:
I'm attempting to use the MKMapView.  I've succeeded in making the world map appear.  However, I can't seem to change the region:

I have a button that will perform this:

NSLog(@"%f, %f, %f, %f,
mapView.region.center.latitude,
mapView.region.center.longitude,
mapView.region.span.latitudeDelta,
mapView.region.span.longitudeDelta);

Now, in my viewDidLoad method, I attempt to set a starting region to view:

CLLocationCoordinate2D startCoord;
startCoord.latitude = 49.0;
startCoord.longitude = -123.0;
[mapView setRegion:MKCoordinateRegionMakeWithDistance(startCoord, 200, 200) animated:YES];

When the view does load, it shows the same world map instead of a smaller area as expected.  Immediately logging the region's attributes gives me:

0.000000, 0.001417, 0.000000, 0.000000

Moving the map around a bit, resizing and zooming doesn't change these values (except that the second one goes back to 0.000000).

It would appear to be that mapView.region does not correspond to what I'm seeing on the screen, but I'm quite certain I made the IB links correctly, I'm looking at them right now.  What could be the problem?

Body:
You need to do

CLLocationCoordinate2D startCoord = CLLocationCoordinate2DMake(49, -123);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:MKCoordinateRegionMakeWithDistance(startCoord, 200, 200)];
[mapView setRegion:adjustedRegion animated:YES];


问:
How to put a path param to the request body before validation happens?
I got the following test entity:

```<code>public class Test {
    public String id;
    public String name;
}
</code>```

My test resource looks like this:

```<code>@Path("test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {
    @Path("{id}")
    @POST
    public Test test(@Valid Test test){
        return test;
    }
}
</code>```

If I do  a POST with name as request body, I will end up with an entity which has a name but no id set. If I want to have set the id, I define a @PathParam("id") String id and then set the id with test.id = id. That is what I am using right now.

In this case, if I put a @NotNull constraint to the ID, the validation fails.

How can I 'put' the parsed ID to the request body, before the validation is happening? Ideal, not manually in any case.

答:
You should remove the @NotNull annotation and ensure that no ID is given from the POST request. And in your GET endpoints ensure that the field is not null, probably with an own annotation. I did this with my own annotation @TestIdNull(false).

In your code you would place the annotation like this:

```<code>@Path("{id}")
@POST
public Test test(@TestIdNull(true) Test test){
    return test;
}
</code>```

while the annotation interface looks quite simple:

```<code>@Target({ElementType.PARAMETER,ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = PetIdNullValidator.class)
public @interface TestIdNull {
  String message() default "Post request. ID value forbidden.";
  boolean value() default true;
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};
}
</code>```

and the implementation would be

```<code>@Provider
@NoArgsConstructor
public class TestIdNullValidator implements ConstraintValidator<TestIdNull, Test> {

  private boolean switchNullCheck;

  /**
   * {@inheritDoc}
   */
  @Override
  public void initialize(final TestIdNull constraintAnnotation) {
    switchNullCheck = constraintAnnotation.value();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isValid(final Test test, final ConstraintValidatorContext context) {
    if (null == test) {
        return true;
    }

    context.disableDefaultConstraintViolation();
    context.buildConstraintViolationWithTemplate("ENTER YOUR MESSAGE HERE").addConstraintViolation();

    return switchNullCheck ? test.id() == null : test.id() != null;
  }
}
</code>```

On your "way back" (the GET methods) you must ensure the ID is not null with placing the annotation to your DTO. Code could look like this:

```<code>@TestIdNull(false)
final Test test = mapper.map(entity, Test.class);
</code>```

I know it's not a very elegant way but your idea placing the ID in a POST first and then validate is not possible I'm afraid.

Body:
I got the following test entity:

public class Test {
    public String id;
    public String name;
}

My test resource looks like this:

@Path("test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {
    @Path("{id}")
    @POST
    public Test test(@Valid Test test){
        return test;
    }
}

If I do  a POST with name as request body, I will end up with an entity which has a name but no id set. If I want to have set the id, I define a @PathParam("id") String id and then set the id with test.id = id. That is what I am using right now.

In this case, if I put a @NotNull constraint to the ID, the validation fails.

How can I 'put' the parsed ID to the request body, before the validation is happening? Ideal, not manually in any case.

Body:
You should remove the @NotNull annotation and ensure that no ID is given from the POST request. And in your GET endpoints ensure that the field is not null, probably with an own annotation. I did this with my own annotation @TestIdNull(false).

In your code you would place the annotation like this:

@Path("{id}")
@POST
public Test test(@TestIdNull(true) Test test){
    return test;
}

while the annotation interface looks quite simple:

@Target({ElementType.PARAMETER,ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = PetIdNullValidator.class)
public @interface TestIdNull {
  String message() default "Post request. ID value forbidden.";
  boolean value() default true;
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};
}

and the implementation would be

@Provider
@NoArgsConstructor
public class TestIdNullValidator implements ConstraintValidator<TestIdNull, Test> {

  private boolean switchNullCheck;

  /**
   * {@inheritDoc}
   */
  @Override
  public void initialize(final TestIdNull constraintAnnotation) {
    switchNullCheck = constraintAnnotation.value();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isValid(final Test test, final ConstraintValidatorContext context) {
    if (null == test) {
        return true;
    }

    context.disableDefaultConstraintViolation();
    context.buildConstraintViolationWithTemplate("ENTER YOUR MESSAGE HERE").addConstraintViolation();

    return switchNullCheck ? test.id() == null : test.id() != null;
  }
}

On your "way back" (the GET methods) you must ensure the ID is not null with placing the annotation to your DTO. Code could look like this:

@TestIdNull(false)
final Test test = mapper.map(entity, Test.class);

I know it's not a very elegant way but your idea placing the ID in a POST first and then validate is not possible I'm afraid.


问:
How to use Sidebar Search Plugin in AdminLTE v3
In my project I'm using AdminLTE from https://cdnjs.cloudflare.com/ajax/libs/admin-lte/3.0.5/js/adminlte.min.js but it doesn't load SidebarSearch.js on it.

How do I use this plugin in my project? Does anyone have a simple example to show me, because in the documentation itself it is not clear how to use this plugin.

mainly at this point:

```<code>$('[data-widget="sidebar-search"]').SidebarSearch('toggle')
</code>```

Where in HTML / JS should I put this line of code?

答:
To answer your question, simply add it in a script tag before the closing body tag of your page, example:

```<code><html>
  <head>
    ...
  </head>
  <body>
    ...
    <script>
      $(document).ready(function()
      {
        // Example to toggle dropdown list of the search bar
        $('[data-widget="sidebar-search"]').SidebarSearch('toggle');

        // Example to initialize the plugin with options
          let options = {
          arrowSign: '/',
          minLength: 2,
          highlightClass: 'text-yellow',
          notFoundText: 'No results'
          ...
        };

        ("[data-widget="sidebar-search"]").SidebarSearch(options);
      });

    </script>
  </body>
</html>
</code>```

However this method seems to return duplicate results.

Preferred method

Just add the options as attributes beside data-widget="sidebar-search".

It should look like this data-not-found-text='No results' data-highlight-class='text-yellow' data-min-length='2'

adminLTE documentation

Body:
In my project I'm using AdminLTE from https://cdnjs.cloudflare.com/ajax/libs/admin-lte/3.0.5/js/adminlte.min.js but it doesn't load SidebarSearch.js on it.

How do I use this plugin in my project? Does anyone have a simple example to show me, because in the documentation itself it is not clear how to use this plugin.

mainly at this point:

$('[data-widget="sidebar-search"]').SidebarSearch('toggle')

Where in HTML / JS should I put this line of code?

Body:
To answer your question, simply add it in a script tag before the closing body tag of your page, example:

<html>
  <head>
    ...
  </head>
  <body>
    ...
    <script>
      $(document).ready(function()
      {
        // Example to toggle dropdown list of the search bar
        $('[data-widget="sidebar-search"]').SidebarSearch('toggle');

        // Example to initialize the plugin with options
          let options = {
          arrowSign: '/',
          minLength: 2,
          highlightClass: 'text-yellow',
          notFoundText: 'No results'
          ...
        };

        ("[data-widget="sidebar-search"]").SidebarSearch(options);
      });

    </script>
  </body>
</html>

However this method seems to return duplicate results.

Preferred method

Just add the options as attributes beside data-widget="sidebar-search".

It should look like this data-not-found-text='No results' data-highlight-class='text-yellow' data-min-length='2'

adminLTE documentation


问:
ASP.NET Core - Get tuple with two values
I just want to get the user's role and ID from the user table. But I do not know why the following code gives an error!!!

public Tuple<Guid,Guid> GetUserId(string mobile)
{
    return _context.Users.Select(u => new Tuple<Guid,Guid,Boolean>(u.UserId,u.RoleId,u.Mobile == mobile));
}
```

I searched a lot but did not find an answer?

Error:

答:
you are getting errors for casting as you are converting boolean to string.

```<code>u.Mobile == mobile
</code>```

it will return Boolean value, not a string.

correct code

```<code> public Tuple<Guid,Guid> GetUserId(string mobile)
    {
        return _context.Users.Select(u => new Tuple<Guid,Guid,Boolean>(u.UserId,u.RoleId,u.Mobile == mobile));
    }
</code>```

Body:
I just want to get the user's role and ID from the user table. But I do not know why the following code gives an error!!!

public Tuple<Guid,Guid> GetUserId(string mobile)
{
    return _context.Users.Select(u => new Tuple<Guid,Guid,Boolean>(u.UserId,u.RoleId,u.Mobile == mobile));
}

I searched a lot but did not find an answer?

Error:

Body:
you are getting errors for casting as you are converting boolean to string.

u.Mobile == mobile

it will return Boolean value, not a string.

correct code

 public Tuple<Guid,Guid> GetUserId(string mobile)
    {
        return _context.Users.Select(u => new Tuple<Guid,Guid,Boolean>(u.UserId,u.RoleId,u.Mobile == mobile));
    }


问:
Can I have a hide/show button but the hidden script doesn't show?
This is my code, but I don't know how to debug it. Please help me and my code. I am trying to add a hide/show button for my contents list, but I don't know what is wrong with it. It is greatly appreciated. Ummm... I don't know what to say as I have to add more information. Just comment to ask any queries.</p>
```<code><!DOCTYPE html>
<html>
    <head>
        <title>How to be Asian</title>
        <style type="text/css">
            h1, h2, h3, h4, h5, h6 {
                font-weight: bold;
                border: 0px;
                margin: 2px;
            }
            h2
                {
                text-indent: 20px;
            }
            ul {
                margin-top: 2%;
            }
            body {
                margin: 2px;
                border: 5px;
                padding: 13px;
            }
            #Contents {
                display: table;
                padding: 7px;
                border: 1px solid #a2a9b1;
                background-color: #f8f9fa;
                font-size: 95%;
                text-align: left;
                float: right;
                width: 15%;
            }
            #Quote {
                text-align: center;
                line-height: 2em;
                padding-left: 25%;
                padding-right: 25%;
                padding-top: 20px;
                padding-bottom: 20px;
                display: block;
            }
            .Bonus {
                display: inline;
                font-size: 1.3em;
            }

            body{
                padding: 1%;
                margin: 1%
            }

            p h1{
                display: inline;
                float: left;
            }
        </style>

    </head>
    <body>
        <script>
            function myFunction() {
                var x = document.getElementById("Contents");
                    if (x.style.display === "none") {
                        x.style.display = "block";
                    } else {
                        x.style.display = "none";
                    }
                }
        </script>
        <div id="Contents">
            <h1 id="Contents">Contents</h1><button onclick="myFunction()">[show]</button>

            <ol>
                <li><a href="#Chapter_1">Chapter 1: Early Childhood</a></li>
                <li><a href="#Chapter_2">Chapter 2: Primary School Education</a></li>
                <li><a href="#Chapter_3">Chapter 3: High School Education</a></li>
                <li><a href="#Chapter_4">Chapter 4: College/University Education</a></li>
                <li><a href="#Chapter_5">Chapter 5: Employment</a></li>
                <li><a href="#Chapter_6">Chapter 6: Relationships</a></li>
                <li><a href="#Chapter_7">Chapter 7: Family Gatherings</a></li>
                <ol>
                    <li><a href="#Chapter_7.1">Chapter 7.1: Public Holidays</a></li>
                    <li><a href="#Chapter_7.2">Chapter 7.2: Death and mourning</a></li>
                </ol>
                <li><a href="#Chapter_8">Chapter 8: Retirement</a></li>
                <li><a href="#Chapter_9">Chapter 9: Death</a></li>
            </ol>
        </div>
        <div>
            <h1 id="Chapter_1">Chapter 1: Early Childhood</h1>
            <p>When Asian kids go through pre-schooling years and primary school, children are always put under pressure and always neglected so that they work harder and feel like they are worth something after some time and not actually useless.<br><span id="Quote">"We just never praise our children, always compare them to people who are better, so they grow up never feeling good enough and then have to constantly outdo everybody else to feel like they aren’t worthless." <br> Quoted from Stven He's father</span></p>
        </div>
        <div>
            <h1 id="Chapter_2">Chapter 2: Primary School Education</h1>
            <p>Asian kids are always compared to their peers by their parents. This is because Asian parents want the best of the child. This also means that children are used too much for the simplest of their demands. <br> <br> During this period of learning, PTSD is most used so that children are trained to cope "in the future". "In the future" meaning whenever you go back to your parents house when you are and adult. But this training will deal emotional damage, social anxiety and negliegence. This part of life is when most of the tactics are used so that the child can get used to them. Once they know how to leave the situation, create more problems for the child so that they get more experience. </p>
            <p>This period of their life is when you can take advantage of them. For example, when you are shopping, tell your child that you are going to get something common in the household, like rice. Then, go to the aisle and watch them go to the cashier person and panic as you are assumed to get rice. Once they start getting constipated, go back with a 5kg bag of rice and start telling your child off for constipating in public. </p>
            <div style="text-align: center;">
                <h4 class="Bonus">BONUS! </h4><p class="Bonus">If you can humiliate your child in front of anyone, especially your child's friends, it will intergrate information for life. </p>
            </div>
        </div>
        <div>
            <h1 id="Chapter_3">Chapter 3: High School Education</h1>
            <p>This period of life is when you get to choose his choices. </p>
        </div>
        <div>
            <h1 id="Chapter_4">Chapter 4: College/University Education</h1>
        </div>
        <div>
            <h1 id="Chapter_5">Chapter 5: Employment</h1>
        </div>
        <div>
            <h1 id="Chapter_6">Chapter 6: Relationships</h1>
        </div>
        <div>
            <h1 id="Chapter_7">Chapter 7: Family Gatherings</h1>
            <h2 id="Chapter_7.1">Chapter 7.1: Public Holidays</h2>
            <h2 id="Chapter_7.2">Chapter 7.2: Death and mourning</h2>
        </div>
        <div>
            <h1 id="Chapter_8">Chapter 8: Retirement</h1>
        </div>
        <div>
            <h1 id="Chapter_9">Chapter 9: Death</h1>
        </div>
    </body>
</html>
</code>```

答:
I ran your code, Its fine function wise but the button hides with the div. I guess that's the problem you are referring to.

Now a few things.

Ids should be treated as unique so don't give the same id to many tags, use class instead.

The button that hides the content needs to be outside the container that you are trying to hide.

<!DOCTYPE html>

        <title>How to be Asian</title>

                 <button onclick="myFunction()">[show]</button>

Contents

Chapter 1: Early Childhood

Chapter 2: Primary School Education

Chapter 3: High School Education

Chapter 4: College/University Education

Chapter 5: Employment

Chapter 6: Relationships

Chapter 7: Family Gatherings

Chapter 7.1: Public Holidays

Chapter 7.2: Death and mourning

Chapter 8: Retirement

Chapter 9: Death

Chapter 1: Early Childhood

When Asian kids go through pre-schooling years and primary school, children are always put under pressure and always neglected so that they work harder and feel like they are worth something after some time and not actually useless.
"We just never praise our children, always compare them to people who are better, so they grow up never feeling good enough and then have to constantly outdo everybody else to feel like they aren’t worthless."
 Quoted from Stven He's father

Chapter 2: Primary School Education

Asian kids are always compared to their peers by their parents. This is because Asian parents want the best of the child. This also means that children are used too much for the simplest of their demands.

 During this period of learning, PTSD is most used so that children are trained to cope "in the future". "In the future" meaning whenever you go back to your parents house when you are and adult. But this training will deal emotional damage, social anxiety and negliegence. This part of life is when most of the tactics are used so that the child can get used to them. Once they know how to leave the situation, create more problems for the child so that they get more experience.

This period of their life is when you can take advantage of them. For example, when you are shopping, tell your child that you are going to get something common in the household, like rice. Then, go to the aisle and watch them go to the cashier person and panic as you are assumed to get rice. Once they start getting constipated, go back with a 5kg bag of rice and start telling your child off for constipating in public.

BONUS!

If you can humiliate your child in front of anyone, especially your child's friends, it will intergrate information for life.

Chapter 3: High School Education

This period of life is when you get to choose his choices.

Chapter 4: College/University Education

Chapter 5: Employment

Chapter 6: Relationships

Chapter 7: Family Gatherings

Chapter 7.1: Public Holidays

Chapter 7.2: Death and mourning

Chapter 8: Retirement

Chapter 9: Death

```

Body:
This is my code, but I don't know how to debug it. Please help me and my code. I am trying to add a hide/show button for my contents list, but I don't know what is wrong with it. It is greatly appreciated. Ummm... I don't know what to say as I have to add more information. Just comment to ask any queries.

<!DOCTYPE html>

        <title>How to be Asian</title>

Contents
<button onclick="myFunction()">[show]</button>

Chapter 1: Early Childhood

Chapter 2: Primary School Education

Chapter 3: High School Education

Chapter 4: College/University Education

Chapter 5: Employment

Chapter 6: Relationships

Chapter 7: Family Gatherings

Chapter 7.1: Public Holidays

Chapter 7.2: Death and mourning

Chapter 8: Retirement

Chapter 9: Death

Chapter 1: Early Childhood

When Asian kids go through pre-schooling years and primary school, children are always put under pressure and always neglected so that they work harder and feel like they are worth something after some time and not actually useless.
"We just never praise our children, always compare them to people who are better, so they grow up never feeling good enough and then have to constantly outdo everybody else to feel like they aren’t worthless."
 Quoted from Stven He's father

Chapter 2: Primary School Education

Asian kids are always compared to their peers by their parents. This is because Asian parents want the best of the child. This also means that children are used too much for the simplest of their demands.

 During this period of learning, PTSD is most used so that children are trained to cope "in the future". "In the future" meaning whenever you go back to your parents house when you are and adult. But this training will deal emotional damage, social anxiety and negliegence. This part of life is when most of the tactics are used so that the child can get used to them. Once they know how to leave the situation, create more problems for the child so that they get more experience.

This period of their life is when you can take advantage of them. For example, when you are shopping, tell your child that you are going to get something common in the household, like rice. Then, go to the aisle and watch them go to the cashier person and panic as you are assumed to get rice. Once they start getting constipated, go back with a 5kg bag of rice and start telling your child off for constipating in public.

BONUS!

If you can humiliate your child in front of anyone, especially your child's friends, it will intergrate information for life.

Chapter 3: High School Education

This period of life is when you get to choose his choices.

Chapter 4: College/University Education

Chapter 5: Employment

Chapter 6: Relationships

Chapter 7: Family Gatherings

Chapter 7.1: Public Holidays

Chapter 7.2: Death and mourning

Chapter 8: Retirement

Chapter 9: Death

Body:
I ran your code, Its fine function wise but the button hides with the div. I guess that's the problem you are referring to.

Now a few things.

Ids should be treated as unique so don't give the same id to many tags, use class instead.

The button that hides the content needs to be outside the container that you are trying to hide.

<!DOCTYPE html>
<html>
    <head>
        <title>How to be Asian</title>
        <style type="text/css">
            h1, h2, h3, h4, h5, h6 {
                font-weight: bold;
                border: 0px;
                margin: 2px;
            }
            h2
                {
                text-indent: 20px;
            }
            ul {
                margin-top: 2%;
            }
            body {
                margin: 2px;
                border: 5px;
                padding: 13px;
            }
            #Contents {
                display: table;
                padding: 7px;
                border: 1px solid #a2a9b1;
                background-color: #f8f9fa;
                font-size: 95%;
                text-align: left;
                float: right;
                width: 15%;
            }
            #Quote {
                text-align: center;
                line-height: 2em;
                padding-left: 25%;
                padding-right: 25%;
                padding-top: 20px;
                padding-bottom: 20px;
                display: block;
            }
            .Bonus {
                display: inline;
                font-size: 1.3em;
            }

            body{
                padding: 1%;
                margin: 1%
            }

            p h1{
                display: inline;
                float: left;
            }
        </style>

    </head>
    <body>
        <script>
            function myFunction() {
                var x = document.getElementById("Contents");
                    if (x.style.display === "none") {
                        x.style.display = "block";
                    } else {
                        x.style.display = "none";
                    }
                }
        </script>
                 <button onclick="myFunction()">[show]</button>
   <div id="Contents">
            <h1>Contents</h1>
            <ol>
                <li><a href="#Chapter_1">Chapter 1: Early Childhood</a></li>
                <li><a href="#Chapter_2">Chapter 2: Primary School Education</a></li>
                <li><a href="#Chapter_3">Chapter 3: High School Education</a></li>
                <li><a href="#Chapter_4">Chapter 4: College/University Education</a></li>
                <li><a href="#Chapter_5">Chapter 5: Employment</a></li>
                <li><a href="#Chapter_6">Chapter 6: Relationships</a></li>
                <li><a href="#Chapter_7">Chapter 7: Family Gatherings</a></li>
                <ol>
                    <li><a href="#Chapter_7.1">Chapter 7.1: Public Holidays</a></li>
                    <li><a href="#Chapter_7.2">Chapter 7.2: Death and mourning</a></li>
                </ol>
                <li><a href="#Chapter_8">Chapter 8: Retirement</a></li>
                <li><a href="#Chapter_9">Chapter 9: Death</a></li>
            </ol>
        </div>
        <div>
            <h1 id="Chapter_1">Chapter 1: Early Childhood</h1>
            <p>When Asian kids go through pre-schooling years and primary school, children are always put under pressure and always neglected so that they work harder and feel like they are worth something after some time and not actually useless.<br><span id="Quote">"We just never praise our children, always compare them to people who are better, so they grow up never feeling good enough and then have to constantly outdo everybody else to feel like they aren’t worthless." <br> Quoted from Stven He's father</span></p>
        </div>
        <div>
            <h1 id="Chapter_2">Chapter 2: Primary School Education</h1>
            <p>Asian kids are always compared to their peers by their parents. This is because Asian parents want the best of the child. This also means that children are used too much for the simplest of their demands. <br> <br> During this period of learning, PTSD is most used so that children are trained to cope "in the future". "In the future" meaning whenever you go back to your parents house when you are and adult. But this training will deal emotional damage, social anxiety and negliegence. This part of life is when most of the tactics are used so that the child can get used to them. Once they know how to leave the situation, create more problems for the child so that they get more experience. </p>
            <p>This period of their life is when you can take advantage of them. For example, when you are shopping, tell your child that you are going to get something common in the household, like rice. Then, go to the aisle and watch them go to the cashier person and panic as you are assumed to get rice. Once they start getting constipated, go back with a 5kg bag of rice and start telling your child off for constipating in public. </p>
            <div style="text-align: center;">
                <h4 class="Bonus">BONUS! </h4><p class="Bonus">If you can humiliate your child in front of anyone, especially your child's friends, it will intergrate information for life. </p>
            </div>
        </div>
        <div>
            <h1 id="Chapter_3">Chapter 3: High School Education</h1>
            <p>This period of life is when you get to choose his choices. </p>
        </div>
        <div>
            <h1 id="Chapter_4">Chapter 4: College/University Education</h1>
        </div>
        <div>
            <h1 id="Chapter_5">Chapter 5: Employment</h1>
        </div>
        <div>
            <h1 id="Chapter_6">Chapter 6: Relationships</h1>
        </div>
        <div>
            <h1 id="Chapter_7">Chapter 7: Family Gatherings</h1>
            <h2 id="Chapter_7.1">Chapter 7.1: Public Holidays</h2>
            <h2 id="Chapter_7.2">Chapter 7.2: Death and mourning</h2>
        </div>
        <div>
            <h1 id="Chapter_8">Chapter 8: Retirement</h1>
        </div>
        <div>
            <h1 id="Chapter_9">Chapter 9: Death</h1>
        </div>
    </body>
</html>


问:
Use preg_replace() to add two backslashes before each match
I have code below, what I need to change to get result mercedes\\-benz instead of mercedes\-benz

```<code>$value = 'mercedes-benz';
$pattern = '/(\+|-|\/|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/';
$replace = '\\\\${1}';
echo preg_replace($pattern, $replace, $value);
</code>```

答:
Welcome to the joys of "leaning toothpick syndrome" - backslash is such a commonly used escape character that it frequently requires escaping multiple times. Let's have a look at your case:

Required output (presumably because of some other escaping context): \\

Escape each \ with an additional \ for use in the PCRE regex engine: \\\\

Escape each \ there for use in a PHP string: \\\\\\\\

```<code>$value = 'mercedes-benz';
$pattern = '/(\+|-|\/|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/';
$replace = '\\\\\\\\${1}';
echo preg_replace($pattern, $replace, $value);
</code>```

As mickmackusa points out, you can get away with six rather than eight backslashes in some cases, such as a replacement of '\\\\\\'; this works because the regex engine sees \\\, which is an escaped backslash (\\) followed by a single backslash (\) that can't be escaping anything because it's the end of the string. Simply doubling for each "layer" of escaping is probably safer than learning when this short-cut is and isn't valid, though.

Body:
I have code below, what I need to change to get result mercedes\\-benz instead of mercedes\-benz

$value = 'mercedes-benz';
$pattern = '/(\+|-|\/|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/';
$replace = '\\\\${1}';
echo preg_replace($pattern, $replace, $value);

Body:
Welcome to the joys of "leaning toothpick syndrome" - backslash is such a commonly used escape character that it frequently requires escaping multiple times. Let's have a look at your case:

Required output (presumably because of some other escaping context): \\

Escape each \ with an additional \ for use in the PCRE regex engine: \\\\

Escape each \ there for use in a PHP string: \\\\\\\\

$value = 'mercedes-benz';
$pattern = '/(\+|-|\/|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/';
$replace = '\\\\\\\\${1}';
echo preg_replace($pattern, $replace, $value);

As mickmackusa points out, you can get away with six rather than eight backslashes in some cases, such as a replacement of '\\\\\\'; this works because the regex engine sees \\\, which is an escaped backslash (\\) followed by a single backslash (\) that can't be escaping anything because it's the end of the string. Simply doubling for each "layer" of escaping is probably safer than learning when this short-cut is and isn't valid, though.


问:
How can I use a Timer of 2 seconds inside a fragment?
This is my Fragment.kt

class SplashFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_splash, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
            // My Timer
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
                }
            }, 2000)

    }
}
```
<p><code>This is my Logcat error</code></p>
```2022-02-06 20:37:34.755 27478-27510/com.finite.livelocationtest E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    Process: com.finite.livelocationtest, PID: 27478
    java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
        at android.widget.Toast.getLooper(Toast.java:179)
        at android.widget.Toast.<init>(Toast.java:164)
        at android.widget.Toast.makeText(Toast.java:492)
        at android.widget.Toast.makeText(Toast.java:480)
        at com.finite.livelocationtest.ui.fragment.SplashFragment$onViewCreated$1.run(SplashFragment.kt:31)
        at java.util.TimerThread.mainLoop(Timer.java:562)
        at java.util.TimerThread.run(Timer.java:512)
```

What do I want to achieve?

I want to go from this fragment to the next fragment after a time of 2 seconds time, please let me know any possible way to achieve this.

答:
just use the Android Handler for 2-second delay. Here is the code sample

```<code>Handler(Looper.getMainLooper()).postDelayed({
   //this portion is run when the handler is completing 2 second of delay
}, 2000)
</code>```

Works on both activity and fragment

Body:
This is my Fragment.kt

class SplashFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_splash, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
            // My Timer
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
                }
            }, 2000)

    }
}

This is my Logcat error

2022-02-06 20:37:34.755 27478-27510/com.finite.livelocationtest E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    Process: com.finite.livelocationtest, PID: 27478
    java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
        at android.widget.Toast.getLooper(Toast.java:179)
        at android.widget.Toast.<init>(Toast.java:164)
        at android.widget.Toast.makeText(Toast.java:492)
        at android.widget.Toast.makeText(Toast.java:480)
        at com.finite.livelocationtest.ui.fragment.SplashFragment$onViewCreated$1.run(SplashFragment.kt:31)
        at java.util.TimerThread.mainLoop(Timer.java:562)
        at java.util.TimerThread.run(Timer.java:512)

What do I want to achieve?

I want to go from this fragment to the next fragment after a time of 2 seconds time, please let me know any possible way to achieve this.

Body:
just use the Android Handler for 2-second delay. Here is the code sample

Handler(Looper.getMainLooper()).postDelayed({
   //this portion is run when the handler is completing 2 second of delay
}, 2000)

Works on both activity and fragment