问:
GridView Paging, unable to get the correct Datakey value
GridView

```<code><asp:GridView ID="GridView1" runat="server" AllowPaging="True"
    AllowSorting="True" PagerSettings-Position="TopAndBottom"
    PagerSettings-Mode="Numeric" PageSize="40" CellPadding="4" DataSourceID="dsEquipmentGridView"
    ForeColor="#333333" GridLines="Horizontal" Style="font-size: x-small" AutoGenerateColumns="False"
    DataKeyNames="IREF" OnRowEditing="GridView1_RowEditing" OnRowUpdated="GridView1_RowUpdated"
    OnSorted="GridView1_Sorted" OnSorting="GridView1_Sorting" OnPageIndexChanged="GridView1_PageIndexChanged1"
    OnPageIndexChanging="GridView1_PageIndexChanging" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
    OnSelectedIndexChanging="GridView1_SelectedIndexChanging" OnRowCommand="GridView1_RowCommand"
    BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
    OnRowCancelingEdit="GridView1_RowCancelingEdit" onload="GridView1_Load"
    ondatabound="GridView1_DataBound">
    <PagerSettings Position="TopAndBottom" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <Columns>
 <asp:CommandField ShowDeleteButton="False" ShowSelectButton="true" EditText="QuickEdit"
     HeaderText="Manage" SelectText="Manage" />
</code>```

For the first page loaded, it shows the correct DataKey value if I click on the command field.

However if I change to the next page of results, upon selecting a record the corresponding value is incorrect. It seems to keep the previous page information. How do I overcome this?

EDIT:

In the GridView1_SelectedIndexChanged method, I used the following:

```<code>    // Determine the index of the selected row.
    int index = GridView1.SelectedIndex;

    // Display the primary key value of the selected row.
    HttpContext.Current.Response.Write("The primary key value of the selected row is " + GridView1.DataKeys[index].Value.ToString() + ".<br>");

    GridViewRow row = GridView1.Rows[index];

    int rowindex = row.RowIndex;
    HttpContext.Current.Response.Write("rowindex-> " + rowindex.ToString() + "<br>");

    int ID = (int)GridView1.DataKeys[row.DataItemIndex - (GridView1.PageIndex * GridView1.PageSize)].Value;

    HttpContext.Current.Response.Write("row.DataItemIndex" + ID.ToString()+"<br>");

    int Userid = Convert.ToInt32(GridView1.DataKeys[index].Value);

    HttpContext.Current.Response.Write("Userid" + Userid.ToString() + "<br>");
</code>```

I am unable to get the correct value after paging.

答:
I may be late.
But for others, i reply this.

"Rebind gridview again before using DataKey array"

it works for me.
Hope it works for others too.

ContentLicense: CC BY-SA 2.5

Body:
GridView

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
    AllowSorting="True" PagerSettings-Position="TopAndBottom"
    PagerSettings-Mode="Numeric" PageSize="40" CellPadding="4" DataSourceID="dsEquipmentGridView"
    ForeColor="#333333" GridLines="Horizontal" Style="font-size: x-small" AutoGenerateColumns="False"
    DataKeyNames="IREF" OnRowEditing="GridView1_RowEditing" OnRowUpdated="GridView1_RowUpdated"
    OnSorted="GridView1_Sorted" OnSorting="GridView1_Sorting" OnPageIndexChanged="GridView1_PageIndexChanged1"
    OnPageIndexChanging="GridView1_PageIndexChanging" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
    OnSelectedIndexChanging="GridView1_SelectedIndexChanging" OnRowCommand="GridView1_RowCommand"
    BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
    OnRowCancelingEdit="GridView1_RowCancelingEdit" onload="GridView1_Load"
    ondatabound="GridView1_DataBound">
    <PagerSettings Position="TopAndBottom" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <Columns>
 <asp:CommandField ShowDeleteButton="False" ShowSelectButton="true" EditText="QuickEdit"
     HeaderText="Manage" SelectText="Manage" />

For the first page loaded, it shows the correct DataKey value if I click on the command field.

However if I change to the next page of results, upon selecting a record the corresponding value is incorrect. It seems to keep the previous page information. How do I overcome this?

EDIT:

In the GridView1_SelectedIndexChanged method, I used the following:

    // Determine the index of the selected row.
    int index = GridView1.SelectedIndex;

    // Display the primary key value of the selected row.
    HttpContext.Current.Response.Write("The primary key value of the selected row is " + GridView1.DataKeys[index].Value.ToString() + ".
");

    GridViewRow row = GridView1.Rows[index];

    int rowindex = row.RowIndex;
    HttpContext.Current.Response.Write("rowindex-> " + rowindex.ToString() + "
");

    int ID = (int)GridView1.DataKeys[row.DataItemIndex - (GridView1.PageIndex * GridView1.PageSize)].Value;

    HttpContext.Current.Response.Write("row.DataItemIndex" + ID.ToString()+"
");

    int Userid = Convert.ToInt32(GridView1.DataKeys[index].Value);

    HttpContext.Current.Response.Write("Userid" + Userid.ToString() + "
");

I am unable to get the correct value after paging.


来源: stackexchange

问:
Can't access post route from API callback
I use a webhook to receive callback post from an API server. I've tested to post data from postman, it's works fine but from API server i can't receive anything.
But when i changed webhook by using webhook.site, it's work, but with my domain webhook its not, didn't even access my post route.
My route:

```<code>Route::group(['namespace' => 'Web'], function () {
//Callback card
Route::post('/callback', 'CustomersController@callbackCard');
</code>```

My Controller:(If accessed post route will store a file)

```<code>public function callbackCard(Request $request){
    Storage::put('Accessed.txt', '1');

}
</code>```

Sorry for my bad English
Can anyboy help me.

答:
the callback API just send Post with application/x-www-form-urlencoded;charset=utf-8
my url: domain/callback
default namespace Web</p>

ContentLicense: CC BY-SA 4.0

Body:
I use a webhook to receive callback post from an API server. I've tested to post data from postman, it's works fine but from API server i can't receive anything.
But when i changed webhook by using webhook.site, it's work, but with my domain webhook its not, didn't even access my post route.
My route:

Route::group(['namespace' => 'Web'], function () {
//Callback card
Route::post('/callback', 'CustomersController@callbackCard');

My Controller:(If accessed post route will store a file)

public function callbackCard(Request $request){
    Storage::put('Accessed.txt', '1');

}

Sorry for my bad English
Can anyboy help me.


问:
Use PhpStorm to automate API testing
I am using PhpStorm to automate my API testing. I have a response data format like:

```<code>{"status":"OK","result":{"data":[{"id":2,"name":"store","slug":"store"},
{"id":51,"name":"store-1","slug":"store-1"},{"id":76,"name":"store-2","slug":"store-2"},
{"id":60,"name":"test-drive","slug":"Test Drive"},
{"id":52,"name":"commencal","slug":"Commencal"}]}}
</code>```

From here, I want to read the name data to compare for testing API as below

```<code> client.test("check_store", function() {
    client.assert(response.body.data.name=== "store", "store not found");
 });
</code>```

I am not sure about the format of response.body.data.name.
Is there anyone help me to do that.

答:
I have solved the problem and want to share it with others. After writing the below statement, the problem has been resolved.
    response.body.result.data[0].name</p>

Title: Use PhpStorm to automate API testing

Body:
I am using PhpStorm to automate my API testing. I have a response data format like:

{"status":"OK","result":{"data":[{"id":2,"name":"store","slug":"store"},
{"id":51,"name":"store-1","slug":"store-1"},{"id":76,"name":"store-2","slug":"store-2"},
{"id":60,"name":"test-drive","slug":"Test Drive"},
{"id":52,"name":"commencal","slug":"Commencal"}]}}

From here, I want to read the name data to compare for testing API as below

 client.test("check_store", function() {
    client.assert(response.body.data.name=== "store", "store not found");
 });

I am not sure about the format of response.body.data.name.
Is there anyone help me to do that.


问:
Count blank cells in a row except the ones on both sides
My data looks like below. I want to count consecutive blank cells in a row except the blank cells at the beginning and at the end. My logic is to return the max. For the case below, the returned value should be 2, not 5.

答:
For row #3:

Say we are interested in consecutive blanks from C3 to J3:

We can mark consecutive blanks with a "helper" row,  In D4 enter:

```<code>=IF(AND(D3="",OR(C3="",E3="")),"X","")
</code>```

and copy this over to cell I4.

Then in another cell enter:

```<code>=COUNTIF(C4:J4,"=X")
</code>```

We can avoid the "helper" row if you use a VBA user defined function:

```<code>Option Explicit
Public Function consecb(rng As Range) As Long
    Dim nFirst As Long, nLast As Long, i As Long
    Dim roww As Long

    nFirst = rng.Find(what:="*", after:=rng(1)).Column
    nLast = rng.Find(what:="*", after:=rng(1), searchdirection:=xlPrevious).Column
    roww = rng.Row

    For i = nFirst + 1 To nLast - 1
        If Cells(roww, i) = "" And (Cells(roww, i - 1) = "" Or Cells(roww, i + 1) = "") Then
            consecb = consecb + 1
        End If
    Next i

End Function
</code>```

In the worksheet you would use it like:

```<code>=consecb(3:3)
</code>```

Body:
For row #3:

Say we are interested in consecutive blanks from C3 to J3:

We can mark consecutive blanks with a "helper" row,  In D4 enter:

=IF(AND(D3="",OR(C3="",E3="")),"X","")

and copy this over to cell I4.

Then in another cell enter:

=COUNTIF(C4:J4,"=X")

We can avoid the "helper" row if you use a VBA user defined function:

Option Explicit
Public Function consecb(rng As Range) As Long
    Dim nFirst As Long, nLast As Long, i As Long
    Dim roww As Long

    nFirst = rng.Find(what:="*", after:=rng(1)).Column
    nLast = rng.Find(what:="*", after:=rng(1), searchdirection:=xlPrevious).Column
    roww = rng.Row

    For i = nFirst + 1 To nLast - 1
        If Cells(roww, i) = "" And (Cells(roww, i - 1) = "" Or Cells(roww, i + 1) = "") Then
            consecb = consecb + 1
        End If
    Next i

End Function

In the worksheet you would use it like:

=consecb(3:3)


问:
Windows - Find all images on an external hard drive
I have an old hard drive containing multiple hard drive backups, so there are hundreds of thousands of unsorted files and folders.

So I have to sort it out and delete everything I don't need, the problem is that there are family photos, class photos, etc. (pretty much everywhere)

How to locate (and even be able to view) all the photos in a folder or even on the entire hard drive ?

With the windows file explorer, I tried this:

But it doesn't give me any results even on folders full of photos

Is it possible to do this with windows explorer on an external hard drive? Do you know simple software is quick to do this?

答: If it has hundreds of thousands of unsorted files and folders then wait after sorting by pictures. The many files will slow the computer so it might take about an hour to load the pictures.</p>


问:
Axios HTTP DELETE request returns 415 error
I'm building a React.js app with ASP.NET Core as backend following a tutorial course. I'm using Axios to handle HTTP requests, I tested the get, post, put requests working fine, but keep getting error during a del request. Here is the simplified function that produces the same error:

```<code>  const handleDeleteActivityTest = () => {
    Axios.delete('https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456');
  }
</code>```

And the request prints the following error messages in the console:

DELETE https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456 415
  (Unsupported Media Type)

createError.js:16 Uncaught (in promise) Error: Request failed with status code 415
      at createError (createError.js:16)
      at settle (settle.js:17)
      at XMLHttpRequest.handleLoad (xhr.js:61)

But I tested in Postman, and the delete request works just fine and returns a 200 OK response, and I can see in the database that the entry is deleted:

Postman DELETE response

I would really appreciate if someone can educate me what's going on here. Thank you and stay safe & happy.

EDIT ----------------------------------

Here is the backend code that handles the HTTP request. It is divided into two parts-- 1.) controller that receives the HTTP request and 2.) MediatR class that handles it:

1.)

```<code>namespace API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ActivitiesController : ControllerBase
    {
        private readonly IMediator _mediator;

        public ActivitiesController(IMediator mediator)
        {
            _mediator = mediator;
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult<Unit>> Delete(Guid id, Delete.Command command)
        {
            command.Id = id;
            return await _mediator.Send(command);
        }
    }
}
</code>```

2.)

```<code>namespace Application.Activities
{
    public class Delete
    {
        public class Command : IRequest
        {
            public Guid Id { get; set; }
        }

        public class Handler : IRequestHandler<Command>
        {
            private readonly DataContext _context;

            public Handler(DataContext context)
            {
                _context = context;
            }

            public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var activity = await _context.Activities.FindAsync(request.Id);

                if (activity == null)
                    throw new Exception("Could not find activity");

                _context.Remove(activity);

                var success = await _context.SaveChangesAsync() > 0;

                if (success) return Unit.Value;

                throw new Exception("Problem saving changes");
            }
        }
    }
}
</code>```

I found that the HttpDelete method in the controller receives id as a Guid, but in the React app id is typed as string, so I changed the type to string in the controller and MediatR class, but same http error 415.

答:
Axios doesn't send a content-type on a delete call. It looks like ASP.net core wants a content-type.

As a workaround you could just add a body to the delete call then Axios will add a content-type and that should do the trick.

```<code>const handleDeleteActivityTest = () => {
    Axios.delete('https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456', {
      data: {foo: 'bar'}
    });
  }
</code>```

Body:
I'm building a React.js app with ASP.NET Core as backend following a tutorial course. I'm using Axios to handle HTTP requests, I tested the get, post, put requests working fine, but keep getting error during a del request. Here is the simplified function that produces the same error:

  const handleDeleteActivityTest = () => {
    Axios.delete('https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456');
  }

And the request prints the following error messages in the console:

DELETE https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456 415
  (Unsupported Media Type)

createError.js:16 Uncaught (in promise) Error: Request failed with status code 415
      at createError (createError.js:16)
      at settle (settle.js:17)
      at XMLHttpRequest.handleLoad (xhr.js:61)

But I tested in Postman, and the delete request works just fine and returns a 200 OK response, and I can see in the database that the entry is deleted:

Postman DELETE response

I would really appreciate if someone can educate me what's going on here. Thank you and stay safe & happy.

EDIT ----------------------------------

Here is the backend code that handles the HTTP request. It is divided into two parts-- 1.) controller that receives the HTTP request and 2.) MediatR class that handles it:

