问:
How can I sort a JPA query result where the parameter is a String and the result is a List of Objects?
I'm writing a Spring Boot API endpoint and I need to return a list of Airlines ordered by a String (description) of 3 or more chars, the List must be sorted with the results that match the String at the beginning of the word at the top and the rest by alphabetical order

Airline class:

```<code>@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "airline")
public class Airline implements Serializable {
    private static final long serialVersionUID = -5962418077659300886L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column
    private String code;

    @Column
    private String description;
}
</code>```

I get the list that matches the String but I cannot get the order right

AirlineRepository

```<code>public interface AirlineRepository extends JpaRepository<Airline, Integer> {
    Airline getById(Integer id);

    List<Airline> findByDescriptionContainingIgnoreCase(String description, Pageable pageable);
    List<Airline> findByDescriptionStartsWithIgnoreCase(String description, Pageable pageable);
}
</code>```

If I search the keyword 'ala' all airlines whose name starts with 'ala' should come first.

This is what I get

```<code>{
  "status": "SUCCESS",
  "message": "Execution Successful",
  "totalCount": 10,
  "content": [
    {
      "id": 962,
      "code": "6T",
      "description": "Air Mandalay"
    },
    {
      "id": 46,
      "code": "NZ",
      "description": "Air New Zealand"
    },
    {
      "id": 18,
      "code": "AS",
      "description": "Alaska Airlines"
    },
    {
      "id": 519,
      "code": "KO",
      "description": "Alaska Central Express"
    },
    {
      "id": 477,
      "code": "J5",
      "description": "Alaska Seaplane"
    },
    {
      "id": 30,
      "code": "YZ",
      "description": "ALAS URUGUAY"
    },
    {
      "id": 324,
      "code": "C9",
      "description": "Alphaland Aviation"
    },
    {
      "id": 286,
      "code": "A7",
      "description": "Calafia Airlines"
    },
    {
      "id": 330,
      "code": "CE",
      "description": "Chalair"
    },
    {
      "id": 521,
      "code": "L3",
      "description": "DHL de Guatemala"
    }
  ],
  "timestamp": null
}````
```

答:
i'm not quite sure if i understood your requirement completly.

To fetch all airlines in an ordered way i would add the following method to the AirlineRepository

```<code>List<Airline> findByDescriptionStartsWithIgnoreCaseOrderByDescriptionAsc(String description, Pageable pageable);
</code>```

If you also need all other airlines i would add this method, too.

```<code>List<Airline> findByDescriptionNotLikeIgnoreCaseOrderByDescriptionAsc(String description, Pageable pageable);
</code>```

Add an '%' to the description and combine both lists.

Body:
I'm writing a Spring Boot API endpoint and I need to return a list of Airlines ordered by a String (description) of 3 or more chars, the List must be sorted with the results that match the String at the beginning of the word at the top and the rest by alphabetical order

Airline class:

@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "airline")
public class Airline implements Serializable {
    private static final long serialVersionUID = -5962418077659300886L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column
    private String code;

    @Column
    private String description;
}

I get the list that matches the String but I cannot get the order right

AirlineRepository

public interface AirlineRepository extends JpaRepository<Airline, Integer> {
    Airline getById(Integer id);

    List<Airline> findByDescriptionContainingIgnoreCase(String description, Pageable pageable);
    List<Airline> findByDescriptionStartsWithIgnoreCase(String description, Pageable pageable);
}

If I search the keyword 'ala' all airlines whose name starts with 'ala' should come first.

This is what I get

{
  "status": "SUCCESS",
  "message": "Execution Successful",
  "totalCount": 10,
  "content": [
    {
      "id": 962,
      "code": "6T",
      "description": "Air Mandalay"
    },
    {
      "id": 46,
      "code": "NZ",
      "description": "Air New Zealand"
    },
    {
      "id": 18,
      "code": "AS",
      "description": "Alaska Airlines"
    },
    {
      "id": 519,
      "code": "KO",
      "description": "Alaska Central Express"
    },
    {
      "id": 477,
      "code": "J5",
      "description": "Alaska Seaplane"
    },
    {
      "id": 30,
      "code": "YZ",
      "description": "ALAS URUGUAY"
    },
    {
      "id": 324,
      "code": "C9",
      "description": "Alphaland Aviation"
    },
    {
      "id": 286,
      "code": "A7",
      "description": "Calafia Airlines"
    },
    {
      "id": 330,
      "code": "CE",
      "description": "Chalair"
    },
    {
      "id": 521,
      "code": "L3",
      "description": "DHL de Guatemala"
    }
  ],
  "timestamp": null
}````

Body:
i'm not quite sure if i understood your requirement completly.

To fetch all airlines in an ordered way i would add the following method to the AirlineRepository

List<Airline> findByDescriptionStartsWithIgnoreCaseOrderByDescriptionAsc(String description, Pageable pageable);

If you also need all other airlines i would add this method, too.

List<Airline> findByDescriptionNotLikeIgnoreCaseOrderByDescriptionAsc(String description, Pageable pageable);

Add an '%' to the description and combine both lists.


来源: stackexchange

问:
Android M Light and Dark status bar programmatically - how to make it dark again?
In the Android M we have ability to make status bar icons dark. To do that we can specify attribute in the theme's xml:

```<code><item name="android:windowLightStatusBar">true</item>
</code>```

OR we cat set it at runtime with this code:

```<code>View someView = findViewById(R.id.some_view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    someView.setSystemUiVisibility(someView.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
</code>```

And it actually works fine. But question is how to properly set a status bar mode to dark at runtime?

I already tried these variants:

```<code>// Makes status bar mode dark, but also hides it along with all navigation views.
someView.setSystemUiVisibility(someView.getSystemUiVisibility() | ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

// Does nothing
someView.setSystemUiVisibility(someView.getSystemUiVisibility() & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

// Also does nothing
someView.setSystemUiVisibility(someView.getSystemUiVisibility() ^ View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
</code>```

So how it can be done the right way?

答:
systemUiVisibility - is deprecated now. You can use WindowInsetsControllerCompat instead.

private val insetsController: WindowInsetsControllerCompat? by lazy {
    activity?.window?.let { window -> WindowInsetsControllerCompat(window, window.decorView) }
}

private fun setLightStatusBar(light: Boolean) {
    insetsController?.isAppearanceLightStatusBars = light
}
```
<p><strong>UPD</strong>:
Above constructor for <code>WindowInsetsControllerCompat</code> is deprecated, so use the following instantiation instead:</p>
<pre class="lang-kotlin prettyprint-override"><code>private val insetsController: WindowInsetsControllerCompat? by lazy {
    activity?.window?.decorView?.let(ViewCompat::getWindowInsetsController)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In the Android M we have ability to make status bar icons dark. To do that we can specify attribute in the theme's xml:

<item name="android:windowLightStatusBar">true</item>

OR we cat set it at runtime with this code:

View someView = findViewById(R.id.some_view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    someView.setSystemUiVisibility(someView.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}

And it actually works fine. But question is how to properly set a status bar mode to dark at runtime?

I already tried these variants:

// Makes status bar mode dark, but also hides it along with all navigation views.
someView.setSystemUiVisibility(someView.getSystemUiVisibility() | ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

// Does nothing
someView.setSystemUiVisibility(someView.getSystemUiVisibility() & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

// Also does nothing
someView.setSystemUiVisibility(someView.getSystemUiVisibility() ^ View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

So how it can be done the right way?

Body:
systemUiVisibility - is deprecated now. You can use WindowInsetsControllerCompat instead.

private val insetsController: WindowInsetsControllerCompat? by lazy {
    activity?.window?.let { window -> WindowInsetsControllerCompat(window, window.decorView) }
}

private fun setLightStatusBar(light: Boolean) {
    insetsController?.isAppearanceLightStatusBars = light
}

UPD:
Above constructor for WindowInsetsControllerCompat is deprecated, so use the following instantiation instead:

private val insetsController: WindowInsetsControllerCompat? by lazy {
    activity?.window?.decorView?.let(ViewCompat::getWindowInsetsController)
}


问:
Give multiple permissions to a role - Spatie
How can we assign multiple permissions to a single role at once?

```<code>    $permission1 = Permission::create(['name' => 'Create Client']);
    $permission2 = Permission::create(['name' => 'View Invoice']);
    $permission3 = Permission::create(['name' => 'Add Product']);

    $role = Role::findById(1);

    $role->givePermissionTo($permission1);
</code>```

In above, I'm only giving permission to the first one.

As this is also achived by,   $role->syncPermissions($permissions);  Im confused how $permission includes multiple permissions?

Any advice please?

答:
hello my suggestion is to use

$role = Role::findById(1);
$role->givePermissionTo(Permission::all());

Body:
How can we assign multiple permissions to a single role at once?

    $permission1 = Permission::create(['name' => 'Create Client']);
    $permission2 = Permission::create(['name' => 'View Invoice']);
    $permission3 = Permission::create(['name' => 'Add Product']);

    $role = Role::findById(1);

    $role->givePermissionTo($permission1);

In above, I'm only giving permission to the first one.

As this is also achived by,   $role->syncPermissions($permissions);  Im confused how $permission includes multiple permissions?

Any advice please?


问:
Make an image look like it is placed over 2
 boxes with CSS

Hello I need to position an image as in the example. Theoretically it looks like it is positioned over 2 seperate  boxes with different background colors, that is the goal, but practically it is not possible, at least for me. How to solve the problem?

答:
Usually you'd do this with flex and vertical alignment, but since you want specifically the image to be between boxes i'd say absolute is the way to go here

.card {
    display: block;
    margin-left: 80px; /* image width + 20px */
}

.header, .image-container {
    display: block;
    margin: 0;
}

.header h1 {
  margin: 0;
}

.image-container {
  height: 1px;
  position: relative;
}

.image-container .image {
  display; inlnie-block;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: purple;
  position: absolute;
  top: -50%;
  left: -10px;
  transform: translateY(-50%) translateX(-100%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card">
  <div class="header">
    <h1>Header</h1>
  </div>
  <div class="image-container">
    <div class="image"></div>
  </div>
  <div class="header">
    <h1>Header 2</h1>
  </div>
</div></code>```

Title: Make an image look like it is placed over 2 <div> boxes with CSS

Body:
Usually you'd do this with flex and vertical alignment, but since you want specifically the image to be between boxes i'd say absolute is the way to go here

.card {
    display: block;
    margin-left: 80px; /* image width + 20px */
}

.header, .image-container {
    display: block;
    margin: 0;
}

.header h1 {
  margin: 0;
}

.image-container {
  height: 1px;
  position: relative;
}

.image-container .image {
  display; inlnie-block;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: purple;
  position: absolute;
  top: -50%;
  left: -10px;
  transform: translateY(-50%) translateX(-100%);
}

<div class="card">
  <div class="header">
    <h1>Header</h1>
  </div>
  <div class="image-container">
    <div class="image"></div>
  </div>
  <div class="header">
    <h1>Header 2</h1>
  </div>
</div>


