问:
Blazor WebAssembly with Clean Architecture
I am working on a proof of concept project using Blazor WebAssembly.  The project already has a React front end that I am hoping to replicate in Blazor.

I have the following projects in my solution:

Domain - contains entities and does not reference any other layers

Application - references the domain and contains DTOs,
commands/queries (using MediatR/Dapper), validators (using
FluidValidation) and interfaces for subsequent layers to implement

Persistence – references application and uses EF Core to store the
domain models in the database

API - a Web API that registers everything using DI and exposes the
commands/queries from the application layer via controllers

React Front End - uses AJAX to talk to the API

I would like to reference the Application layer in a Blazor WebAssembly project so that I can reuse the validation rules that exist against the DTOs.  Would it be possible for somebody to step though the code in the browser and extract sensitive information, such as connection strings, from the commands/queries?

For example, a simple query may look like this and stepping through the code would allow the IDbConnection to be inspected:

```<code>public class PayCategoryListQueryHandler
    : IRequestHandler<PayCategoryListQuery, PayCategoryListQueryVm>
  {
    private readonly IDbConnection _connection;

    public PayCategoryListQueryHandler(IDbConnection connection)
    {
      _connection = connection;
    }

    public async Task<PayCategoryListQueryVm> Handle(PayCategoryListQuery query, CancellationToken cancellationToken)
    {
      {
        var viewModel = new PayCategoryListQueryVm();

        viewModel.AddRange(
          await _connection.QueryAsync<PayCategoryListItemDto>(
            "SELECT Id, Description, MakeAttendedTimeZero, IsOffSite, IsVisibleToClient FROM PayCategory ORDER BY Description"));

        return viewModel;
      }
    }
  }
</code>```

Do I need to extract the DTOs and their validation a separate layer that does not contain any database access code to prevent the connection string being leaked?

Clarification

To try and clarify the issue I would like to try and explain my situation a bit better.

My current application uses a React front end with Formik and Yup providing the validation.  This means that each time a change is made to a validation rule I need to reflect it in two places – the Application layer and the React application. I was hoping that moving to Blazor would alleviate the duplication by only having to maintain validation rules in the Application layer.

The architecture I am currently using is based upon the NorthwindTraders sample application.

Using that example, CreateCustomerCommand makes use of CreateCustomerCommandValidator which will respond to POST requests via CustomersController.  In order to use this for client-side validation in Blazor WebAssembly I would currently need to reference the Application layer.

Given this scenario should all the commands (not command handlers) and validators be moved to a separate project which could then be referenced by Blazor.  The command handlers could remain in the Application layer therefore removing any database access code.

答:
Create a new dotnet.standard-project called something like, MyProject.Domain.Shared. There you put all communication (poco-)classes.

The Shared-Project is consumed by your Domain-Project, Application-Layer and Client-Layer.
The Domain-Project is consumed by the Application-Layer and Persistence-Layer.

In the Shared-Project you put:

DTOs

Requests

Responses

Validators

In the Application-Project you put:

Request Handlers

Response Handlers

In the Domain-Project you put:

Domain-Objects

Repository-Interfaces

Handlers which consumes the requests and produce responses)

Body:
I am working on a proof of concept project using Blazor WebAssembly.  The project already has a React front end that I am hoping to replicate in Blazor.

I have the following projects in my solution:

Domain - contains entities and does not reference any other layers

Application - references the domain and contains DTOs,
commands/queries (using MediatR/Dapper), validators (using
FluidValidation) and interfaces for subsequent layers to implement

Persistence – references application and uses EF Core to store the
domain models in the database

API - a Web API that registers everything using DI and exposes the
commands/queries from the application layer via controllers

React Front End - uses AJAX to talk to the API

I would like to reference the Application layer in a Blazor WebAssembly project so that I can reuse the validation rules that exist against the DTOs.  Would it be possible for somebody to step though the code in the browser and extract sensitive information, such as connection strings, from the commands/queries?

For example, a simple query may look like this and stepping through the code would allow the IDbConnection to be inspected:

public class PayCategoryListQueryHandler
    : IRequestHandler<PayCategoryListQuery, PayCategoryListQueryVm>
  {
    private readonly IDbConnection _connection;

    public PayCategoryListQueryHandler(IDbConnection connection)
    {
      _connection = connection;
    }

    public async Task<PayCategoryListQueryVm> Handle(PayCategoryListQuery query, CancellationToken cancellationToken)
    {
      {
        var viewModel = new PayCategoryListQueryVm();

        viewModel.AddRange(
          await _connection.QueryAsync<PayCategoryListItemDto>(
            "SELECT Id, Description, MakeAttendedTimeZero, IsOffSite, IsVisibleToClient FROM PayCategory ORDER BY Description"));

        return viewModel;
      }
    }
  }

Do I need to extract the DTOs and their validation a separate layer that does not contain any database access code to prevent the connection string being leaked?

Clarification

To try and clarify the issue I would like to try and explain my situation a bit better.

My current application uses a React front end with Formik and Yup providing the validation.  This means that each time a change is made to a validation rule I need to reflect it in two places – the Application layer and the React application. I was hoping that moving to Blazor would alleviate the duplication by only having to maintain validation rules in the Application layer.

The architecture I am currently using is based upon the NorthwindTraders sample application.

Using that example, CreateCustomerCommand makes use of CreateCustomerCommandValidator which will respond to POST requests via CustomersController.  In order to use this for client-side validation in Blazor WebAssembly I would currently need to reference the Application layer.

Given this scenario should all the commands (not command handlers) and validators be moved to a separate project which could then be referenced by Blazor.  The command handlers could remain in the Application layer therefore removing any database access code.


来源: stackexchange

问:
How to give the result of a pipelined function as a default parameter?
I have created these 4 types :

```<code>record type myrecord1 is (...)
record type myrecord2 is (...)

table tableofmyrecord1 is table of myrecord1;
table tableofmyrecord2 is table of myrecord2;
</code>```

and 2 functions :

```<code>function  a(k in tableofmyrecord2) return packageName.tableofmyrecord1 PIPELINED;
function  b return packageName.tableofmyrecord2  PIPELINED;
</code>```

I can effectively give a default parameter ; null, the table empty, a table that I have create, but I can give directly the result of a of pipelined function.

```<code>function  a return packageName.tOfmyrecord(k in tableofmyrecord2 :=package.b)   PIPELINED
</code>```

This does'nt work.

This solution does'nt work too.

```<code>declare
    defaultArgOFA :=package.b;
    function  a return packageName.tOfmyrecord(k in tableofmyrecord2 :=defaultArgOFA)  PIPELINED
</code>```

same error

PLS-00653: aggregate/table functions are not allowed

答:
This error says that you cannot call pipelined functions using PLSQL, so you can't directly write v:=a(). But you can use SQL. Below is an example where pipelined b gets input from pipelined a and multiplies salaries.

Package:

```<code>create or replace package pkg is
  type tr is record (id int, name varchar2(10), sal int);
  type tt is table of tr;
  function a return tt pipelined;
  function b(par in tt) return tt pipelined;
end pkg;
</code>```

Body:

```<code>create or replace package body pkg is

function a return tt pipelined is
  v_tr tr;
begin
  v_tr.id := 1;  v_tr.name := 'Mark';  v_tr.sal := 100;
  pipe row (v_tr);

  v_tr.id := 2;  v_tr.name := 'Pete';  v_tr.sal := 120;
  pipe row (v_tr);
  return;
end;

function b(par in tt) return tt pipelined is
  v_tr tr;
begin
  for i in 1..par.last loop
    v_tr := par(i);
    v_tr.sal := v_tr.sal * 10;
    pipe row (v_tr);
  end loop;
  return;
end;

end pkg;
</code>```

And this test worked for me:

```<code>select * from table(pkg.b(pkg.a));
</code>```

Result:

```<code>    ID NAME              SAL
------ ---------- ----------
     1 Mark             1000
     2 Pete             1200
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created these 4 types :

record type myrecord1 is (...)
record type myrecord2 is (...)

table tableofmyrecord1 is table of myrecord1;
table tableofmyrecord2 is table of myrecord2;

and 2 functions :

function  a(k in tableofmyrecord2) return packageName.tableofmyrecord1 PIPELINED;
function  b return packageName.tableofmyrecord2  PIPELINED;

I can effectively give a default parameter ; null, the table empty, a table that I have create, but I can give directly the result of a of pipelined function.

function  a return packageName.tOfmyrecord(k in tableofmyrecord2 :=package.b)   PIPELINED

This does'nt work.

This solution does'nt work too.

declare
    defaultArgOFA :=package.b;
    function  a return packageName.tOfmyrecord(k in tableofmyrecord2 :=defaultArgOFA)  PIPELINED

same error

PLS-00653: aggregate/table functions are not allowed

Body:
This error says that you cannot call pipelined functions using PLSQL, so you can't directly write v:=a(). But you can use SQL. Below is an example where pipelined b gets input from pipelined a and multiplies salaries.

Package:

create or replace package pkg is
  type tr is record (id int, name varchar2(10), sal int);
  type tt is table of tr;
  function a return tt pipelined;
  function b(par in tt) return tt pipelined;
end pkg;

Body:

create or replace package body pkg is

function a return tt pipelined is
  v_tr tr;
begin
  v_tr.id := 1;  v_tr.name := 'Mark';  v_tr.sal := 100;
  pipe row (v_tr);

  v_tr.id := 2;  v_tr.name := 'Pete';  v_tr.sal := 120;
  pipe row (v_tr);
  return;
end;

function b(par in tt) return tt pipelined is
  v_tr tr;
begin
  for i in 1..par.last loop
    v_tr := par(i);
    v_tr.sal := v_tr.sal * 10;
    pipe row (v_tr);
  end loop;
  return;
end;

end pkg;

And this test worked for me:

select * from table(pkg.b(pkg.a));

Result:

    ID NAME              SAL
------ ---------- ----------
     1 Mark             1000
     2 Pete             1200


问:
s3 images not loading after copying it from one bucket to another of same account
I have copied images from one bucket to another and now i am unable to access images. Error shows
AccessDenied message.

I have verified file exists in bucket but unable to access it. If i remove same image and upload it again then it is working.

Please suggest any reason if anything i missed during copying bucket data from one to another.

Link which was working with old bucket and now not accessible with new bucket

```<code>https://abc.s3.amazonaws.com/uploads/profile/image/16923/client_thumb_CINDERELLA_12
</code>```

答:
You are trying to access the public URL for the S3 object and it works only if you open the bucket publically. You have to set your new bucket publically accessible and ALSO set the bucket policy such as:

```<code>{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"PublicRead",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::examplebucket/*"]
    }
  ]
}
</code>```

where the examplebucket is the name for the bucket.

Body:
I have copied images from one bucket to another and now i am unable to access images. Error shows
AccessDenied message.

I have verified file exists in bucket but unable to access it. If i remove same image and upload it again then it is working.

Please suggest any reason if anything i missed during copying bucket data from one to another.

Link which was working with old bucket and now not accessible with new bucket

https://abc.s3.amazonaws.com/uploads/profile/image/16923/client_thumb_CINDERELLA_12

Body:
You are trying to access the public URL for the S3 object and it works only if you open the bucket publically. You have to set your new bucket publically accessible and ALSO set the bucket policy such as:

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"PublicRead",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::examplebucket/*"]
    }
  ]
}

where the examplebucket is the name for the bucket.


问:
Python lambda inside range
In the following code I'm supposed to print what is shown in the "should be" portion of the comments in the main method. Not sure how to fix. For example, when the argument is 0 it should print 3 but I get 6. Thank you. </p>

```<code>def get_sum_metrics(predictions, metrics=None):
    if metrics is None:
        metrics = []

    for i in range(3):
        metrics.append(lambda x: x + i)

    sum_metrics = 0
    for metric in metrics:
        sum_metrics += metric(predictions)

    return sum_metrics

def main():
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9
    print(get_sum_metrics(3, [lambda x: x]))  # Should be (3) + (3 + 0) + (3 + 1) + (3 + 2) = 15
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9
</code>```

答:
You have got messed up with the lambda function.The error came because of the free variable assigning error.So,you can replace the code with the following code.

```<code>    for i in range(3):
        metrics.append(lambda x,i=i: x + i)
</code>```

This is the entire code

```<code>def get_sum_metrics(predictions, metrics=None):
    if metrics is None:
        metrics = []

    for i in range(3):
        metrics.append(lambda x,i=i: x + i)

    sum_metrics = 0
    for metric in metrics:
        sum_metrics += metric(predictions)

    return sum_metrics

def main():
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9
    print(get_sum_metrics(3, [lambda x: x]))  # Should be (3) + (3 + 0) + (3 + 1) + (3 + 2) = 15
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9

main()

</code>```

It's better if you refer this thread. It has a full explanation about lambda function.

And if get confused with the relevant theory use this code which is written  according to your case that is more simple and easy to understand

```<code>def get_sum_metrics(predictions, metrics=None):
    if metrics is None:
        metrics = []

    func=lambda x,i: x + i

    sum_metrics = 0
    for i in range(3):
        sum_metrics += func(predictions,i)

    for metric in metrics:
        sum_metrics+=metric(predictions)
    return sum_metrics

def main():
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9
    print(get_sum_metrics(3, [lambda x: x]))  # Should be (3) + (3 + 0) + (3 + 1) + (3 + 2) = 15
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9

main()

</code>```

Title: Python lambda inside range

Body:
In the following code I'm supposed to print what is shown in the "should be" portion of the comments in the main method. Not sure how to fix. For example, when the argument is 0 it should print 3 but I get 6. Thank you.

def get_sum_metrics(predictions, metrics=None):
    if metrics is None:
        metrics = []

    for i in range(3):
        metrics.append(lambda x: x + i)

    sum_metrics = 0
    for metric in metrics:
        sum_metrics += metric(predictions)

    return sum_metrics

def main():
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9
    print(get_sum_metrics(3, [lambda x: x]))  # Should be (3) + (3 + 0) + (3 + 1) + (3 + 2) = 15
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9

Body:
You have got messed up with the lambda function.The error came because of the free variable assigning error.So,you can replace the code with the following code.

    for i in range(3):
        metrics.append(lambda x,i=i: x + i)

This is the entire code

def get_sum_metrics(predictions, metrics=None):
    if metrics is None:
        metrics = []

    for i in range(3):
        metrics.append(lambda x,i=i: x + i)

    sum_metrics = 0
    for metric in metrics:
        sum_metrics += metric(predictions)

    return sum_metrics

def main():
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9
    print(get_sum_metrics(3, [lambda x: x]))  # Should be (3) + (3 + 0) + (3 + 1) + (3 + 2) = 15
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9

main()

It's better if you refer this thread. It has a full explanation about lambda function.

And if get confused with the relevant theory use this code which is written  according to your case that is more simple and easy to understand

def get_sum_metrics(predictions, metrics=None):
    if metrics is None:
        metrics = []

    func=lambda x,i: x + i

    sum_metrics = 0
    for i in range(3):
        sum_metrics += func(predictions,i)

    for metric in metrics:
        sum_metrics+=metric(predictions)
    return sum_metrics

def main():
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9
    print(get_sum_metrics(3, [lambda x: x]))  # Should be (3) + (3 + 0) + (3 + 1) + (3 + 2) = 15
    print(get_sum_metrics(0))  # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3
    print(get_sum_metrics(1))  # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6
    print(get_sum_metrics(2))  # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9

main()


问:
How to have fixed div height irrespective of image height within it
I have a row with three coloumns. I want to have a image on each coloumn's divs with same height irrespective of image size in each div.

I want the images to get resized with in a div. But i get different size of divs as the image size of myImage1.png, myImage2.png and myImage3.png is different.

This is happening because i have fixed padding in my 'bg' class. Can somebody help me to fix this? Below is my HTML and CSS code.

```<code><div class="row IDE_container">
    <div class="col-lg-3 col-md-3 col-sm-3">
        <div class="bg">
            <img src="myImage1.png" class="IDE_div" />
        </div>
    </div>

    <div class="col-lg-2 col-md-2 col-sm-2">
        <div class="circle_bg circle_bg_sm">
            <img src="myImage2.png" class="IDE_div" />
        </div>
    </div>

    <div class="col-lg-3 col-md-3 col-sm-3">
        <div class="circle_bg">
            <img src="myImage3.png" class="IDE_div" />
        </div>
    </div>
</div>

.bg{
    background-color: #ededed;
    border-radius: 100%;
    text-align: center;
    padding: 35% 5%;
    width: max-content;
    max-width: 100%;
    box-shadow: 0 0 3px 1px #DDD;
}

.IDE_div {
display: inline-block;
position: relative;
width: 100%;
height: 100%;
}

.IDE_container {
    display: flex;
    align-items: baseline;
  }
</code>```

答:
You need to set a height or max-height on the divs containing the images, or they will adapt to the height of their content (the images). As you've set the images to take up 100% width and height, and haven't constrained their parents, they will get as large as they can based on the original image size.

So, for example :

```<code>.IDE_container {
  display: flex;
  align-items: baseline;

  div.col-3 {

    div {
      height: 200px;

      .IDE_div {
        display: inline-block;
        position: relative;
        width: 100%;
        height: 100%;

        &::before {
          content: "";
          position: absolute;
          top: 50%;
          left: 50%;
          width: var(--val);
          padding-bottom: var(--val);
          transform: translate(-50%, -50%);
          z-index: -1;
          border-radius: 50%;
        }
      }
    }
  }
}
</code>```

You could give all containers the same class (e.g. fixed-height-bg) to style them more easily.

Also note: You don't need to give your columns individual classes for different screen sizes, as they always take up the same proportion. So, you can just use

```<code> <div class="col-3">
        <div class="circle_bg">
            <img src="myImage3.png" class="IDE_div" />
        </div>
    </div>
</code>```

EDITED to add: if you want the images to maintain their proportions, you need to change your css to look like this:

```<code>img {
  height: 100%; /* height of the parent container if specified, or of the image itself */
  width: auto; /* will maintain the proportions of the image */
}
</code>```

You can also switch those values, to height: auto; width: 100%; if you want the images to take the full width.

Body:
I have a row with three coloumns. I want to have a image on each coloumn's divs with same height irrespective of image size in each div.

I want the images to get resized with in a div. But i get different size of divs as the image size of myImage1.png, myImage2.png and myImage3.png is different.

This is happening because i have fixed padding in my 'bg' class. Can somebody help me to fix this? Below is my HTML and CSS code.

.bg{
    background-color: #ededed;
    border-radius: 100%;
    text-align: center;
    padding: 35% 5%;
    width: max-content;
    max-width: 100%;
    box-shadow: 0 0 3px 1px #DDD;
}

.IDE_div {
display: inline-block;
position: relative;
width: 100%;
height: 100%;
}

.IDE_container {
    display: flex;
    align-items: baseline;
  }

Body:
You need to set a height or max-height on the divs containing the images, or they will adapt to the height of their content (the images). As you've set the images to take up 100% width and height, and haven't constrained their parents, they will get as large as they can based on the original image size.

So, for example :

.IDE_container {
  display: flex;
  align-items: baseline;

  div.col-3 {

    div {
      height: 200px;

      .IDE_div {
        display: inline-block;
        position: relative;
        width: 100%;
        height: 100%;

        &::before {
          content: "";
          position: absolute;
          top: 50%;
          left: 50%;
          width: var(--val);
          padding-bottom: var(--val);
          transform: translate(-50%, -50%);
          z-index: -1;
          border-radius: 50%;
        }
      }
    }
  }
}

You could give all containers the same class (e.g. fixed-height-bg) to style them more easily.

Also note: You don't need to give your columns individual classes for different screen sizes, as they always take up the same proportion. So, you can just use

 <div class="col-3">
        <div class="circle_bg">
            <img src="myImage3.png" class="IDE_div" />
        </div>
    </div>

EDITED to add: if you want the images to maintain their proportions, you need to change your css to look like this:

img {
  height: 100%; /* height of the parent container if specified, or of the image itself */
  width: auto; /* will maintain the proportions of the image */
}

You can also switch those values, to height: auto; width: 100%; if you want the images to take the full width.


问:
Strange behavior running JAR in different machines
I found a strange (at least for me) behavior in my small Java application.
I have an app.jar which running from command line to do a simple task. The task is, find duplicate values from the given list and remove them. The application was developed with JDK-7 and running with JRE-7.

From command line of my PC everything is OK, but when running the same JAR in virtual machine which is Windows-7 as mine and with the same JRE it doesn’t remove duplicates and no any error occurs.

Here is my code:

```<code>public List<String> removeDuplicatedFin(List<String> coreList,
            Map<String, String> strToRemoveMap) {
        for (int y = 0; y < coreList.size(); y++) {
            String str = coreList.get(y).getPosts().get(0).getMyStr();
            String id = coreList.get(y).getPosts().get(0).getId();
            if (strToRemoveMap.get(str) != null
                    && strToRemoveMap.get(str).equals(idPost)) {
                coreList.get(y).getPosts().remove(0);
            }
        }
        return coreList;
    }