1.)

namespace API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ActivitiesController : ControllerBase
    {
        private readonly IMediator _mediator;

        public ActivitiesController(IMediator mediator)
        {
            _mediator = mediator;
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult<Unit>> Delete(Guid id, Delete.Command command)
        {
            command.Id = id;
            return await _mediator.Send(command);
        }
    }
}

2.)

namespace Application.Activities
{
    public class Delete
    {
        public class Command : IRequest
        {
            public Guid Id { get; set; }
        }

        public class Handler : IRequestHandler<Command>
        {
            private readonly DataContext _context;

            public Handler(DataContext context)
            {
                _context = context;
            }

            public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var activity = await _context.Activities.FindAsync(request.Id);

                if (activity == null)
                    throw new Exception("Could not find activity");

                _context.Remove(activity);

                var success = await _context.SaveChangesAsync() > 0;

                if (success) return Unit.Value;

                throw new Exception("Problem saving changes");
            }
        }
    }
}

I found that the HttpDelete method in the controller receives id as a Guid, but in the React app id is typed as string, so I changed the type to string in the controller and MediatR class, but same http error 415.

Body:
Axios doesn't send a content-type on a delete call. It looks like ASP.net core wants a content-type.

As a workaround you could just add a body to the delete call then Axios will add a content-type and that should do the trick.

const handleDeleteActivityTest = () => {
    Axios.delete('https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456', {
      data: {foo: 'bar'}
    });
  }


问:
Can a volume be mounted to a running container in Kubernetes?
If I have a running Kubernetes deployment with a container, without any mounted storage, running in one of the pods, is it possible to mount a volume to this container without redepoyling?</p>

答:
Based on Updating a Deployment- Kuberentes

A Deployment’s rollout is triggered if and only if the Deployment’s Pod template (that is, .spec.template) is changed, for example, if the labels or container images of the template are updated. Other updates, such as scaling the Deployment, do not trigger a rollout.

Add a volume to a deployment involves add .spec.template.spec.volumes to deployment's pod template, will indeed trigger a redeployment of the pod.

Can you elaborate further on what you are trying to do? This might be another way to achieve what you are trying to do.


问:
How can I fix the error: can't mix packed and unpacked types?
I am trying to build a 4:1 multiplexer using 2:1 multiplexers that I've built. I am getting a few errors whenever I try typing the command vsim mux4_test.

Array connection type 'reg$[1:0]' is incompatible with 'wire[1:0]' for
  port (sel): can't mix packed and unpacked types.

Port size (1) does not match connection size (32) for port 'Z'. The
  port definition is at: NOT.sv(3).

Illegal output or inout port connection for port 'Z'.

And here's my attempt in doing it:

For 2:1 mux:

```<code>module mux2 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic sel,         // Select input
    output logic z           // Output
);

logic w1,w2,w3,w4,w5,w6,w7,w8;
NOT # (.Tpdlh(10), .Tpdhl(8)) g1(.Z(w1) , .A(d0));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g4(.Z(w5), .A(w1), .B(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g2(.Z(w2) , .A(d1));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g5(.Z(w6), .A(w2), .B(w3));
NOT # (.Tpdlh(10), .Tpdhl(8)) g3(.Z(w3) , .A(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g6(.Z(w7) , .A(w5));
NOT # (.Tpdlh(10), .Tpdhl(8)) g7(.Z(w8) , .A(w6));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g8(.Z(z) , .A(w7), .B(w8));

endmodule
</code>```

for 4:1 mux:

```<code>module mux4 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic d2,          // Data input 2
    input logic d3,          // Data input 3
    input logic [1:0] sel,   // Select input
    output logic z           // Output
);

logic w1,w2;

mux2 mux2a(
.d0(d0),
.d1(d1),
.sel(sel[0]),
.z(w1)
);

mux2 mux2b(
.d2(d0),
.d3(d1),
.sel(sel[0]),
.z(w2)
);

mux2 mux2c(
.d0(w1),
.d1(w2),
.sel(sel[1]),
.z(z)
);

endmodule
</code>```

and finally my testbench

```<code>module mux4_test;
logic d0,d1,d2,d3,sel[1:0], z;

mux4 m4a(
.d0(d0),
.d1(d1),
.d2(d2),
.d3(d3),
.sel(sel),
.z(z)
);

initial begin
d0=1'b0;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

#20
d0=1'b1;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

end

endmodule
</code>```

答:
Array connection type 'reg$[1:0]' is incompatible with 'wire[1:0]' for port (sel): can't mix packed and unpacked types.

Here sel is defined as an unpacked array of 2 single bits:

```<code>logic d0,d1,d2,d3,sel[1:0], z;
</code>```

Here is the definition of the port where sel is defined as packed array (vector) of 2 bits.

```<code>input logic [1:0] sel
</code>```

System verilog does not allow assignments between them. so, the port .sel(sel), causes the issue. To fix, you need to declare both the same way. I suggest to change declaration of the variable to

```<code>logic [1:0] sel;
</code>```

Port size (1) does not match connection size (32) for port 'Z'. The port definition is at: NOT.sv(3).

This points to the file NOT.sv, which seems to be a definition of the module NOT. you need to provide this module in your example.

Body:
I am trying to build a 4:1 multiplexer using 2:1 multiplexers that I've built. I am getting a few errors whenever I try typing the command vsim mux4_test.

Array connection type 'reg$[1:0]' is incompatible with 'wire[1:0]' for
  port (sel): can't mix packed and unpacked types.

Port size (1) does not match connection size (32) for port 'Z'. The
  port definition is at: NOT.sv(3).

Illegal output or inout port connection for port 'Z'.

And here's my attempt in doing it:

For 2:1 mux:

module mux2 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic sel,         // Select input
    output logic z           // Output
);

logic w1,w2,w3,w4,w5,w6,w7,w8;
NOT # (.Tpdlh(10), .Tpdhl(8)) g1(.Z(w1) , .A(d0));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g4(.Z(w5), .A(w1), .B(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g2(.Z(w2) , .A(d1));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g5(.Z(w6), .A(w2), .B(w3));
NOT # (.Tpdlh(10), .Tpdhl(8)) g3(.Z(w3) , .A(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g6(.Z(w7) , .A(w5));
NOT # (.Tpdlh(10), .Tpdhl(8)) g7(.Z(w8) , .A(w6));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g8(.Z(z) , .A(w7), .B(w8));

endmodule

for 4:1 mux:

module mux4 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic d2,          // Data input 2
    input logic d3,          // Data input 3
    input logic [1:0] sel,   // Select input
    output logic z           // Output
);

logic w1,w2;

mux2 mux2a(
.d0(d0),
.d1(d1),
.sel(sel[0]),
.z(w1)
);

mux2 mux2b(
.d2(d0),
.d3(d1),
.sel(sel[0]),
.z(w2)
);

mux2 mux2c(
.d0(w1),
.d1(w2),
.sel(sel[1]),
.z(z)
);

endmodule

and finally my testbench

module mux4_test;
logic d0,d1,d2,d3,sel[1:0], z;

mux4 m4a(
.d0(d0),
.d1(d1),
.d2(d2),
.d3(d3),
.sel(sel),
.z(z)
);

initial begin
d0=1'b0;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

#20
d0=1'b1;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

end

endmodule

Body:
Array connection type 'reg$[1:0]' is incompatible with 'wire[1:0]' for port (sel): can't mix packed and unpacked types.