问:
Google Script subtract an entire column from the other
So I'm currently working on a meal planner that looks at my current inventory of ingredients and then looks through the recipes in the spreadsheet to determine what I do/don't need to make those recipes that week and then returns a shopping list. I want to add a button to update that inventory by adding the ingredients from the shopping list. I have the values set up in different columns, but I can't figure out the code to add the values respectively. I have never done any coding, so this is based off of what I found on Google. Here's the code I currently have:

```<code>function AddtoInventory() {

var ss = SpreadsheetApp.getActiveSheet();
  var num1 = ss.getRange('AA3:AA').getValue();
  var num2 = ss.getRange('E3:E').getValue();
  ss.getRange('E3:E').setValue(num1+num2);

}
</code>```

But this just adds the first set of values (AA3+E3) and changes the current inventory for every ingredient to that same value. I want it to add AA3+E3 and change the value of E3 to that sum and then AA4+E4 and change the value of E4 to that sum and so on if that makes sense.

答:
Subtract and entire column

```<code>function AddtoInventory() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  let col27 = sh.getRange(3, 27, sh.getLastRow() - 2).getValues();
  let col5 = sh.getRange(3, 5, sh.getLastRow() - 2).getValues();
  col5.forEach((r, i) => {
    r[0] -= col27[i][0];
  });
  sh.getRange(3, 5, col5.length, col5[0].length).setValues(col5);
}
</code>```

Body:
So I'm currently working on a meal planner that looks at my current inventory of ingredients and then looks through the recipes in the spreadsheet to determine what I do/don't need to make those recipes that week and then returns a shopping list. I want to add a button to update that inventory by adding the ingredients from the shopping list. I have the values set up in different columns, but I can't figure out the code to add the values respectively. I have never done any coding, so this is based off of what I found on Google. Here's the code I currently have:

function AddtoInventory() {

var ss = SpreadsheetApp.getActiveSheet();
  var num1 = ss.getRange('AA3:AA').getValue();
  var num2 = ss.getRange('E3:E').getValue();
  ss.getRange('E3:E').setValue(num1+num2);

}

But this just adds the first set of values (AA3+E3) and changes the current inventory for every ingredient to that same value. I want it to add AA3+E3 and change the value of E3 to that sum and then AA4+E4 and change the value of E4 to that sum and so on if that makes sense.

Body:
Subtract and entire column

function AddtoInventory() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  let col27 = sh.getRange(3, 27, sh.getLastRow() - 2).getValues();
  let col5 = sh.getRange(3, 5, sh.getLastRow() - 2).getValues();
  col5.forEach((r, i) => {
    r[0] -= col27[i][0];
  });
  sh.getRange(3, 5, col5.length, col5[0].length).setValues(col5);
}


问:
stored procedure with dynamic view doesn't refresh number of fields
I'm going crazy with this stored procedure.
I post the complete dump hoping someone could explain my mistake.

```<code>drop table if exists questions;

create table questions (
id int not null auto_increment primary key,
description varchar(200)
) engine = myisam;

insert into questions (description)
values
('Question 1'),
('Question 2'),
('Question 3');

drop table if exists answers;

create table answers (
id int not null auto_increment primary key,
question_id int,
description varchar(10)
) engine = myisam;

insert into answers (question_id,description)
values
(1,'no'),
(1,'no'),
(1,'yes'),
(1,'no'),
(1,'yes'),
(2,'no'),
(2,'yes'),
(2,'yes'),
(2,'yes'),
(2,'no'),
(2,'no'),
(2,'no'),
(2,'yes'),
(2,'no'),
(3,'no'),
(3,'no'),
(3,'no'),
(3,'yes');
</code>```

This is my stored procedure:

```<code>delimiter //
drop procedure if exists dynamic_view //
create procedure dynamic_view()
begin
declare cnt int default 0;
declare finito int default 0;
declare qid int;
declare qdescription varchar(100);
declare qanswer varchar(100);
declare i int default 1;
declare j int;
declare str varchar(20000) default '';
declare str2 varchar(20000);
declare str3 varchar(20000);
declare curs1 cursor for select id,description from questions order by id;
declare curs2 cursor for select description from answers where question_id = qid;
declare continue handler for not found set finito = 1;
-- drop table if exists tmp;
select count(*) as num into @cnt from answers group by question_id order by num desc limit 1;
drop table if exists tmp;
while i <= @cnt do
    set str = concat(str,'answer',i,' varchar(10),');
    set i = i + 1;
end while;
set str = substr(str,1,char_length(str)-1);
set @str = concat('create temporary table tmp (id int,question varchar(200),',str,');');
prepare stmt from @str;
execute stmt;
deallocate prepare stmt;
open curs1;
mio_loop:loop
fetch curs1 into qid,qdescription;
if finito = 1 then
close curs1;
leave mio_loop;
end if;
open curs2;
set str2 = 'insert into tmp (id,question,';
set j = 1;
set str3 = '';
mio_loop2:loop
fetch curs2 into qanswer;
if finito = 1 then set finito = 0;
    close curs2;
    leave mio_loop2;
end if;
set str2 = concat(str2,'answer',j,',');
set str3 = concat(str3,"'",qanswer,"',");
set j = j + 1;
end loop mio_loop2;
set str2 = substr(str2,1,char_length(str2)-1);
set str3 = substr(str3,1,char_length(str3)-1);
set @str2 = concat(str2,') values (',qid,",'",qdescription,"',",str3,');');
prepare stmt from @str2;
execute stmt;
deallocate prepare stmt;
end loop mio_loop;
select * from tmp;
end; //
delimiter ;
</code>```

and when i call it I get this output

```<code>mysql> call dynamic_view();
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+---------+
| id   | question   | answer1 | answer2 | answer3 | answer4 | answer5 | answer6 | answer7 | answer8 | answer9 |
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+---------+
|    1 | Question 1 | no      | no      | yes     | no      | yes     | NULL    | NULL    | NULL    | NULL    |
|    2 | Question 2 | no      | yes     | yes     | yes     | no      | no      | no      | yes     | no      |
|    3 | Question 3 | no      | no      | no      | yes     | NULL    | NULL    | NULL    | NULL    | NULL    |
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+---------+
3 rows in set (0.23 sec)
</code>```

Now let's suppose that I delete a record that has question_id = 2.
This is the id that has the maximum number of records, that is 9. If I delete it the records become 8, so last column MUST disappeared.

```<code>delete from answers where id = 14;
</code>```

If I recall my sp I get this error:

```<code>Error Code : 1054
Unknown column 'pivot.tmp.answer9' in 'field list'
</code>```

However, if I execute again the whole code of the stored procedure and then I recall it I get the correct result:

```<code>mysql> call dynamic_view();
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+
| id   | question   | answer1 | answer2 | answer3 | answer4 | answer5 | answer6 | answer7 | answer8 |
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+
|    1 | Question 1 | no      | no      | yes     | no      | yes     | NULL    | NULL    | NULL    |
|    2 | Question 2 | no      | yes     | yes     | yes     | no      | no      | no      | yes     |
|    3 | Question 3 | no      | no      | no      | yes     | NULL    | NULL    | NULL    | NULL    |
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+
3 rows in set (0.19 sec)
</code>```

I can't understand why since I drop the temporary table. Thanks in advance.
edit. I wanted to start a bounty but I don't find the button. :)

I've just read on meta that I can start a bounty only after two days. Never noted it. Hope someone could help me the same :)

答:
Once I saw similar question. Have a look at this link - unable to add columns dynamically to table using alter

Nick, I'd suggest you to use prepared statement to output data from temporary table (...this table was created with prepared statement in the SP, and this looks like a bug - SELECT * inside PROCEDURE gives "Unknown column" on second loop if tbl changed).

Just change last line -

```<code>select * from tmp';
</code>```

with this code -