</code>```

coreList is the main list

strToRemoveMap contains values to be deleted

Any idea or some help please?

Thanks in advance

答:
Contrary to what you may think that you have discovered, the correct way to compare two strings in Java is to use String.equals; see How do I compare strings in Java?.

There are situations where str1 == str2 is false and str1.equals(str2) is true.  Two strings that are equal are not necessarily the same object.

However, it is not possible for str1 == str2 to be true and str1.equals(str2) to be false; the specification of String.equals does not allow that.

If you have really come across a situation where that seems to be the case, then the most likely explanation is that you have a race condition or memory anomaly caused by the behavior of another thread.  It is hard to be more specific without seeing your real code in action.

This could also explain why your (actual) code works in some circumstances and not others.  It is not unusual for concurrency related bugs to only show up on certain platforms.  For example, they might be OS dependent, or Java version dependent or they might depend on the number of physical cores your system has.

For what it is worth, your (supposed) example method does not compile.  Since coreList is a List<String>, coreList.get(y) will give you a String.  But String doesn't declare a getPosts() method so the three places where you have coreList.get(y).getPosts() will be compilation errors.

I suspect that you have modified the actual code that exhibits the problem.  But in doing so you have turned it into something that is nonsensical. This is why we asked for a minimal reproducible example.

ContentLicense: CC BY-SA 3.0

Body:
I found a strange (at least for me) behavior in my small Java application.
I have an app.jar which running from command line to do a simple task. The task is, find duplicate values from the given list and remove them. The application was developed with JDK-7 and running with JRE-7.

From command line of my PC everything is OK, but when running the same JAR in virtual machine which is Windows-7 as mine and with the same JRE it doesn’t remove duplicates and no any error occurs.

Here is my code:

public List<String> removeDuplicatedFin(List<String> coreList,
            Map<String, String> strToRemoveMap) {
        for (int y = 0; y < coreList.size(); y++) {
            String str = coreList.get(y).getPosts().get(0).getMyStr();
            String id = coreList.get(y).getPosts().get(0).getId();
            if (strToRemoveMap.get(str) != null
                    && strToRemoveMap.get(str).equals(idPost)) {
                coreList.get(y).getPosts().remove(0);
            }
        }
        return coreList;
    }

coreList is the main list

strToRemoveMap contains values to be deleted

Any idea or some help please?

Thanks in advance


问:
need help to take phpMyAdmin database's backup
i want to  backup my database from php file...

i am using phpMyAdmin as back end. i want to create excel file from that data base is it possible? yes then how? give me some suggestion on it thanks in advance...

my one more querty is:

if i am running this php code then when it store that file..? i've checked into the phpMyAdmin bt that was not inside that the code is as below

```<code><?php
include 'config.php';
include 'opendb.php';
$tableName  = 'mypet';
$backupFile = 'backup/mypet.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $login_master";
$result = mysql_query($query);

include 'closedb.php';
?>
</code>```

答:
Once you have selected your database, you should click on "Export" tab. You  will be shown a page with a number of options (which tables to export, the name of the export file, the type of file, whether excel or sql or whatever...).

Anyway, I suggest to use the command line if possible.

Body:
i want to  backup my database from php file...

i am using phpMyAdmin as back end. i want to create excel file from that data base is it possible? yes then how? give me some suggestion on it thanks in advance...

my one more querty is:

if i am running this php code then when it store that file..? i've checked into the phpMyAdmin bt that was not inside that the code is as below

<?php
include 'config.php';
include 'opendb.php';
$tableName  = 'mypet';
$backupFile = 'backup/mypet.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $login_master";
$result = mysql_query($query);

include 'closedb.php';
?>


问:
UnboundLocalError: local variable 'csv_file' referenced before assignment
When I run my code I get these errors:

```<code>if not csv_file.name.endswith('.csv'):

</code>```

UnboundLocalError: local variable 'csv_file' referenced before
  assignment

views.py

```<code>import csv, io
from django.shortcuts import render
from django.contrib import messages
from .models import Profile

# Create your views here.# one parameter named request
def profile_upload(request):    # declaring template
    template = "profile_upload.html"
    data = Profile.objects.all()# prompt is a context variable that can have different values      depending on their context
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data
              }
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        return render(request, template, prompt)
        csv_file = request.FILES['file']    # let's check if it is a csv file
    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'THIS IS NOT A CSV FILE')
        data_set = csv_file.read().decode('UTF-8')    # setup a stream which is when we loop through each line we are able to handle a data in a stream
        io_string = io.StringIO(data_set)
        next(io_string)
        for column in csv.reader(io_string, delimiter=',', quotechar="|"):
            _, created = Profile.objects.update_or_create(
                name=column[0],
                email=column[1],
                address=column[2],
                phone=column[3],
                profile=column[4]
            )
        context = {}
        return render(request, template, context)

</code>```

I am not sure why I am getting this error, it would be great if anyone can help me figure out what I am doing wrong.

答:
You wrote more complicated logic over there...

First you should check that if there are any file or not

Then you have to write your condition for if not csv_file.name.endswith('.csv'):

Example :-

```<code>def profile_upload(request):
    # your logic

    if request.method == "GET":
        csv_file = request.FILES['file']
        return render(request, template, prompt)
    else:
        csv_file = None

    if csv_file:
        if not csv_file.name.endswith('.csv'):
            # your logic
            return render(request, template, context)
</code>```

Body:
When I run my code I get these errors:

if not csv_file.name.endswith('.csv'):

UnboundLocalError: local variable 'csv_file' referenced before
  assignment

views.py

import csv, io
from django.shortcuts import render
from django.contrib import messages
from .models import Profile

# Create your views here.# one parameter named request
def profile_upload(request):    # declaring template
    template = "profile_upload.html"
    data = Profile.objects.all()# prompt is a context variable that can have different values      depending on their context
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data
              }
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        return render(request, template, prompt)
        csv_file = request.FILES['file']    # let's check if it is a csv file
    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'THIS IS NOT A CSV FILE')
        data_set = csv_file.read().decode('UTF-8')    # setup a stream which is when we loop through each line we are able to handle a data in a stream
        io_string = io.StringIO(data_set)
        next(io_string)
        for column in csv.reader(io_string, delimiter=',', quotechar="|"):
            _, created = Profile.objects.update_or_create(
                name=column[0],
                email=column[1],
                address=column[2],
                phone=column[3],
                profile=column[4]
            )
        context = {}
        return render(request, template, context)

I am not sure why I am getting this error, it would be great if anyone can help me figure out what I am doing wrong.

Body:
You wrote more complicated logic over there...

First you should check that if there are any file or not

Then you have to write your condition for if not csv_file.name.endswith('.csv'):

Example :-

def profile_upload(request):
    # your logic

    if request.method == "GET":
        csv_file = request.FILES['file']
        return render(request, template, prompt)
    else:
        csv_file = None

    if csv_file:
        if not csv_file.name.endswith('.csv'):
            # your logic
            return render(request, template, context)


问:
How to make CSS height 100% scrollable?
I want to make the two-tone background. 50% of left side is in the main background color and 50% right side in another color (say pink). I could accomplish that but now facing another problem. When the mouse cursor is on the pink background color, the page becomes unscrollable. How to fix this and make it scrollable?

html code

html,
body {
  margin: 0;
  overflow: scroll;
  height: 100%;
  background-color: #f5f5f5;
}

#background {
  position: fixed;
  top: 0px;
  left: 50%;
  width: 50%;
  height: 100%;
  background-color: pink;
  z-index: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="background"></div>
</body></code>```

答:
You dont't have to use another div for two-tone background you can acheive by just this:

```<code>html,
body {
  margin: 0;
  overflow: auto;
  min-height: 100%;
  background: linear-gradient(to left, pink 0%,pink 50%,#000000 50%,white 50%,white 100%); /* W3C */
}
</code>```

Have a look at a working pen here
If you want to follow the approach you are doing then yes you can give min-height: 100%; to html.

Title: How to make CSS height 100% scrollable?

Body:
You dont't have to use another div for two-tone background you can acheive by just this:

html,
body {
  margin: 0;
  overflow: auto;
  min-height: 100%;
  background: linear-gradient(to left, pink 0%,pink 50%,#000000 50%,white 50%,white 100%); /* W3C */
}

Have a look at a working pen here
If you want to follow the approach you are doing then yes you can give min-height: 100%; to html.


问:
How to make php dynamic queries
im trying to change query depending on what user has selected. In my case there are displayed two photos with labels pulled from data base. And depending which image is clicked i want that label to be used in query who will display items associated in database with that label. I tried using global variables, but it i didn't work for me. I cant figure out how to insert data into query after user clicked something

There is code fragment where i pull photos with labels from database, and depending on which i select i want "$modeliai_results['Modelis']" (vehicle model label) to be sent and used in another query below

```<code><div class="eile">
    <?php
    echo '
    <a href="standartiniskatalogas.php?page=kategorijos"/>
    <img src="data:image/jpeg;base64,'.base64_encode( $modeliai_results['Nuotrauka'] ).'"/>
    <div class="description">'.$modeliai_results['Marke'].' '.$modeliai_results['Modelis'].'
    </div></a>';
?>
</code>```

Page from second image which should execute query depending on selection from previous page:

```<code><?php
    $kategorijos_sql="SELECT * FROM kategorijos (HERE SHOULD BE ADDED: "WHERE Modelis='MODEL NAME WHICH WAS SELECTED WHEN PRESSED ON IMAGE'";
    $kategorijos_query=mysqli_query($dbconnect, $kategorijos_sql);
    $kategorijos_results=mysqli_fetch_assoc($kategorijos_query);

do{
    echo '
    <div class="eile2">
    <a href="isore/isore.html">
    <img src="data:image/jpeg;base64,'.base64_encode( $kategorijos_results['Nuotrauka'] ).'"/>
    <div class="description">'.$kategorijos_results['Kategorija'].'</div>
    </a></div>'; /* uzdaro echo*/
    }
    while ($kategorijos_results=mysqli_fetch_assoc($kategorijos_query))
     ?>
</code>```

ps. Im not using any extra tools or libraries.

Selecting object
Display data associated with object

答:
My mistake was that i concentrated on "onclick" event which would set global variable and that global variable would be used in query. Problem was that, php with java script not so big friends and would create not linkable URLs to same content. The solution was to use simple thing "$_GET". Assign $_GET to some php variable, and then use it in "href". That way when you click on any kind of object with "a href="'.$variable.'"> bla bla /a>" you get redirected to page with added tail to URL from which you can access to use in other queries</p>

```<code> <?php
        $model= $_GET['model']; //variable from URL tail
        $category= $_GET['category'];

        $category_sql="SELECT * FROM service WHERE Model='$model' AND Category='$category'"; //my SQL where i use variables selected from URL
        $category_query=mysqli_query($dbconnect, $category_sql);
        $category_results=mysqli_fetch_assoc($category_query);
        do{

            echo ' //print html together with php code
        <tr class="data">
            <td>
                <a href="catalogue.php? page=service&model='.$model.'&category='.$category.'&service='.$category_results['Name'].'"> //here i make href which when clicked will pass values named with $ sign
<img src="data:image/jpeg;base64,'.base64_encode( $category_results['Image'] ).'"/>//Here i take image from data base
<br><button>'.$category_results['Name'].'</button></a>
            </td>
            <td> <p>'.$category_results['Description'].'</p> //I take values from data base
            </td>
            <td>'.$category_results['Price'].' €</td>
        </tr>';
    }
    while ($category_results=mysqli_fetch_assoc($category_query)) //loop which cycles through all data base items
         ?>
</code>```

Title: How to make php dynamic queries

Body:
im trying to change query depending on what user has selected. In my case there are displayed two photos with labels pulled from data base. And depending which image is clicked i want that label to be used in query who will display items associated in database with that label. I tried using global variables, but it i didn't work for me. I cant figure out how to insert data into query after user clicked something

There is code fragment where i pull photos with labels from database, and depending on which i select i want "$modeliai_results['Modelis']" (vehicle model label) to be sent and used in another query below

    <?php
    echo '

'.$modeliai_results['Marke'].' '.$modeliai_results['Modelis'].'

';
?>

Page from second image which should execute query depending on selection from previous page:

<?php
    $kategorijos_sql="SELECT * FROM kategorijos (HERE SHOULD BE ADDED: "WHERE Modelis='MODEL NAME WHICH WAS SELECTED WHEN PRESSED ON IMAGE'";
    $kategorijos_query=mysqli_query($dbconnect, $kategorijos_sql);
    $kategorijos_results=mysqli_fetch_assoc($kategorijos_query);

do{
    echo '

'.$kategorijos_results['Kategorija'].'

'; /* uzdaro echo*/
    }
    while ($kategorijos_results=mysqli_fetch_assoc($kategorijos_query))
     ?>

ps. Im not using any extra tools or libraries.

Selecting object
Display data associated with object

Body:
My mistake was that i concentrated on "onclick" event which would set global variable and that global variable would be used in query. Problem was that, php with java script not so big friends and would create not linkable URLs to same content. The solution was to use simple thing "$_GET". Assign $_GET to some php variable, and then use it in "href". That way when you click on any kind of object with "a href="'.$variable.'"> bla bla /a>" you get redirected to page with added tail to URL from which you can access to use in other queries

 <?php
        $model= $_GET['model']; //variable from URL tail
        $category= $_GET['category'];

        $category_sql="SELECT * FROM service WHERE Model='$model' AND Category='$category'"; //my SQL where i use variables selected from URL
        $category_query=mysqli_query($dbconnect, $category_sql);
        $category_results=mysqli_fetch_assoc($category_query);
        do{

            echo ' //print html together with php code
        <tr class="data">
            <td>
                <a href="catalogue.php? page=service&model='.$model.'&category='.$category.'&service='.$category_results['Name'].'"> //here i make href which when clicked will pass values named with $ sign
<img src="data:image/jpeg;base64,'.base64_encode( $category_results['Image'] ).'"/>//Here i take image from data base
<br><button>'.$category_results['Name'].'</button></a>
            </td>
            <td> <p>'.$category_results['Description'].'</p> //I take values from data base
            </td>
            <td>'.$category_results['Price'].' &euro;</td>
        </tr>';
    }
    while ($category_results=mysqli_fetch_assoc($category_query)) //loop which cycles through all data base items
         ?>


问:
Comparing characters in strings
I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.

For instance,

```<code>a = "HORSE"
b = "TIGER"
</code>```

And it would return 5 (as all characters in the same position are different)

Here's what I've been working on.

```<code>def Differences(one, two):
    difference = []
    for i in list(one):
        if list(one)[i] != list(two)[i]:
            difference = difference+1
    return difference
</code>```

That gives an error "List indices must be integers not strings"

And so I've tried turning it to int by using int(ord(

```<code>def Differences(one, two):
    difference = 0
    for i in list(one):
        if int(ord(list(one)[i])) != int(ord(list(two)[i])):
            difference = difference+1
    return difference
</code>```

Which also returns the same error.

When I print list(one)[1] != list(two)[1] it eithers returns True or False, as the comparison is correctly made.

Can you tell me how to correct my code for this purpose?

答:
a = ['a' , 'b'  , 'c' , 'd' , 'd' , 'c']
b = ['a' , 'b' , 'c' ]
index = []

if len(a) == len(b):
    for i in range(len(a)):
            if a[i]!=b[i]:
                index.append(a[i])
    if len(index) > 0:
        print("The array is not same")

    else:
        print("The array is same")

else:
    print("The array is not same")```

Title: Comparing characters in strings

Body:
I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.

For instance,

a = "HORSE"
b = "TIGER"

And it would return 5 (as all characters in the same position are different)

Here's what I've been working on.

def Differences(one, two):
    difference = []
    for i in list(one):
        if list(one)[i] != list(two)[i]:
            difference = difference+1
    return difference

That gives an error "List indices must be integers not strings"

And so I've tried turning it to int by using int(ord(

def Differences(one, two):
    difference = 0
    for i in list(one):
        if int(ord(list(one)[i])) != int(ord(list(two)[i])):
            difference = difference+1
    return difference

Which also returns the same error.

When I print list(one)[1] != list(two)[1] it eithers returns True or False, as the comparison is correctly made.

Can you tell me how to correct my code for this purpose?


问:
How to do backward pagination in dynamoDB with LastEvaluatedKey?
```<code>  param.FilterExpression = "#black_listed = :black_listed_val";
  param.Limit = 5
  param.ExpressionAttributeValues = {":black_listed_val": body.blacklisted};
  param.ExpressionAttributeNames = {"#black_listed": "black_listed"}
  param.ScanIndexForward = true
  param.ExclusiveStartKey = {"id": "11931258-b582-4d2d-98d9-aa8ae0fe2e43"}
</code>```

I can do forward pagination with this code, but how could I go back?

答:
Change

```<code>param.ScanIndexForward = true
</code>```

to

```<code>param.ScanIndexForward = false
</code>```

Body:
  param.FilterExpression = "#black_listed = :black_listed_val";
  param.Limit = 5
  param.ExpressionAttributeValues = {":black_listed_val": body.blacklisted};
  param.ExpressionAttributeNames = {"#black_listed": "black_listed"}
  param.ScanIndexForward = true
  param.ExclusiveStartKey = {"id": "11931258-b582-4d2d-98d9-aa8ae0fe2e43"}

I can do forward pagination with this code, but how could I go back?

Body:
Change

param.ScanIndexForward = true

to

param.ScanIndexForward = false


问:
How can I load and app onto my device for testing
I just started building and app using Xcode and I wanted to test it on my phone but I get 2 errors on my general tab. I followed the apple tutorial on building my first app but I want to get it on my phone. I am not registered to the apple developer program.

Not tried much as I am new to the iOS programming world

1) Failed to create provisioning profile.
The app ID "com.example.FoodTracker" cannot be registered to your development team. Change your bundle identifier to a unique string to try again.

2)No profiles for 'com.example.FoodTracker' were found
Xcode couldn't find any iOS App Development provisioning profiles matching 'com.example.FoodTracker'.

答: I got it to work by editing the bundle identifier to something unique.</p>


问:
AS3 listen for keypress, but global
When I add a keypress eventlistener to the stage, it does not fire when the focus is on an other object ... How can I listen for any keypress event regardless of the focus?</p>

答: try to hang keyboard event on stage

Title: AS3 listen for keypress, but global

Body: try to hang keyboard event on stage


问:
How to delete duplicates from one table, but keeping only one record?
Hello SQL query experts!
I have one table called 'mytable' which has 2 columns such as id and title .
I tried to remove duplicates except only one record(row) comparing title.
Below was my choice:

```<code>DELETE FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)
</code>```

error : Error in query (1064): Syntax error near '* FROM `myTable` AS `m1` WHERE `m1`.`id` NOT IN (SELECT MIN(`b`.`id`) as `reco' at line 1
but I faced a trouble and tried to resolve this problem more than 2 hours.
It seems like very simple problem.
But I can't figure it out. So I am asking to stackoverflow!

And mainly, I see something strange.
I tried like this but it has no any error.

```<code>SELECT * FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)
</code>```

When I run this query, I can obtain the list of records(rows) I want to delete from 'myTable' table.

Why do I face a deletion problem although I can obtain the list to delete?

I need your help really.
Thanks everyone!

答:
I think Gordon's answer lays the gist. Recently had to do something similar, ended up with this (applied to your situation):

```<code>DELETE FROM mytable WHERE id IN (
    SELECT *
    FROM (
        SELECT m.id
        FROM my_table m
        WHERE m.id NOT IN (
            SELECT MAX(m.id)
            FROM my_table sub
            GROUP BY sub.title
            HAVING COUNT(sub.title) > 1
        )
        AND m.id NOT IN (
            SELECT MAX(sub2.id)
            FROM my_table sub2
            GROUP BY sub2.title
            HAVING COUNT(sub2.title) = 1
        )
  ) AS m
)
</code>```

The extra wrapper was necessary (if I remember correctly) because sub-query was not allowed in a DELETE statement (but could be used like shown).

This will remove all the records, by ID, that have a count (of title) greater than 0, but will not remove the latest (max) record.

NOTE: this is a very intensive query. Indexes on ID & Title are recommended and even then: sloooowwww. Ran this through just 100k records with indexes and still takes about 10 seconds.

Body:
Hello SQL query experts!
I have one table called 'mytable' which has 2 columns such as id and title .
I tried to remove duplicates except only one record(row) comparing title.
Below was my choice:

DELETE FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)

error : Error in query (1064): Syntax error near '* FROM `myTable` AS `m1` WHERE `m1`.`id` NOT IN (SELECT MIN(`b`.`id`) as `reco' at line 1
but I faced a trouble and tried to resolve this problem more than 2 hours.
It seems like very simple problem.
But I can't figure it out. So I am asking to stackoverflow!

And mainly, I see something strange.
I tried like this but it has no any error.

SELECT * FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)

When I run this query, I can obtain the list of records(rows) I want to delete from 'myTable' table.

Why do I face a deletion problem although I can obtain the list to delete?

I need your help really.
Thanks everyone!

Body:
I think Gordon's answer lays the gist. Recently had to do something similar, ended up with this (applied to your situation):

DELETE FROM mytable WHERE id IN (
    SELECT *
    FROM (
        SELECT m.id
        FROM my_table m
        WHERE m.id NOT IN (
            SELECT MAX(m.id)
            FROM my_table sub
            GROUP BY sub.title
            HAVING COUNT(sub.title) > 1
        )
        AND m.id NOT IN (
            SELECT MAX(sub2.id)
            FROM my_table sub2
            GROUP BY sub2.title
            HAVING COUNT(sub2.title) = 1
        )
  ) AS m
)

The extra wrapper was necessary (if I remember correctly) because sub-query was not allowed in a DELETE statement (but could be used like shown).

This will remove all the records, by ID, that have a count (of title) greater than 0, but will not remove the latest (max) record.

NOTE: this is a very intensive query. Indexes on ID & Title are recommended and even then: sloooowwww. Ran this through just 100k records with indexes and still takes about 10 seconds.


问:
Unable to install Microsoft ODBC Driver 17 for alpine based docker
I have been trying to install the Microsoft ODBC Driver 17 for SQL Server for alpine in my dockerfile. I run the following commands in my docker file

Taken from - https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15#alpine-linux

```<code>
RUN wget https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7 8d28ddafb39b/msodbcsql17_17.5.1.1-1_amd64.apk
RUN wget https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql tools_17.5.1.2-1_amd64.apk

RUN wget https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/msodbcsql17_17.5.1.1-1_amd64.sig
RUN wget https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql-tools_17.5.1.2-1_amd64.sig

RUN apk add gnupg
RUN wget https://packages.microsoft.com/keys/microsoft.asc  | gpg --import -
RUN gpg --verify msodbcsql_17.5.1.1-1_amd64.sig msodbcsql_17.5.1.1-1_amd64.apk

RUN apk add --allow-untrusted msodbcsql_17.5.1.1-1_amd64.apk
RUN apk add --allow-untrusted mssql-tools_17.5.1.1-1_amd64.apk

</code>```

However, I get the following message each time. I can see in the run interactive mode that the files are there.

can't open 'msodbcsql_17.5.1.1-1_amd64.sig': No such file or directory

答: You're downloading msodbcsql17_17.5.1.1-1_amd64.sig and trying to verify msodbcsql_17.5.1.1-1_amd64.sig. Double-check the filename as the error message says.

Body:
I have been trying to install the Microsoft ODBC Driver 17 for SQL Server for alpine in my dockerfile. I run the following commands in my docker file

Taken from - https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15#alpine-linux

RUN wget https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7 8d28ddafb39b/msodbcsql17_17.5.1.1-1_amd64.apk
RUN wget https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql tools_17.5.1.2-1_amd64.apk

RUN wget https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/msodbcsql17_17.5.1.1-1_amd64.sig
RUN wget https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql-tools_17.5.1.2-1_amd64.sig

RUN apk add gnupg
RUN wget https://packages.microsoft.com/keys/microsoft.asc  | gpg --import -
RUN gpg --verify msodbcsql_17.5.1.1-1_amd64.sig msodbcsql_17.5.1.1-1_amd64.apk

RUN apk add --allow-untrusted msodbcsql_17.5.1.1-1_amd64.apk
RUN apk add --allow-untrusted mssql-tools_17.5.1.1-1_amd64.apk

However, I get the following message each time. I can see in the run interactive mode that the files are there.

can't open 'msodbcsql_17.5.1.1-1_amd64.sig': No such file or directory


问:
Post Tweet with YouTube Video URL using Tweepy
I notice that if I Tweet normally (from the browser) with a message followed by a YouTube video link, Twitter displays the video's thumbnail, as follows:

However, if I use the following code to send the Tweet instead:

```<code>import tweepy
import json
youtube_url = r'https://www.youtube.com/watch?v=tj-fmOnbBpU&t=0s'
# account tokens
twitter_keys = json.load(open('twitter_keys.json'))
auth = tweepy.OAuthHandler(twitter_keys["consumer_key"], twitter_keys["consumer_secret"]) # authentication of consumer key and secret
auth.set_access_token(twitter_keys["access_token"], twitter_keys["access_token_secret"]) # authentication of access token and secret
api = tweepy.API(auth)
twitter_text = "My message " + youtube_url
api.update_status(status ="{}".format(twitter_text)) # send a tweet
</code>```

I get something like this:

As you can see, Twitter doesn't show the preview for the URL, even after a few days. I don't understand why this is. How can I fix my code so that the Tweet sent through the API shows the preview of the YouTube video link?

答: As pointed out, the issue was that the URL was using two forward slashes for the path, as can be seen in the screenshot.</p>

Body:
I notice that if I Tweet normally (from the browser) with a message followed by a YouTube video link, Twitter displays the video's thumbnail, as follows:

However, if I use the following code to send the Tweet instead:

import tweepy
import json
youtube_url = r'https://www.youtube.com/watch?v=tj-fmOnbBpU&t=0s'
# account tokens
twitter_keys = json.load(open('twitter_keys.json'))
auth = tweepy.OAuthHandler(twitter_keys["consumer_key"], twitter_keys["consumer_secret"]) # authentication of consumer key and secret
auth.set_access_token(twitter_keys["access_token"], twitter_keys["access_token_secret"]) # authentication of access token and secret
api = tweepy.API(auth)
twitter_text = "My message " + youtube_url
api.update_status(status ="{}".format(twitter_text)) # send a tweet

I get something like this:

As you can see, Twitter doesn't show the preview for the URL, even after a few days. I don't understand why this is. How can I fix my code so that the Tweet sent through the API shows the preview of the YouTube video link?


问:
Java Spring Adding or removing @Component at runtime is possible?
I have something like this.

```<code>@Component public class JohnStephen
@Component public class Guadalupe
@Component public class CristianOrtiz
@Component public class CristinaCuellar
/*AND SO ON*/
</code>```

All the profiles are creating all the beans because all the beans can be used on each environment.

I have over 1000 beans created, right? but I did realize that I need just one on each application startup is required I mean I know which of them is required and I can pass that info on the JVM vm_options something like this.

```<code>vm-options beanToCreate=CristianOrtiz
</code>```

On this info I would like that CristianOrtiz only is set as a bean and not the others can this be done in any way in Spring?

答:
You could use spring profiles to switch these on and of at startup but not at runtime.

Annotate each of these Components with @Profile("profileName") and activate them with -Dspring.profiles.active=profileName as a commandline parameter.

Further reading:
- a nice primer on baeldung

Body:
I have something like this.

@Component public class JohnStephen
@Component public class Guadalupe
@Component public class CristianOrtiz
@Component public class CristinaCuellar
/*AND SO ON*/

All the profiles are creating all the beans because all the beans can be used on each environment.

I have over 1000 beans created, right? but I did realize that I need just one on each application startup is required I mean I know which of them is required and I can pass that info on the JVM vm_options something like this.

vm-options beanToCreate=CristianOrtiz

On this info I would like that CristianOrtiz only is set as a bean and not the others can this be done in any way in Spring?


问:
FFmpeg returns negative PTS and DTS for first non key frame
We have some envelope of FFmpeg, that processes the video.
The tree first frames of video are: B -> B -> I as shown below:

PTS and DTS returns negative for first frame:

We have some code, that skips the frames that are below some timepoint (0 for first frame).
Is it possible to ask FFmpeg to start from first frame and not from first I frame?

答: I found that we modified AVContext::strat_time manualy, and set value based on DTS of a first valid video packet. The problem solved, when I set value based on PTS of a first valid packet as a start_time.</p>


问:
How to serve static pages
I need to serve static index.html page from "/" GET request in spring-web.

My module is included into bigger one, packaged as WAR and deployed to tomcat.

I've tried

```<code>@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
        registry.addResourceHandler("/WEB-INF/classes/index.html")
                .addResourceLocations("/WEB-INF/classes/index.html");
    }
}
</code>```

and placed index.html in resources folder. Still 404. Can anybody help me out with understanding what have I done wrong?

答:
The pattern of the ResourceHandler should reflect the query path, in your case /index.html

Resources inside a jar/war /WEB-INF/classes/ can be accessed via classpath:, in your case classpath:/index.html

So your config should have been like this

```<code>@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/index.html")
                .addResourceLocations("classpath:/index.html");
    }
}
</code>```

You can simplify if you have more resources with

```<code>registry.addResourceHandler("/*.html")
        .addResourceLocations("classpath:/");
</code>```

Title: How to serve static pages

Body:
I need to serve static index.html page from "/" GET request in spring-web.

My module is included into bigger one, packaged as WAR and deployed to tomcat.

I've tried

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
        registry.addResourceHandler("/WEB-INF/classes/index.html")
                .addResourceLocations("/WEB-INF/classes/index.html");
    }
}

and placed index.html in resources folder. Still 404. Can anybody help me out with understanding what have I done wrong?

Body:
The pattern of the ResourceHandler should reflect the query path, in your case /index.html

Resources inside a jar/war /WEB-INF/classes/ can be accessed via classpath:, in your case classpath:/index.html

So your config should have been like this

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/index.html")
                .addResourceLocations("classpath:/index.html");
    }
}

You can simplify if you have more resources with

registry.addResourceHandler("/*.html")
        .addResourceLocations("classpath:/");


问:
Why gammu only works with sudo?
I use gammu on a Raspberry PI 3, running Ubuntu 18.04.3 and a Huawei E303C 3G modem (in "/dev/ttyUSB0").

The program seems to work fine, but I always need to invoke "sudo" to complete the commands. Otherwise the following message is displayed: "Error opening device, you do not have the required permission.".

In Google searches and right here in Stackoverflow describri that you need to grant permissions on the device. I tried two different settings but none affected gammu behavior, it still requires sudo in all operations.