Here sel is defined as an unpacked array of 2 single bits:

logic d0,d1,d2,d3,sel[1:0], z;

Here is the definition of the port where sel is defined as packed array (vector) of 2 bits.

input logic [1:0] sel

System verilog does not allow assignments between them. so, the port .sel(sel), causes the issue. To fix, you need to declare both the same way. I suggest to change declaration of the variable to

logic [1:0] sel;

Port size (1) does not match connection size (32) for port 'Z'. The port definition is at: NOT.sv(3).

This points to the file NOT.sv, which seems to be a definition of the module NOT. you need to provide this module in your example.


问:
Insert a booking only if not already taken in a SQLite Database
Lets consider the following database

CREATE TABLE IF NOT EXISTS resources (id INTEGER PRIMARY KEY AUTOINCREMENT, , name TEXT);
CREATE TABLE IF NOT EXISTS bookings (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  resource_id INT,
  start_date DATETIME,
  end_date DATETIME,
  FOREIGN KEY(resource_id) REFERENCES resources(id)
);

INSERT INTO resources (name) VALUES ("Meeting Room Marie Curie")
```

<p>I would like to create a new 'booking' for a specified 'resource', only if there is not a booking already created for that resource. </p>

<p>I have tried the following request but it keeps create a booking anyway. I think there is something wrong with the condition in the second SELECT statement.</p>

<pre class="lang-sql prettyprint-override"><code>
INSERT INTO bookings(resource_id, start_date, end_date)
    SELECT 1, "2020-06-02T19:00:00", "2020-06-02T20:00:00"
EXCEPT
    SELECT id, start_date, end_date FROM bookings
        WHERE
          resource_id = 1
          AND ( "2020-06-02T19:00:00" >= end_date OR "2020-06-02T20:00:00" <= start_date ) = 1
</code>```

thanks in advance for your help

答:
The best that you could do is define the column resource_id to be unique:

```<code>resource_id INT UNIQUE
</code>```

so there is no case of duplicates.

Then use INSERT OR IGNORE:

```<code>INSERT OR IGNORE INTO bookings(resource_id, start_date, end_date)
SELECT 1, "2020-06-02T19:00:00", "2020-06-02T20:00:00"
</code>```

If there is already a row in bookings with resource_id = 1 then nothing will be inserted because of the unique constraint.

If you can't change the table then use NOT EXISTS:

```<code>INSERT INTO bookings(resource_id, start_date, end_date)
SELECT 1, "2020-06-02T19:00:00", "2020-06-02T20:00:00"
WHERE NOT EXISTS (SELECT * FROM bookings WHERE resource_id = 1)
</code>```

In your code there is also this condition:

```<code>AND ("2020-06-02T19:00:00" >= end_date OR "2020-06-02T20:00:00" <= start_date) = 1
</code>```

You can include it in the last query:

```<code>INSERT INTO bookings(resource_id, start_date, end_date)
SELECT 1, "2020-06-02T19:00:00", "2020-06-02T20:00:00"
WHERE NOT EXISTS (
  SELECT * FROM bookings
  WHERE resource_id = 1
  AND ("2020-06-02T19:00:00" >= end_date OR "2020-06-02T20:00:00" <= start_date)
)
</code>```

No need for ...= 1

Body:
Lets consider the following database

CREATE TABLE IF NOT EXISTS resources (id INTEGER PRIMARY KEY AUTOINCREMENT, , name TEXT);
CREATE TABLE IF NOT EXISTS bookings (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  resource_id INT,
  start_date DATETIME,
  end_date DATETIME,
  FOREIGN KEY(resource_id) REFERENCES resources(id)
);

INSERT INTO resources (name) VALUES ("Meeting Room Marie Curie")

I would like to create a new 'booking' for a specified 'resource', only if there is not a booking already created for that resource.

I have tried the following request but it keeps create a booking anyway. I think there is something wrong with the condition in the second SELECT statement.

INSERT INTO bookings(resource_id, start_date, end_date)
    SELECT 1, "2020-06-02T19:00:00", "2020-06-02T20:00:00"
EXCEPT
    SELECT id, start_date, end_date FROM bookings
        WHERE
          resource_id = 1
          AND ( "2020-06-02T19:00:00" >= end_date OR "2020-06-02T20:00:00" <= start_date ) = 1

thanks in advance for your help

Body:
The best that you could do is define the column resource_id to be unique:

resource_id INT UNIQUE

so there is no case of duplicates.

Then use INSERT OR IGNORE:

INSERT OR IGNORE INTO bookings(resource_id, start_date, end_date)
SELECT 1, "2020-06-02T19:00:00", "2020-06-02T20:00:00"

If there is already a row in bookings with resource_id = 1 then nothing will be inserted because of the unique constraint.

If you can't change the table then use NOT EXISTS:

INSERT INTO bookings(resource_id, start_date, end_date)
SELECT 1, "2020-06-02T19:00:00", "2020-06-02T20:00:00"
WHERE NOT EXISTS (SELECT * FROM bookings WHERE resource_id = 1)

In your code there is also this condition:

AND ("2020-06-02T19:00:00" >= end_date OR "2020-06-02T20:00:00" <= start_date) = 1

You can include it in the last query:

INSERT INTO bookings(resource_id, start_date, end_date)
SELECT 1, "2020-06-02T19:00:00", "2020-06-02T20:00:00"
WHERE NOT EXISTS (
  SELECT * FROM bookings
  WHERE resource_id = 1
  AND ("2020-06-02T19:00:00" >= end_date OR "2020-06-02T20:00:00" <= start_date)
)

No need for ...= 1


问:
Generating synthetic data out of real data (For Regression Problem)

My dataset looks like the info provided in the picture. This is a regression problem where I have to predict 'LOS' (last column). My dataset consists of around 2000 samples or rows. I would love to create more rows(synthetic-data) out of real data to improve my model result.

I found its quite easy for classification task but having difficulties for regression cases.

Any help in python environment would be really helpful.

Thanks in advance

答:
You could use SMOGN

From Documentation:

A Python implementation of Synthetic Minority Over-Sampling Technique for Regression with Gaussian Noise (SMOGN). Conducts the Synthetic Minority Over-Sampling Technique for Regression (SMOTER) with traditional interpolation, as well as with the introduction of Gaussian Noise (SMOTER-GN).

But take it look here before implementing the same.


问:
Removing key/value pairs in list of dictionary having None Values
inputs : [{'test1': 'test', 'test2': None}]

Exected output : [{'test1': 'test'}]

答:
You can get the desired output using the list comprehension - list comprehension

```<code>inputs = [{'test1': 'test', 'test2': None}]

output = [{k: v for k, v in var.items() if v is not None} for var in inputs]
print(output)
</code>```

Result:

```<code>[{'test1': 'test'}]
</code>```

Body:
You can get the desired output using the list comprehension - list comprehension

inputs = [{'test1': 'test', 'test2': None}]

output = [{k: v for k, v in var.items() if v is not None} for var in inputs]
print(output)

Result:

[{'test1': 'test'}]


问:
Why .click event handler is not updated here?
I am passing a table row to a function which is supposed to update the onclick attribute on an anchor.

Whatever I have tried I am not able to set it to a new value. I can see that it is jQuery selects the anchor. But when I alert before an after, onclick attribute still points to the same value not the 'url' parameter that is provided to the function:

```<code>function modifyTrEditUrl(tr, url) {

           console.log(tr.find('td:eq(6) a')[0]);

           tr.find('td:eq(6) a')
                .attr('onclick', url); // I have tried
                                       //.click(function(e){..}) way too!

           console.log(tr.find('td:eq(6) a')[0]); //still the same value! :(
        }
</code>```

Any advices?

答: use .bind or .live , .live to late bind</p>

ContentLicense: CC BY-SA 3.0

Body:
I am passing a table row to a function which is supposed to update the onclick attribute on an anchor.

Whatever I have tried I am not able to set it to a new value. I can see that it is jQuery selects the anchor. But when I alert before an after, onclick attribute still points to the same value not the 'url' parameter that is provided to the function:

function modifyTrEditUrl(tr, url) {

           console.log(tr.find('td:eq(6) a')[0]);

           tr.find('td:eq(6) a')
                .attr('onclick', url); // I have tried
                                       //.click(function(e){..}) way too!

           console.log(tr.find('td:eq(6) a')[0]); //still the same value! :(
        }

Any advices?

Body: use .bind or .live , .live to late bind


问:
Typescript generic function doesn't complain about callback return type
Typescript generic function doesn't complain about callback return type. Shouldn't it complain that types do not match like it does with the object? Why this is a valid typescript?

```<code>const a = <T>(shape: T | (() => T)): T => {
    return shape instanceof Function ? shape() : shape;
}

const func = () => ({ x: '', o: '' });
a<{ x: string }>(func); // this should fail to compile

a<{ x: string }>({ x: '', o: '' }); // fails to compile
</code>```

Playground Link

答: contextual type (in your case a<{ x: string }>(func); ) do not perform excess property check, there's no spec about this, so maybe that's by design

Body:
Typescript generic function doesn't complain about callback return type. Shouldn't it complain that types do not match like it does with the object? Why this is a valid typescript?

const a = <T>(shape: T | (() => T)): T => {
    return shape instanceof Function ? shape() : shape;
}

const func = () => ({ x: '', o: '' });
a<{ x: string }>(func); // this should fail to compile

a<{ x: string }>({ x: '', o: '' }); // fails to compile

Playground Link


问:
Finding transpose of each element of list separately in python
I have a List of N items, each of d dimensions (so essentially a N x d list). For each of the items, I want to find the product of item transposed with itself, So, x.xT for each of the N items. This will give me a N x d x d array. How can I do it efficiently in numpy. At this moment, I am looping through each of the items and finding the transpose separately.

```<code>for i in range(len(mu[0])):
    current_mu = mu[i] # list of d elements
    distances = []
    for index in range(len(samples)):
        distance = np.asarray(current_mu - samples[index])[:, None] # list of d elements
        distances.append(distance * distance.T) # each becomes d x d
</code>```

Can I remove the second nested loop or is it required?

答:
You can use numpy.einsum as follows:

import numpy as np

N,d = 10,5

mu = np.random.rand(N,d)
r = np.einsum('ni,nj->nij', mu, mu)

r.shape
(10,5,5)
```

<p>Comparing to a for-loop implementation:</p>

<pre class="lang-py prettyprint-override"><code>def for_loop(a):
    N,d = a.shape
    r = np.zeros((N,d,d))
    for i in range(N):
        r[i] = a[i][:,None] @ a[i][None,:]

# N>d case
N,d = 1000,500
mu = np.random.rand(N,d)

%timeit np.einsum('ni,nj->nij', mu, mu)
1.29 s ± 11.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit for_loop(mu)
2.36 s ± 45.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# N<d case
N,d = 100,1000
mu = np.random.rand(N,d)

%timeit np.einsum('ni,nj->nij', mu, mu)
521 ms ± 9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit for_loop(mu)
976 ms ± 18.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

</code>```