```<code>PREPARE stmt FROM 'select * from tmp';
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm going crazy with this stored procedure.
I post the complete dump hoping someone could explain my mistake.

drop table if exists questions;

create table questions (
id int not null auto_increment primary key,
description varchar(200)
) engine = myisam;

insert into questions (description)
values
('Question 1'),
('Question 2'),
('Question 3');

drop table if exists answers;

create table answers (
id int not null auto_increment primary key,
question_id int,
description varchar(10)
) engine = myisam;

insert into answers (question_id,description)
values
(1,'no'),
(1,'no'),
(1,'yes'),
(1,'no'),
(1,'yes'),
(2,'no'),
(2,'yes'),
(2,'yes'),
(2,'yes'),
(2,'no'),
(2,'no'),
(2,'no'),
(2,'yes'),
(2,'no'),
(3,'no'),
(3,'no'),
(3,'no'),
(3,'yes');

This is my stored procedure:

delimiter //
drop procedure if exists dynamic_view //
create procedure dynamic_view()
begin
declare cnt int default 0;
declare finito int default 0;
declare qid int;
declare qdescription varchar(100);
declare qanswer varchar(100);
declare i int default 1;
declare j int;
declare str varchar(20000) default '';
declare str2 varchar(20000);
declare str3 varchar(20000);
declare curs1 cursor for select id,description from questions order by id;
declare curs2 cursor for select description from answers where question_id = qid;
declare continue handler for not found set finito = 1;
-- drop table if exists tmp;
select count(*) as num into @cnt from answers group by question_id order by num desc limit 1;
drop table if exists tmp;
while i <= @cnt do
    set str = concat(str,'answer',i,' varchar(10),');
    set i = i + 1;
end while;
set str = substr(str,1,char_length(str)-1);
set @str = concat('create temporary table tmp (id int,question varchar(200),',str,');');
prepare stmt from @str;
execute stmt;
deallocate prepare stmt;
open curs1;
mio_loop:loop
fetch curs1 into qid,qdescription;
if finito = 1 then
close curs1;
leave mio_loop;
end if;
open curs2;
set str2 = 'insert into tmp (id,question,';
set j = 1;
set str3 = '';
mio_loop2:loop
fetch curs2 into qanswer;
if finito = 1 then set finito = 0;
    close curs2;
    leave mio_loop2;
end if;
set str2 = concat(str2,'answer',j,',');
set str3 = concat(str3,"'",qanswer,"',");
set j = j + 1;
end loop mio_loop2;
set str2 = substr(str2,1,char_length(str2)-1);
set str3 = substr(str3,1,char_length(str3)-1);
set @str2 = concat(str2,') values (',qid,",'",qdescription,"',",str3,');');
prepare stmt from @str2;
execute stmt;
deallocate prepare stmt;
end loop mio_loop;
select * from tmp;
end; //
delimiter ;

and when i call it I get this output

mysql> call dynamic_view();
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+---------+
| id   | question   | answer1 | answer2 | answer3 | answer4 | answer5 | answer6 | answer7 | answer8 | answer9 |
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+---------+
|    1 | Question 1 | no      | no      | yes     | no      | yes     | NULL    | NULL    | NULL    | NULL    |
|    2 | Question 2 | no      | yes     | yes     | yes     | no      | no      | no      | yes     | no      |
|    3 | Question 3 | no      | no      | no      | yes     | NULL    | NULL    | NULL    | NULL    | NULL    |
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+---------+
3 rows in set (0.23 sec)

Now let's suppose that I delete a record that has question_id = 2.
This is the id that has the maximum number of records, that is 9. If I delete it the records become 8, so last column MUST disappeared.

delete from answers where id = 14;

If I recall my sp I get this error:

Error Code : 1054
Unknown column 'pivot.tmp.answer9' in 'field list'

However, if I execute again the whole code of the stored procedure and then I recall it I get the correct result:

mysql> call dynamic_view();
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+
| id   | question   | answer1 | answer2 | answer3 | answer4 | answer5 | answer6 | answer7 | answer8 |
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+
|    1 | Question 1 | no      | no      | yes     | no      | yes     | NULL    | NULL    | NULL    |
|    2 | Question 2 | no      | yes     | yes     | yes     | no      | no      | no      | yes     |
|    3 | Question 3 | no      | no      | no      | yes     | NULL    | NULL    | NULL    | NULL    |
+------+------------+---------+---------+---------+---------+---------+---------+---------+---------+
3 rows in set (0.19 sec)

I can't understand why since I drop the temporary table. Thanks in advance.
edit. I wanted to start a bounty but I don't find the button. :)

I've just read on meta that I can start a bounty only after two days. Never noted it. Hope someone could help me the same :)

Body:
Once I saw similar question. Have a look at this link - unable to add columns dynamically to table using alter

Nick, I'd suggest you to use prepared statement to output data from temporary table (...this table was created with prepared statement in the SP, and this looks like a bug - SELECT * inside PROCEDURE gives "Unknown column" on second loop if tbl changed).

Just change last line -

select * from tmp';

with this code -

PREPARE stmt FROM 'select * from tmp';
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


问:
Getting Consent from DocuSign in a Console App context
I am struggling to get access tokens from .net console app context. I am getting them and they work, but they expire too fast.

I checked the other two threads in stackoverflow, in both answers it was stated, that once you get the consent per IK and per user, you don't have to do it anymore. However once I get the bearer token from the return_url and use it to request the access tokens a few minutes after the bearer was obtained, I get response with "error_description:expired_client_token".

So me manually obtaining bearer from the browser in order to set it as a parameter (again manually) in my console app and having the bearer expiration duration just a few minutes doesn't match "Consent is needed only once, ever, per a specific integration and a user".
I see that docusign uses cookies' values/expiration and can probably reverse engineer a GET call to account-d.docusign to get the bearer from the console app context, but that's not what I'd expect from an API provider.

For reference I'm using the following URL to manually get the bearer from the browser:
https://account-d.docusign.com/oauth/auth?response_type=code&scope=signature&client_id=d69848a8-2a93-4d03-ab40-bcabda8a7e8f&redirect_uri=https://www.docusign.com
But as stated above, it does expire in a few mins to get the aforementioned error_description
Thank you in advance!

答:
Response type = code is the Authorization Code grant flow.

But for a console app where the implementation of the application is downloaded to the user's machine, the Implicit grant flow must be used.

This is because the Authorization Code grant flow includes a second API call, from the app to the OAuth Service Provider. This second call is used to exchange the authorization code for an access token. This second call requires a secret value, but there is no guaranteed method for keeping a secret in an app that's downloaded to the user's machine.

The Implicit grant flow immediately returns the access token to your app for use in calling the API.

Using the Implicit grant with a console app

Here are the steps. I also discuss this use case in my Electron React apps post.

The key is to use Private-Use URI Scheme Redirection to handle the authentication and receive the resulting access token. See RFC 8252 §7.1

Your app registers a http private scheme such as com.example.name_of_my_app with the operating system (windows). This way, any URL like com.example.name_of_my_app://app will be directed to your application to be processed.

Configure your DocuSign client id (integration key) to enable implicit grant and to use com.example.name_of_my_app://app as a return URL. No secret is needed.

When a user wants to authenticate with DocuSign via your app:

Your app initiates the implicit grant flow with the DocuSign OAuth Service Provider by "opening" the URL

```<code>https://account-d.docusign.com/oauth/auth?response_type=token&
    scope=signature&client_id=xxxx-xxxx&
    redirect_uri=com.example.name_of_my_app://app
</code>```

Windows should open the default browser to the URL. The result will be the authentication page from DocuSign. Your app should NOT open a web view or similar. The operating system's browser should be automatically activated.

After the authentication is done, consent will be requested if needed.

Next, DocuSign will respond to the browser with a redirect to the redirect_uri. This will trigger your application and give your application the access token needed for API calls to DocuSign.

For some operating systems, your app can close the browser window that was created as a result of its URL open.

See the blog post for more info.

Added

As Ben says, your specific problem is that the authorization code that you receive back in the first step of the Authorization Code grant flow only lasts a minute or so. During that time, you exchange it for an access token (which lasts for 8 hours). But as I say above, you should not be using the authorization code grant flow, you should be using the implicit grant flow.

Body:
Response type = code is the Authorization Code grant flow.

But for a console app where the implementation of the application is downloaded to the user's machine, the Implicit grant flow must be used.

This is because the Authorization Code grant flow includes a second API call, from the app to the OAuth Service Provider. This second call is used to exchange the authorization code for an access token. This second call requires a secret value, but there is no guaranteed method for keeping a secret in an app that's downloaded to the user's machine.

The Implicit grant flow immediately returns the access token to your app for use in calling the API.

Using the Implicit grant with a console app

Here are the steps. I also discuss this use case in my Electron React apps post.

The key is to use Private-Use URI Scheme Redirection to handle the authentication and receive the resulting access token. See RFC 8252 §7.1

Your app registers a http private scheme such as com.example.name_of_my_app with the operating system (windows). This way, any URL like com.example.name_of_my_app://app will be directed to your application to be processed.

Configure your DocuSign client id (integration key) to enable implicit grant and to use com.example.name_of_my_app://app as a return URL. No secret is needed.

When a user wants to authenticate with DocuSign via your app:

Your app initiates the implicit grant flow with the DocuSign OAuth Service Provider by "opening" the URL

https://account-d.docusign.com/oauth/auth?response_type=token&
    scope=signature&client_id=xxxx-xxxx&
    redirect_uri=com.example.name_of_my_app://app

Windows should open the default browser to the URL. The result will be the authentication page from DocuSign. Your app should NOT open a web view or similar. The operating system's browser should be automatically activated.

After the authentication is done, consent will be requested if needed.

Next, DocuSign will respond to the browser with a redirect to the redirect_uri. This will trigger your application and give your application the access token needed for API calls to DocuSign.

For some operating systems, your app can close the browser window that was created as a result of its URL open.

See the blog post for more info.

Added

As Ben says, your specific problem is that the authorization code that you receive back in the first step of the Authorization Code grant flow only lasts a minute or so. During that time, you exchange it for an access token (which lasts for 8 hours). But as I say above, you should not be using the authorization code grant flow, you should be using the implicit grant flow.


问:
Pygame draw multiple/duplicate sprites same class
The Problem:
I want to add the exact same Sprite (it's a 25x25 white box) behind another one

the Sprite starts off at x,y 300,300
I have key functions that allow the Sprite to move in any direction

Let's say, that I move my Sprite to x,y 150,210... how do I grab that NEW position of that original Sprite, and then draw a copy of that Sprite directly "behind" that Sprites new position of x,y 150,210?

The end result is:

there are TWO 25x25 squares together.

On keypress, the two squares should always stay together. The "TWO" could be 10 or 20 or 40 squares at any point

I do not want to increase the height of the sprite as a solution, I explicitly want a copy of the sprite

Please let me know if this question requires better context etc.
Thanks in advance

Minimal reproducible example

```<code>import pygame
from random import randint
from sys import exit

pygame.init()
game_active = True
clock = pygame.time.Clock() #an object to track time

def display_surface():
    disp_surface = pygame.display.set_mode(size = (610, 700))
    return disp_surface
disp_surface = display_surface()