First I created the file "/etc/udev/rules.d/69-gammu-acl.rules" with the following content

```<code>ACTION!="add|change", GOTO="gammu_acl_rules_end"

KERNEL!="ttyUSB[0-9]*", GOTO="gammu_acl_rules_end"
SUBSYSTEM!="tty", GOTO="gammu_acl_rules_end"

ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1506", TAG+="uaccess"

LABEL="gammu_acl_rules_end"
</code>```

Then I created the file "/etc/udev/rules.d/99-phone.rules" with the following content:

```<code>KERNEL=="ttyUSB[0-9]*", SUBSYSTEM="tty", ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1506", NAME="phone", MODE="0666", SYMLINK+="phone"
</code>```

The way is this really ?! Is something wrong with my settings ?! Could you help me?!

答:
Please try this:

First of all you should know what users you have, you can know with this command

```<code>  $ whoami
user_name
</code>```

You must enter the name of the user in this command:

```<code>$ sudo usermod -a -G dialout user_name
</code>```

You must restart the computer to be added to the new group.

Then you can use gammu without the sudo command, for example:

```<code>$ gammu sendsms TEXT +589999999999 -text "Halooo .."
</code>```

This work for me.

Title: Why gammu only works with sudo?

Body:
I use gammu on a Raspberry PI 3, running Ubuntu 18.04.3 and a Huawei E303C 3G modem (in "/dev/ttyUSB0").

The program seems to work fine, but I always need to invoke "sudo" to complete the commands. Otherwise the following message is displayed: "Error opening device, you do not have the required permission.".

In Google searches and right here in Stackoverflow describri that you need to grant permissions on the device. I tried two different settings but none affected gammu behavior, it still requires sudo in all operations.

First I created the file "/etc/udev/rules.d/69-gammu-acl.rules" with the following content

ACTION!="add|change", GOTO="gammu_acl_rules_end"

KERNEL!="ttyUSB[0-9]*", GOTO="gammu_acl_rules_end"
SUBSYSTEM!="tty", GOTO="gammu_acl_rules_end"

ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1506", TAG+="uaccess"

LABEL="gammu_acl_rules_end"

Then I created the file "/etc/udev/rules.d/99-phone.rules" with the following content:

KERNEL=="ttyUSB[0-9]*", SUBSYSTEM="tty", ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1506", NAME="phone", MODE="0666", SYMLINK+="phone"

The way is this really ?! Is something wrong with my settings ?! Could you help me?!

Body:
Please try this:

First of all you should know what users you have, you can know with this command

  $ whoami
user_name

You must enter the name of the user in this command:

$ sudo usermod -a -G dialout user_name

You must restart the computer to be added to the new group.

Then you can use gammu without the sudo command, for example:

$ gammu sendsms TEXT +589999999999 -text "Halooo .."

This work for me.


问:
scroll view is not responding when navigated again
i had created a navigation based small application. When I click to the table row, it display controller having UIScrollView and number of TextFields added in it, when i returned back to main controller, then again i navigate to that controller, it do not scroll and still contain previous values in textfield. I am not able to know where is the problem.

Here is my code:

rootcontroller.m

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   switch(indexPath.row)
    {
        case 1:
            if(insertViewController == nil)
        insertViewController = [[insertView alloc] initWithNibName:@"insertView" bundle:[NSBundle mainBundle]];
            [self.navigationController pushViewController:insertViewController animated:YES];
            break;
            //[insertViewController release];
          }
  }
</code>```

insertviewcontoller.m

```<code>#import "insertView.h"
#import "RootViewController.h"
#import "Foundation/Foundation.h"

#define kTabBarHeight 5.0
#define kKeyboardAnimationDuration 1.0

@implementation insertView
@synthesize scroll;
- (void)viewDidLoad {
    [super viewDidLoad];

        //for scrolling

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:self.view.window];
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:self.view.window];
      keyboardIsShown = NO;
    //make contentSize bigger than your scrollSize (you will need to figure out for your own use case)
    CGSize scrollContentSize = CGSizeMake(320, 345);
    self.scroll.contentSize = scrollContentSize;

}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}

- (void)keyboardWillHide:(NSNotification *)n
{
    NSDictionary* userInfo = [n userInfo];

    // get the size of the keyboard
    NSValue* boundsValue = [userInfo objectForKey:UIKeyboardBoundsUserInfoKey];
    CGSize keyboardSize = [boundsValue CGRectValue].size;

    // resize the scrollview
    CGRect viewFrame = self.scroll.frame;
    // I'm also subtracting a constant kTabBarHeight because my UIScrollView was offset by the UITabBar so really only the portion of the keyboard that is leftover pass the UITabBar is obscuring my UIScrollView.
    viewFrame.size.height += (keyboardSize.height - kTabBarHeight);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    // The kKeyboardAnimationDuration I am using is 0.3
    [UIView setAnimationDuration:kKeyboardAnimationDuration];
    [self.scroll setFrame:viewFrame];
    [UIView commitAnimations];

    keyboardIsShown = NO;
}

- (void)keyboardWillShow:(NSNotification *)n
{
    // This is an ivar I'm using to ensure that we do not do the frame size adjustment on the UIScrollView if the keyboard is already shown.  This can happen if the user, after fixing editing a UITextField, scrolls the resized UIScrollView to another UITextField and attempts to edit the next UITextField.  If we were to resize the UIScrollView again, it would be disastrous.  NOTE: The keyboard notification will fire even when the keyboard is already shown.
    if (keyboardIsShown) {
        return;
    }

    NSDictionary* userInfo = [n userInfo];

    // get the size of the keyboard
    NSValue* boundsValue = [userInfo objectForKey:UIKeyboardBoundsUserInfoKey];
    CGSize keyboardSize = [boundsValue CGRectValue].size;

    // resize the noteView
    CGRect viewFrame = self.scroll.frame;
    // I'm also subtracting a constant kTabBarHeight because my UIScrollView was offset by the UITabBar so really only the portion of the keyboard that is leftover pass the UITabBar is obscuring my UIScrollView.
    viewFrame.size.height -= (keyboardSize.height - kTabBarHeight);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    // The kKeyboardAnimationDuration I am using is 0.3
    [UIView setAnimationDuration:kKeyboardAnimationDuration];
    [self.scroll setFrame:viewFrame];
    [UIView commitAnimations];

    keyboardIsShown = YES;
}
- (void)dealloc {
    [super dealloc];
    [scroll release];
    [nmtf release];
    [phtf release];
    [addtf release];
}
</code>```

答: update  viewDidLoad method  into viewWillAppear:(BOOL)animated in your insertviewcontoller.m page

Body:
i had created a navigation based small application. When I click to the table row, it display controller having UIScrollView and number of TextFields added in it, when i returned back to main controller, then again i navigate to that controller, it do not scroll and still contain previous values in textfield. I am not able to know where is the problem.

Here is my code:

rootcontroller.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   switch(indexPath.row)
    {
        case 1:
            if(insertViewController == nil)
        insertViewController = [[insertView alloc] initWithNibName:@"insertView" bundle:[NSBundle mainBundle]];
            [self.navigationController pushViewController:insertViewController animated:YES];
            break;
            //[insertViewController release];
          }
  }

insertviewcontoller.m

#import "insertView.h"
#import "RootViewController.h"
#import "Foundation/Foundation.h"

#define kTabBarHeight 5.0
#define kKeyboardAnimationDuration 1.0

@implementation insertView
@synthesize scroll;
- (void)viewDidLoad {
    [super viewDidLoad];

        //for scrolling

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:self.view.window];
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:self.view.window];
      keyboardIsShown = NO;
    //make contentSize bigger than your scrollSize (you will need to figure out for your own use case)
    CGSize scrollContentSize = CGSizeMake(320, 345);
    self.scroll.contentSize = scrollContentSize;

}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}

- (void)keyboardWillHide:(NSNotification *)n
{
    NSDictionary* userInfo = [n userInfo];

    // get the size of the keyboard
    NSValue* boundsValue = [userInfo objectForKey:UIKeyboardBoundsUserInfoKey];
    CGSize keyboardSize = [boundsValue CGRectValue].size;

    // resize the scrollview
    CGRect viewFrame = self.scroll.frame;
    // I'm also subtracting a constant kTabBarHeight because my UIScrollView was offset by the UITabBar so really only the portion of the keyboard that is leftover pass the UITabBar is obscuring my UIScrollView.
    viewFrame.size.height += (keyboardSize.height - kTabBarHeight);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    // The kKeyboardAnimationDuration I am using is 0.3
    [UIView setAnimationDuration:kKeyboardAnimationDuration];
    [self.scroll setFrame:viewFrame];
    [UIView commitAnimations];

    keyboardIsShown = NO;
}

- (void)keyboardWillShow:(NSNotification *)n
{
    // This is an ivar I'm using to ensure that we do not do the frame size adjustment on the UIScrollView if the keyboard is already shown.  This can happen if the user, after fixing editing a UITextField, scrolls the resized UIScrollView to another UITextField and attempts to edit the next UITextField.  If we were to resize the UIScrollView again, it would be disastrous.  NOTE: The keyboard notification will fire even when the keyboard is already shown.
    if (keyboardIsShown) {
        return;
    }

    NSDictionary* userInfo = [n userInfo];

    // get the size of the keyboard
    NSValue* boundsValue = [userInfo objectForKey:UIKeyboardBoundsUserInfoKey];
    CGSize keyboardSize = [boundsValue CGRectValue].size;

    // resize the noteView
    CGRect viewFrame = self.scroll.frame;
    // I'm also subtracting a constant kTabBarHeight because my UIScrollView was offset by the UITabBar so really only the portion of the keyboard that is leftover pass the UITabBar is obscuring my UIScrollView.
    viewFrame.size.height -= (keyboardSize.height - kTabBarHeight);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    // The kKeyboardAnimationDuration I am using is 0.3
    [UIView setAnimationDuration:kKeyboardAnimationDuration];
    [self.scroll setFrame:viewFrame];
    [UIView commitAnimations];

    keyboardIsShown = YES;
}
- (void)dealloc {
    [super dealloc];
    [scroll release];
    [nmtf release];
    [phtf release];
    [addtf release];
}


问:
AWS: OverflowError when downloading file from s3 to lambda tmp folder
I want to download file from a s3 and save it into the tmp folder of my lambda. But I accountered a stange and unexpected error that makes me crazy: OverflowError: timestamp too large to convert to C _PyTime_t

Here is my code, did I miss something?

```<code>s3 = boto3.resource('s3')
bucket_name = 'my_bucket'
keys = ['private.pkcs8', 'public.pubkey']
for key in keys:
    try:
        local_file_name = 'tmp/' + key
        s3.Bucket(bucket_name).download_file(key, local_file_name)
    except botocore.exceptions.ClientError as e:
      if e.response['Error']['Code'] == "404":
          continue
      else:
          raise