In both cases resulting in almost 2x performances.

Body:
I have a List of N items, each of d dimensions (so essentially a N x d list). For each of the items, I want to find the product of item transposed with itself, So, x.xT for each of the N items. This will give me a N x d x d array. How can I do it efficiently in numpy. At this moment, I am looping through each of the items and finding the transpose separately.

for i in range(len(mu[0])):
    current_mu = mu[i] # list of d elements
    distances = []
    for index in range(len(samples)):
        distance = np.asarray(current_mu - samples[index])[:, None] # list of d elements
        distances.append(distance * distance.T) # each becomes d x d

Can I remove the second nested loop or is it required?

Body:
You can use numpy.einsum as follows:

import numpy as np

N,d = 10,5

mu = np.random.rand(N,d)
r = np.einsum('ni,nj->nij', mu, mu)

r.shape
(10,5,5)

Comparing to a for-loop implementation:

def for_loop(a):
    N,d = a.shape
    r = np.zeros((N,d,d))
    for i in range(N):
        r[i] = a[i][:,None] @ a[i][None,:]

# N>d case
N,d = 1000,500
mu = np.random.rand(N,d)

%timeit np.einsum('ni,nj->nij', mu, mu)
1.29 s ± 11.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit for_loop(mu)
2.36 s ± 45.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# N<d case
N,d = 100,1000
mu = np.random.rand(N,d)

%timeit np.einsum('ni,nj->nij', mu, mu)
521 ms ± 9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit for_loop(mu)
976 ms ± 18.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In both cases resulting in almost 2x performances.


问:
How to get a font name from a font file?

Possible Duplicate:

  Fonts problem, typeface,windows name…

First I am looking to get the typeface name of a font that isn't installed, it is just in a folder.

And second question is how to get the Windows name font like "arialblackno1.ttf" that have typeface "arialblack".

答: For the second question, you can try to look into the registry, key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts.</p>


问:
Generate unique random numbers in Dart
How can I generate two different random numbers in dart?

I have generated two random numbers using code below.

```<code>int rand1 = Random().nextInt(16);
int rand2 = Random().nextInt(16);
</code>```

```<code>if(rand1 == rand2)
  // generate new random
</code>```

How do I generate new random numbers until rand1 != rand2?

答:
maybe useful for you.

'max' is exclusive. the unique result number is in the return List.

```<code>List<int> getRandomNums(int countOfNum, int max) {
    int num = 0;
    List<int> numList = [];
    var random = Random();
    int i = 0;
    while ( i < countOfNum) {
      int oldNum = num;
      num = random.nextInt(max);
      if (numList.contains(num)) continue;
      numList.add(num);
      i++;
    }
    return numList;
  }
</code>```

Title: Generate unique random numbers in Dart

Body:
How can I generate two different random numbers in dart?

I have generated two random numbers using code below.

int rand1 = Random().nextInt(16);
int rand2 = Random().nextInt(16);

if(rand1 == rand2)
  // generate new random

How do I generate new random numbers until rand1 != rand2?

Body:
maybe useful for you.

'max' is exclusive. the unique result number is in the return List.

List<int> getRandomNums(int countOfNum, int max) {
    int num = 0;
    List<int> numList = [];
    var random = Random();
    int i = 0;
    while ( i < countOfNum) {
      int oldNum = num;
      num = random.nextInt(max);
      if (numList.contains(num)) continue;
      numList.add(num);
      i++;
    }
    return numList;
  }


问:
Detect if UITableView section header is floating
is there a way to detect if a header of a section in an UITableView is currently floating? I want to scroll the table view to the header position only if it is floating.

Thanks in advance!

答:
iOS 11.0+ solution for UITableViews as well as UICollectionViews

In both cases, use the scrollViewDidScroll method. You can use the currentHeader property to store current header displayed at the top. HEIGHT_OF_HEADER_VIEW is a value you should specify yourself.

For UITableView

```<code>private var currentHeader: UITableViewHeaderFooterView? {
    willSet {
        // Handle `old` header
    } didSet {
        // Hanlde `new` header
    }
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let point = CGPoint(x: 0, y: HEIGHT_OF_HEADER_VIEW + tableView.contentOffset.y + tableView.adjustedContentInset.top)
    guard let path = tableView.indexPathForRow(at: point) else {
        return
    }

    let section = path.section
    let rect = tableView.rectForHeader(inSection: section)
    let converted = tableView.convert(rect, to: tableView.superview)
    let safeAreaInset = tableView.safeAreaInsets.top

    // Adding 1 offset because of large titles that sometimes cause slighly wrong converted values
    guard converted.origin.y <= safeAreaInset,
        let header = tableView.headerView(forSection: section) else {
        return
    }
    currentHeader = header
}
</code>```

For UICollectionView

```<code>private var currentHeader: UICollectionReusableView? {
    willSet {
        // Handle `old` header
    } didSet {
        // Handle `new` header
    }
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let x = (collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.sectionInset.left ?? 0
    let point = CGPoint(x: x, y: HEIGHT_OF_HEADER_VIEW + collectionView.contentOffset.y + collectionView.adjustedContentInset.top)

    guard let path = collectionView.indexPathForItem(at: point),
        let rect = collectionView.layoutAttributesForSupplementaryElement(ofKind: UICollectionView.elementKindSectionHeader, at: IndexPath(row: 0, section: path.section))?.frame else {
        return
    }

    let converted = collectionView.convert(rect, to: collectionView.superview)
    let safeAreaInset = collectionView.safeAreaInsets.top

    guard converted.origin.y <= safeAreaInset,
        let header = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(row: 0, section: path.section)) else {
        return
    }
    currentHeader = header
}
</code>```

Body:
iOS 11.0+ solution for UITableViews as well as UICollectionViews

In both cases, use the scrollViewDidScroll method. You can use the currentHeader property to store current header displayed at the top. HEIGHT_OF_HEADER_VIEW is a value you should specify yourself.

For UITableView

private var currentHeader: UITableViewHeaderFooterView? {
    willSet {
        // Handle `old` header
    } didSet {
        // Hanlde `new` header
    }
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let point = CGPoint(x: 0, y: HEIGHT_OF_HEADER_VIEW + tableView.contentOffset.y + tableView.adjustedContentInset.top)
    guard let path = tableView.indexPathForRow(at: point) else {
        return
    }

    let section = path.section
    let rect = tableView.rectForHeader(inSection: section)
    let converted = tableView.convert(rect, to: tableView.superview)
    let safeAreaInset = tableView.safeAreaInsets.top

    // Adding 1 offset because of large titles that sometimes cause slighly wrong converted values
    guard converted.origin.y <= safeAreaInset,
        let header = tableView.headerView(forSection: section) else {
        return
    }
    currentHeader = header
}

For UICollectionView

private var currentHeader: UICollectionReusableView? {
    willSet {
        // Handle `old` header
    } didSet {
        // Handle `new` header
    }
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let x = (collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.sectionInset.left ?? 0
    let point = CGPoint(x: x, y: HEIGHT_OF_HEADER_VIEW + collectionView.contentOffset.y + collectionView.adjustedContentInset.top)

    guard let path = collectionView.indexPathForItem(at: point),
        let rect = collectionView.layoutAttributesForSupplementaryElement(ofKind: UICollectionView.elementKindSectionHeader, at: IndexPath(row: 0, section: path.section))?.frame else {
        return
    }

    let converted = collectionView.convert(rect, to: collectionView.superview)
    let safeAreaInset = collectionView.safeAreaInsets.top

    guard converted.origin.y <= safeAreaInset,
        let header = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(row: 0, section: path.section)) else {
        return
    }
    currentHeader = header
}


问:
Node.js application works on heroku but not if downloaded from github
I have this project: https://github.com/FablabRUC/apiproject

This project is pushed via git from my local computer to Github. The project is able to run on Heroku if I deploy the local files. The problem is that when I download the Github project and try the exact same deploy strategy the result is different. The downloaded files are running fine locally, but Heroku don't like them. Is Github adding something I don't know of? Or what do you think could be the problem?

This is the Heroku logs from the project when its downloaded via github:

```<code>2020-06-01T12:02:08.000000+00:00 app[api]: Build succeeded
2020-06-01T12:02:10.653378+00:00 heroku[web.1]: Starting process with command `npm start`
2020-06-01T12:02:14.703102+00:00 app[web.1]:
2020-06-01T12:02:14.703115+00:00 app[web.1]: > api_fablab_deploy@1.0.0 start /app
2020-06-01T12:02:14.703120+00:00 app[web.1]: > node server.js
2020-06-01T12:02:14.703120+00:00 app[web.1]:
2020-06-01T12:02:15.639089+00:00 app[web.1]: internal/modules/cjs/loader.js:969
2020-06-01T12:02:15.639116+00:00 app[web.1]: throw err;
2020-06-01T12:02:15.639116+00:00 app[web.1]: ^
2020-06-01T12:02:15.639116+00:00 app[web.1]:
2020-06-01T12:02:15.639117+00:00 app[web.1]: Error: Cannot find module './User'
2020-06-01T12:02:15.639118+00:00 app[web.1]: Require stack:
2020-06-01T12:02:15.639119+00:00 app[web.1]: - /app/user/UserController.js
2020-06-01T12:02:15.639119+00:00 app[web.1]: - /app/app.js
2020-06-01T12:02:15.639120+00:00 app[web.1]: - /app/server.js
2020-06-01T12:02:15.639122+00:00 app[web.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)
2020-06-01T12:02:15.639123+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:842:27)
2020-06-01T12:02:15.639123+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:1026:19)
2020-06-01T12:02:15.639124+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:72:18)
2020-06-01T12:02:15.639124+00:00 app[web.1]: at Object.<anonymous> (/app/user/UserController.js:7:12)
2020-06-01T12:02:15.639125+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1138:30)
2020-06-01T12:02:15.639125+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
2020-06-01T12:02:15.639126+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:986:32)
2020-06-01T12:02:15.639126+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:879:14)
2020-06-01T12:02:15.639127+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:1026:19)
2020-06-01T12:02:15.639127+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:72:18)
2020-06-01T12:02:15.639128+00:00 app[web.1]: at Object.<anonymous> (/app/app.js:6:22)
2020-06-01T12:02:15.639128+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1138:30)
2020-06-01T12:02:15.639129+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
2020-06-01T12:02:15.639129+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:986:32)
2020-06-01T12:02:15.639129+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:879:14) {
2020-06-01T12:02:15.639130+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2020-06-01T12:02:15.639131+00:00 app[web.1]: requireStack: [ '/app/user/UserController.js', '/app/app.js', '/app/server.js' ]
2020-06-01T12:02:15.639132+00:00 app[web.1]: }
2020-06-01T12:02:15.649939+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-06-01T12:02:15.650376+00:00 app[web.1]: npm ERR! errno 1
2020-06-01T12:02:15.652026+00:00 app[web.1]: npm ERR! api_fablab_deploy@1.0.0 start: `node server.js`
2020-06-01T12:02:15.652295+00:00 app[web.1]: npm ERR! Exit status 1
2020-06-01T12:02:15.652555+00:00 app[web.1]: npm ERR!
2020-06-01T12:02:15.652774+00:00 app[web.1]: npm ERR! Failed at the api_fablab_deploy@1.0.0 start script.
2020-06-01T12:02:15.652987+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-06-01T12:02:15.684689+00:00 app[web.1]:
2020-06-01T12:02:15.684745+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-06-01T12:02:15.684883+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-06-01T12_02_15_662Z-debug.log
2020-06-01T12:02:15.770591+00:00 heroku[web.1]: Process exited with status 1
2020-06-01T12:02:15.821633+00:00 heroku[web.1]: State changed from starting to crashed
2020-06-01T12:02:15.824137+00:00 heroku[web.1]: State changed from crashed to starting
2020-06-01T12:02:18.080879+00:00 heroku[web.1]: Starting process with command `npm start`
2020-06-01T12:02:20.896285+00:00 app[web.1]:
2020-06-01T12:02:20.896313+00:00 app[web.1]: > api_fablab_deploy@1.0.0 start /app
2020-06-01T12:02:20.896314+00:00 app[web.1]: > node server.js
2020-06-01T12:02:20.896314+00:00 app[web.1]:
2020-06-01T12:02:21.536306+00:00 app[web.1]: internal/modules/cjs/loader.js:969
2020-06-01T12:02:21.536351+00:00 app[web.1]: throw err;
2020-06-01T12:02:21.536351+00:00 app[web.1]: ^
2020-06-01T12:02:21.536352+00:00 app[web.1]:
2020-06-01T12:02:21.536352+00:00 app[web.1]: Error: Cannot find module './User'
2020-06-01T12:02:21.536352+00:00 app[web.1]: Require stack:
2020-06-01T12:02:21.536353+00:00 app[web.1]: - /app/user/UserController.js
2020-06-01T12:02:21.536354+00:00 app[web.1]: - /app/app.js
2020-06-01T12:02:21.536354+00:00 app[web.1]: - /app/server.js
2020-06-01T12:02:21.536355+00:00 app[web.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)
2020-06-01T12:02:21.536355+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:842:27)
2020-06-01T12:02:21.536356+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:1026:19)
2020-06-01T12:02:21.536356+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:72:18)
2020-06-01T12:02:21.536357+00:00 app[web.1]: at Object.<anonymous> (/app/user/UserController.js:7:12)
2020-06-01T12:02:21.536357+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1138:30)
2020-06-01T12:02:21.536358+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
2020-06-01T12:02:21.536358+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:986:32)
2020-06-01T12:02:21.536358+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:879:14)
2020-06-01T12:02:21.536358+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:1026:19)
2020-06-01T12:02:21.536359+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:72:18)
2020-06-01T12:02:21.536359+00:00 app[web.1]: at Object.<anonymous> (/app/app.js:6:22)
2020-06-01T12:02:21.536359+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1138:30)
2020-06-01T12:02:21.536359+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
2020-06-01T12:02:21.536360+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:986:32)
2020-06-01T12:02:21.536360+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:879:14) {
2020-06-01T12:02:21.536360+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2020-06-01T12:02:21.536361+00:00 app[web.1]: requireStack: [ '/app/user/UserController.js', '/app/app.js', '/app/server.js' ]
2020-06-01T12:02:21.536361+00:00 app[web.1]: }
2020-06-01T12:02:21.544004+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-06-01T12:02:21.544293+00:00 app[web.1]: npm ERR! errno 1
2020-06-01T12:02:21.545512+00:00 app[web.1]: npm ERR! api_fablab_deploy@1.0.0 start: `node server.js`
2020-06-01T12:02:21.545659+00:00 app[web.1]: npm ERR! Exit status 1
2020-06-01T12:02:21.545834+00:00 app[web.1]: npm ERR!
2020-06-01T12:02:21.545985+00:00 app[web.1]: npm ERR! Failed at the api_fablab_deploy@1.0.0 start script.
2020-06-01T12:02:21.546113+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-06-01T12:02:21.564586+00:00 app[web.1]:
2020-06-01T12:02:21.564995+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-06-01T12:02:21.565128+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-06-01T12_02_21_548Z-debug.log
2020-06-01T12:02:21.646999+00:00 heroku[web.1]: Process exited with status 1
2020-06-01T12:02:21.691304+00:00 heroku[web.1]: State changed from starting to crashed
2020-06-01T12:02:37.000133+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=murmuring-earth-53207.herokuapp.com request_id=9c562652-4f24-476c-8fa7-ac52d7d3e4d7 fwd="212.237.134.177" dyno= connect= service= status=503 bytes= protocol=https
2020-06-01T12:02:37.318817+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=murmuring-earth-53207.herokuapp.com request_id=4163db93-a422-4fb9-a129-0d1e3b10b9ae fwd="212.237.134.177" dyno= connect= service= status=503 bytes= protocol=https
</code>```

答: This is likely caused by case sensitivity. On line 7 of UserController.js you require ./User but the file is titled user.js. Heroku is likely case insensitive, whereas your file system is not. I imagine capitalizing the file name, or changing the require to all lowercase should resolve your issue here.

Body:
I have this project: https://github.com/FablabRUC/apiproject

This project is pushed via git from my local computer to Github. The project is able to run on Heroku if I deploy the local files. The problem is that when I download the Github project and try the exact same deploy strategy the result is different. The downloaded files are running fine locally, but Heroku don't like them. Is Github adding something I don't know of? Or what do you think could be the problem?

This is the Heroku logs from the project when its downloaded via github:

2020-06-01T12:02:08.000000+00:00 app[api]: Build succeeded
2020-06-01T12:02:10.653378+00:00 heroku[web.1]: Starting process with command `npm start`
2020-06-01T12:02:14.703102+00:00 app[web.1]:
2020-06-01T12:02:14.703115+00:00 app[web.1]: > api_fablab_deploy@1.0.0 start /app
2020-06-01T12:02:14.703120+00:00 app[web.1]: > node server.js
2020-06-01T12:02:14.703120+00:00 app[web.1]:
2020-06-01T12:02:15.639089+00:00 app[web.1]: internal/modules/cjs/loader.js:969
2020-06-01T12:02:15.639116+00:00 app[web.1]: throw err;
2020-06-01T12:02:15.639116+00:00 app[web.1]: ^
2020-06-01T12:02:15.639116+00:00 app[web.1]:
2020-06-01T12:02:15.639117+00:00 app[web.1]: Error: Cannot find module './User'
2020-06-01T12:02:15.639118+00:00 app[web.1]: Require stack:
2020-06-01T12:02:15.639119+00:00 app[web.1]: - /app/user/UserController.js
2020-06-01T12:02:15.639119+00:00 app[web.1]: - /app/app.js
2020-06-01T12:02:15.639120+00:00 app[web.1]: - /app/server.js
2020-06-01T12:02:15.639122+00:00 app[web.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)
2020-06-01T12:02:15.639123+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:842:27)
2020-06-01T12:02:15.639123+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:1026:19)
2020-06-01T12:02:15.639124+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:72:18)
2020-06-01T12:02:15.639124+00:00 app[web.1]: at Object.<anonymous> (/app/user/UserController.js:7:12)
2020-06-01T12:02:15.639125+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1138:30)
2020-06-01T12:02:15.639125+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
2020-06-01T12:02:15.639126+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:986:32)
2020-06-01T12:02:15.639126+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:879:14)
2020-06-01T12:02:15.639127+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:1026:19)
2020-06-01T12:02:15.639127+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:72:18)
2020-06-01T12:02:15.639128+00:00 app[web.1]: at Object.<anonymous> (/app/app.js:6:22)
2020-06-01T12:02:15.639128+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1138:30)
2020-06-01T12:02:15.639129+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
2020-06-01T12:02:15.639129+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:986:32)
2020-06-01T12:02:15.639129+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:879:14) {
2020-06-01T12:02:15.639130+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2020-06-01T12:02:15.639131+00:00 app[web.1]: requireStack: [ '/app/user/UserController.js', '/app/app.js', '/app/server.js' ]
2020-06-01T12:02:15.639132+00:00 app[web.1]: }
2020-06-01T12:02:15.649939+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-06-01T12:02:15.650376+00:00 app[web.1]: npm ERR! errno 1
2020-06-01T12:02:15.652026+00:00 app[web.1]: npm ERR! api_fablab_deploy@1.0.0 start: `node server.js`
2020-06-01T12:02:15.652295+00:00 app[web.1]: npm ERR! Exit status 1
2020-06-01T12:02:15.652555+00:00 app[web.1]: npm ERR!
2020-06-01T12:02:15.652774+00:00 app[web.1]: npm ERR! Failed at the api_fablab_deploy@1.0.0 start script.
2020-06-01T12:02:15.652987+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-06-01T12:02:15.684689+00:00 app[web.1]:
2020-06-01T12:02:15.684745+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-06-01T12:02:15.684883+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-06-01T12_02_15_662Z-debug.log
2020-06-01T12:02:15.770591+00:00 heroku[web.1]: Process exited with status 1
2020-06-01T12:02:15.821633+00:00 heroku[web.1]: State changed from starting to crashed
2020-06-01T12:02:15.824137+00:00 heroku[web.1]: State changed from crashed to starting
2020-06-01T12:02:18.080879+00:00 heroku[web.1]: Starting process with command `npm start`
2020-06-01T12:02:20.896285+00:00 app[web.1]:
2020-06-01T12:02:20.896313+00:00 app[web.1]: > api_fablab_deploy@1.0.0 start /app
2020-06-01T12:02:20.896314+00:00 app[web.1]: > node server.js
2020-06-01T12:02:20.896314+00:00 app[web.1]:
2020-06-01T12:02:21.536306+00:00 app[web.1]: internal/modules/cjs/loader.js:969
2020-06-01T12:02:21.536351+00:00 app[web.1]: throw err;
2020-06-01T12:02:21.536351+00:00 app[web.1]: ^
2020-06-01T12:02:21.536352+00:00 app[web.1]:
2020-06-01T12:02:21.536352+00:00 app[web.1]: Error: Cannot find module './User'
2020-06-01T12:02:21.536352+00:00 app[web.1]: Require stack:
2020-06-01T12:02:21.536353+00:00 app[web.1]: - /app/user/UserController.js
2020-06-01T12:02:21.536354+00:00 app[web.1]: - /app/app.js
2020-06-01T12:02:21.536354+00:00 app[web.1]: - /app/server.js
2020-06-01T12:02:21.536355+00:00 app[web.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)
2020-06-01T12:02:21.536355+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:842:27)
2020-06-01T12:02:21.536356+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:1026:19)
2020-06-01T12:02:21.536356+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:72:18)
2020-06-01T12:02:21.536357+00:00 app[web.1]: at Object.<anonymous> (/app/user/UserController.js:7:12)
2020-06-01T12:02:21.536357+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1138:30)
2020-06-01T12:02:21.536358+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
2020-06-01T12:02:21.536358+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:986:32)
2020-06-01T12:02:21.536358+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:879:14)
2020-06-01T12:02:21.536358+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:1026:19)
2020-06-01T12:02:21.536359+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:72:18)
2020-06-01T12:02:21.536359+00:00 app[web.1]: at Object.<anonymous> (/app/app.js:6:22)
2020-06-01T12:02:21.536359+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1138:30)
2020-06-01T12:02:21.536359+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
2020-06-01T12:02:21.536360+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:986:32)
2020-06-01T12:02:21.536360+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:879:14) {
2020-06-01T12:02:21.536360+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2020-06-01T12:02:21.536361+00:00 app[web.1]: requireStack: [ '/app/user/UserController.js', '/app/app.js', '/app/server.js' ]
2020-06-01T12:02:21.536361+00:00 app[web.1]: }
2020-06-01T12:02:21.544004+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-06-01T12:02:21.544293+00:00 app[web.1]: npm ERR! errno 1
2020-06-01T12:02:21.545512+00:00 app[web.1]: npm ERR! api_fablab_deploy@1.0.0 start: `node server.js`
2020-06-01T12:02:21.545659+00:00 app[web.1]: npm ERR! Exit status 1
2020-06-01T12:02:21.545834+00:00 app[web.1]: npm ERR!
2020-06-01T12:02:21.545985+00:00 app[web.1]: npm ERR! Failed at the api_fablab_deploy@1.0.0 start script.
2020-06-01T12:02:21.546113+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-06-01T12:02:21.564586+00:00 app[web.1]:
2020-06-01T12:02:21.564995+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-06-01T12:02:21.565128+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-06-01T12_02_21_548Z-debug.log
2020-06-01T12:02:21.646999+00:00 heroku[web.1]: Process exited with status 1
2020-06-01T12:02:21.691304+00:00 heroku[web.1]: State changed from starting to crashed
2020-06-01T12:02:37.000133+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=murmuring-earth-53207.herokuapp.com request_id=9c562652-4f24-476c-8fa7-ac52d7d3e4d7 fwd="212.237.134.177" dyno= connect= service= status=503 bytes= protocol=https
2020-06-01T12:02:37.318817+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=murmuring-earth-53207.herokuapp.com request_id=4163db93-a422-4fb9-a129-0d1e3b10b9ae fwd="212.237.134.177" dyno= connect= service= status=503 bytes= protocol=https