class square(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        image1 = pygame.image.load("square1.png").convert_alpha()
        x_pos = 300
        y_pos = 300

        self.image = image1
        self.rect = self.image.get_rect(x = x_pos,y = y_pos)

squaregroup = pygame.sprite.GroupSingle()
squaregroup.add(square())

while True:
    for eachevent in pygame.event.get():
        if eachevent.type == pygame.QUIT:
            pygame.quit()
            exit()

        if eachevent.type == pygame.KEYDOWN and eachevent.key == pygame.K_SPACE:
            game_active = True

        keys = pygame.key.get_pressed()
        events = pygame.event.get()

        left = keys[pygame.K_LEFT]
        right = keys[pygame.K_RIGHT]
        up = keys[pygame.K_UP]
        down = keys[pygame.K_DOWN]

        if left:
            squaregroup.sprite.rect.x -= 1
        if right:
            squaregroup.sprite.rect.x += 1
        if up:
            squaregroup.sprite.rect.y -= 1
        if down:
            squaregroup.sprite.rect.y += 1

    if game_active:
        disp_surface = display_surface()
        squaregroup.draw(disp_surface)

    else:
        disp_surface.fill((64,64,64))

    pygame.display.update()
    clock.tick(60)
</code>```

答:
here is one possible solution
i have created a pygame.sprite.group() instead of groupsingle()
and then added the squares there and it works fine
you can get more squares appear on the back by clicking space bar key and get the new x,y by original_sq.rect.x and original_sq.rect.y
moreover commenting line number 68 will show you how new square is created and displayed</p>
```<code>import pygame
from random import randint
from sys import exit

pygame.init()
game_active = True
clock = pygame.time.Clock() #an object to track time

def display_surface():
    disp_surface = pygame.display.set_mode(size = (610, 700))
    return disp_surface
disp_surface = display_surface()

class square(pygame.sprite.Sprite):
    def __init__(self,x_pos=300,y_pos=300,color=(255,0,0)):
        super().__init__()
        image1 = pygame.Surface([25,25])
        image1.fill((color))
        self.x_pos = x_pos
        self.y_pos = y_pos

        self.image = image1
        self.rect = self.image.get_rect(x = x_pos,y = y_pos)
    #this is just the same movements nothing new
    def update(self,left,right,up,down):
        if left:
            self.rect.left-=1
        if right:
            self.rect.right+=1
        if up:
            self.rect.top-=1
        if down:
            self.rect.bottom+=1

squaregroup = pygame.sprite.Group()
original_sq=square()
squaregroup.add(original_sq)
while True:
    for eachevent in pygame.event.get():
        if eachevent.type == pygame.QUIT:
            pygame.quit()
            exit()

        if eachevent.type == pygame.KEYDOWN and eachevent.key == pygame.K_SPACE:
            game_active = True

            # this line add a rect above all the rects but the original is still on top of that because of draw
            squaregroup.add(square(original_sq.rect.x,original_sq.rect.y,(original_sq.rect.x%255,original_sq.rect.x%255,original_sq.rect.y%255)))
            #squaregroup.add(square(original_sq.rect.x,original_sq.rect.y))

            #this shows that there are actually some squares dwarn behind the original_sq
            print(len(squaregroup))
        keys = pygame.key.get_pressed()
        events = pygame.event.get()

        left = keys[pygame.K_LEFT]
        right = keys[pygame.K_RIGHT]
        up = keys[pygame.K_UP]
        down = keys[pygame.K_DOWN]

        squaregroup.update(left,right,up,down)

    if game_active:
        disp_surface = display_surface()
        squaregroup.draw(disp_surface)

        #comment the bellow line to remove the original square and then you will be able to see different color square when you move and press space because the new rect created by pressing spacebar is on top
        pygame.draw.rect(disp_surface,(255,255,255),original_sq)
    else:
        disp_surface.fill((64,64,64))

    pygame.display.update()
    clock.tick(60)
</code>```

Body:
The Problem:
I want to add the exact same Sprite (it's a 25x25 white box) behind another one

the Sprite starts off at x,y 300,300
I have key functions that allow the Sprite to move in any direction

Let's say, that I move my Sprite to x,y 150,210... how do I grab that NEW position of that original Sprite, and then draw a copy of that Sprite directly "behind" that Sprites new position of x,y 150,210?

The end result is:

there are TWO 25x25 squares together.

On keypress, the two squares should always stay together. The "TWO" could be 10 or 20 or 40 squares at any point

I do not want to increase the height of the sprite as a solution, I explicitly want a copy of the sprite

Please let me know if this question requires better context etc.
Thanks in advance

Minimal reproducible example

import pygame
from random import randint
from sys import exit

pygame.init()
game_active = True
clock = pygame.time.Clock() #an object to track time

def display_surface():
    disp_surface = pygame.display.set_mode(size = (610, 700))
    return disp_surface
disp_surface = display_surface()

class square(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        image1 = pygame.image.load("square1.png").convert_alpha()
        x_pos = 300
        y_pos = 300

        self.image = image1
        self.rect = self.image.get_rect(x = x_pos,y = y_pos)

squaregroup = pygame.sprite.GroupSingle()
squaregroup.add(square())

while True:
    for eachevent in pygame.event.get():
        if eachevent.type == pygame.QUIT:
            pygame.quit()
            exit()

        if eachevent.type == pygame.KEYDOWN and eachevent.key == pygame.K_SPACE:
            game_active = True

        keys = pygame.key.get_pressed()
        events = pygame.event.get()

        left = keys[pygame.K_LEFT]
        right = keys[pygame.K_RIGHT]
        up = keys[pygame.K_UP]
        down = keys[pygame.K_DOWN]

        if left:
            squaregroup.sprite.rect.x -= 1
        if right:
            squaregroup.sprite.rect.x += 1
        if up:
            squaregroup.sprite.rect.y -= 1
        if down:
            squaregroup.sprite.rect.y += 1

    if game_active:
        disp_surface = display_surface()
        squaregroup.draw(disp_surface)

    else:
        disp_surface.fill((64,64,64))

    pygame.display.update()
    clock.tick(60)

Body:
here is one possible solution
i have created a pygame.sprite.group() instead of groupsingle()
and then added the squares there and it works fine
you can get more squares appear on the back by clicking space bar key and get the new x,y by original_sq.rect.x and original_sq.rect.y
moreover commenting line number 68 will show you how new square is created and displayed

import pygame
from random import randint
from sys import exit

pygame.init()
game_active = True
clock = pygame.time.Clock() #an object to track time

def display_surface():
    disp_surface = pygame.display.set_mode(size = (610, 700))
    return disp_surface
disp_surface = display_surface()

class square(pygame.sprite.Sprite):
    def __init__(self,x_pos=300,y_pos=300,color=(255,0,0)):
        super().__init__()
        image1 = pygame.Surface([25,25])
        image1.fill((color))
        self.x_pos = x_pos
        self.y_pos = y_pos

        self.image = image1
        self.rect = self.image.get_rect(x = x_pos,y = y_pos)
    #this is just the same movements nothing new
    def update(self,left,right,up,down):
        if left:
            self.rect.left-=1
        if right:
            self.rect.right+=1
        if up:
            self.rect.top-=1
        if down:
            self.rect.bottom+=1

squaregroup = pygame.sprite.Group()
original_sq=square()
squaregroup.add(original_sq)
while True:
    for eachevent in pygame.event.get():
        if eachevent.type == pygame.QUIT:
            pygame.quit()
            exit()

        if eachevent.type == pygame.KEYDOWN and eachevent.key == pygame.K_SPACE:
            game_active = True

            # this line add a rect above all the rects but the original is still on top of that because of draw
            squaregroup.add(square(original_sq.rect.x,original_sq.rect.y,(original_sq.rect.x%255,original_sq.rect.x%255,original_sq.rect.y%255)))
            #squaregroup.add(square(original_sq.rect.x,original_sq.rect.y))

            #this shows that there are actually some squares dwarn behind the original_sq
            print(len(squaregroup))
        keys = pygame.key.get_pressed()
        events = pygame.event.get()

        left = keys[pygame.K_LEFT]
        right = keys[pygame.K_RIGHT]
        up = keys[pygame.K_UP]
        down = keys[pygame.K_DOWN]

        squaregroup.update(left,right,up,down)

    if game_active:
        disp_surface = display_surface()
        squaregroup.draw(disp_surface)

        #comment the bellow line to remove the original square and then you will be able to see different color square when you move and press space because the new rect created by pressing spacebar is on top
        pygame.draw.rect(disp_surface,(255,255,255),original_sq)
    else:
        disp_surface.fill((64,64,64))

    pygame.display.update()
    clock.tick(60)


问:
Zip multiple arrays in PHP based on their identical keys and not their indices or their positions in array
I have two arrays:

```<code>$a = ['one'=>1,'two'=> 2,'three'=> 3,'four'=> 4,'five'=> 5, 'six' => 6];
$b = ['one'=>'uno', 'three'=>'tres','two'=> 'dos', 'four'=>'cuatro', 'five'=>'cinco'];
</code>```

note that in $b Array 'three' and 'two' keys are not in same order as $a. also 'six' key is not available in $b Array.

I want this result as output:

```<code>Array
(
    [0] => Array
        (
            [0] => 1
            [1] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => cinco
        )

)
</code>```

I tried to use array_map but it don't detect keys and just zip them based of their indices:

```<code>$d = array_map(null, $a, $b);
</code>```

答:
modified ikhvjs answer (when keys in both arrays are not same as each others):</p>
```<code>$a = ['one' => 1, 'two' => 2, 'four' => 4, 'five' => 5, 'six' => 6];
$b = ['one' => 'uno', 'three' => 'tres', 'two' => 'dos', 'four' => 'cuatro', 'five' => 'cinco'];
$r=array_intersect_key($a,$b);
$output = [];
foreach ($r as $key => $value) {
    $output[] = [$value,  $b[$key]];
}
echo "```";
print_r($output);
echo "```";
</code>```

Body:
I have two arrays:

$a = ['one'=>1,'two'=> 2,'three'=> 3,'four'=> 4,'five'=> 5, 'six' => 6];
$b = ['one'=>'uno', 'three'=>'tres','two'=> 'dos', 'four'=>'cuatro', 'five'=>'cinco'];

note that in $b Array 'three' and 'two' keys are not in same order as $a. also 'six' key is not available in $b Array.

I want this result as output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => cinco
        )

)

I tried to use array_map but it don't detect keys and just zip them based of their indices:

$d = array_map(null, $a, $b);

Body:
modified ikhvjs answer (when keys in both arrays are not same as each others):

$a = ['one' => 1, 'two' => 2, 'four' => 4, 'five' => 5, 'six' => 6];
$b = ['one' => 'uno', 'three' => 'tres', 'two' => 'dos', 'four' => 'cuatro', 'five' => 'cinco'];
$r=array_intersect_key($a,$b);
$output = [];
foreach ($r as $key => $value) {
    $output[] = [$value,  $b[$key]];
}
echo "<pre>";
print_r($output);
echo "</pre>";


问:
IE9 svg onload accessing parent/top
in IE9, when a SVG is embedded using (object) tags, any ECMAScript embedded inside the SVG cannot access the parent / top HTML document. this works for any other browser, though.
developing using linux only i never realized that until today. the problem is, all our SVGs contain a onload method to signal to the parent HTML document that the SVG DOM is ready. unfortunately, there is no other way to determine whether the SVG's DOM is ready except for polling which i consider highly inelegant.
so ... is there any known workaround for this? that is, access the parent HTML document from within a SVG in IE9?
or any other cross-browser / cross plattform method to determine whether a SVG is completely loaded which does NOT involve polling and timeouts but callbacks?
i'd rather not use a fully blown framework for this like the jQuery SVG plugin.</p>

答:
ok. after a sleepless night i finally figured it out. without any instructions IE9 seems to render pages in Quirks mode. when in Quirks mode SVGs are obviously sandboxed and any ECMAScript inside the SVG cannot access the parent document.

whenever IE9 is forced to actually render a page using IE9 standards everything works like a charm.

use

```<code><meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</code>```

to force IE9 standard mode

Title: IE9 svg onload accessing parent/top

Body:
ok. after a sleepless night i finally figured it out. without any instructions IE9 seems to render pages in Quirks mode. when in Quirks mode SVGs are obviously sandboxed and any ECMAScript inside the SVG cannot access the parent document.

whenever IE9 is forced to actually render a page using IE9 standards everything works like a charm.

use

<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

to force IE9 standard mode


问:
Vim: how to remap a "general" key
One thing I really like in Vim is it's hability to have multiple clipboards available. However I hate to write "ay to yank and "ap to paste, I'd rather have something closer to the classical Ctrl-c, Ctrl-v, like ←a (←: AltGr + y) and þa (þ: AltGr + p).

I could make a remap like nnoremap ←a "ay in this case, but then I would only have the buffer "a" available to use this way. So the question is: could I make a remap such as nnoremap ←{key} "{key}y in vim, that would replace the {key} with whatever I typed, so that I could use any character as a register with only one remap? (←q becomes "qy, ←w becomes "wy, etc...)

Btw: yes, AltGr keys like "←" and "þ" works just like any other letter for commands.

答:
The left-hand side of a mapping can't be dynamic.

The easiest way to deal with that limitation is simply to loop through a list:

```<code>for reg in 'abcdefghijklmnopqrstuvwxyz'
    execute 'nnoremap ←' .. reg .. ' "' .. reg .. 'y'
    execute 'nnoremap þ' .. reg .. ' "' .. reg .. 'p'
endfor
</code>```

See :help :for, :help :execute, :help expr-...

Note that y is an operator and an operator is supposed to "operate" on a motion. This means that all those "{char}y normal mode mappings are useless. For this to actually be useful, you would need to:

make visual mode mappings for y,

make a custom operator for use in normal mode, see :help :map-operator.

Title: Vim: how to remap a "general" key

Body:
The left-hand side of a mapping can't be dynamic.

The easiest way to deal with that limitation is simply to loop through a list:

for reg in 'abcdefghijklmnopqrstuvwxyz'
    execute 'nnoremap ←' .. reg .. ' "' .. reg .. 'y'
    execute 'nnoremap þ' .. reg .. ' "' .. reg .. 'p'
endfor

See :help :for, :help :execute, :help expr-...

Note that y is an operator and an operator is supposed to "operate" on a motion. This means that all those "{char}y normal mode mappings are useless. For this to actually be useful, you would need to:

make visual mode mappings for y,

make a custom operator for use in normal mode, see :help :map-operator.


问:
CSS Grid not centering the top row
I have an issue with the top row in the following layout. It would not center and just stay on the left part of the two columns.

It need it to be on the center like the bottom part. The one on the bottom works fine at centering itself even though I used the same way via CSS Grid. Please check the image I attached.

#about-container {
  grid-area: first;
}

#ul-first {
  grid-area: second;
}

#ul-second {
  grid-area: third;
}

#ul-third {
  grid-area: fourth;
}

.footer-links {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas:
    "first first"
    "second third"
    "fourth fourth";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="footer-links">
  <div class="about-container">
    <div class="about">
      <h1>Title</h1>
      <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed, aperiam quaerat? Nam reprehenderit, amet minus illum natus facere accusamus aut voluptatem. Sapiente ipsa praesentium unde, voluptatem assumenda facilis asperiores eum!</p>
    </div>
  </div>
  <div class="list" id="ul-first">
    <ul>
      <li>Why Buy From Us</li>
      <li>Company Policy</li>
      <li>Maintenance</li>
      <li>Financing</li>
    </ul>
  </div>
  <div class="list" id="ul-second">
    <ul>
      <li>Request a Quote</li>
      <li>Get in Touch with Us</li>
      <li>Book Preventive Maintenance</li>
    </ul>
  </div>
  <div class="list" id="ul-third">
    <ul>
      <li>Nissan GT-R</li>
      <li>Mitsubishi Lancer</li>
      <li>Toyota Corolla Touring</li>
      <li>McLaren P1</li>
    </ul>
  </div>
</section></code>```

答:
First, there is an error in your code : in your CSS, you specify rules for the id : #about-container but it doesn't exist in your HTML (it's a class in there).

Second, your code doesn't yield the result you have in your image (it seems you are using the property text-align:center; that I can't ssee in the code you share).