</code>```

I have the same error when retrieving s3 as Client and not Resource.
With different log, I could check the error comes with the "download_file" function.

Please, help me!!!

EDIT: the full stack trace of the error

14:04:36
  [ERROR] 2020-02-18T14:04:36.104Z f8f5aef0-18a3-41d0-951f-4d979fb24aa4 timestamp too large to convert to C _PyTime_t
  14:04:36
  Traceback (most recent call last):
  14:04:36
  File "/opt/python/boto3/s3/inject.py", line 172, in download_file
  14:04:36
  extra_args=ExtraArgs, callback=Callback)
  
  14:04:36
  File "/opt/python/boto3/s3/transfer.py", line 307, in download_file
  14:04:36
  future.result()
  14:04:36
  File "/opt/python/s3transfer/futures.py", line 106, in result
  14:04:36
  return self._coordinator.result()
  14:04:36
  File "/opt/python/s3transfer/futures.py", line 265, in result
  14:04:36
  raise self._exception
  
  14:04:36
  File "/opt/python/s3transfer/tasks.py", line 255, in _main
  14:04:36
  self._submit(transfer_future=transfer_future, **kwargs)
  14:04:36
  File "/opt/python/s3transfer/download.py", line 343, in _submit
  14:04:36
  **transfer_future.meta.call_args.extra_args
  14:04:36
  File "/opt/python/botocore/client.py", line 276, in _api_call
  14:04:36
  return self._make_api_call(operation_name, kwargs)
  14:04:36
  File "/opt/python/botocore/client.py", line 586, in _make_api_call
  14:04:36
  raise error_class(parsed_response, operation_name)
  14:04:36
  botocore.exceptions.ClientError: An error occurred (400) when calling the HeadObject operation: Bad Request
  14:04:36
  During handling of the above exception, another exception occurred:
  14:04:36
  Traceback (most recent call last):
  14:04:36
  File "/var/task/lb_get_tlb_connection_token_rds.py", line 181, in lambda_handler
  14:04:36
  bucket.download_file(key, local_file_name, ExtraArgs={'VersionId': 'foo'})
  14:04:36
  File "/opt/python/boto3/s3/inject.py", line 246, in bucket_download_file
  14:04:36
  ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
  14:04:36
  File "/opt/python/boto3/s3/inject.py", line 172, in download_file
  14:04:36
  extra_args=ExtraArgs, callback=Callback)
  
  14:04:36
  File "/opt/python/boto3/s3/transfer.py", line 325, in exit
  14:04:36
  self._manager.exit(*args)
  14:04:36
  File "/opt/python/s3transfer/manager.py", line 539, in exit
  14:04:36
  self._shutdown(cancel, cancel_msg, cancel_exc_type)
  14:04:36
  File "/opt/python/s3transfer/manager.py", line 578, in _shutdown
  14:04:36
  self._submission_executor.shutdown()
  
  14:04:36
  File "/opt/python/s3transfer/futures.py", line 474, in shutdown
  14:04:36
  self._executor.shutdown(wait)
  14:04:36
  File "/opt/python/concurrent/futures/thread.py", line 169, in shutdown
  14:04:36
  t.join(sys.maxsize)
  14:04:36
  File "/var/lang/lib/python3.7/threading.py", line 1048, in join
  14:04:36
  self._wait_for_tstate_lock(timeout=max(timeout, 0))
  14:04:36
  File "/var/lang/lib/python3.7/threading.py", line 1060, in _wait_for_tstate_lock
  14:04:36
  elif lock.acquire(block, timeout):
  14:04:36
  OverflowError: timestamp too large to convert to C _PyTime_t

答:
This looks like runtime problem, probably related to this bug: https://bugs.python.org/issue25155

Try changing your lambda runtime to the latest supported (Python 3.8 as of time of writing) and see if the problem persists.

Body:
I want to download file from a s3 and save it into the tmp folder of my lambda. But I accountered a stange and unexpected error that makes me crazy: OverflowError: timestamp too large to convert to C _PyTime_t

Here is my code, did I miss something?

s3 = boto3.resource('s3')
bucket_name = 'my_bucket'
keys = ['private.pkcs8', 'public.pubkey']
for key in keys:
    try:
        local_file_name = 'tmp/' + key
        s3.Bucket(bucket_name).download_file(key, local_file_name)
    except botocore.exceptions.ClientError as e:
      if e.response['Error']['Code'] == "404":
          continue
      else:
          raise

I have the same error when retrieving s3 as Client and not Resource.
With different log, I could check the error comes with the "download_file" function.

Please, help me!!!

EDIT: the full stack trace of the error

14:04:36
  [ERROR] 2020-02-18T14:04:36.104Z f8f5aef0-18a3-41d0-951f-4d979fb24aa4 timestamp too large to convert to C _PyTime_t
  14:04:36
  Traceback (most recent call last):
  14:04:36
  File "/opt/python/boto3/s3/inject.py", line 172, in download_file
  14:04:36
  extra_args=ExtraArgs, callback=Callback)
  
  14:04:36
  File "/opt/python/boto3/s3/transfer.py", line 307, in download_file
  14:04:36
  future.result()
  14:04:36
  File "/opt/python/s3transfer/futures.py", line 106, in result
  14:04:36
  return self._coordinator.result()
  14:04:36
  File "/opt/python/s3transfer/futures.py", line 265, in result
  14:04:36
  raise self._exception
  
  14:04:36
  File "/opt/python/s3transfer/tasks.py", line 255, in _main
  14:04:36
  self._submit(transfer_future=transfer_future, **kwargs)
  14:04:36
  File "/opt/python/s3transfer/download.py", line 343, in _submit
  14:04:36
  **transfer_future.meta.call_args.extra_args
  14:04:36
  File "/opt/python/botocore/client.py", line 276, in _api_call
  14:04:36
  return self._make_api_call(operation_name, kwargs)
  14:04:36
  File "/opt/python/botocore/client.py", line 586, in _make_api_call
  14:04:36
  raise error_class(parsed_response, operation_name)
  14:04:36
  botocore.exceptions.ClientError: An error occurred (400) when calling the HeadObject operation: Bad Request
  14:04:36
  During handling of the above exception, another exception occurred:
  14:04:36
  Traceback (most recent call last):
  14:04:36
  File "/var/task/lb_get_tlb_connection_token_rds.py", line 181, in lambda_handler
  14:04:36
  bucket.download_file(key, local_file_name, ExtraArgs={'VersionId': 'foo'})
  14:04:36
  File "/opt/python/boto3/s3/inject.py", line 246, in bucket_download_file
  14:04:36
  ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
  14:04:36
  File "/opt/python/boto3/s3/inject.py", line 172, in download_file
  14:04:36
  extra_args=ExtraArgs, callback=Callback)
  
  14:04:36
  File "/opt/python/boto3/s3/transfer.py", line 325, in exit
  14:04:36
  self._manager.exit(*args)
  14:04:36
  File "/opt/python/s3transfer/manager.py", line 539, in exit
  14:04:36
  self._shutdown(cancel, cancel_msg, cancel_exc_type)
  14:04:36
  File "/opt/python/s3transfer/manager.py", line 578, in _shutdown
  14:04:36
  self._submission_executor.shutdown()
  
  14:04:36
  File "/opt/python/s3transfer/futures.py", line 474, in shutdown
  14:04:36
  self._executor.shutdown(wait)
  14:04:36
  File "/opt/python/concurrent/futures/thread.py", line 169, in shutdown
  14:04:36
  t.join(sys.maxsize)
  14:04:36
  File "/var/lang/lib/python3.7/threading.py", line 1048, in join
  14:04:36
  self._wait_for_tstate_lock(timeout=max(timeout, 0))
  14:04:36
  File "/var/lang/lib/python3.7/threading.py", line 1060, in _wait_for_tstate_lock
  14:04:36
  elif lock.acquire(block, timeout):
  14:04:36
  OverflowError: timestamp too large to convert to C _PyTime_t


问:
How can we setup Cypress for IE and Edge?
I need to use Cypress for testing angular and react application on Internet Explorer and Microsoft edge. I have gone through some links which mentions that Cypress supports only Chrome, Chromium and Electron. Is it true ? if not the how can i use it for testing IE and Edge.?</p>

答:
Cypress released Cross browser support in February 6, 2020 in their 4.0.0 update.

The list of supported browsers is now updated with a few more browsers.


问:
replace value in datafrme if another value is empty
I have a dataframe:

```<code>x = data.frame(group = c(1,1,1,2,2,3,3,3,4,4),
               subgroup = c(1.1, 1.2, 1.3, 2.1, 2.2, 3.1, 3.2, 3.3, 4.1, 4.2),
               type = c("good", 'good', 'bad', 'bad', 'good', 'bad', 'bad', 'good', 'good', '')
)
</code>```

I want to replace subgroup value to "A" if type is empty.so exceted output is:

```<code>x = data.frame(group = c(1,1,1,2,2,3,3,3,4,4),
               subgroup = c(1.1, 1.2, 1.3, 2.1, 2.2, 3.1, 3.2, 3.3, 4.1, "A"),
               type = c("good", 'good', 'bad', 'bad', 'good', 'bad', 'bad', 'good', 'good', '')
)
</code>```

I tried this:

```<code>if (x$type = '') {
  x$subgroup = "A"
}
</code>```

But it didnt work. How could i do it?

答:
Using base R you can simply choose the values that match your condition (subgroup value in row where type is empty) and then replace them:

```<code>x$subgroup[x$type == ""] <- "A"
x
#>    group subgroup type
#> 1      1      1.1 good
#> 2      1      1.2 good
#> 3      1      1.3  bad
#> 4      2      2.1  bad
#> 5      2      2.2 good
#> 6      3      3.1  bad
#> 7      3      3.2  bad
#> 8      3      3.3 good
#> 9      4      4.1 good
#> 10     4        A
</code>```

Alternativly, you can use dplyr/tidyverse and an ifelse statement:

```<code>library(dplyr)
x %>%
  mutate(subgroup = ifelse(test = type == "", yes = "A", no = subgroup))