问:
jaspersoft visualize auth undefined url segment
Why do I see this in console.log (authentication is blocked)

http://example.com/jasperserver-pro/undefined/require.config.js 404

when using

```<code> visualize(
     {
        server: 'http://example.com/jasperserver-pro/',
        auth: {
           token: authToken,
           preAuth: true,
           tokenName: "pp"
        },
     },
</code>```

Different from the docs my visualize.js is not in /client rather /optimized-scripts, could this be causing an issue? is /client hard coded?

答: /client is hardcoded and not on file system. Not obvious and not documented.</p>

Body:
Why do I see this in console.log (authentication is blocked)

http://example.com/jasperserver-pro/undefined/require.config.js 404

when using

 visualize(
     {
        server: 'http://example.com/jasperserver-pro/',
        auth: {
           token: authToken,
           preAuth: true,
           tokenName: "pp"
        },
     },

Different from the docs my visualize.js is not in /client rather /optimized-scripts, could this be causing an issue? is /client hard coded?


问:
Visual studio professional 2015 - can't connect to VSO - SplitterDistance error
I'm running Visual Studio Professional 2015 on Windows 10, and I'm attempting to connect to Visual Studio Online using the "manage connections" feature from the team explorer.  Every time I click on Manage Connections \ Connect to Team Project, an error appears immediately above:

SplitterDistance must be between Panel1MinSize and Width - Panel2MinSize.

Based on researching this issue, this error appears in various forms in previous versions of Visual Studio, but it's not clear to me how to fix it in 2015. Here are a couple of things I tried...

A "repair" of Visual Studio didn't improve the situation

Switching the Source Control plugin selection from Microsoft git provider to Visual Studio Team Foundation Server didn't net anything different.

Is anyone aware of a patch/fix for this issue, or an alternative way to connect to VSO other than the Manage Connections \ Connect to Team Project feature?

答:
VS 2015 UI does not manage the high resolution well. Most of us will use a full-screen RDP connection to the virtual machine, Windows takes the native resolution of your notebook by default, passes this to Visual Studio and this leads to the said error message. The full HD resolution of 1920 x 1080 already means trouble.

The solution is simple:

Sign off from the VM.

Change the RDP connection settings from the
fullscreen to 1024x768.

Sign on to the VM.

Start Visual Studio and connect to the Team Explorer for the first time.

Close Visual Studio and let it save your preferences.

Next time, the error message will not occur even when connecting to another DevOps server.


问:
Flutter DropdownButtonFormField.onChanged doesn't update UI
I have a screen with a DropdownButtonFormField:

```<code>var _list = ['foo', 'bar'];
String _value;

build() {
  ...
  DropdownButtonFormField(
    items: _items(ctx),
    onChanged: (item) => _onChanged(ctx, item),
    value: _value,
  )
  ...
}

List<DropdownMenuItem<String>> _items(ctx) {
  final specialNone = DropdownMenuItem(
    child: Text('NONE'),
    value: '#none',
  );
  final specialNew = DropdownMenuItem(
    child: Text('CREATE NEW'),
    value: '#new',
  );

  return [
    specialNone,
    specialNew,
    ..._list.map((o) => DropdownMenuItem(child: Text(o), value: o)).toList()
  ];
}

void _onChanged(ctx, String value) async {
  if (value == '#new') {
    final result = await Navigator.pushNamed(ctx, '/vendor');

    if (result != null)
      setState(() {
        _list.add(result);
        _value = result;
      });
  } else if (value == '#none')
    setState(() {
      _value = null;
    });
  else
    setState(() {
      _value = value;
    });
}
</code>```

There's a special item "CREATE NEW" in the items list. When clicked, a new item will be added to the list, and I want it to be selected instead of selecting "CREATE NEW".

NOTE: If you change DropdownButtonFormField to DropdownButton, it will work.

答:
Try out this code if you doesn't want to update UI </p>

```<code>DropdownButton<String>(
      value: dropdownValue,
      icon: Icon(Icons.arrow_downward),
      iconSize: 24,
      elevation: 16,
      style: TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged:(value){},
      items: <String>['One', 'Two', 'Free', 'Four']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
</code>```

Body:
I have a screen with a DropdownButtonFormField:

var _list = ['foo', 'bar'];
String _value;

build() {
  ...
  DropdownButtonFormField(
    items: _items(ctx),
    onChanged: (item) => _onChanged(ctx, item),
    value: _value,
  )
  ...
}

List<DropdownMenuItem<String>> _items(ctx) {
  final specialNone = DropdownMenuItem(
    child: Text('NONE'),
    value: '#none',
  );
  final specialNew = DropdownMenuItem(
    child: Text('CREATE NEW'),
    value: '#new',
  );

  return [
    specialNone,
    specialNew,
    ..._list.map((o) => DropdownMenuItem(child: Text(o), value: o)).toList()
  ];
}

void _onChanged(ctx, String value) async {
  if (value == '#new') {
    final result = await Navigator.pushNamed(ctx, '/vendor');

    if (result != null)
      setState(() {
        _list.add(result);
        _value = result;
      });
  } else if (value == '#none')
    setState(() {
      _value = null;
    });
  else
    setState(() {
      _value = value;
    });
}

There's a special item "CREATE NEW" in the items list. When clicked, a new item will be added to the list, and I want it to be selected instead of selecting "CREATE NEW".

NOTE: If you change DropdownButtonFormField to DropdownButton, it will work.

Body:
Try out this code if you doesn't want to update UI

DropdownButton<String>(
      value: dropdownValue,
      icon: Icon(Icons.arrow_downward),
      iconSize: 24,
      elevation: 16,
      style: TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged:(value){},
      items: <String>['One', 'Two', 'Free', 'Four']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );


问:
Tensorflow flow_from_dataframe put all the pixel to white
He,
I am using flow_from_dataframe to manage image but at the end of the computation i get all the wrong pixel of the image, below i show all my code, can someone help me

```<code>batch_size = 12
train_datagen = ImageDataGenerator(
rescale = 1. / 255,\
zoom_range=0.1,\
rotation_range=10,\
width_shift_range=0.1,\
height_shift_range=0.1,\
horizontal_flip=True,\
vertical_flip=False,)

train_generator_left_cc = train_datagen.flow_from_dataframe(
dataframe=df,
target_size=(256,256),
x_col="left_cc",
y_col=["lb","lm","rb","rm","left_cc"],
color_mode="rgb",
batch_size=batch_size,
class_mode="multi_output",
shuffle=False,
interpolation="bilinear"

)

train_generator_right_cc = train_datagen.flow_from_dataframe(
dataframe=df,
target_size=(256,256),
x_col="right_cc",
y_col=["lb","lm","rb","rm", "right_cc"],
color_mode="rgb",
batch_size=batch_size,
class_mode="multi_output",
shuffle=False,
)

x1,y1=train_generator_left_cc.next()
x2,y2=train_generator_right_cc.next()

i=11
image = x1[i]
label = (y1[0][i],y1[1][i],y1[2][i],y1[3][i],y1[4][i])  # categorical from one-hot-encoding
print("Image shape: ", image.shape)

print(label)
pyplot.imshow(image.squeeze())
pyplot.show()
image = x2[i]
label = (y2[0][i],y2[1][i],y2[2][i],y2[3][i]) # categorical from one-hot-encoding
print(label)
pyplot.imshow(image)
pyplot.show()

#i put the directory of the image in the label of the dataset to make test
image_decoded = tf.image.decode_png(tf.io.read_file(y2[4][i]), channels=3)

arr_ = np.squeeze(image_decoded)
pyplot.imshow(arr_)
pyplot.show()
</code>```

and here there is the result image:
result of the flow_from_dataframe

what i need

答: In the tensor flow library there is a bug to process the resize function so I build a custom generator for the image</p>

Body:
He,
I am using flow_from_dataframe to manage image but at the end of the computation i get all the wrong pixel of the image, below i show all my code, can someone help me

batch_size = 12
train_datagen = ImageDataGenerator(
rescale = 1. / 255,\
zoom_range=0.1,\
rotation_range=10,\
width_shift_range=0.1,\
height_shift_range=0.1,\
horizontal_flip=True,\
vertical_flip=False,)

train_generator_left_cc = train_datagen.flow_from_dataframe(
dataframe=df,
target_size=(256,256),
x_col="left_cc",
y_col=["lb","lm","rb","rm","left_cc"],
color_mode="rgb",
batch_size=batch_size,
class_mode="multi_output",
shuffle=False,
interpolation="bilinear"

)

train_generator_right_cc = train_datagen.flow_from_dataframe(
dataframe=df,
target_size=(256,256),
x_col="right_cc",
y_col=["lb","lm","rb","rm", "right_cc"],
color_mode="rgb",
batch_size=batch_size,
class_mode="multi_output",
shuffle=False,
)

x1,y1=train_generator_left_cc.next()
x2,y2=train_generator_right_cc.next()

i=11
image = x1[i]
label = (y1[0][i],y1[1][i],y1[2][i],y1[3][i],y1[4][i])  # categorical from one-hot-encoding
print("Image shape: ", image.shape)

print(label)
pyplot.imshow(image.squeeze())
pyplot.show()
image = x2[i]
label = (y2[0][i],y2[1][i],y2[2][i],y2[3][i]) # categorical from one-hot-encoding
print(label)
pyplot.imshow(image)
pyplot.show()

#i put the directory of the image in the label of the dataset to make test
image_decoded = tf.image.decode_png(tf.io.read_file(y2[4][i]), channels=3)

arr_ = np.squeeze(image_decoded)
pyplot.imshow(arr_)
pyplot.show()

and here there is the result image:
result of the flow_from_dataframe

what i need


问:
Identify the changed fields in django post_save signal
I'm using django's post_save signal to execute some statements after saving the model.

```<code>class Mode(models.Model):
    name = models.CharField(max_length=5)
    mode = models.BooleanField()

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Mode)
def post_save(sender, instance, created, **kwargs):
        # do some stuff
        pass
</code>```

Now I want to execute a statement based on whether the value of the mode field has changed or not.

```<code>@receiver(post_save, sender=Mode)
def post_save(sender, instance, created, **kwargs):
        # if value of `mode` has changed:
        #  then do this
        # else:
        #  do that
        pass
</code>```

I looked at a few SOF threads and a blog but couldn't find a solution to this. All of them were trying to use the pre_save method or form which are not my use case. https://docs.djangoproject.com/es/1.9/ref/signals/#post-save in the  django docs doesn't mention a direct way to do this.

An answer in the link below looks promising but I don't know how to use it. I'm not sure if the latest django version supports it or not, because I used ipdb to debug this and found that the instance variable has no attribute has_changed as mentioned in the below answer.

Django: When saving, how can you check if a field has changed?

答:
You can use update_fields in django signals.

```<code>@receiver(post_save, sender=Mode)
def post_save(sender, instance, created, **kwargs):

    # only update instance
    if not created:

        update_fields = kwargs.get('update_fields') or set()

        # value of `mode` has changed:
        if 'mode' in update_fields:
            # then do this
            pass
        else:
            # do that
            pass
</code>```

Body:
I'm using django's post_save signal to execute some statements after saving the model.

class Mode(models.Model):
    name = models.CharField(max_length=5)
    mode = models.BooleanField()

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Mode)
def post_save(sender, instance, created, **kwargs):
        # do some stuff
        pass