To answer your question, you can center the first element by using : .about { width:50%; margin:0 auto; }
With your example, it would be (I also correted both errors I pointed out above) :

#about-container {
  grid-area: first;
}

.about {
  width: 50%;
  margin: 0 auto;
}

#ul-first {
  grid-area: second;
  text-align: center;
}

#ul-second {
  grid-area: third;
  text-align: center;
}

#ul-third {
  grid-area: fourth;
  text-align: center;
}

.footer-links {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas:
    "first first"
    "second third"
    "fourth fourth";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="footer-links">
  <div id="about-container">
    <div class="about">
      <h1>Title</h1>
      <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed, aperiam quaerat? Nam reprehenderit, amet minus illum natus facere accusamus aut voluptatem. Sapiente ipsa praesentium unde, voluptatem assumenda facilis asperiores eum!</p>
    </div>
  </div>
  <div class="list" id="ul-first">
    <ul>
      <li>Why Buy From Us</li>
      <li>Company Policy</li>
      <li>Maintenance</li>
      <li>Financing</li>
    </ul>
  </div>
  <div class="list" id="ul-second">
    <ul>
      <li>Request a Quote</li>
      <li>Get in Touch with Us</li>
      <li>Book Preventive Maintenance</li>
    </ul>
  </div>
  <div class="list" id="ul-third">
    <ul>
      <li>Nissan GT-R</li>
      <li>Mitsubishi Lancer</li>
      <li>Toyota Corolla Touring</li>
      <li>McLaren P1</li>
    </ul>
  </div>
</section></code>```

Title: CSS Grid not centering the top row

Body:
I have an issue with the top row in the following layout. It would not center and just stay on the left part of the two columns.

It need it to be on the center like the bottom part. The one on the bottom works fine at centering itself even though I used the same way via CSS Grid. Please check the image I attached.

#about-container {
  grid-area: first;
}

#ul-first {
  grid-area: second;
}

#ul-second {
  grid-area: third;
}

#ul-third {
  grid-area: fourth;
}

.footer-links {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas:
    "first first"
    "second third"
    "fourth fourth";
}

Title

 Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed, aperiam quaerat? Nam reprehenderit, amet minus illum natus facere accusamus aut voluptatem. Sapiente ipsa praesentium unde, voluptatem assumenda facilis asperiores eum!

Why Buy From Us

Company Policy

Maintenance

Financing

Request a Quote

Get in Touch with Us

Book Preventive Maintenance

Nissan GT-R

Mitsubishi Lancer

Toyota Corolla Touring

McLaren P1

Body:
First, there is an error in your code : in your CSS, you specify rules for the id : #about-container but it doesn't exist in your HTML (it's a class in there).

Second, your code doesn't yield the result you have in your image (it seems you are using the property text-align:center; that I can't ssee in the code you share).

To answer your question, you can center the first element by using : .about { width:50%; margin:0 auto; }
With your example, it would be (I also correted both errors I pointed out above) :

#about-container {
  grid-area: first;
}

.about {
  width: 50%;
  margin: 0 auto;
}

#ul-first {
  grid-area: second;
  text-align: center;
}

#ul-second {
  grid-area: third;
  text-align: center;
}

#ul-third {
  grid-area: fourth;
  text-align: center;
}

.footer-links {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas:
    "first first"
    "second third"
    "fourth fourth";
}

<section class="footer-links">
  <div id="about-container">
    <div class="about">
      <h1>Title</h1>
      <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed, aperiam quaerat? Nam reprehenderit, amet minus illum natus facere accusamus aut voluptatem. Sapiente ipsa praesentium unde, voluptatem assumenda facilis asperiores eum!</p>
    </div>
  </div>
  <div class="list" id="ul-first">
    <ul>
      <li><a href="#">Why Buy From Us</a></li>
      <li><a href="#">Company Policy</a></li>
      <li><a href="#">Maintenance</a></li>
      <li><a href="#">Financing</a></li>
    </ul>
  </div>
  <div class="list" id="ul-second">
    <ul>
      <li><a href="#">Request a Quote</a></li>
      <li><a href="#">Get in Touch with Us</a></li>
      <li><a href="#">Book Preventive Maintenance</a></li>
    </ul>
  </div>
  <div class="list" id="ul-third">
    <ul>
      <li><a href="#">Nissan GT-R</a></li>
      <li><a href="#">Mitsubishi Lancer</a></li>
      <li><a href="#">Toyota Corolla Touring</a></li>
      <li><a href="#">McLaren P1</a></li>
    </ul>
  </div>
</section>


问:
Oracle: updating data in referenced partition scenario is taking longer time
I have table partitioned on a column(rcrd_expry_ts) of date type. We are updating this rcrd_expry_ts weekly by another job. We noticed the update query is taking quite longer time (1 to 1.5 min) even for few rows and I think longer time is taken for actually moving data internally to different partitioned. There can be a million of rows eligible to update rcrd_expry_ts by our weekly job.

```<code> CREATE TABLE tbl_parent
(
   "parentId" NUMBER NOT NULL ENABLE,
    "RCRD_DLT_TSTP" timestamp default timestamp '9999-01-01 00:00:00' NOT NULL
)
PARTITION BY RANGE ("RCRD_DLT_TSTP") INTERVAL (NUMTOYMINTERVAL('1','MONTH'))  (PARTITION "P1"  VALUES LESS THAN (TO_DATE('2010-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')));

 CREATE TABLE tbl_child
 (
   "foreign_id" NUMBER NOT NULL ENABLE,
   "id" NUMBER NOT NULL ENABLE,
   constraint fk_id foreign key("foreign_id") references
   tbl_parent("parentId")
 )partition by reference (fk_id);
</code>```

I am updating RCRD_DLT_TSTP in parent table from some another job (using simple update query) but I noticed that it took around 1 to 1.5 min to execute, probably due to creating partition and move data into corresponding partition. Is there any better way to achieve this in Oracle

答:
The table has a referenced partitioned child. So any rows moving partition in the parent will have to be cascaded to the child table too.

This means you could be moving substantially more rows that the "few rows" that change in the parent.

It's also worth checking if the update can identify the rows it needs to change faster too.

You can do this by getting the plan for the update statement like this:

```<code>update /*+ gather_plan_statistics */ <your update statement>;

select *
from   table(dbms_xplan.display_cursor( format => 'ALLSTATS LAST' ));
</code>```

This will give you the plan for the update with its run time stats. This will help in identifying if there are any indexes you can create to improve performance.

Is there any better way to achieve this in Oracle

This is a question that needs to be answered in the larger context. You may well be able to make this process faster by unpartitioning the table and using indexes to identify the rows to change.

But this affects all the other statements that access this table. To what extent do they benefit from partitioning? If the answer is substantially, is it worth making this process faster at the expense of these others? What trade-offs are you willing to make here?

Body:
I have table partitioned on a column(rcrd_expry_ts) of date type. We are updating this rcrd_expry_ts weekly by another job. We noticed the update query is taking quite longer time (1 to 1.5 min) even for few rows and I think longer time is taken for actually moving data internally to different partitioned. There can be a million of rows eligible to update rcrd_expry_ts by our weekly job.

 CREATE TABLE tbl_parent
(
   "parentId" NUMBER NOT NULL ENABLE,
    "RCRD_DLT_TSTP" timestamp default timestamp '9999-01-01 00:00:00' NOT NULL
)
PARTITION BY RANGE ("RCRD_DLT_TSTP") INTERVAL (NUMTOYMINTERVAL('1','MONTH'))  (PARTITION "P1"  VALUES LESS THAN (TO_DATE('2010-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')));

 CREATE TABLE tbl_child
 (
   "foreign_id" NUMBER NOT NULL ENABLE,
   "id" NUMBER NOT NULL ENABLE,
   constraint fk_id foreign key("foreign_id") references
   tbl_parent("parentId")
 )partition by reference (fk_id);

I am updating RCRD_DLT_TSTP in parent table from some another job (using simple update query) but I noticed that it took around 1 to 1.5 min to execute, probably due to creating partition and move data into corresponding partition. Is there any better way to achieve this in Oracle

Body:
The table has a referenced partitioned child. So any rows moving partition in the parent will have to be cascaded to the child table too.

This means you could be moving substantially more rows that the "few rows" that change in the parent.

It's also worth checking if the update can identify the rows it needs to change faster too.

You can do this by getting the plan for the update statement like this:

update /*+ gather_plan_statistics */ <your update statement>;

select *
from   table(dbms_xplan.display_cursor( format => 'ALLSTATS LAST' ));

This will give you the plan for the update with its run time stats. This will help in identifying if there are any indexes you can create to improve performance.

Is there any better way to achieve this in Oracle

This is a question that needs to be answered in the larger context. You may well be able to make this process faster by unpartitioning the table and using indexes to identify the rows to change.

But this affects all the other statements that access this table. To what extent do they benefit from partitioning? If the answer is substantially, is it worth making this process faster at the expense of these others? What trade-offs are you willing to make here?


问:
Is it possible to change out an image src="" before the original image loads
I've been looking at Javascript that can change the src of an image. I'm simply wondering if this can be done before the browser attempts to fetch the original image.

Example.

```<code>Src="Large-Image"
</code>```

Can I (with javascript, I would imagine.. node.JS maybe?) serve the user src="smaller-image"?

Obviously, there would be no performance gain if the browser loads the large image first.

答:
Well, I am a little late to the party... But yeah, of course you can!

The trick is to do EXACTLY what everyone warns you "not to do" and reference your JS file in the  section of your webpage. This way, your JavaScript loads before anything else.

Then use document.addEventListener('DOMContentLoaded', ()=> {...}); to grab your image element, as soon as the DOM is available (but before the image file is loaded).

Here is the HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <script src="main.js"></script>
  </head>
  <body>
    <img src="original_image_URL">
  </body>
</html>
</code>```

and here is main.js which goes with it:

```<code>document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('img').src = 'new_image_URL';
});
</code>```

Have fun!

OwnerDisplayName: David Sigley

Body:
I've been looking at Javascript that can change the src of an image. I'm simply wondering if this can be done before the browser attempts to fetch the original image.

Example.

Src="Large-Image"

Can I (with javascript, I would imagine.. node.JS maybe?) serve the user src="smaller-image"?

Obviously, there would be no performance gain if the browser loads the large image first.

Body:
Well, I am a little late to the party... But yeah, of course you can!

The trick is to do EXACTLY what everyone warns you "not to do" and reference your JS file in the <head> section of your webpage. This way, your JavaScript loads before anything else.

Then use document.addEventListener('DOMContentLoaded', ()=> {...}); to grab your image element, as soon as the DOM is available (but before the image file is loaded).

Here is the HTML:

<!DOCTYPE html>
<html>
  <head>
    <script src="main.js"></script>
  </head>
  <body>
    <img src="original_image_URL">
  </body>
</html>

and here is main.js which goes with it:

document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('img').src = 'new_image_URL';
});