#>    group subgroup type
#> 1      1      1.1 good
#> 2      1      1.2 good
#> 3      1      1.3  bad
#> 4      2      2.1  bad
#> 5      2      2.2 good
#> 6      3      3.1  bad
#> 7      3      3.2  bad
#> 8      3      3.3 good
#> 9      4      4.1 good
#> 10     4        A
</code>```

Body:
I have a dataframe:

x = data.frame(group = c(1,1,1,2,2,3,3,3,4,4),
               subgroup = c(1.1, 1.2, 1.3, 2.1, 2.2, 3.1, 3.2, 3.3, 4.1, 4.2),
               type = c("good", 'good', 'bad', 'bad', 'good', 'bad', 'bad', 'good', 'good', '')
)

I want to replace subgroup value to "A" if type is empty.so exceted output is:

x = data.frame(group = c(1,1,1,2,2,3,3,3,4,4),
               subgroup = c(1.1, 1.2, 1.3, 2.1, 2.2, 3.1, 3.2, 3.3, 4.1, "A"),
               type = c("good", 'good', 'bad', 'bad', 'good', 'bad', 'bad', 'good', 'good', '')
)

I tried this:

if (x$type = '') {
  x$subgroup = "A"
}

But it didnt work. How could i do it?

Body:
Using base R you can simply choose the values that match your condition (subgroup value in row where type is empty) and then replace them:

x$subgroup[x$type == ""] <- "A"
x
#>    group subgroup type
#> 1      1      1.1 good
#> 2      1      1.2 good
#> 3      1      1.3  bad
#> 4      2      2.1  bad
#> 5      2      2.2 good
#> 6      3      3.1  bad
#> 7      3      3.2  bad
#> 8      3      3.3 good
#> 9      4      4.1 good
#> 10     4        A

Alternativly, you can use dplyr/tidyverse and an ifelse statement:

library(dplyr)
x %>%
  mutate(subgroup = ifelse(test = type == "", yes = "A", no = subgroup))
#>    group subgroup type
#> 1      1      1.1 good
#> 2      1      1.2 good
#> 3      1      1.3  bad
#> 4      2      2.1  bad
#> 5      2      2.2 good
#> 6      3      3.1  bad
#> 7      3      3.2  bad
#> 8      3      3.3 good
#> 9      4      4.1 good
#> 10     4        A


问:
checkbox always bind to false even if it is checked asp.net mvc 5
i have created a list of model binder with checkbox  that is supposed to handle my forms  but when i post to controller it always set checkbox to false even if it is checked on client side, any help?

my model

```<code>   public class RoleCheckbox
{
    public int id { get; set; }
    public bool ischecked { get; set; }
    public string name { get; set; }
}

public class UsersNew
{
    public IList<RoleCheckbox> Roles { get; set; }
    [Required,MaxLength(128)]
    public string username { get; set; }
    [Required,DataType(DataType.Password)]
    public string password { get; set; }
    [Required,MaxLength(256),DataType(DataType.EmailAddress)]
    public string email { get; set; }

}
</code>```

client code

```<code>  <div class="panel panel-default">
    <div class="panel-heading">Roles</div>
    <div class="panel-body">
        <ul class="list-group">
            @for (var i = 0; i < Model.Roles.Count; i++)
            {
                <li class="list-group-item">
                    @Html.Hidden("Roles[" +i +"].id",Model.Roles[i].id)
                    <label for="Roles_@(i)_ischecked">
                        @Html.CheckBox("Roles[" +i+ "].id",Model.Roles[i].ischecked)
                        @Model.Roles[i].name
                    </label>
                </li>

            }
        </ul>
    </div>
</div>
</code>```

my method

```<code>HttpPost,ValidateAntiForgeryToken]
    public ActionResult New(UsersNew form)
    {

        var user = new User();
        syncRole(form.Roles, user.Roles);

        if (Database.Session.Query<User>().Any(u => u.username == form.username))
            ModelState.AddModelError("username", "username must be unique");
        if (!ModelState.IsValid)
            return View(form);

        user.email = form.email;
        user.username = form.username;
        user.SetPassword(form.password);
        Database.Session.Save(user);
        return RedirectToAction("index");
    }
</code>```

答: I had the same problem. What worked for me was taking off the value="xxx" tag.  Then it functioned normally.  (Weird, I know.)</p>

Body:
i have created a list of model binder with checkbox  that is supposed to handle my forms  but when i post to controller it always set checkbox to false even if it is checked on client side, any help?

my model

   public class RoleCheckbox
{
    public int id { get; set; }
    public bool ischecked { get; set; }
    public string name { get; set; }
}

public class UsersNew
{
    public IList<RoleCheckbox> Roles { get; set; }
    [Required,MaxLength(128)]
    public string username { get; set; }
    [Required,DataType(DataType.Password)]
    public string password { get; set; }
    [Required,MaxLength(256),DataType(DataType.EmailAddress)]
    public string email { get; set; }

}

client code

Roles

            @for (var i = 0; i < Model.Roles.Count; i++)
            {

                    @Html.Hidden("Roles[" +i +"].id",Model.Roles[i].id)

                        @Html.CheckBox("Roles[" +i+ "].id",Model.Roles[i].ischecked)
                        @Model.Roles[i].name

            }

my method

HttpPost,ValidateAntiForgeryToken]
    public ActionResult New(UsersNew form)
    {

        var user = new User();
        syncRole(form.Roles, user.Roles);

        if (Database.Session.Query<User>().Any(u => u.username == form.username))
            ModelState.AddModelError("username", "username must be unique");
        if (!ModelState.IsValid)
            return View(form);

        user.email = form.email;
        user.username = form.username;
        user.SetPassword(form.password);
        Database.Session.Save(user);
        return RedirectToAction("index");
    }


问:
How to count the number of rows containing a specific number in it's column
I would like to echo a count how many rows are containing the same specific number.

I have a column called "member_group_id" in my db.

For example, the leader group id is "4" some members have this number assigned in the db, so I would like to do something like:

```<code>$countLeaders = count($row['member_group_id'] == 4);
</code>```

How could I do that?

Here is my db query:

```<code>$result = mysqli_query($con,"SELECT * FROM core_members WHERE member_group_id IN (4, 7, 8, 6, 11) ORDER BY
    CASE member_group_id
        WHEN '4' THEN 1
        WHEN '7' THEN 2
        WHEN '8' THEN 3
        WHEN '6' THEN 4
        WHEN '11' THEN 5
    END ASC, name ASC");
</code>```

Here's my actual loop and desired result:

```<code>while($row = mysqli_fetch_array($result)){
    $group = $row['member_group_id'];
    $countLeaders = count($group == 4);
}

echo "<span>" . $countLeaders . " Leaders</span>";
</code>```

答:
If I understand, you got all the result from your query as an array, with something like pg_fetch_all :

```<code>$result = [
    [
        'id'     => 'whatever',
        'and'    => 'whatever',
        'other'  => 'whatever'
        'fields' => 'whatever'
        'member_group_id' => 1,
    ],
    [
        'id'     => 'whatever',
        'and'    => 'whatever',
        'other'  => 'whatever'
        'fields' => 'whatever'
        'member_group_id' => 3,
    ],
    [
        'id'     => 'whatever',
        'and'    => 'whatever',
        'other'  => 'whatever'
        'fields' => 'whatever'
        'member_group_id' => 1,
    ],
]
</code>```

And  you want to know how many of records have ['member_group_id'] == 1

You can use

```<code>count(
    array_filter(
        function($item) { return ($item['member_group_id'] == 1); },
        $result
    )
)
</code>```

array_filter walks through the array and keeps only items for which the function returns true.

Body:
I would like to echo a count how many rows are containing the same specific number.

I have a column called "member_group_id" in my db.

For example, the leader group id is "4" some members have this number assigned in the db, so I would like to do something like:

$countLeaders = count($row['member_group_id'] == 4);

How could I do that?

Here is my db query:

$result = mysqli_query($con,"SELECT * FROM core_members WHERE member_group_id IN (4, 7, 8, 6, 11) ORDER BY
    CASE member_group_id
        WHEN '4' THEN 1
        WHEN '7' THEN 2
        WHEN '8' THEN 3
        WHEN '6' THEN 4
        WHEN '11' THEN 5
    END ASC, name ASC");

Here's my actual loop and desired result:

while($row = mysqli_fetch_array($result)){
    $group = $row['member_group_id'];
    $countLeaders = count($group == 4);
}

echo "" . $countLeaders . " Leaders";

Body:
If I understand, you got all the result from your query as an array, with something like pg_fetch_all :

$result = [
    [
        'id'     => 'whatever',
        'and'    => 'whatever',
        'other'  => 'whatever'
        'fields' => 'whatever'
        'member_group_id' => 1,
    ],
    [
        'id'     => 'whatever',
        'and'    => 'whatever',
        'other'  => 'whatever'
        'fields' => 'whatever'
        'member_group_id' => 3,
    ],
    [
        'id'     => 'whatever',
        'and'    => 'whatever',
        'other'  => 'whatever'
        'fields' => 'whatever'
        'member_group_id' => 1,
    ],
]

And  you want to know how many of records have ['member_group_id'] == 1

You can use

count(
    array_filter(
        function($item) { return ($item['member_group_id'] == 1); },
        $result
    )
)

array_filter walks through the array and keeps only items for which the function returns true.


问:
rdlc report in C#, ASP.net
In report I have follwing Coloumns

```<code>TIN_Number,Period,Tax_pay,Tax_credited
</code>```

i have period in 4 quater per year. for example If I am giving period between 200704 to 200903 than it is printing 200706,200709,200712,200803,200806,200809,200812,200903 for one TIN number on one row each having same TIN number. I want to seprate this period in quarter wise formate. i want to display sum of total tax_pay and Tax_credited as per quater per year.  please give me solution. thank u

答:
How you want your report is not really clear - why do you need TIN_Number in your data if you don't want to report against it?

Regardless, from whatever you have stated, you need to add group on period field and in group footer, add sum of tax_pay and tax_credited.

Title: rdlc report in C#, ASP.net

Body:
In report I have follwing Coloumns

TIN_Number,Period,Tax_pay,Tax_credited

i have period in 4 quater per year. for example If I am giving period between 200704 to 200903 than it is printing 200706,200709,200712,200803,200806,200809,200812,200903 for one TIN number on one row each having same TIN number. I want to seprate this period in quarter wise formate. i want to display sum of total tax_pay and Tax_credited as per quater per year.  please give me solution. thank u