Now I want to execute a statement based on whether the value of the mode field has changed or not.

@receiver(post_save, sender=Mode)
def post_save(sender, instance, created, **kwargs):
        # if value of `mode` has changed:
        #  then do this
        # else:
        #  do that
        pass

I looked at a few SOF threads and a blog but couldn't find a solution to this. All of them were trying to use the pre_save method or form which are not my use case. https://docs.djangoproject.com/es/1.9/ref/signals/#post-save in the  django docs doesn't mention a direct way to do this.

An answer in the link below looks promising but I don't know how to use it. I'm not sure if the latest django version supports it or not, because I used ipdb to debug this and found that the instance variable has no attribute has_changed as mentioned in the below answer.

Django: When saving, how can you check if a field has changed?

Body:
You can use update_fields in django signals.

@receiver(post_save, sender=Mode)
def post_save(sender, instance, created, **kwargs):

    # only update instance
    if not created:

        update_fields = kwargs.get('update_fields') or set()

        # value of `mode` has changed:
        if 'mode' in update_fields:
            # then do this
            pass
        else:
            # do that
            pass


问:
Mongoose populate with filter
My schema:

```<code>const ProductSchema = new Schema({
    Category: String,
    Subcategory: String,
    Name: String,
    Offers: [{ type: ObjectId, ref: "Offer" }]
})

const OfferSchema = new Schema({
    Quantity: Number,
    Images: [String],
    Price: Number,
    Size: String,
    Color: String
})
</code>```

I am doing query for products with filter offers with limit and skip. I tried this:

```<code>const products = await ProductSchema.find({ ...someFilter }).populate({
    path: "Offers",
    match: {
        Quantity: { $gt: 2 },
        Images: { $exists: true, $ne: [] }
    }
}).skip(skip).limit(limit)
</code>```

And I want to get only documents where length of offers is > 0. But I get documents with empty Offers. If I filter like this:

```<code>products.filter(item => item.Offers.length > 0)
</code>```

My pagination will break. Can you help me?

答:
Just require the Offers field to not be empty like so:

```<code>const products = await ProductSchema.find(
    {
        ...someFilter,
        "Offers.0": {$exists: true}
    }
).populate({
    path: "Offers",
    match: {
        Quantity: {$gt: 2},
        Images: {$exists: true, $ne: []}
    }
}).skip(skip).limit(limit)
</code>```

Title: Mongoose populate with filter

Body:
My schema:

const ProductSchema = new Schema({
    Category: String,
    Subcategory: String,
    Name: String,
    Offers: [{ type: ObjectId, ref: "Offer" }]
})

const OfferSchema = new Schema({
    Quantity: Number,
    Images: [String],
    Price: Number,
    Size: String,
    Color: String
})

I am doing query for products with filter offers with limit and skip. I tried this:

const products = await ProductSchema.find({ ...someFilter }).populate({
    path: "Offers",
    match: {
        Quantity: { $gt: 2 },
        Images: { $exists: true, $ne: [] }
    }
}).skip(skip).limit(limit)

And I want to get only documents where length of offers is > 0. But I get documents with empty Offers. If I filter like this:

products.filter(item => item.Offers.length > 0)

My pagination will break. Can you help me?

Body:
Just require the Offers field to not be empty like so:

const products = await ProductSchema.find(
    {
        ...someFilter,
        "Offers.0": {$exists: true}
    }
).populate({
    path: "Offers",
    match: {
        Quantity: {$gt: 2},
        Images: {$exists: true, $ne: []}
    }
}).skip(skip).limit(limit)


问:
How to validate a salesforce react input component?
The salesforce lightning design system documents an onInvalid callback for the Input component.  It does not appear to provide any examples though.

I have tried something similar to the following code.  When I change the input to an invalid value, for example 2, then the error handler is not executed.

```<code><Input type='number'
       minValue={3}
       value={someValue}
       onChange={someChangeHandler}
       onInvalid={someErrorHandler} />
</code>```

How can I use onInvalid to validate an input?

Any examples of the correct usage would be appreciated.

答:
It seems that minValue is used to define the range of a counter Input together with maxValue.

You can use onChange to test the current input against your custom validation and set a Boolean isError state variable that you can use to conditionally set some errorText.

Body:
The salesforce lightning design system documents an onInvalid callback for the Input component.  It does not appear to provide any examples though.

I have tried something similar to the following code.  When I change the input to an invalid value, for example 2, then the error handler is not executed.

<Input type='number'
       minValue={3}
       value={someValue}
       onChange={someChangeHandler}
       onInvalid={someErrorHandler} />

How can I use onInvalid to validate an input?

Any examples of the correct usage would be appreciated.


问:
Compare two strings of ints in java
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10? </p>

```<code>String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";
</code>```

答: I would not perform the comparison on the raw strings.  Instead, first convert each String to a List<Integer> using String.split() and Integer.parseInt() on each result.  Then sort() the lists into ascending order, and then it becomes very easy to compare them.

Title: Compare two strings of ints in java

Body:
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10?

String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";


问:
How to initialize struct with anonymous array
I'm trying to create nested structs with anonymous array initialization:

```<code>struct CIpv6Address {
    uint16_t* address;
};

struct CIpv6Cidr {
    CIpv6Address* address;
    uint16_t cidr;
};

CIpv6Cidr cIpv6Cidr1{
    CIpv6Address {
        (uint16_t[]){0xfdaa, 0, 0, 0, 0, 0, 0, 1};
    },
    64
};
</code>```

but I'm getting:

error: taking address of temporary array
               (uint16_t[]){0xfdaa, 0, 0, 0, 0, 0, 0, 1};

and also