Have fun!


问:
How to best manage file either gz or not?
Hi I wonder if there is a better way in terms of code readability and repetition.

I have a large file that do not fit in memory. The file is either compressed .gz or not.

If it is compressed I need to open it using gzip from standard lib.

I am not sure the code I ended up is the best way to deal with that situation.

```<code>import gzip
from Path import pathlib

def parse_open_file(openfile):
    """parse the content of the file"""
    return

def parse_file(file_: Path):
    if file.suffix == ".gz":
        with gzip.open(file_, 'rb') as f:
            parse_open_file(f)
    else:
        with open(file_, 'rb') as f:
            parse_open_file(f)
</code>```

答:
One way to handle this is to assign either open or gzip.open to a variable, depending on file type, then use that as an 'alias' in the with statement.  For example:

```<code>if file.suffix == ".gz":
  myOpen = gzip.open
else:
  myOpen = open

with myOpen(file_, 'rb') as f:
  parse_open_file(f)
</code>```

Body:
Hi I wonder if there is a better way in terms of code readability and repetition.

I have a large file that do not fit in memory. The file is either compressed .gz or not.

If it is compressed I need to open it using gzip from standard lib.

I am not sure the code I ended up is the best way to deal with that situation.

import gzip
from Path import pathlib

def parse_open_file(openfile):
    """parse the content of the file"""
    return

def parse_file(file_: Path):
    if file.suffix == ".gz":
        with gzip.open(file_, 'rb') as f:
            parse_open_file(f)
    else:
        with open(file_, 'rb') as f:
            parse_open_file(f)

Body:
One way to handle this is to assign either open or gzip.open to a variable, depending on file type, then use that as an 'alias' in the with statement.  For example:

if file.suffix == ".gz":
  myOpen = gzip.open
else:
  myOpen = open

with myOpen(file_, 'rb') as f:
  parse_open_file(f)


问:
apple apns server max can take how many request in 10 minute?
my application send out 10k of request to APNS server in ~10 mins and non of them reach my clients. any idea ? is there a max cap?

By upgrade my developer account from 'Individual' to 'company' account, can solve my issue?

答:
Do you send them all in one connection or do you make 10,000 separate requests to the APNS servers?  Can you post some code?

No problem sending that many as I do.

It is also in no way linked to whether you have an individual or company account either.


答:
Use strptime to parse the dates, then strftime to format them. map can map that filter over your entire list.

```<code>$ cat tmp.json
[
  "1934/08/20",
  "1961/01/10",
  "1952/01/25",
  "1967/07/24"
]
$ jq 'map(strptime("%Y/%m/%d") | strftime("%F"))' tmp.json
[
  "1934-08-20",
  "1961-01-10",
  "1952-01-25",
  "1967-07-24"
]
</code>```

(%F is a shortcut, where available, for %Y-%m-%d.)

Title: jq: replache slash by dash chracter

Body:
I need to replace slash character by "-".

I mean:

[
  "1934/08/20",
  "1961/01/10",
  "1952/01/25",
  "1967/07/24"
]

I need:

[
  "1934-0820",
  "1961-01-10",
  "1952-01-25",
  "1967-07-24"
]

Is there anyway to get it?

Body:
Use strptime to parse the dates, then strftime to format them. map can map that filter over your entire list.

$ cat tmp.json
[
  "1934/08/20",
  "1961/01/10",
  "1952/01/25",
  "1967/07/24"
]
$ jq 'map(strptime("%Y/%m/%d") | strftime("%F"))' tmp.json
[
  "1934-08-20",
  "1961-01-10",
  "1952-01-25",
  "1967-07-24"
]

(%F is a shortcut, where available, for %Y-%m-%d.)


问:
How can I call OpenCV focalsFromHomography from Python?
OpenCV documentation says

```<code>focalsFromHomography()
void cv::detail::focalsFromHomography   (const Mat &H,
    double &    f0,
    double &    f1,
    bool &      f0_ok,
    bool &      f1_ok
)
Python:
    cv.detail.focalsFromHomography( H, f0, f1, f0_ok, f1_ok ) -> None
</code>```

and indeed I can call focalsFromHomography this way, without error:

```<code>    f0 = 0.0
    f1 = 0.0
    f0_ok = False
    f1_ok = False
    r = cv.detail.focalsFromHomography(
        mat,
        f0, f1,
        f0_ok, f1_ok
    )
</code>```

Of course, it does not return anything, and it does not, cannot, change f0 and f1.

If I call it like this:

```<code>    f0 = c_double()
    f1 = c_double()
    f0_ok = c_bool()
    f1_ok = c_bool()
    r = cv.detail.focalsFromHomography(
        mat,
        byref(f0), byref(f1),
        byref(f0_ok), byref(f1_ok)
    )
</code>```

I get an error "TypeError: Argument 'f0' can not be treated as a double", which is true, f0 is not a double, but a reference to a double, because I want to receive the result in f0.

How can I call "focalsFromHomography" and receive the estimated focals?

So far my only solution is to copy the algorithm from OpenCV source and manually translate it to Python code, line by line. It is only 20 lines, so it is doable, but it is not nice.

答:
Sadly, I am answering my own question. It looks like that rewriting the code in Python seems to be the only solution.

```<code>@staticmethod
def _focalsfromhomography(
    mat: np.ndarray) -> tuple[float | None, float | None]:
    """
    Estimate focal lengths from the given homography under
    the assumption that the camera undergoes rotations
    around its center only.

    https://docs.opencv.org/4.x/d4/dbc/group__stitching__autocalib.html
    https://github.com/opencv/opencv/blob/4.x/modules/stitching/src/autocalib.cpp
    Rewriten in pure Python, because it was a bit difficult
    to call the native OpenCV function.
    :param mat: Homography matrix
    :return: (f0, f1)
    """
    # Fast access
    h = np.reshape(mat, 9)

    # f1
    f1 = None
    # Denominators
    d1 = h[6] * h[7]
    d2 = (h[7] - h[6]) * (h[7] + h[6])
    # Focal squares value candidates
    v1 = -(h[0] * h[1] + h[3] * h[4])
    v1 = v1 / d1 if d1 != 0.0 else -1.0
    v2 = (h[0] - h[1]) * (h[0] + h[1]) + (h[3] - h[4]) * (h[3] + h[4])
    v2 = v2 / d2 if d2 != 0.0 else -1.0
    if v1 < v2:
        v1, v2 = v2, v1
    if v1 > 0 and v2 > 0:
        f1 = math.sqrt(v1 if abs(d1) > abs(d2) else v2)
    elif v1 > 0:
        f1 = math.sqrt(v1)

    # f0
    f0 = None
    # Denominators
    d1 = h[0] * h[3] + h[1] * h[4]
    d2 = (h[0] - h[3]) * (h[0] + h[3]) + (h[1] - h[4]) * (h[1] + h[4])
    # Focal squares value candidates
    v1 = -h[2] * h[5]
    v1 = v1 / d1 if d1 != 0.0 else -1.0
    v2 = (h[5] - h[2]) * (h[5] + h[2])
    v2 = v2 / d2 if d2 != 0.0 else -1.0
    if v1 < v2:
        v1, v2 = v2, v1
    if v1 > 0 and v2 > 0:
        f0 = math.sqrt(v1 if abs(d1) > abs(d2) else v2)
    elif v1 > 0:
        f0 = math.sqrt(v1)

    return f0, f1
</code>```

This works, but it isn't the solution I am looking for. I hope someone can do it better.

Body:
OpenCV documentation says

focalsFromHomography()
void cv::detail::focalsFromHomography   (const Mat &H,
    double &    f0,
    double &    f1,
    bool &      f0_ok,
    bool &      f1_ok
)
Python:
    cv.detail.focalsFromHomography( H, f0, f1, f0_ok, f1_ok ) -> None

and indeed I can call focalsFromHomography this way, without error:

    f0 = 0.0
    f1 = 0.0
    f0_ok = False
    f1_ok = False
    r = cv.detail.focalsFromHomography(
        mat,
        f0, f1,
        f0_ok, f1_ok
    )

Of course, it does not return anything, and it does not, cannot, change f0 and f1.

If I call it like this:

    f0 = c_double()
    f1 = c_double()
    f0_ok = c_bool()
    f1_ok = c_bool()
    r = cv.detail.focalsFromHomography(
        mat,
        byref(f0), byref(f1),
        byref(f0_ok), byref(f1_ok)
    )

I get an error "TypeError: Argument 'f0' can not be treated as a double", which is true, f0 is not a double, but a reference to a double, because I want to receive the result in f0.

How can I call "focalsFromHomography" and receive the estimated focals?

So far my only solution is to copy the algorithm from OpenCV source and manually translate it to Python code, line by line. It is only 20 lines, so it is doable, but it is not nice.

Body:
Sadly, I am answering my own question. It looks like that rewriting the code in Python seems to be the only solution.

@staticmethod
def _focalsfromhomography(
    mat: np.ndarray) -> tuple[float | None, float | None]:
    """
    Estimate focal lengths from the given homography under
    the assumption that the camera undergoes rotations
    around its center only.

    https://docs.opencv.org/4.x/d4/dbc/group__stitching__autocalib.html
    https://github.com/opencv/opencv/blob/4.x/modules/stitching/src/autocalib.cpp
    Rewriten in pure Python, because it was a bit difficult
    to call the native OpenCV function.
    :param mat: Homography matrix
    :return: (f0, f1)
    """
    # Fast access
    h = np.reshape(mat, 9)

    # f1
    f1 = None
    # Denominators
    d1 = h[6] * h[7]
    d2 = (h[7] - h[6]) * (h[7] + h[6])
    # Focal squares value candidates
    v1 = -(h[0] * h[1] + h[3] * h[4])
    v1 = v1 / d1 if d1 != 0.0 else -1.0
    v2 = (h[0] - h[1]) * (h[0] + h[1]) + (h[3] - h[4]) * (h[3] + h[4])
    v2 = v2 / d2 if d2 != 0.0 else -1.0
    if v1 < v2:
        v1, v2 = v2, v1
    if v1 > 0 and v2 > 0:
        f1 = math.sqrt(v1 if abs(d1) > abs(d2) else v2)
    elif v1 > 0:
        f1 = math.sqrt(v1)

    # f0
    f0 = None
    # Denominators
    d1 = h[0] * h[3] + h[1] * h[4]
    d2 = (h[0] - h[3]) * (h[0] + h[3]) + (h[1] - h[4]) * (h[1] + h[4])
    # Focal squares value candidates
    v1 = -h[2] * h[5]
    v1 = v1 / d1 if d1 != 0.0 else -1.0
    v2 = (h[5] - h[2]) * (h[5] + h[2])
    v2 = v2 / d2 if d2 != 0.0 else -1.0
    if v1 < v2:
        v1, v2 = v2, v1
    if v1 > 0 and v2 > 0:
        f0 = math.sqrt(v1 if abs(d1) > abs(d2) else v2)
    elif v1 > 0:
        f0 = math.sqrt(v1)

    return f0, f1

This works, but it isn't the solution I am looking for. I hope someone can do it better.


问:
WooCommerce Archive page product link not working anymore after custom snippet
I wanted to add the product category above the product title in my archive page. I've found a way to do it here and I've used this code.

```<code>/**
* @return add category link and title above the title or below the category
*
*/
function theme_slug_add_category_above_title() {
    global $product;
    echo wc_get_product_category_list( $product->get_id() );
}
add_action( 'woocommerce_shop_loop_item_title', 'theme_slug_add_category_above_title', 9 );
</code>```

This works fine. However after adding this code the product title isn't linking anymore to the product page.
Sadly I understand almost nothing of PHP. I do understand that it's probably a wrap with the image and title that is now cut short because of the category added in between them.

The image links fine. How can I add the link back to the title as well?

Thanks in advance!

答:
Try this:

```<code>function theme_slug_add_category_above_title() {
    global $product;

    $terms = wp_list_pluck( get_the_terms( $product->get_id(), 'product_cat' ), 'name');
    foreach( $terms as $term ) {
        echo $term;
    }

}
add_action( 'woocommerce_shop_loop_item_title', 'theme_slug_add_category_above_title', 9 );
</code>```

This code doesn't add the link to the category.

Body:
I wanted to add the product category above the product title in my archive page. I've found a way to do it here and I've used this code.

/**
* @return add category link and title above the title or below the category
*
*/
function theme_slug_add_category_above_title() {
    global $product;
    echo wc_get_product_category_list( $product->get_id() );
}
add_action( 'woocommerce_shop_loop_item_title', 'theme_slug_add_category_above_title', 9 );

This works fine. However after adding this code the product title isn't linking anymore to the product page.
Sadly I understand almost nothing of PHP. I do understand that it's probably a wrap with the image and title that is now cut short because of the category added in between them.

The image links fine. How can I add the link back to the title as well?

Thanks in advance!

Body:
Try this:

function theme_slug_add_category_above_title() {
    global $product;

    $terms = wp_list_pluck( get_the_terms( $product->get_id(), 'product_cat' ), 'name');
    foreach( $terms as $term ) {
        echo $term;
    }

}
add_action( 'woocommerce_shop_loop_item_title', 'theme_slug_add_category_above_title', 9 );

This code doesn't add the link to the category.


问:
Do we need to do Consumer Driven Contract Testing Kafka Driven Micro-services when we have the Scheme Registry?
I am trying to understand if the concept of Consumer-Driven Contracts ( CDC ) is still valid in the context of Kafka based Event Driven Architecture.

In the RESTful world, Consumer-Driven Contract verification is vital, because there is no concept of schema evolution based compatibility testing that happens at runtime. A bad producer may be free to change the schema and deploy without notifying consumers and if the APIs are not versioned properly, that may break your consumers if the producer hasn't paid attention to the consumer patterns. So the concept of CDC provides the best way in my opinion to ensure that producers stay consumer compliant as they evolve their schemas.

Now, focusing on the Kafka based EDA, the concept of Schema Registry plays a bigger role in consumer - producer relationships. It acts as the coordinator between consumers and producers helping to evolve schemas with a level of compatibility you desire so that producers won't break consumers or at least it has been made very difficult to do so. With that trust in place, I am trying to understand if the concept of CDC is still applicable for Kafka / Schema Registry driven micro-service architectures?

Referring: https://docs.confluent.io/cloud/current/client-apps/testing.html#schema-management-and-evolution