error: expected primary-expression before '{' token
           CIpv6Address {

The first error I kinda know why. But I don't want to allocate an array with new as it'd need to be deleted somehow after. Is there a simple way to simply put a little address there?

And for the second error I have no idea

答:
That's not how you initialize variables in C. In C initialization has a form like type variable = value - there has to be a = between the name of the variable and {. Also without the use of typedef you have to use the keyword struct in front of the name.

How to initialize struct with anonymous array

You can use compound literals. At file scope compound literals have static storage duration, but at block scope they have automatic storage duration - as always you have to watch out for lifetime of objects. You can godbolt link:

```<code>#include <stdint.h>

struct CIpv6Address {
    uint16_t* address;
};

struct CIpv6Cidr {
    struct CIpv6Address* address;
    uint16_t cidr;
};

struct CIpv6Cidr cIpv6Cidr1 = {
    &(struct CIpv6Address){
        (uint16_t[]){0xfdaa, 0, 0, 0, 0, 0, 0, 1},
    },
    64
};
</code>```

Body:
I'm trying to create nested structs with anonymous array initialization:

struct CIpv6Address {
    uint16_t* address;
};

struct CIpv6Cidr {
    CIpv6Address* address;
    uint16_t cidr;
};

CIpv6Cidr cIpv6Cidr1{
    CIpv6Address {
        (uint16_t[]){0xfdaa, 0, 0, 0, 0, 0, 0, 1};
    },
    64
};

but I'm getting:

error: taking address of temporary array
               (uint16_t[]){0xfdaa, 0, 0, 0, 0, 0, 0, 1};

and also

error: expected primary-expression before '{' token
           CIpv6Address {

The first error I kinda know why. But I don't want to allocate an array with new as it'd need to be deleted somehow after. Is there a simple way to simply put a little address there?

And for the second error I have no idea

Body:
That's not how you initialize variables in C. In C initialization has a form like type variable = value - there has to be a = between the name of the variable and {. Also without the use of typedef you have to use the keyword struct in front of the name.

How to initialize struct with anonymous array

You can use compound literals. At file scope compound literals have static storage duration, but at block scope they have automatic storage duration - as always you have to watch out for lifetime of objects. You can godbolt link:

#include <stdint.h>

struct CIpv6Address {
    uint16_t* address;
};

struct CIpv6Cidr {
    struct CIpv6Address* address;
    uint16_t cidr;
};

struct CIpv6Cidr cIpv6Cidr1 = {
    &(struct CIpv6Address){
        (uint16_t[]){0xfdaa, 0, 0, 0, 0, 0, 0, 1},
    },
    64
};


问:
MathJax elements attribute specified on startup, but still applys to everything
I want to only apply MathJax to text inside

Based on the documentation, I have added the following.

```

However, MathJax still typesets the entire page. I know as a last resort I could do MathJax.typeset(document.querySelectorAll('span.math-tex')) on window load, but I'd rather do it the way it was intended if possible. Has anyone else faced similar problems?

答:
There are two problems with your code.  First, according to the documentation you link to, the elements is supposed to be an array of elements or element selectors, not just a single string.  So you should use

            elements: ["span.math-tex"]
```

<p>Second, there was a big in the handling of the <code>elements</code> array in version 3.0.1 (see the issue report) that is fixed in the current version (3.0.5), so you need to update to that version.</p>

<p>E.g.,</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
    MathJax = {
        startup: {
            elements: ["span.math-tex"]
        },
        tex: {
            inlineMath: [['$', '$'], ['\\(', '\\)']],
            displayMath: [['$$','$$'],['\\[','\\]']],
            processEscapes: true
        }
    }
  </script>
  <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3.0.5/es5/tex-mml-chtml.js"></script>

$$\text{not processed}$$

<span class="math-tex">
$$\text{processed}$$
</span></code>```

Body:
I want to only apply MathJax to text inside

Based on the documentation, I have added the following.

However, MathJax still typesets the entire page. I know as a last resort I could do MathJax.typeset(document.querySelectorAll('span.math-tex')) on window load, but I'd rather do it the way it was intended if possible. Has anyone else faced similar problems?

Body:
There are two problems with your code.  First, according to the documentation you link to, the elements is supposed to be an array of elements or element selectors, not just a single string.  So you should use

            elements: ["span.math-tex"]

Second, there was a big in the handling of the elements array in version 3.0.1 (see the issue report) that is fixed in the current version (3.0.5), so you need to update to that version.

E.g.,

<script>
    MathJax = {
        startup: {
            elements: ["span.math-tex"]
        },
        tex: {
            inlineMath: [['$', '$'], ['\\(', '\\)']],
            displayMath: [['$$','$$'],['\\[','\\]']],
            processEscapes: true
        }
    }
  </script>
  <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3.0.5/es5/tex-mml-chtml.js"></script>

$$\text{not processed}$$

<span class="math-tex">
$$\text{processed}$$
</span>


问:
What does 'super.main' mean in Blogger template
The main includable contains this code from Blog1 widget -

```<code> <b:includable id='main'>
      <!--<b:include name='noContentPlaceholder'/>-->

      <b:comment>Cap the total number of ads (widgets and inline ads).</b:comment>
      <b:with value='3' var='maxNumAds'>
      <b:with value='data:widgets.AdSense.size' var='numDesktopAds'>
      <b:with value='data:widgets.AdSense count (w => w.sectionId != "ads")' var='numMobileAds'>
      <b:comment>Filter out the featured post, but only on the homepage.</b:comment>
      <b:with value='data:widgets.FeaturedPost filter (w => w.sectionId == "page_body") map (w => w.postId)' var='featuredPostIds'>
      <b:with value='data:view.isHomepage  ? data:posts filter (post => post.id not in data:featuredPostIds)   : data:posts' var='posts'>
        <b:include name='super.main'/>
      </b:with>
      </b:with>
      </b:with>
      </b:with>
      </b:with>
    </b:includable>
</code>```

I can understand other tags and expressions used in this code snippet but I cannot figure out what "super.main" means.
When I placed a parent div around the include tag, I realised it nested feed of posts. But which includable does it call?

答: Each includable tag has a default version stored in the Blogger side. super.main is the default main tag by Blogger.

Body:
The main includable contains this code from Blog1 widget -

      Cap the total number of ads (widgets and inline ads).

       w.sectionId != "ads")' var='numMobileAds'>
      Filter out the featured post, but only on the homepage.
       w.sectionId == "page_body") map (w => w.postId)' var='featuredPostIds'>
       post.id not in data:featuredPostIds)   : data:posts' var='posts'>

I can understand other tags and expressions used in this code snippet but I cannot figure out what "super.main" means.
When I placed a parent div around the include tag, I realised it nested feed of posts. But which includable does it call?


问:
Save coins when the server restarts?
Moin I made my own script with coins. But when the server restarts the coins are set to 0 at each time someone has an idea how to set that that which can be saved. (Scripts not so long)

Here's the script:

```<code>command /coins:
    aliases: coin
    trigger:
        send "&e&lEndless &7● &aDu hast &e%{coins::%player%}% &aCoins" to player

Command /pay [<player>] [<number>]:
    trigger:
        if arg-1 is set:
            if arg-1 is not player:
                if arg-2 is smaller than {coins::%player%}:
                    remove arg-2 from {coins::%player%}
                    add arg-2 to {coins::%arg-1%}
                    send " &7Du hast &e%arg-2% Coins &7an &a%arg-1% &7gesendet!" to player
                    send " &7Du hast &e%arg-2% Coins &7von &a%player% &7erhalten!" to arg-1
                    stop

                else if arg-2 is bigger than {coins::%player%}:
                    send "&e&lEndless &7● &cDu hast nicht genügend &eCoins"
                    stop

            else if arg-1 is player:
                send "&e&lEndless &7● &7Du kannst dir selber kein Geld geben!"
                stop

        else if arg-1 is not set:
            send "&e&lEndless &7● &7Nutze&8: &e/pay <Spieler> <Anzahl>"
            stop

on first join:
    set {coins::%player%} to 2000

every 1 tick:
    loop all players:
        if {coins::%loop-player%} is below 0:
            set {coins::%loop-player%} to 0
        if {coins::%loop-player%} is not set:
            set {coins::%loop-player%} to 0

command /removecoins [<player>] [<number>]:
    permission: coins.remcoins
    permission message: &e&lEndless &7● &c&lKeine Erlaubnis
    trigger:
        if arg-1 is set:
            if arg-2 is a number:
                remove arg-2 from {coins::%arg-1%}
                send "&e&lEndless &7● &7%arg-1% wurden &e%arg-2% Coins &7abgezogen!"
                stop

        if arg-1 is not set:
            send "&e&lEndless &7● &7Bitte gebe einen Spieler und Beitrag an!"
            stop

command /admin [<player>] [<number>]:
    permission: coins.remcoins
    permission message: &e&lEndless &7● &c&lKeine Erlaubnis
    trigger:
        if arg-1 is set:
            if arg-2 is a number:
                remove arg-2 from {coins::%arg-1%}
                stop

        if arg-1 is not set:
            stop

Command /addcoins [<player>] [<number>]:
    permission: coins.givecoins
    permission message: &e&lEndless &7● &c&lKeine Erlaubnis
    trigger:
        if arg-1 is set:
            if arg-2 is a number:
                add arg-2 to {coins::%arg-1%}
                send "&e&lEndless &7● &7%arg-1% hat &e%arg-2% Coins &7erhalten!"
                stop

            else if arg-2 is not a number:
                send "&e&lEndless &7● &7Das ist keine Anzahl!"

        if arg-1 is not set:
            send "&e&lEndless &7● &7Bitte gebe einen Spieler und Beitrag an!"
            stop
</code>```

答:
```<code>on server stop:
        save-all
        set {coins ::%players%} to "%{coins ::%players%}%"
</code>```

You need to make it make sure it saves it and the game it will set all online players coins to what they have to try and save it also saves the game to save skript and the coins on the server stop.

Title: Save coins when the server restarts?

Body:
Moin I made my own script with coins. But when the server restarts the coins are set to 0 at each time someone has an idea how to set that that which can be saved. (Scripts not so long)

Here's the script:

command /coins:
    aliases: coin
    trigger:
        send "&e&lEndless &7● &aDu hast &e%{coins::%player%}% &aCoins" to player

Command /pay [<player>] [<number>]:
    trigger:
        if arg-1 is set:
            if arg-1 is not player:
                if arg-2 is smaller than {coins::%player%}:
                    remove arg-2 from {coins::%player%}
                    add arg-2 to {coins::%arg-1%}
                    send " &7Du hast &e%arg-2% Coins &7an &a%arg-1% &7gesendet!" to player
                    send " &7Du hast &e%arg-2% Coins &7von &a%player% &7erhalten!" to arg-1
                    stop

                else if arg-2 is bigger than {coins::%player%}:
                    send "&e&lEndless &7● &cDu hast nicht genügend &eCoins"
                    stop

            else if arg-1 is player:
                send "&e&lEndless &7● &7Du kannst dir selber kein Geld geben!"
                stop

        else if arg-1 is not set:
            send "&e&lEndless &7● &7Nutze&8: &e/pay <Spieler> <Anzahl>"
            stop

on first join:
    set {coins::%player%} to 2000

every 1 tick:
    loop all players:
        if {coins::%loop-player%} is below 0:
            set {coins::%loop-player%} to 0
        if {coins::%loop-player%} is not set:
            set {coins::%loop-player%} to 0

command /removecoins [<player>] [<number>]:
    permission: coins.remcoins
    permission message: &e&lEndless &7● &c&lKeine Erlaubnis
    trigger:
        if arg-1 is set:
            if arg-2 is a number:
                remove arg-2 from {coins::%arg-1%}
                send "&e&lEndless &7● &7%arg-1% wurden &e%arg-2% Coins &7abgezogen!"
                stop

        if arg-1 is not set:
            send "&e&lEndless &7● &7Bitte gebe einen Spieler und Beitrag an!"
            stop

command /admin [<player>] [<number>]:
    permission: coins.remcoins
    permission message: &e&lEndless &7● &c&lKeine Erlaubnis
    trigger:
        if arg-1 is set:
            if arg-2 is a number:
                remove arg-2 from {coins::%arg-1%}
                stop

        if arg-1 is not set:
            stop

Command /addcoins [<player>] [<number>]:
    permission: coins.givecoins
    permission message: &e&lEndless &7● &c&lKeine Erlaubnis
    trigger:
        if arg-1 is set:
            if arg-2 is a number:
                add arg-2 to {coins::%arg-1%}
                send "&e&lEndless &7● &7%arg-1% hat &e%arg-2% Coins &7erhalten!"
                stop

            else if arg-2 is not a number:
                send "&e&lEndless &7● &7Das ist keine Anzahl!"

        if arg-1 is not set:
            send "&e&lEndless &7● &7Bitte gebe einen Spieler und Beitrag an!"
            stop

Body:
on server stop:
        save-all
        set {coins ::%players%} to "%{coins ::%players%}%"

You need to make it make sure it saves it and the game it will set all online players coins to what they have to try and save it also saves the game to save skript and the coins on the server stop.