After your applications are running in production, schemas may evolve but still need to be compatible for all applications that rely on both old and new versions of a schema. Confluent Schema Registry allows for schema evolution and provides compatibility checks to ensure that the contract between producers and consumers is not broken."""

Update: Further more, In Kafka, we mostly use Avro like Schema Oriented Serialization formats, it seems the support within the Contract Testing Frameworks for such formats is limited too.

https://github.com/pact-foundation/pact-jvm/issues/603

Spring cloud contract tests for avro messages using Schema Registry

答:
By default, sure, but the registry checks can be disabled or reversed such that only forward changes are compatible, not including backwards compatible

It's still recommended to do unit testing on your consumer apps for expected inputs from producers, regardless of a gate-keeping registry (which is not a required property for any producer)


问:
How to use model form instances of a formset in Django template
I'm trying to access the instance of the forms in a formset, but it is not working.  I CAN access them using the variable notation, as in {{ form }}, but not in code, as in {% url 'section' form.instance.pk %}.  I need to iterate through the forms in the formset along with the corresponding model instance.

My view:

# views.py

def sec(request, companyurl):
    company = get_if_exists(Company, author=request.user)

    SectionFormSet = modelformset_factory(Section, form=SectionForm, can_delete=True)
    sections = Section.objects.filter(company=company).order_by('order')
    formset = SectionFormSet(request.POST or None,
                             initial=[{'company': company}],
                             queryset=sections

    context = {
        'sections': sections,
        'formset': formset,
    }
    return render(request, 'questions/sections.html', context)
```
<p>My model:</p>
<pre class="lang-py prettyprint-override"><code># models.py

class Section(models.Model):

    section = models.CharField(max_length=100)
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    order = models.PositiveIntegerField(default=1000000)
    show = models.BooleanField(default=True)

    def __str__(self):
        return self.section
</code>```

My Form (I'm using django-crispy forms):

# forms.py
class SectionForm(forms.ModelForm):
    class Meta:
        model = Section
        fields = ['company', 'section', 'show', 'order']
        labels = {
            'section': '',
            'show': 'Show'
        }
    def __init__(self, *args, **kwargs):
        super(SectionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Div(
                Div(HTML("##"), css_class = 'my-handle col-auto'),
                Div('section', css_class='col-3'),
                Div('show', css_class = 'col-auto'),
                Div('DELETE', css_class = 'col-auto'),
                Field('company', type='hidden'),
                Field('order', type='hidden'),
                css_class='row',
            ),
        )
```
<p>My template (<strong>this is where the problem is seen</strong>):</p>
<pre class="lang-html prettyprint-override"><code><form action="#" method="post">
  {% csrf_token %}

  {{ formset.management_form }}

  <div id="simpleList" class="list-group">

  {% for fo in formset %}

    <div class="list-group-item hold">

      {% crispy fo %}

      <!-- TESTING TO SEE IF THIS WORKS, AND IT DOES! -->
      {{ fo.instance }} + {{ fo.instance.pk }} + {{ fo.instance.section }}

      <!-- THE PROBLEM OCCURS WHEN THIS IS ADDED -->

        {{ fo.instance }}

      <!-------------------------------------------->

      <input type="hidden" name="order" value="{{ section.pk }}">

      {% for hid in fo.hidden_fields %}
        {{ hid }}
      {% endfor %}

    </div>

  {% endfor %}

  <button type="submit" class="btn btn-outline-primary">Save changes</button>

</form>
</code>```

When I add the  link line I get

Reverse for 'section' with arguments '(None, '')' not found. 1 pattern(s) tried: ['section/(?P<pk>[0-9]+)/(?P
[^/]+)\\Z']

The error is clear.  fo.instance.pk is None and fo.instance.section is an empty string.  Yet when I remove the anchor tag, the line above appears and shows the correct values for both of these.  I think I know the difference in how the {{  }} and the {%  %}, and I thought I knew how model form instances were tied to the model, but I am missing something.

Thanks for any help.

答:
Formsets create blank forms

The answer was staring me in the face, when I printed the results.  The last form, a blank, of course was giving me None and an empty string, since it had no data to fill it with.  Thus the simple solution is to check for this before trying to form the url with the information.  Therefore, this has nothing to do with the differences between {{ }} and {%  %} nor form instances.

{% for fo in formset %}

      {% crispy fo %}

      {{ fo.instance }} + {{ fo.instance.pk }} + {{ fo.instance.section }}

      {% if fo.instance.pk %}

           {{ fo.instance }}

      {%  endif %}

      <input type="hidden" name="order" value="{{ section.pk }}">

      {% for hid in fo.hidden_fields %}
        {{ hid }}
      {% endfor %}

  {% endfor %}

  <button type="submit" class="btn btn-outline-primary">Save changes</button>

</form>

```

Body:
I'm trying to access the instance of the forms in a formset, but it is not working.  I CAN access them using the variable notation, as in {{ form }}, but not in code, as in {% url 'section' form.instance.pk %}.  I need to iterate through the forms in the formset along with the corresponding model instance.

My view:

# views.py

def sec(request, companyurl):
    company = get_if_exists(Company, author=request.user)

    SectionFormSet = modelformset_factory(Section, form=SectionForm, can_delete=True)
    sections = Section.objects.filter(company=company).order_by('order')
    formset = SectionFormSet(request.POST or None,
                             initial=[{'company': company}],
                             queryset=sections

    context = {
        'sections': sections,
        'formset': formset,
    }
    return render(request, 'questions/sections.html', context)

My model:

# models.py

class Section(models.Model):

    section = models.CharField(max_length=100)
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    order = models.PositiveIntegerField(default=1000000)
    show = models.BooleanField(default=True)

    def __str__(self):
        return self.section

My Form (I'm using django-crispy forms):

# forms.py
class SectionForm(forms.ModelForm):
    class Meta:
        model = Section
        fields = ['company', 'section', 'show', 'order']
        labels = {
            'section': '',
            'show': 'Show'
        }
    def __init__(self, *args, **kwargs):
        super(SectionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Div(
                Div(HTML("##"), css_class = 'my-handle col-auto'),
                Div('section', css_class='col-3'),
                Div('show', css_class = 'col-auto'),
                Div('DELETE', css_class = 'col-auto'),
                Field('company', type='hidden'),
                Field('order', type='hidden'),
                css_class='row',
            ),
        )

My template (this is where the problem is seen):

<form action="#" method="post">
  {% csrf_token %}

  {{ formset.management_form }}

  {% for fo in formset %}

      {% crispy fo %}

      {{ fo.instance }} + {{ fo.instance.pk }} + {{ fo.instance.section }}

        {{ fo.instance }}

      <input type="hidden" name="order" value="{{ section.pk }}">

      {% for hid in fo.hidden_fields %}
        {{ hid }}
      {% endfor %}

  {% endfor %}

  <button type="submit" class="btn btn-outline-primary">Save changes</button>

</form>

When I add the  link line I get

Reverse for 'section' with arguments '(None, '')' not found. 1 pattern(s) tried: ['section/(?P<pk>[0-9]+)/(?P
[^/]+)\\Z']

The error is clear.  fo.instance.pk is None and fo.instance.section is an empty string.  Yet when I remove the anchor tag, the line above appears and shows the correct values for both of these.  I think I know the difference in how the {{  }} and the {%  %}, and I thought I knew how model form instances were tied to the model, but I am missing something.

Thanks for any help.

Body:
Formsets create blank forms

The answer was staring me in the face, when I printed the results.  The last form, a blank, of course was giving me None and an empty string, since it had no data to fill it with.  Thus the simple solution is to check for this before trying to form the url with the information.  Therefore, this has nothing to do with the differences between {{ }} and {%  %} nor form instances.

{% for fo in formset %}

    <div class="list-group-item hold">

      {% crispy fo %}

      <!-- TESTING TO SEE IF THIS WORKS, AND IT DOES! -->
      {{ fo.instance }} + {{ fo.instance.pk }} + {{ fo.instance.section }}

      <!-- THE PROBLEM OCCURED WHEN THIS WAS ADDED -->
      <!-- THE SIMPLE SOLUTION: --------------------->
      {% if fo.instance.pk %}
         <a href="{% url 'section' fo.instance.pk fo.instance.section %}">
           {{ fo.instance }}
         </a>
      {%  endif %}
      <!-------------------------------------------->

      <input type="hidden" name="order" value="{{ section.pk }}">

      {% for hid in fo.hidden_fields %}
        {{ hid }}
      {% endfor %}

    </div>

  {% endfor %}

  <button type="submit" class="btn btn-outline-primary">Save changes</button>

</form>


问:
cannot be used as a JSX component Its return type string | Element is not a valid JSX element Type 'string' is not assignable to type 'Element | null'
I created a react function  EventDateTooltip:

```<code>import React from 'react';
import { endOfDay, isToday, isTomorrow, isYesterday } from 'date-fns';
import { useTranslation } from 'react-i18next';
import I18nWrapper from '../i18n-wrapper';
import DateFormater from '../formaters/date-formater';

 const EventDateTooltip = ({ date }: { date: string }) => {
 const { t } = useTranslation();
 const dateTooltip = endOfDay(new Date(date));
  if (isTomorrow(dateTooltip)) return t('tooltip.event.date.tomorrow');
  if (isYesterday(dateTooltip)) return t('tooltip.event.date.yesterday');
  if (isToday(dateTooltip)) return t('tooltip.event.date.today');

 return (
   <>
  <span key={date.toString()}>
    <I18nWrapper translateKey="tooltip.event.date.the" />{' '}
    <DateFormater dateToFomat={date} formater="full-date" />
  </span>
</>
  );
};

export default EventDateTooltip;
</code>```

this function return a text and a translated date.

when I call this function on another component:

```<code> <EventDateTooltip date={props.event.endDate}></EventDateTooltip>;
</code>```

the call returns the following error message:

```<code>Its return type 'string | Element' is not a valid JSX element.
   Type 'string' is not assignable to type 'Element | null'.  TS2786
</code>```

has anyone got the following message ?

答:
As stated in this answer, currently TypeScript's React types do not allow you to return a string from a React component and include that in a component tree.

You can wrap your strings with fragments to avoid the error:

```<code>// [...]
  if (isTomorrow(dateTooltip)) return <>t('tooltip.event.date.tomorrow')</>;
  if (isYesterday(dateTooltip)) return <>t('tooltip.event.date.yesterday')</>;
  if (isToday(dateTooltip)) return <>t('tooltip.event.date.today')</>;
// [...]
</code>```

Body:
I created a react function  EventDateTooltip:

import React from 'react';
import { endOfDay, isToday, isTomorrow, isYesterday } from 'date-fns';
import { useTranslation } from 'react-i18next';
import I18nWrapper from '../i18n-wrapper';
import DateFormater from '../formaters/date-formater';

 const EventDateTooltip = ({ date }: { date: string }) => {
 const { t } = useTranslation();
 const dateTooltip = endOfDay(new Date(date));
  if (isTomorrow(dateTooltip)) return t('tooltip.event.date.tomorrow');
  if (isYesterday(dateTooltip)) return t('tooltip.event.date.yesterday');
  if (isToday(dateTooltip)) return t('tooltip.event.date.today');

 return (
   <>

    <I18nWrapper translateKey="tooltip.event.date.the" />{' '}
    <DateFormater dateToFomat={date} formater="full-date" />

</>
  );
};

export default EventDateTooltip;

this function return a text and a translated date.

when I call this function on another component:

 <EventDateTooltip date={props.event.endDate}></EventDateTooltip>;

the call returns the following error message:

Its return type 'string | Element' is not a valid JSX element.
   Type 'string' is not assignable to type 'Element | null'.  TS2786

has anyone got the following message ?

Body:
As stated in this answer, currently TypeScript's React types do not allow you to return a string from a React component and include that in a component tree.

You can wrap your strings with fragments to avoid the error:

// [...]
  if (isTomorrow(dateTooltip)) return <>t('tooltip.event.date.tomorrow')</>;
  if (isYesterday(dateTooltip)) return <>t('tooltip.event.date.yesterday')</>;
  if (isToday(dateTooltip)) return <>t('tooltip.event.date.today')</>;
// [...]


问:
Why doesn't the for loop save each roll value in each iteration to the histogram?
I am creating a for loop to inspect regression to the mean with dice rolls.
Wanted outcome would that histogram shows all the roll values that came on each iteration.

Why doesn't the for loop save each roll value in each iteration to the histogram?

Furthermore PyCharm takes forever to load if n> 20000 values therefore the code doesn't execute fully in that case.

```<code>import numpy as np

import matplotlib.pyplot as plt

sums = 0

values = [1, 2, 3, 4, 5, 6]

numbers = [500, 1000, 2000, 5000, 10000, 15000, 20000, 50000, 100000]

n = np.random.choice(numbers)

for i in range(n):

    roll = np.random.choice(values) + np.random.choice(values)
    sums = roll + sums
    h, h2 = np.histogram(sums, range(2, 14))
    plt.bar(h2[:-1], h / n)
    plt.title(n)
plt.show()
</code>```

Current output

答:
You are now overwriting h and h2 in every iteration. Instead, you could append the values to a list and make a histogram of the entire list:

```<code>import numpy as np

import matplotlib.pyplot as plt

sums = 0

values = [1, 2, 3, 4, 5, 6]

numbers = [500, 1000, 2000, 5000, 10000, 15000, 20000, 50000, 100000]

n = np.random.choice(numbers)

all_rolls = []

for i in range(n):

    roll = np.random.choice(values) + np.random.choice(values)
    all_rolls.append(roll)
h, h2 = np.histogram(all_rolls, range(2, 14))
plt.bar(h2[:-1], h / n)
plt.title(n)
plt.show()
</code>```

Output:

Body:
I am creating a for loop to inspect regression to the mean with dice rolls.
Wanted outcome would that histogram shows all the roll values that came on each iteration.

Why doesn't the for loop save each roll value in each iteration to the histogram?

Furthermore PyCharm takes forever to load if n> 20000 values therefore the code doesn't execute fully in that case.

import numpy as np

import matplotlib.pyplot as plt

sums = 0

values = [1, 2, 3, 4, 5, 6]

numbers = [500, 1000, 2000, 5000, 10000, 15000, 20000, 50000, 100000]

n = np.random.choice(numbers)

for i in range(n):

    roll = np.random.choice(values) + np.random.choice(values)
    sums = roll + sums
    h, h2 = np.histogram(sums, range(2, 14))
    plt.bar(h2[:-1], h / n)
    plt.title(n)
plt.show()

Current output

Body:
You are now overwriting h and h2 in every iteration. Instead, you could append the values to a list and make a histogram of the entire list:

import numpy as np

import matplotlib.pyplot as plt

sums = 0

values = [1, 2, 3, 4, 5, 6]

numbers = [500, 1000, 2000, 5000, 10000, 15000, 20000, 50000, 100000]

n = np.random.choice(numbers)

all_rolls = []

for i in range(n):

    roll = np.random.choice(values) + np.random.choice(values)
    all_rolls.append(roll)
h, h2 = np.histogram(all_rolls, range(2, 14))
plt.bar(h2[:-1], h / n)
plt.title(n)
plt.show()

Output:


问:
How does namenode query block information from datanode?
I can query information about how my files (stored in HDFS) are stored in blocks via hdfs fsck / -files -blocks.

As I understand, the namenode does not store information about the location of the blocks of each file and instead loads that information from the datanodes. Reference - Why datanode sends the block location information to namenode?

So if the namenode is querying the information from the datanodes, the namenode should know where the datanodes metadata is located. Which would mean that there technically could be a pathway from -

```<code> NameNode FSImage -> DataNodes metadata -> Info about how data is stored in blocks
</code>```

There are files that have names that look something like bl*.meta but I think they just contain the checksum information for the blocks and therefore may not be relevant here. Reference - What metadata is stored on a datanode in HDFS?

Where do the datanodes store the file -> block mapping?

Since there could be multiple datanodes with file data split across them, how do I get this information from the NameNode's FSImage/edit logs?

答:
You can get the block information directly from the bl*.meta.  This information is sent to the NameNode when a Datanode comes online.  The information is in the meta files but really the position on the disks itself is what is used to generate the meta files when a node starts (implied by hadoop 2.6 manual balancing of disks).

You may find it helpful to study some of the github projects that are created to balance datanode disks as it requires knowledge of metadata.

You may want to look at some of the github tools availble for analyzing FSImage. Which may help you find the information you are looking for.

Body:
I can query information about how my files (stored in HDFS) are stored in blocks via hdfs fsck / -files -blocks.

As I understand, the namenode does not store information about the location of the blocks of each file and instead loads that information from the datanodes. Reference - Why datanode sends the block location information to namenode?

So if the namenode is querying the information from the datanodes, the namenode should know where the datanodes metadata is located. Which would mean that there technically could be a pathway from -

 NameNode FSImage -> DataNodes metadata -> Info about how data is stored in blocks

There are files that have names that look something like bl*.meta but I think they just contain the checksum information for the blocks and therefore may not be relevant here. Reference - What metadata is stored on a datanode in HDFS?

Where do the datanodes store the file -> block mapping?

Since there could be multiple datanodes with file data split across them, how do I get this information from the NameNode's FSImage/edit logs?