问:
How to remove one value from a key in localstorage that has many values?
I've seen this question asked before but the solutions didn't help me hence why i've asked it again.

Currently, I am storing values into an array and that array is getting stored into localstorage.

This is the object

```<code>data.items -

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}
</code>```

I have mapped through this and used 'name' as the value. I am calling this value through a button using this function

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

  function checkId(e) {
    if (e.target.value !== ""){
      if (!favs.includes(e.target.value)){
      favs.push(e.target.value);
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      }
    }

    }
</code>```

and to remove the value from localstorage I am using this function.

```<code>function removeId(e, value) {
    if (e.target.value !== "") {

      favs.pop(e.target.value);
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value];
      localStorage.setItem("name", JSON.stringify(stored));
      console.log(stored);

    }
  }
</code>```

Although the value is being removed from the array, it is not being removed from localstorage.

side note - I am calling this function with a separate button.

console log

```<code>array (item is gone)
[]

localstorage (the value is still there)
[
    "Spiral-Up-Cut-Router-Bit"
]
</code>```

But if I select another item to be added to localstorage, then the previous item gets removed.

```<code>UNFAVORITE - FUNCTION REMOVEid
[
        "Spiral-Up-Cut-Router-Bit"
    ]

 NEW FAVORITE - FUNCTION NEWId

[
    "graphqless"
]
</code>```

I hope this makes sense, I tried to add detail to it as best as possible.

答:
As suggested, use splice (which will also update the Array's length) to delete the entry from the Array.

const stored = JSON.parse(localStorage.getItem("name"));
const index = stored.indexOf(nameValue);
if (index !== -1) {
  stored.splice(index, 1);
  localStorage.setItem("name", JSON.stringify(stored));
}
```

See:

Body:
I've seen this question asked before but the solutions didn't help me hence why i've asked it again.

Currently, I am storing values into an array and that array is getting stored into localstorage.

This is the object

data.items -

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}

I have mapped through this and used 'name' as the value. I am calling this value through a button using this function

const favs = [];

  function checkId(e) {
    if (e.target.value !== ""){
      if (!favs.includes(e.target.value)){
      favs.push(e.target.value);
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      }
    }

    }

and to remove the value from localstorage I am using this function.

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

      favs.pop(e.target.value);
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value];
      localStorage.setItem("name", JSON.stringify(stored));
      console.log(stored);

    }
  }

Although the value is being removed from the array, it is not being removed from localstorage.

side note - I am calling this function with a separate button.

console log

array (item is gone)
[]

localstorage (the value is still there)
[
    "Spiral-Up-Cut-Router-Bit"
]

But if I select another item to be added to localstorage, then the previous item gets removed.

UNFAVORITE - FUNCTION REMOVEid
[
        "Spiral-Up-Cut-Router-Bit"
    ]

 NEW FAVORITE - FUNCTION NEWId

[
    "graphqless"
]

I hope this makes sense, I tried to add detail to it as best as possible.

Body:
As suggested, use splice (which will also update the Array's length) to delete the entry from the Array.

const stored = JSON.parse(localStorage.getItem("name"));
const index = stored.indexOf(nameValue);
if (index !== -1) {
  stored.splice(index, 1);
  localStorage.setItem("name", JSON.stringify(stored));
}

See:


来源: stackexchange

问:
can we use value of a variable into a function into another function
here I am getting the Customer data from the database and I store it into custDetail variable, I know it's a local variable how can I use it as a global variable.

```<code> const dashboardReq = async (req, res, next) => {

try {
    const regCust = await registeredUser.findOne({ mobile: req.params.mobile });

if (regCust == null) {
  console.log("No user found");
} else {
  const custDetail = await registeredUser.findOne(req.params);  **/// here I store the data into variable **

res.status(201).json({
  status: "success",
  data: { custDetail },
});

 } catch (error) {
    res.status(400).json({
      status: "fail",
      data: next(error),
    });
  }
};
</code>```

now I want to use the value of custDetail variable into another function
here is the code

```<code>const gasService = async (req, res, next , dashboardReq ) => {

 try {
    const { customerNo, bookingNo, bookingDate } = req.body;
    const userName = dashboardReq.name;   **/// here is try to get value**
    const userMobile = dashboardReq.mobile; **/// here is try to get value**
    const newGasService = await gasData.create({
      userName,
      userMobile,
      customerNo,
      bookingNo,
      bookingDate,
    });

res.status(201).json({
  status: "success",
  data: { gasService: newGasService },
});

 }

catch (error) {
    res.status(400).json({
      status: "fail",
      data: next(error),
    });
  }
};
</code>```

答: You can initialize custDetail outiside the scope of dashboardReq function (before it), let custDetail; and then assign the value inside the function as custDetail = await registeredUser.findOne(req.params); and then reuse it anywhere including gasService function

ContentLicense: CC BY-SA 4.0

Body:
here I am getting the Customer data from the database and I store it into custDetail variable, I know it's a local variable how can I use it as a global variable.

 const dashboardReq = async (req, res, next) => {

try {
    const regCust = await registeredUser.findOne({ mobile: req.params.mobile });

if (regCust == null) {
  console.log("No user found");
} else {
  const custDetail = await registeredUser.findOne(req.params);  **/// here I store the data into variable **

res.status(201).json({
  status: "success",
  data: { custDetail },
});

 } catch (error) {
    res.status(400).json({
      status: "fail",
      data: next(error),
    });
  }
};

now I want to use the value of custDetail variable into another function
here is the code

const gasService = async (req, res, next , dashboardReq ) => {

 try {
    const { customerNo, bookingNo, bookingDate } = req.body;
    const userName = dashboardReq.name;   **/// here is try to get value**
    const userMobile = dashboardReq.mobile; **/// here is try to get value**
    const newGasService = await gasData.create({
      userName,
      userMobile,
      customerNo,
      bookingNo,
      bookingDate,
    });

res.status(201).json({
  status: "success",
  data: { gasService: newGasService },
});

 }

catch (error) {
    res.status(400).json({
      status: "fail",
      data: next(error),
    });
  }
};


问:
Prevent empty multiple inputs from insertion to data base mysql
I have a 200 inputs ( 200 rows ) in my web page , the back end user some time enter 20 or 50 inputs and left the rest empty

how to prevent empty inputs from insertion to db

I get around that by deleting the rows with condition but is consuming time

this is my code

```<code><?php
include("db.php");
include("header.php");

if (isset($_POST['invoice_btn'])) {

    $userId = $_POST['userId'];
    $invoice_to = $_POST['companyName'];
    $subTotal = $_POST['subTotal'];
    $taxAmount = $_POST['taxAmount'];
    $taxRate = $_POST['taxRate'];
    $totalAftertax = $_POST['totalAftertax'];
    $amountPaid = $_POST['amountPaid'];
    $amountDue = $_POST['amountDue'];
    $notes = $_POST['notes'];
    $productCode = $_POST['productCode'];
    $productName = $_POST['productName'];
    $quantity = $_POST['quantity'];
    $price = $_POST['price'];
    $total = $_POST['total'];
    $dateTime = $_POST['dateTime'];

    $submitbutton = $_POST['invoice_btn'];

    if ($submitbutton) {
        if (empty($productCode)) {

            die(" Product code empty ");
        } else {

            $sqlInsert = "INSERT INTO invoice_order (invoice_to,order_date, order_total_before_tax, order_total_tax, order_tax_per, order_total_after_tax, order_amount_paid, order_total_amount_due, notes)
                    VALUES ('$invoice_to' ,'$dateTime', '$subTotal', '$taxAmount','$taxRate', '$totalAftertax','$amountPaid', '$amountDue','$notes')";
            $result = mysqli_query($conn, $sqlInsert);

            // The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query.
            $lastInsertId = mysqli_insert_id($conn);

            foreach ($productCode as $index => $productCodes) {

                $s_productCode  = $productCodes;
                $s_productName  = $productName[$index];
                $s_quantity     = $quantity[$index];
                $s_price     = $price[$index];
                $s_total     = $total[$index];

                $sqlInsertItem = "INSERT INTO invoice_order_item (order_id, item_code, item_name, order_item_quantity, order_item_price, order_item_final_amount)
                    VALUES ( '$lastInsertId' , '$s_productCode' , '$s_productName' , '$s_quantity', '$s_price', '$s_total')";
                $result2 = mysqli_query($conn, $sqlInsertItem);

                // Update Quantity on Hand from Produc table
                $sqlUpdateQty = "UPDATE product SET pro_quantity = pro_quantity-$s_quantity WHERE pro_id = $s_productCode ";
                $result3 = mysqli_query($conn, $sqlUpdateQty);

                //delete extra rows that are empty .
                $sqlDelete = "DELETE FROM `invoice_order_item` WHERE `item_code`=''";
                $Delresult = mysqli_query($conn, $sqlDelete);
            } // end foreach
        }; // end else
    } // end if
</code>```

答:
In your foreach loop, add a condition before the insertion:

```<code>if (empty($s_productCode)) continue;
</code>```

If the condition becomes true, continue will make the parser skip the rest of the code in the loop.

Body:
I have a 200 inputs ( 200 rows ) in my web page , the back end user some time enter 20 or 50 inputs and left the rest empty

how to prevent empty inputs from insertion to db

I get around that by deleting the rows with condition but is consuming time

this is my code

<?php
include("db.php");
include("header.php");

if (isset($_POST['invoice_btn'])) {

    $userId = $_POST['userId'];
    $invoice_to = $_POST['companyName'];
    $subTotal = $_POST['subTotal'];
    $taxAmount = $_POST['taxAmount'];
    $taxRate = $_POST['taxRate'];
    $totalAftertax = $_POST['totalAftertax'];
    $amountPaid = $_POST['amountPaid'];
    $amountDue = $_POST['amountDue'];
    $notes = $_POST['notes'];
    $productCode = $_POST['productCode'];
    $productName = $_POST['productName'];
    $quantity = $_POST['quantity'];
    $price = $_POST['price'];
    $total = $_POST['total'];
    $dateTime = $_POST['dateTime'];

    $submitbutton = $_POST['invoice_btn'];

    if ($submitbutton) {
        if (empty($productCode)) {

            die(" Product code empty ");
        } else {

            $sqlInsert = "INSERT INTO invoice_order (invoice_to,order_date, order_total_before_tax, order_total_tax, order_tax_per, order_total_after_tax, order_amount_paid, order_total_amount_due, notes)
                    VALUES ('$invoice_to' ,'$dateTime', '$subTotal', '$taxAmount','$taxRate', '$totalAftertax','$amountPaid', '$amountDue','$notes')";
            $result = mysqli_query($conn, $sqlInsert);

            // The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query.
            $lastInsertId = mysqli_insert_id($conn);

            foreach ($productCode as $index => $productCodes) {

                $s_productCode  = $productCodes;
                $s_productName  = $productName[$index];
                $s_quantity     = $quantity[$index];
                $s_price     = $price[$index];
                $s_total     = $total[$index];

                $sqlInsertItem = "INSERT INTO invoice_order_item (order_id, item_code, item_name, order_item_quantity, order_item_price, order_item_final_amount)
                    VALUES ( '$lastInsertId' , '$s_productCode' , '$s_productName' , '$s_quantity', '$s_price', '$s_total')";
                $result2 = mysqli_query($conn, $sqlInsertItem);

                // Update Quantity on Hand from Produc table
                $sqlUpdateQty = "UPDATE product SET pro_quantity = pro_quantity-$s_quantity WHERE pro_id = $s_productCode ";
                $result3 = mysqli_query($conn, $sqlUpdateQty);

                //delete extra rows that are empty .
                $sqlDelete = "DELETE FROM `invoice_order_item` WHERE `item_code`=''";
                $Delresult = mysqli_query($conn, $sqlDelete);
            } // end foreach
        }; // end else
    } // end if

Body:
In your foreach loop, add a condition before the insertion:

if (empty($s_productCode)) continue;

If the condition becomes true, continue will make the parser skip the rest of the code in the loop.


问:
ethstats on http://homestead.test:8081 don't display my nodes
I am following this guide https://www.sitepoint.com/puppeth-introduction/ to create my private ethereum network. Although ethstats looks fine when I install it, it does not display the nodes of the next steps (for example boot node). This happens when I pick for domain homestead.test .
If my domain is 192.168.10.10 the nodes display fine. Why is this happening? Any idea?</p>

答:
It looks the domain name is not connected to the IP.
Try to add the correct setting the the etc/hosts file. (You may need to edit the file as administrator).

The file is located at windows: : c:\Windows\System32\Drivers\etc\hosts

In case you are using mac this can help: https://help.nexcess.net/how-to-find-the-hosts-file-on-my-mac

```<code>192.168.10.10  homestead.test
</code>```

Body:
It looks the domain name is not connected to the IP.
Try to add the correct setting the the etc/hosts file. (You may need to edit the file as administrator).

The file is located at windows: : c:\Windows\System32\Drivers\etc\hosts

In case you are using mac this can help: https://help.nexcess.net/how-to-find-the-hosts-file-on-my-mac

192.168.10.10  homestead.test


问:
Java Hibernate Many To One Question
I am having problem with my Hibernate Mapping.
I have a many to one mapping between my entity.
The two tables in my Oracle DB are the following...

```<code>Employee
--------------------------
EMPLOYEE_ID
EMPLOYEE_FIRST_NAME
EMPLOYEE_LAST_NAME
HEALTH_PLAN_ID
Health_Plan
------------------=
HEALTH_PLAN_ID
HEALTH_PLAN_NAME
HEALTH_PLAN_RATE
</code>```

And my mapping...

```<code>@Entity
@Table(name = "Employee")
@SequenceGenerator(name = "employee_seq", sequenceName = "employee_seq")
public class Employee {
    private int employeeId;
    private String firstName;
    private String lastName;
    private HealthPlan plan;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "employee_seq")
    @Column(name = "employee_id", nullable = false)
    public int getEmployeeId() {
        return employeeId;
    }
    @Column(name = "employee_first_name", nullable = false)
    public String getFirstName() {
        return firstName;
    }
    @Column(name = "employee_last_name", nullable = false)
    public String getLastName() {
        return lastName;
    }
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "HEALTH_PLAN_ID")
    public HealthPlan getPlan() {
        return plan;
    }
}

@Entity
@Table(name = "HEALTH_PLAN")
@SequenceGenerator(name = "HEALTH_PLAN_SEQ", sequenceName = "HEALTH_PLAN_SEQ")
public class HealthPlan {
    private int healthPlanId;
    private String healthPlanName;
    private double healthPlanRate;
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "HEALTH_PLAN_SEQ")
    @Column(nullable = false, name = "HEALTH_PLAN_ID")
    public int getHealthPlanId() {
        return healthPlanId;
    }
    @Column(nullable = false, name = "HEALTH_PLAN_NAME", unique = true)
    public String getHealthPlanName() {
        return healthPlanName;
    }
    @Column(nullable = false, name = "HEALTH_PLAN_RATE")
    public double getHealthPlanRate() {
        return healthPlanRate;
    }
}
</code>```

When I ran below code....

```<code>    public static void main(String[] args) throws SQLException {
        HealthPlanDaoImpl healthDao = new HealthPlanDaoImpl();
        EmployeeDaoImpl empDao = new EmployeeDaoImpl();

        HealthPlan plan = new HealthPlan();
        plan.setHealthPlanName("PLAN B");
        plan.setHealthPlanRate(5.0);

        Employee emp = new Employee();
        emp.setPlan(plan);
        emp.setFirstName("Jane");
        emp.setLastName("Doe");
        boolean isSuccess = empDao.addEmployee(emp);
        System.out.println(isSuccess);

    }
public class EmployeeDaoImpl{
    public  boolean addEmployee(Employee emp) {
      boolean bolReturn = true;

      Session session = HibernateUtil.beginTransaction();
      try {
          session.save(emp);
          HibernateUtil.commitTransaction();
      } catch (Exception e) {
          e.printStackTrace();
          bolReturn = false;
          HibernateUtil.rollbackTransaction();
      }
      return bolReturn;
    }
}
</code>```

In the Health_Plan Table, the HEALTH_PLAN_ID = 3 (Which is correct!!!)
In the Employee Table, the HEALTH_PLAN_ID = 1850 (Where did this value came from???  I expect this to be 3 also.)

I tried several times and I notice that in the Employee Table HEALTH_PLAN_ID just increment by 300.
I think I already set the cascade option.

Any hints?

答:
```<code>HealthPlan plan = new HealthPlan();
plan.setHealthPlanName("PLAN B");
plan.setHealthPlanRate(5.0);

Employee emp = new Employee();
emp.setPlan(plan);
emp.setFirstName("Jane");
emp.setLastName("Doe");
</code>```

creates a new HealthPlan instance for every Employee instance created. The original HealthPlan instance is not used in a new mapping between a new Employee and an existing HealthPlan. If you query for the existing HealthPlan instance, and then set it to every Employee, you will find that the health plan id will be consistent across objects.

The discrepancy in the values for the HEALTH_PLAN_ID values can be attributed to the afore mentioned behavior of your test code. Also, the sequence allocation size would have been incremented by 50, which is the default, and you happen to be seeing the result of six consecutive sequence increment operations. Note, that Hibernate will update sequences in a different transaction, so you will find that the sequence values will increment even if you rollback the current transaction.

On a different note, I would advise against using a unidirectional @ManyToOne relationship with a CascadeType value of ALL. Do you really want to delete the HealthPlan of all Employee instances if one Employee is removed, or for that matter, allow updates of HealthPlan instances from an Employee to be propagated for merge events?

ContentLicense: CC BY-SA 3.0

Title: Java Hibernate Many To One Question

Body:
I am having problem with my Hibernate Mapping.
I have a many to one mapping between my entity.
The two tables in my Oracle DB are the following...

Employee
--------------------------
EMPLOYEE_ID
EMPLOYEE_FIRST_NAME
EMPLOYEE_LAST_NAME
HEALTH_PLAN_ID
Health_Plan
------------------=
HEALTH_PLAN_ID
HEALTH_PLAN_NAME
HEALTH_PLAN_RATE

And my mapping...

@Entity
@Table(name = "Employee")
@SequenceGenerator(name = "employee_seq", sequenceName = "employee_seq")
public class Employee {
    private int employeeId;
    private String firstName;
    private String lastName;
    private HealthPlan plan;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "employee_seq")
    @Column(name = "employee_id", nullable = false)
    public int getEmployeeId() {
        return employeeId;
    }
    @Column(name = "employee_first_name", nullable = false)
    public String getFirstName() {
        return firstName;
    }
    @Column(name = "employee_last_name", nullable = false)
    public String getLastName() {
        return lastName;
    }
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "HEALTH_PLAN_ID")
    public HealthPlan getPlan() {
        return plan;
    }
}

@Entity
@Table(name = "HEALTH_PLAN")
@SequenceGenerator(name = "HEALTH_PLAN_SEQ", sequenceName = "HEALTH_PLAN_SEQ")
public class HealthPlan {
    private int healthPlanId;
    private String healthPlanName;
    private double healthPlanRate;
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "HEALTH_PLAN_SEQ")
    @Column(nullable = false, name = "HEALTH_PLAN_ID")
    public int getHealthPlanId() {
        return healthPlanId;
    }
    @Column(nullable = false, name = "HEALTH_PLAN_NAME", unique = true)
    public String getHealthPlanName() {
        return healthPlanName;
    }
    @Column(nullable = false, name = "HEALTH_PLAN_RATE")
    public double getHealthPlanRate() {
        return healthPlanRate;
    }
}

When I ran below code....

    public static void main(String[] args) throws SQLException {
        HealthPlanDaoImpl healthDao = new HealthPlanDaoImpl();
        EmployeeDaoImpl empDao = new EmployeeDaoImpl();

        HealthPlan plan = new HealthPlan();
        plan.setHealthPlanName("PLAN B");
        plan.setHealthPlanRate(5.0);

        Employee emp = new Employee();
        emp.setPlan(plan);
        emp.setFirstName("Jane");
        emp.setLastName("Doe");
        boolean isSuccess = empDao.addEmployee(emp);
        System.out.println(isSuccess);

    }
public class EmployeeDaoImpl{
    public  boolean addEmployee(Employee emp) {
      boolean bolReturn = true;

      Session session = HibernateUtil.beginTransaction();
      try {
          session.save(emp);
          HibernateUtil.commitTransaction();
      } catch (Exception e) {
          e.printStackTrace();
          bolReturn = false;
          HibernateUtil.rollbackTransaction();
      }
      return bolReturn;
    }
}

In the Health_Plan Table, the HEALTH_PLAN_ID = 3 (Which is correct!!!)
In the Employee Table, the HEALTH_PLAN_ID = 1850 (Where did this value came from???  I expect this to be 3 also.)

I tried several times and I notice that in the Employee Table HEALTH_PLAN_ID just increment by 300.
I think I already set the cascade option.

Any hints?

Body:
HealthPlan plan = new HealthPlan();
plan.setHealthPlanName("PLAN B");
plan.setHealthPlanRate(5.0);

Employee emp = new Employee();
emp.setPlan(plan);
emp.setFirstName("Jane");
emp.setLastName("Doe");

creates a new HealthPlan instance for every Employee instance created. The original HealthPlan instance is not used in a new mapping between a new Employee and an existing HealthPlan. If you query for the existing HealthPlan instance, and then set it to every Employee, you will find that the health plan id will be consistent across objects.

The discrepancy in the values for the HEALTH_PLAN_ID values can be attributed to the afore mentioned behavior of your test code. Also, the sequence allocation size would have been incremented by 50, which is the default, and you happen to be seeing the result of six consecutive sequence increment operations. Note, that Hibernate will update sequences in a different transaction, so you will find that the sequence values will increment even if you rollback the current transaction.

On a different note, I would advise against using a unidirectional @ManyToOne relationship with a CascadeType value of ALL. Do you really want to delete the HealthPlan of all Employee instances if one Employee is removed, or for that matter, allow updates of HealthPlan instances from an Employee to be propagated for merge events?


问:
How to disable Inkwell image button in flutter
I would like to make the inkwell image button to be disabled. I can disable onTap event, but can't make gray like disabled button. I tried with adding this code

decoration: new BoxDecoration(color:Colors.grey.withOpacity(0.6)),
```
<p>But it doesn't work as I want.</p>
<p>My code:</p>
<pre class="lang-dart prettyprint-override"><code> child: Container(
              decoration:
                  new BoxDecoration(color: Colors.grey.withOpacity(0.6)),
              child: Material(
                //elevation: 4.0,
                clipBehavior: Clip.none,
                color: Colors.black,
                child: Stack(
                  alignment: Alignment.center,
                  fit: StackFit.passthrough,
                  children: [
                    Ink.image(
                      image: AssetImage(ihaveheard_imagepath),
                      fit: BoxFit.cover,
                      width: MediaQuery.of(context).size.width / 4 * 3,
                      height: MediaQuery.of(context).size.width / 6,
                      child: InkWell(onTap: () {}),
                    ),
                    Align(
                      alignment: Alignment.center,
                      child: Padding(
                        padding: EdgeInsets.all(8.0),
                        child: InkWell(
                          child: Text(
                            LocaleKeys.ihaveheard,
                            style: TextStyle(
                                fontSize:
                                    MediaQuery.of(context).size.width / 30,
                                color: Colors.white),
                          ).tr(),
                          onTap: () {
                            ihaveheard_imagepath =
                                "assets/images/greenbutton.png";

                            setState(() {});
                          },
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
</code>```

答:
You can use IgnorePointer as parent widget to prevent tab event.

IgnorePointer(
  ignoring: disableBtn, //true, false
  child: yourWidget()
```
<p>You can pass null to <code>decoration</code> to show default based on tappable state</p>
<pre class="lang-dart prettyprint-override"><code>Container(
 decoration: disableBtn? BoxDecoration(...): null,
 .....
)
</code>```

Body:
I would like to make the inkwell image button to be disabled. I can disable onTap event, but can't make gray like disabled button. I tried with adding this code

decoration: new BoxDecoration(color:Colors.grey.withOpacity(0.6)),

But it doesn't work as I want.

My code:

 child: Container(
              decoration:
                  new BoxDecoration(color: Colors.grey.withOpacity(0.6)),
              child: Material(
                //elevation: 4.0,
                clipBehavior: Clip.none,
                color: Colors.black,
                child: Stack(
                  alignment: Alignment.center,
                  fit: StackFit.passthrough,
                  children: [
                    Ink.image(
                      image: AssetImage(ihaveheard_imagepath),
                      fit: BoxFit.cover,
                      width: MediaQuery.of(context).size.width / 4 * 3,
                      height: MediaQuery.of(context).size.width / 6,
                      child: InkWell(onTap: () {}),
                    ),
                    Align(
                      alignment: Alignment.center,
                      child: Padding(
                        padding: EdgeInsets.all(8.0),
                        child: InkWell(
                          child: Text(
                            LocaleKeys.ihaveheard,
                            style: TextStyle(
                                fontSize:
                                    MediaQuery.of(context).size.width / 30,
                                color: Colors.white),
                          ).tr(),
                          onTap: () {
                            ihaveheard_imagepath =
                                "assets/images/greenbutton.png";

                            setState(() {});
                          },
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),

Body:
You can use IgnorePointer as parent widget to prevent tab event.

IgnorePointer(
  ignoring: disableBtn, //true, false
  child: yourWidget()

You can pass null to decoration to show default based on tappable state

Container(
 decoration: disableBtn? BoxDecoration(...): null,
 .....
)


问:
In DataTemplate ,how to get the page's field by databinding?
```<code>        <ListView
            x:Name="List"
            ItemsSource="{x:Bind taglist}"
            SelectionMode="None">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="x:String">
                    <RelativePanel HorizontalAlignment="Stretch">
                        <TextBlock
                            x:Name="str"
                            Text="{x:Bind}" />
                        <ComboBox
                            ItemsSource="{binding source=combolist}"/>
                    </RelativePanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

combolist is a collection of string ,field of page insatnce.

the textblock control in datatemplate use a list as datasource,but the comboxes use another datasource (only datasource is same,but not mean same selection and control action).

i tried to use {binding} markupextension, but this kind of databinding cannot find the varity.

答:
Give the Page a name:

```<code><Page x:Name="thePage" ...
</code>```

Bind to it using an ElementName:

```<code><ComboBox ItemsSource="{Binding Path=combolist, ElementName=thePage}"/>
</code>```

Finally, you need to turn combolist into a public property  as you cannot bind to fields:

```<code>public List<string> combolist { get; set; }
</code>```

Body:
        <ListView
            x:Name="List"
            ItemsSource="{x:Bind taglist}"
            SelectionMode="None">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="x:String">
                    <RelativePanel HorizontalAlignment="Stretch">
                        <TextBlock
                            x:Name="str"
                            Text="{x:Bind}" />
                        <ComboBox
                            ItemsSource="{binding source=combolist}"/>
                    </RelativePanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

combolist is a collection of string ,field of page insatnce.

the textblock control in datatemplate use a list as datasource,but the comboxes use another datasource (only datasource is same,but not mean same selection and control action).

i tried to use {binding} markupextension, but this kind of databinding cannot find the varity.

Body:
Give the Page a name:

<Page x:Name="thePage" ...

Bind to it using an ElementName:

<ComboBox ItemsSource="{Binding Path=combolist, ElementName=thePage}"/>

Finally, you need to turn combolist into a public property  as you cannot bind to fields:

public List<string> combolist { get; set; }


问:
Filter Table results Self Join
Imagine a large table that contains receipt information. Since it holds so much data, you are required to return a subset of the data, excluding or consolidating rows where possible.

Here is the SQL and results table showing how the data should be returned.

```<code>create table table1
(RecieptNo smallint, Customer varchar(10),  ReceiptDate date,
 ItemDesc varchar(10), Amount smallint)

insert into table1 values
(100, 'Matt','2022-01-05','Ball', 10),
(101, 'Mark','2022-01-07','Hat', 20),
(101, 'Mark','2022-01-07','Jumper', -20),
(101, 'Mark','2022-01-14','Spoon', 30),
(102, 'Luke','2022-01-15','Fork', 15),
(102, 'Luke','2022-01-17','Spork', -10),
(103, 'John','2022-01-20','Orange', 13),
(103, 'John','2022-01-25','Pear', 12)
</code>```

If there are rows on the same receipt where the negative and positive values cancel out, do not return either row.
If there is a receipt with a negative amount not exceeding positive amount, the negative amount should be deducted from positive line.

RecieptNo
Customer
ReceiptDate
ItemDesc
Amount

100
Matt
2022-01-05
Ball
10

101
Mark
2022-01-14
Spoon
30

102
Luke
2022-01-15
Fork
5

103
John
2022-01-20
Orange
13

103
John
2022-01-25
Pear
12

This is proving tricky, any ideas?

答:
Based on table you provided, I suppose you want only row with the earliest date when you have multiple rows with same receipts which bring positive Amount after deduction.

```<code>;WITH cte AS (
SELECT  *
,       SUM( amount) OVER (PARTITION BY RecieptNo ORDER BY RecieptNo, ReceiptDate ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS ActualAmount
,       ROW_NUMBER() OVER (PARTITION BY RecieptNo ORDER BY RecieptNo, ReceiptDate) AS rn
FROM table1)
SELECT RecieptNo, Customer, ReceiptDate, ItemDesc, ActualAmount
FROM cte
WHERE ActualAmount > 0 AND rn = 1
</code>```

Read about window functions and cte's though.

Title: Filter Table results Self Join

Body:
Imagine a large table that contains receipt information. Since it holds so much data, you are required to return a subset of the data, excluding or consolidating rows where possible.

Here is the SQL and results table showing how the data should be returned.

create table table1
(RecieptNo smallint, Customer varchar(10),  ReceiptDate date,
 ItemDesc varchar(10), Amount smallint)

insert into table1 values
(100, 'Matt','2022-01-05','Ball', 10),
(101, 'Mark','2022-01-07','Hat', 20),
(101, 'Mark','2022-01-07','Jumper', -20),
(101, 'Mark','2022-01-14','Spoon', 30),
(102, 'Luke','2022-01-15','Fork', 15),
(102, 'Luke','2022-01-17','Spork', -10),
(103, 'John','2022-01-20','Orange', 13),
(103, 'John','2022-01-25','Pear', 12)

If there are rows on the same receipt where the negative and positive values cancel out, do not return either row.
If there is a receipt with a negative amount not exceeding positive amount, the negative amount should be deducted from positive line.

RecieptNo
Customer
ReceiptDate
ItemDesc
Amount

100
Matt
2022-01-05
Ball
10

101
Mark
2022-01-14
Spoon
30

102
Luke
2022-01-15
Fork
5

103
John
2022-01-20
Orange
13

103
John
2022-01-25
Pear
12

This is proving tricky, any ideas?

Body:
Based on table you provided, I suppose you want only row with the earliest date when you have multiple rows with same receipts which bring positive Amount after deduction.

;WITH cte AS (
SELECT  *
,       SUM( amount) OVER (PARTITION BY RecieptNo ORDER BY RecieptNo, ReceiptDate ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS ActualAmount
,       ROW_NUMBER() OVER (PARTITION BY RecieptNo ORDER BY RecieptNo, ReceiptDate) AS rn
FROM table1)
SELECT RecieptNo, Customer, ReceiptDate, ItemDesc, ActualAmount
FROM cte
WHERE ActualAmount > 0 AND rn = 1

Read about window functions and cte's though.


问:
How to fix Next.js Vercel deployment module not found error
My next.js app works on my machine and was working when deployed on Vercel but now it fails when building on Vercel with the following error:

I've tried deleting node_modules and running npm install a few times but with no joy.

Any help would be hugely appreciated. Thank you!

Running "npm run build"
  20:43:24.926

  tdwcks@1.0.0 build /vercel/5ccaedc9
  20:43:24.926

  next build
  20:43:24.967

  internal/modules/cjs/loader.js:983
  20:43:24.967

    throw err;
  20:43:24.967

    ^
  20:43:24.967

  Error: Cannot find module '../build/output/log'
  20:43:24.967

  Require stack:
  20:43:24.967

  - /vercel/5ccaedc9/node_modules/.bin/next
  20:43:24.967

      at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)
  20:43:24.967

      at Function.Module._load (internal/modules/cjs/loader.js:862:27)
  20:43:24.967

      at Module.require (internal/modules/cjs/loader.js:1042:19)
  20:43:24.967

      at require (internal/modules/cjs/helpers.js:77:18)
  20:43:24.967

      at Object. (/vercel/5ccaedc9/node_modules/.bin/next:2:46)
  20:43:24.967

      at Module._compile (internal/modules/cjs/loader.js:1156:30)
  20:43:24.967

      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
  20:43:24.967

      at Module.load (internal/modules/cjs/loader.js:1000:32)
  20:43:24.967

      at Function.Module._load (internal/modules/cjs/loader.js:899:14)
  20:43:24.967

      at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
  20:43:24.967

    code: 'MODULE_NOT_FOUND',
  20:43:24.967

    requireStack: [ '/vercel/5ccaedc9/node_modules/.bin/next' ]
  20:43:24.967

  }
  20:43:24.969

  npm ERR! code ELIFECYCLE
  20:43:24.969

  npm ERR! errno 1
  20:43:24.970

  npm ERR! tdwcks@1.0.0 build: next build
  20:43:24.970

  npm ERR! Exit status 1
  20:43:24.970

  npm ERR!
  20:43:24.970

  npm ERR! Failed at the tdwcks@1.0.0 build script.
  20:43:24.970

  npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
  20:43:24.974

  npm ERR! A complete log of this run can be found in:
  20:43:24.974

  npm ERR!     /vercel/.npm/_logs/2020-06-17T19_43_24_971Z-debug.log
  20:43:24.979

  Error: Command "npm run build" exited with 1
  20:43:25.342

  [dmesg] follows:
  20:43:25.342

  [  962.449223] ecs-bridge: port 1(veth2a021300) entered disabled state
  20:43:25.342

  [  962.453655] device veth2a021300 entered promiscuous mode
  20:43:25.342

  [  962.457686] ecs-bridge: port 1(veth2a021300) entered blocking state
  20:43:25.342

  [  962.462004] ecs-bridge: port 1(veth2a021300) entered forwarding state
  20:43:26.242

  Done with "package.json"

Here's my Package.json

```<code>{
  "name": "tdwcks",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cjs": "0.0.11",
    "core-util-is": "^1.0.2",
    "framer-motion": "^1.11.0",
    "gray-matter": "^4.0.2",
    "next": "^9.4.4",
    "raw-loader": "^4.0.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-ga": "^3.0.0",
    "react-markdown": "^4.3.1",
    "react-player": "^2.2.0",
    "react-scripts": "^3.4.1"
  },
  "devDependencies": {
    "postcss-preset-env": "^6.7.0",
    "tailwindcss": "^1.4.6"
  }
}
</code>```

答: For me it was a problem with that specific package, when I looked for it in my package.json and under node_modules i couldn't find it. Even though it was working in local builds somehow.</p>

Body:
My next.js app works on my machine and was working when deployed on Vercel but now it fails when building on Vercel with the following error:

I've tried deleting node_modules and running npm install a few times but with no joy.

Any help would be hugely appreciated. Thank you!

Running "npm run build"
  20:43:24.926

  tdwcks@1.0.0 build /vercel/5ccaedc9
  20:43:24.926

  next build
  20:43:24.967

  internal/modules/cjs/loader.js:983
  20:43:24.967

    throw err;
  20:43:24.967

    ^
  20:43:24.967

  Error: Cannot find module '../build/output/log'
  20:43:24.967

  Require stack:
  20:43:24.967

  - /vercel/5ccaedc9/node_modules/.bin/next
  20:43:24.967

      at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)
  20:43:24.967

      at Function.Module._load (internal/modules/cjs/loader.js:862:27)
  20:43:24.967

      at Module.require (internal/modules/cjs/loader.js:1042:19)
  20:43:24.967

      at require (internal/modules/cjs/helpers.js:77:18)
  20:43:24.967

      at Object. (/vercel/5ccaedc9/node_modules/.bin/next:2:46)
  20:43:24.967

      at Module._compile (internal/modules/cjs/loader.js:1156:30)
  20:43:24.967

      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
  20:43:24.967

      at Module.load (internal/modules/cjs/loader.js:1000:32)
  20:43:24.967

      at Function.Module._load (internal/modules/cjs/loader.js:899:14)
  20:43:24.967

      at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
  20:43:24.967

    code: 'MODULE_NOT_FOUND',
  20:43:24.967

    requireStack: [ '/vercel/5ccaedc9/node_modules/.bin/next' ]
  20:43:24.967

  }
  20:43:24.969

  npm ERR! code ELIFECYCLE
  20:43:24.969

  npm ERR! errno 1
  20:43:24.970

  npm ERR! tdwcks@1.0.0 build: next build
  20:43:24.970

  npm ERR! Exit status 1
  20:43:24.970

  npm ERR!
  20:43:24.970

  npm ERR! Failed at the tdwcks@1.0.0 build script.
  20:43:24.970

  npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
  20:43:24.974

  npm ERR! A complete log of this run can be found in:
  20:43:24.974

  npm ERR!     /vercel/.npm/_logs/2020-06-17T19_43_24_971Z-debug.log
  20:43:24.979

  Error: Command "npm run build" exited with 1
  20:43:25.342

  [dmesg] follows:
  20:43:25.342

  [  962.449223] ecs-bridge: port 1(veth2a021300) entered disabled state
  20:43:25.342

  [  962.453655] device veth2a021300 entered promiscuous mode
  20:43:25.342

  [  962.457686] ecs-bridge: port 1(veth2a021300) entered blocking state
  20:43:25.342

  [  962.462004] ecs-bridge: port 1(veth2a021300) entered forwarding state
  20:43:26.242

  Done with "package.json"

Here's my Package.json

{
  "name": "tdwcks",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cjs": "0.0.11",
    "core-util-is": "^1.0.2",
    "framer-motion": "^1.11.0",
    "gray-matter": "^4.0.2",
    "next": "^9.4.4",
    "raw-loader": "^4.0.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-ga": "^3.0.0",
    "react-markdown": "^4.3.1",
    "react-player": "^2.2.0",
    "react-scripts": "^3.4.1"
  },
  "devDependencies": {
    "postcss-preset-env": "^6.7.0",
    "tailwindcss": "^1.4.6"
  }
}


问:
awk calculate the difference with last row and create new column with value
I have a file like this :

```<code>time,VALUE
2022-02-02 00:00:39,57
2022-02-02 00:01:39,58
2022-02-02 00:02:39,59
2022-02-02 00:03:39,59
2022-02-02 00:04:40,62
2022-02-02 00:05:40,60
</code>```

And I would like (maybe the better choice is awk) to create a new column which calculate the difference with last row. Example :

```<code>time,VALUE,Diff
2022-02-02 00:00:39,57,0
2022-02-02 00:01:39,58,1
2022-02-02 00:02:39,59,1
2022-02-02 00:03:39,59,0
2022-02-02 00:04:40,62,3
2022-02-02 00:05:40,60,-2
</code>```

I have this little script  awk 'NR==1{s=$1;next}{print $1-s;s=$1}' but I don't know how to easily add a new colum with results and to add a '0' for the first line

Thanks

Body:
I have a file like this :

time,VALUE
2022-02-02 00:00:39,57
2022-02-02 00:01:39,58
2022-02-02 00:02:39,59
2022-02-02 00:03:39,59
2022-02-02 00:04:40,62
2022-02-02 00:05:40,60

And I would like (maybe the better choice is awk) to create a new column which calculate the difference with last row. Example :

time,VALUE,Diff
2022-02-02 00:00:39,57,0
2022-02-02 00:01:39,58,1
2022-02-02 00:02:39,59,1
2022-02-02 00:03:39,59,0
2022-02-02 00:04:40,62,3
2022-02-02 00:05:40,60,-2

I have this little script  awk 'NR==1{s=$1;next}{print $1-s;s=$1}' but I don't know how to easily add a new colum with results and to add a '0' for the first line

Thanks

Body:
Another awk idea:

awk '
BEGIN {FS=OFS=","}
NR==1 {print $0,"Diff"; next}
      {print $0,(NR==2 ? 0 : $2-last); last=$2}
' file

This generates:

time,VALUE,Diff
2022-02-02 00:00:39,57,0
2022-02-02 00:01:39,58,1
2022-02-02 00:02:39,59,1
2022-02-02 00:03:39,59,0
2022-02-02 00:04:40,62,3
2022-02-02 00:05:40,60,-2


问:
How to create a custom response base in Angular HTTP service?
I am returning a custom response from Spring Boot API as below:

```<code>public static ResponseEntity<Object> generateResponse(String message, HttpStatus status, Object responseObj) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("Message", message);
        map.put("Status", status.value());
        map.put("Output", responseObj);

        return new ResponseEntity<Object>(map,status);
    }
</code>```

which it will return: message, status and the output. So now I am wondering how could I make a custom response in Angular to receive all these three attributes. How should I replace the "???" with? I should be customizing the response base right?

```<code>public Get(): Observable<Book>{
    return this.http.get< ???<Book> >(this.baseUrl).pipe(map(response => response.Output))
  }
</code>```

答:
You can use generics for this.

```<code>interface ApiResponse<T> {
    message: string;
    status: string;
    output: T;
}

interface User {
    id: number;
    username: string;
}

interface BlogPost {
    id: number;
    title: string;
    postedDate: Date;
}
</code>```

Then you can have functions that return an ApiResponse of some specific type. A plain typescript example:

```<code>const getUser = function(): ApiResponse<User> {
    const response: ApiResponse<User> = {
        message: 'test',
        status: 'good',
        output: {
            id: 1,
            username: 'test'
        }
    }
    return response;
}

const getBlog = function(): ApiResponse<BlogPost> {
    const response: ApiResponse<BlogPost> = {
        message: 'test',
        status: 'good',
        output: {
            id: 1,
            title: 'Stuff!',
            postedDate: new Date()
        }
    }
    return response;
}
</code>```

If you know the data in output also shares some common attributes, you can even use generic constraints to further reduce any duplication in your typescript models.

```<code>interface ApiResponse<T extends DbModel> {
    message: string;
    status: string;
    output: T;
}

interface DbModel {
    id: number;
}

interface User extends DbModel {
    username: string;
}

interface ThingThatDoesNotExtendDbModel {
    someField: string;
}

//totally valid
const valid: ApiResponse<User> = { /* fields */};

/*
 * Typescript compile error: Type 'ThingThatDoesNotExtendDbModel' does not satisfy the constraint
 * 'DbModel'.
 *  Property 'id' is missing in type 'ThingThatDoesNotExtendDbModel' but
 *   required in type 'DbModel
 */
 const invalid: ApiResponse<ThingThatDoesNotExtendDbModel> = { /*fields*/};
</code>```

Body:
I am returning a custom response from Spring Boot API as below:

public static ResponseEntity<Object> generateResponse(String message, HttpStatus status, Object responseObj) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("Message", message);
        map.put("Status", status.value());
        map.put("Output", responseObj);

        return new ResponseEntity<Object>(map,status);
    }

which it will return: message, status and the output. So now I am wondering how could I make a custom response in Angular to receive all these three attributes. How should I replace the "???" with? I should be customizing the response base right?

public Get(): Observable<Book>{
    return this.http.get< ???<Book> >(this.baseUrl).pipe(map(response => response.Output))
  }

Body:
You can use generics for this.

interface ApiResponse<T> {
    message: string;
    status: string;
    output: T;
}

interface User {
    id: number;
    username: string;
}

interface BlogPost {
    id: number;
    title: string;
    postedDate: Date;
}

Then you can have functions that return an ApiResponse of some specific type. A plain typescript example:

const getUser = function(): ApiResponse<User> {
    const response: ApiResponse<User> = {
        message: 'test',
        status: 'good',
        output: {
            id: 1,
            username: 'test'
        }
    }
    return response;
}

const getBlog = function(): ApiResponse<BlogPost> {
    const response: ApiResponse<BlogPost> = {
        message: 'test',
        status: 'good',
        output: {
            id: 1,
            title: 'Stuff!',
            postedDate: new Date()
        }
    }
    return response;
}

If you know the data in output also shares some common attributes, you can even use generic constraints to further reduce any duplication in your typescript models.

interface ApiResponse<T extends DbModel> {
    message: string;
    status: string;
    output: T;
}

interface DbModel {
    id: number;
}

interface User extends DbModel {
    username: string;
}

interface ThingThatDoesNotExtendDbModel {
    someField: string;
}

//totally valid
const valid: ApiResponse<User> = { /* fields */};

/*
 * Typescript compile error: Type 'ThingThatDoesNotExtendDbModel' does not satisfy the constraint
 * 'DbModel'.
 *  Property 'id' is missing in type 'ThingThatDoesNotExtendDbModel' but
 *   required in type 'DbModel
 */
 const invalid: ApiResponse<ThingThatDoesNotExtendDbModel> = { /*fields*/};


问:
Update specific firebase auth session custom claims
i m using firebase auth in my app.

auth methods :  custom auth and google sign in. user can login using any of the two.

user can have multiple auth sessions running in multiple devices.

now when the user logs in using custom auth then i set some custom claims[session id] while sending the custom auth token.

QUESTION

in case user signs in using google signin how do i make sure that the custom claim is only applied to specific session [using admin sdk to update custom claims] ?

use case : every session has a unique id so that it can subscribe to it and once the session id deleted from any other device the user gets log out automatically.

thnx in advance

答:
It does appear to be possible to have something similar to per-session custom claims using Custom Tokens, and the custom claims will be "temporary" (not persisted on the Firebase user object).

Authenticate the user on the frontend using the typical Firebase process (Google Sign-In, email/password, etc.)

Send the token to your backend and validate it

Mint a custom token with the desired custom claim using the Firebase Admin SDK

Send the custom token to the frontend

Re-authenticate the user using signInWithCustomToken()

I've found this to be particularly useful when temporarily elevating or modifying a user's permissions (e.g. an admin performing a restricted action on behalf of another user).


问:
Color change in ListView.builder
Color change in ListView.builder

When I get to the layout I fill in the List, this List is passed to ListView and drawn, that is, when you change the mode to night, the color of the tiles does not change until you switch to layout or until you force to redraw ListView itself.

The question is how to change the color of already rendered ListView elements

Creating a ListView is as follows:

```<code>Widget _taskListView() {
    return ListView.builder(
      itemCount: _task.length,
      itemBuilder: (contextItems, index) {
        return _task[index];
      },
    );
  }
</code>```

And here is the card itself, which falls into the List of elements:

```<code>Widget _cardTask(BuildContext context, int index, TaskModel taskModel) {
    return Padding(
      padding: EdgeInsets.only(top: 10.0, left: 5.0, right: 5.0),
      child: InkWell(
        hoverColor: customRed,
        onTap: () {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => SetTimeScreen(taskModel))
          );
        },
        child: Container(
          height: 80,
          decoration: BoxDecoration(
            boxShadow: [
              BoxShadow(
                color: Colors.black12,
                blurRadius: 6.0,
                offset: Offset(0, 2),
              )
            ],
            color: OtherStaticData.darkMode ? customGray50 : Colors.white,
            borderRadius: BorderRadius.all(const Radius.circular(15.0)),
          ),
          child: _cardTaskBody(context, taskModel),
        ),
      ),
    );
  }
</code>```

答: Solution for the problem become architecture pattern BLoC</p>

Title: Color change in ListView.builder

Body:
Color change in ListView.builder

When I get to the layout I fill in the List, this List is passed to ListView and drawn, that is, when you change the mode to night, the color of the tiles does not change until you switch to layout or until you force to redraw ListView itself.

The question is how to change the color of already rendered ListView elements

Creating a ListView is as follows:

Widget _taskListView() {
    return ListView.builder(
      itemCount: _task.length,
      itemBuilder: (contextItems, index) {
        return _task[index];
      },
    );
  }

And here is the card itself, which falls into the List of elements:

Widget _cardTask(BuildContext context, int index, TaskModel taskModel) {
    return Padding(
      padding: EdgeInsets.only(top: 10.0, left: 5.0, right: 5.0),
      child: InkWell(
        hoverColor: customRed,
        onTap: () {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => SetTimeScreen(taskModel))
          );
        },
        child: Container(
          height: 80,
          decoration: BoxDecoration(
            boxShadow: [
              BoxShadow(
                color: Colors.black12,
                blurRadius: 6.0,
                offset: Offset(0, 2),
              )
            ],
            color: OtherStaticData.darkMode ? customGray50 : Colors.white,
            borderRadius: BorderRadius.all(const Radius.circular(15.0)),
          ),
          child: _cardTaskBody(context, taskModel),
        ),
      ),
    );
  }


问:
Powershell: Tried to get output with Display name, lastLogonTime (3O days) and totalitemsize from Exchange
I have this pipeline:

```<code>Get-Mailbox -ResultSize Unlimited –RecipientTypeDetails UserMailbox,SharedMailbox |
    Where {(Get-MailboxStatistics $_.Identity).LastLogonTime -gt (Get-Date).AddDays(-36)} |
    Sort -Property @{e={( Get-MailboxStatistics $_.Identity).LastLogonTime}} -Descending |
    Select-Object DisplayName,@{n="LastLogonTime";e={(Get-MailboxStatistics $_.Identity).LastLogonTime}} |
    Get-MailboxStatistics |
    Select-Object displayname, totalitemsize |
    Export-Csv -Path 'C:\JV'
</code>```

but the output never gets the third column in the output table - size.

DisplayName           LastLogonTime
-----------           -------------
Some User             2/8/2022 2:47:26 PM
Another Name          2/8/2022 2:46:59 PM
Yet AnotherName       2/8/2022 2:46:54 PM
```

答:
I believe this should be a more efficient and straight forward way of getting the data you're looking for:</p>
```<code>$dateLimit = [datetime]::Now.AddDays(-36)

Get-Mailbox -ResultSize Unlimited –RecipientTypeDetails UserMailbox, SharedMailbox | ForEach-Object {
    $stats = Get-MailboxStatistics $_.Identity
    # If the date is lower than the date limit, skip this user.
    if($stats.LastLogonTime -lt $dateLimit) { return }
    [pscustomobject]@{
        DisplayName   = $_.DisplayName
        LastLogonTime = $stats.LastLogonTime
        TotalItemSize = $stats.TotalItemSize
    }
} | Sort-Object LastLogonTime -Descending | Export-Csv -Path 'C:\path\to\csvfile.csv' -NoTypeInformation
</code>```

Body:
I have this pipeline:

Get-Mailbox -ResultSize Unlimited –RecipientTypeDetails UserMailbox,SharedMailbox |
    Where {(Get-MailboxStatistics $_.Identity).LastLogonTime -gt (Get-Date).AddDays(-36)} |
    Sort -Property @{e={( Get-MailboxStatistics $_.Identity).LastLogonTime}} -Descending |
    Select-Object DisplayName,@{n="LastLogonTime";e={(Get-MailboxStatistics $_.Identity).LastLogonTime}} |
    Get-MailboxStatistics |
    Select-Object displayname, totalitemsize |
    Export-Csv -Path 'C:\JV'

but the output never gets the third column in the output table - size.

DisplayName           LastLogonTime
-----------           -------------
Some User             2/8/2022 2:47:26 PM
Another Name          2/8/2022 2:46:59 PM
Yet AnotherName       2/8/2022 2:46:54 PM

Body:
I believe this should be a more efficient and straight forward way of getting the data you're looking for:

$dateLimit = [datetime]::Now.AddDays(-36)

Get-Mailbox -ResultSize Unlimited –RecipientTypeDetails UserMailbox, SharedMailbox | ForEach-Object {
    $stats = Get-MailboxStatistics $_.Identity
    # If the date is lower than the date limit, skip this user.
    if($stats.LastLogonTime -lt $dateLimit) { return }
    [pscustomobject]@{
        DisplayName   = $_.DisplayName
        LastLogonTime = $stats.LastLogonTime
        TotalItemSize = $stats.TotalItemSize
    }
} | Sort-Object LastLogonTime -Descending | Export-Csv -Path 'C:\path\to\csvfile.csv' -NoTypeInformation


问:
'git log' output encoding issues in Windows 10 CLI terminal

Problem

How can I make git log command output properly displayed in the Windows CLI terminal?

Example

As you can see, I can type diacritical characters properly, but on git log, the output is somehow escaped. According to the UTF-8 encoding table, the codes between angle brackets (< and >) from the output correspond to the previously typed git config parameters.

I have tried to set LESSCHARSET environment variable to utf-8 as suggested in one of the answers for similar issue, but then the output is garbled:

I know .git/config is encoded properly with UTF-8 as it's handled by gitk as expected.

Here is the locale command output if necessary:

```<code>LANG=
LC_CTYPE="C.UTF-8"
LC_NUMERIC="C.UTF-8"
LC_TIME="C.UTF-8"
LC_COLLATE="C.UTF-8"
LC_MONETARY="C.UTF-8"
LC_MESSAGES="C.UTF-8"
LC_ALL=
</code>```

The output is the same also in pure Git Bash:

so I believe the problem is shell-independent and relates to Git or its configuration itself.

答:
git config --global core.pager 'less --raw-control-chars'

#Or

git config --global core.pager 'more'
```

Body:
Problem

How can I make git log command output properly displayed in the Windows CLI terminal?

Example

As you can see, I can type diacritical characters properly, but on git log, the output is somehow escaped. According to the UTF-8 encoding table, the codes between angle brackets (< and >) from the output correspond to the previously typed git config parameters.

I have tried to set LESSCHARSET environment variable to utf-8 as suggested in one of the answers for similar issue, but then the output is garbled:

I know .git/config is encoded properly with UTF-8 as it's handled by gitk as expected.

Here is the locale command output if necessary:

LANG=
LC_CTYPE="C.UTF-8"
LC_NUMERIC="C.UTF-8"
LC_TIME="C.UTF-8"
LC_COLLATE="C.UTF-8"
LC_MONETARY="C.UTF-8"
LC_MESSAGES="C.UTF-8"
LC_ALL=

The output is the same also in pure Git Bash:

so I believe the problem is shell-independent and relates to Git or its configuration itself.


问:
Intellij is erroring when reading my build.gradle.kts file
The red notification bar at the top says: /org/gradle/tooling/BuildException (java.lang.NoClassDefFoundError: /org/gradle/tooling/BuildException. I can run a gradle refresh successfully, I can run the project successfully, but I cannot get that error to go away. I think my project is actually running fine, intellij just can't properly interpret the build.gradle.kts file for whatever reason. Does anybody know what to do? I included an image. Clicking on the red bar does nothing. I can find no more information about the error message anywhere. I'm running the latest intellij EDU.

答: Looks like https://youtrack.jetbrains.com/issue/KTIJ-20903. Try to update your gradle version.</p>


问:
How to get the JAR file for sun.misc.BASE64Encoder class?
I have some code in my Activity class that uses sun.misc.BASE64Encoder class. But it is showing java.lang.NoClassDefFoundError : sun.misc.BASE64Encoder. Do I need the jar? Where can I download it from?

答: Don't use sun.* classes. For Base64 in Android, use its native class or add a library to your project that does this (Apache commons, etc.). Alternatively just copy the Android source code to your project (in your own package), if you need to use it on pre-2.2 devices.


问:
How to define configuration dependent properties in VS C++ project?
I'm really new to C++ and Visual Studio, I know there are ifdef and ifndef to do the conditional compilation.
But my boss ask me to create 2 different configurations (similar to debug and release) to automate this. For example:

```<code>#if $(some_configuration_dependent_flag)
  // I can do something specific for only config1
#endif
</code>```

I've already checked the configuration manager, but the dialog is only used to enable/disable the projects in the solution. Where and how to define the variable some_configuration_dependent_flag mentioned above?

答:
Visual Studio allows per config pre-processor definitions.

Use menu Project/Properties (on right click + Properties on the project) to open the Property Page dialog

Then in C/C++ / Preprocessor, you find Preprocessor Definitions. You select the configuration you want to change, and can add or modify any definition.

Body:
I'm really new to C++ and Visual Studio, I know there are ifdef and ifndef to do the conditional compilation.
But my boss ask me to create 2 different configurations (similar to debug and release) to automate this. For example:

#if $(some_configuration_dependent_flag)
  // I can do something specific for only config1
#endif

I've already checked the configuration manager, but the dialog is only used to enable/disable the projects in the solution. Where and how to define the variable some_configuration_dependent_flag mentioned above?


问:
Use deploy key in GitHub Actions to install dependency from private repo
Dependencies in package.json:

```<code>"dependencies": {
    "my-repo": "git+ssh://github.com/org-name/my-repo.git"
  },
</code>```

GitHub Actions:

```<code>name: Test
on: [push, pull_request]
jobs:
  test:
    name: Test
    runs-on: ubuntu-18.04
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Setup Node.js
        uses: actions/setup-node@v2
        with:
          node-version: 12
          registry-url: 'https://npm.pkg.github.com'
          scope: '@org-name'
      - uses: webfactory/ssh-agent@v0.4.1
        with:
          ssh-private-key: ${{ secrets.DEPLOY_KEY }}
      - name: Install dependencies
        run: yarn
      - name: Test
        run: yarn test
</code>```

The DEPLOY_KEY in the GitHub Actions secrets is the private key and I've added the corresponding public key as a deploy key in the dependency repo.

I generated the key with ssh-keygen -m PEM -t rsa -b 4096 -C "ssh://github.com/org-name/my-repo.git" -f ./deploykey -q -N ""

Here's the failure I see in the GitHub Actions output:

```<code>Exit code: 128
Command: git
Arguments: ls-remote --tags --heads ssh://github.com/org-name/my-repo.git
Directory: /home/runner/work/auth-package/auth-package
Output:
Warning: Permanently added the RSA host key for IP address '140.82.112.4' to the list of known hosts.
runner@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

Really losing my mind on this one!

答:
I don't know If I'm getting it right but to access to a different repo you need an access token. Therefore you need a Github Application with a private key secret. https://github.com/settings/apps

You need those three env variables in your workflow:

```<code>  - uses: actions/checkout@v2
  - name: get secrets
    env:
      PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
      APP_ID: ${{ secrets.APP_ID }}
      INSTALLATION_ID: ${{ secrets.INSTALLATION_ID }}
</code>```

Then create your JWT (check your JWT here: https://jwt.io/) to create the access token via REST API

```<code>run: |
      PEM=$PRIVATE_KEY
      GITHUB_APP_ID=$APP_ID
      NOW=$( date +%s )
      IAT="${NOW}"
      EXP=$((${NOW} + 600))
      HEADER_RAW='{"alg":"RS256"}'
      HEADER=$( echo -n "${HEADER_RAW}" | openssl base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n' )
      PAYLOAD_RAW='{"iat":'"${IAT}"',"exp":'"${EXP}"',"iss":'"${GITHUB_APP_ID}"'}'
      PAYLOAD=$( echo -n "${PAYLOAD_RAW}" | openssl base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n' )
      HEADER_PAYLOAD="${HEADER}"."${PAYLOAD}"
      SIGNATURE=$( openssl dgst -sha256 -sign <(echo -n "${PEM}") <(echo -n "${HEADER_PAYLOAD}") | openssl base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n' )
      JWT="${HEADER_PAYLOAD}"."${SIGNATURE}"
</code>```

Then start your API CALL:

```<code>ACCESS_TOKEN=$(curl -sS -X POST \
      -H "Authorization: Bearer "$JWT"" \
      -H "Accept: application/vnd.github.v3+json" \
      https://github.com/api/v3/app/installations/"$INSTALLATION_ID"/access_tokens | grep -o '"token": "[^"]*' | grep -o '[^"]*$')
</code>```

Then start with your Git Clone command:

```<code>git clone https://x-access-token:"$ACCESS_TOKEN"@github.com/../repo.git
      cd repo
      git config --global user.email "<email>"
      git config --global user.name "<name>"
      git branch upload
      git checkout upload
      git commit -m "update"
      git push --set-upstream origin upload
</code>```

Then you can clone other repos in your current one for example. Be aware to grant the app access to the repos.

Body:
Dependencies in package.json:

"dependencies": {
    "my-repo": "git+ssh://github.com/org-name/my-repo.git"
  },

GitHub Actions:

name: Test
on: [push, pull_request]
jobs:
  test:
    name: Test
    runs-on: ubuntu-18.04
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Setup Node.js
        uses: actions/setup-node@v2
        with:
          node-version: 12
          registry-url: 'https://npm.pkg.github.com'
          scope: '@org-name'
      - uses: webfactory/ssh-agent@v0.4.1
        with:
          ssh-private-key: ${{ secrets.DEPLOY_KEY }}
      - name: Install dependencies
        run: yarn
      - name: Test
        run: yarn test

The DEPLOY_KEY in the GitHub Actions secrets is the private key and I've added the corresponding public key as a deploy key in the dependency repo.

I generated the key with ssh-keygen -m PEM -t rsa -b 4096 -C "ssh://github.com/org-name/my-repo.git" -f ./deploykey -q -N ""

Here's the failure I see in the GitHub Actions output:

Exit code: 128
Command: git
Arguments: ls-remote --tags --heads ssh://github.com/org-name/my-repo.git
Directory: /home/runner/work/auth-package/auth-package
Output:
Warning: Permanently added the RSA host key for IP address '140.82.112.4' to the list of known hosts.
runner@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Really losing my mind on this one!

Body:
I don't know If I'm getting it right but to access to a different repo you need an access token. Therefore you need a Github Application with a private key secret. https://github.com/settings/apps

You need those three env variables in your workflow:

  - uses: actions/checkout@v2
  - name: get secrets
    env:
      PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
      APP_ID: ${{ secrets.APP_ID }}
      INSTALLATION_ID: ${{ secrets.INSTALLATION_ID }}

Then create your JWT (check your JWT here: https://jwt.io/) to create the access token via REST API

run: |
      PEM=$PRIVATE_KEY
      GITHUB_APP_ID=$APP_ID
      NOW=$( date +%s )
      IAT="${NOW}"
      EXP=$((${NOW} + 600))
      HEADER_RAW='{"alg":"RS256"}'
      HEADER=$( echo -n "${HEADER_RAW}" | openssl base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n' )
      PAYLOAD_RAW='{"iat":'"${IAT}"',"exp":'"${EXP}"',"iss":'"${GITHUB_APP_ID}"'}'
      PAYLOAD=$( echo -n "${PAYLOAD_RAW}" | openssl base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n' )
      HEADER_PAYLOAD="${HEADER}"."${PAYLOAD}"
      SIGNATURE=$( openssl dgst -sha256 -sign <(echo -n "${PEM}") <(echo -n "${HEADER_PAYLOAD}") | openssl base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n' )
      JWT="${HEADER_PAYLOAD}"."${SIGNATURE}"

Then start your API CALL:

ACCESS_TOKEN=$(curl -sS -X POST \
      -H "Authorization: Bearer "$JWT"" \
      -H "Accept: application/vnd.github.v3+json" \
      https://github.com/api/v3/app/installations/"$INSTALLATION_ID"/access_tokens | grep -o '"token": "[^"]*' | grep -o '[^"]*$')

Then start with your Git Clone command:

git clone https://x-access-token:"$ACCESS_TOKEN"@github.com/../repo.git
      cd repo
      git config --global user.email "<email>"
      git config --global user.name "<name>"
      git branch upload
      git checkout upload
      git commit -m "update"
      git push --set-upstream origin upload

Then you can clone other repos in your current one for example. Be aware to grant the app access to the repos.


问:
Unable configure Alerts and Actions in Kibana
I'm using a Docker Compose file for ELK setup and using the latest version (above 7) for Kibana. Now I set the xpack.encryptedSavedObjects.encryptionKey parameter in the kibana.yml so that I can use the alert and actions feature. But even after that I'm not able to create alert. Can anyone help me please?

I generated 32 character encryption key using Python uuid module.

答:
According to https://github.com/elastic/kibana/issues/57773 the environment variable XPACK_ENCRYPTEDSAVEDOBJECTS_ENCRYPTIONKEY was missing in the kibana config. In Feb 2020 it was merged and is now working.

The encryption key XPACK_ENCRYPTEDSAVEDOBJECTS_ENCRYPTIONKEY has to be 32 characters or longer. https://www.elastic.co/guide/en/kibana/current/using-kibana-with-security.html

A working configuration could look like this:

...
  kibana:
    depends_on:
      - elasticsearch
    image: docker.elastic.co/kibana/kibana:8.0.0-rc2
    container_name: kibana
    environment:
      - ...
      - SERVER_PUBLICBASEURL=https://kibana.stackoverflow.com/
      - XPACK_ENCRYPTEDSAVEDOBJECTS_ENCRYPTIONKEY=a7a6311933d3503b89bc2dbc36572c33a6c10925682e591bffcab6911c06786d
      - ...
...
```


问:
Failed to view image while converting from numpy array
Actually, I have 2d list(5,20000). First, I converted the list into numpy array.

```<code>a = np.array(my_2_dlist)
</code>```

then I normalized the array from 0 to 255 and made all the values to integer. Afterwards, I used python-opencv to write the image.

```<code>min_max_scaler = preprocessing.MinMaxScaler(feature_range=(0, 255))
scaled_x = min_max_scaler.fit_transform(a).astype(np.uint8)
cv2.imwrite('filename.jpeg', scaled_x)
</code>```

It seems to me, I got perfect result for scaled_x, all the values are between 0 to 255 with no negetive numbers. The image was also saved perfectly in my folder.

But when I opened the image I see nothing. I am perplexed; why I am not seeing anything, the very same code is working for other code samples.

答:
imwrite needs to be given uint8 data if the values are 0 to 255.

If the values are float, they must be ranged 0.0 to 1.0.

Body:
Actually, I have 2d list(5,20000). First, I converted the list into numpy array.

a = np.array(my_2_dlist)

then I normalized the array from 0 to 255 and made all the values to integer. Afterwards, I used python-opencv to write the image.

min_max_scaler = preprocessing.MinMaxScaler(feature_range=(0, 255))
scaled_x = min_max_scaler.fit_transform(a).astype(np.uint8)
cv2.imwrite('filename.jpeg', scaled_x)

It seems to me, I got perfect result for scaled_x, all the values are between 0 to 255 with no negetive numbers. The image was also saved perfectly in my folder.

But when I opened the image I see nothing. I am perplexed; why I am not seeing anything, the very same code is working for other code samples.


问:
stable partition in c++ - why is it O(n lg n)?
I was looking at the possible implementation of stable partition in c++: https://en.cppreference.com/w/cpp/algorithm/ranges/stable_partition

it’s stated this is at worst O nlgn.

How is this possible? it seems like in the worst case a rotate is called at every index, resulting in an O n**2 algorithm.

答:
As ALX23z notes, the sample implementation is not conforming with respect to running time. Here is what an O(n log n) in-place stable_partition could look like (at least from an algorithms perspective; if you want a library-grade implementation go look at the actual libraries).

```<code>#include <algorithm>

template <typename Iterator, typename Predicate>
Iterator my_stable_partition(Iterator first, Iterator last,
                             Predicate predicate) {
  auto n = std::distance(first, last);
  if (n <= 1) {
    if (n == 1 && predicate(*first))
      ++first;
    return first;
  }
  auto middle = first;
  std::advance(middle, n / 2);
  auto a = my_stable_partition(first, middle, predicate);
  auto b = my_stable_partition(middle, last, predicate);
  return std::rotate(a, middle, b);
}
</code>```

Here's a quick and dirty test.

```<code>#include "my_stable_partition.cc"
#include <assert.h>
#include <stdlib.h>
#include <vector>

bool odd(int n) { return n % 2 == 0; }

int main() {
  for (int i = 0; i < 1000; i++) {
    std::vector<int> arr(i);
    long long checksum = 0;
    for (int &x : arr) {
      checksum += x = random() / 31337;
    }
    auto mid = my_stable_partition(arr.begin(), arr.end(), odd);
    for (auto it = arr.begin(); it != mid; ++it) {
      assert(odd(*it));
      checksum -= *it;
    }
    for (auto it = mid; it != arr.end(); ++it) {
      assert(!odd(*it));
      checksum -= *it;
    }
    assert(checksum == 0);
  }
}
</code>```

Body:
As ALX23z notes, the sample implementation is not conforming with respect to running time. Here is what an O(n log n) in-place stable_partition could look like (at least from an algorithms perspective; if you want a library-grade implementation go look at the actual libraries).

#include <algorithm>

template <typename Iterator, typename Predicate>
Iterator my_stable_partition(Iterator first, Iterator last,
                             Predicate predicate) {
  auto n = std::distance(first, last);
  if (n <= 1) {
    if (n == 1 && predicate(*first))
      ++first;
    return first;
  }
  auto middle = first;
  std::advance(middle, n / 2);
  auto a = my_stable_partition(first, middle, predicate);
  auto b = my_stable_partition(middle, last, predicate);
  return std::rotate(a, middle, b);
}

Here's a quick and dirty test.

#include "my_stable_partition.cc"
#include <assert.h>
#include <stdlib.h>
#include <vector>

bool odd(int n) { return n % 2 == 0; }

int main() {
  for (int i = 0; i < 1000; i++) {
    std::vector<int> arr(i);
    long long checksum = 0;
    for (int &x : arr) {
      checksum += x = random() / 31337;
    }
    auto mid = my_stable_partition(arr.begin(), arr.end(), odd);
    for (auto it = arr.begin(); it != mid; ++it) {
      assert(odd(*it));
      checksum -= *it;
    }
    for (auto it = mid; it != arr.end(); ++it) {
      assert(!odd(*it));
      checksum -= *it;
    }
    assert(checksum == 0);
  }
}


问:
Select element in shadow-root with css only
is there any way how can I change CSS inside shadow-root without using JS I mean CSS only. I looked through some things but cant find a way how to do it without js.

lets say we have code

```<code><div id="parent">
   #shadow-root (open)
     <div id="child">
     </div>
</div>
</code>```

how can I access child with CSS only?

答:
Only if the component author explicit allows it using the part attribute on the element in the shadow DOM. In that case you can apply CSS to that element using the ::part pseudo element selector:

Here's an example:

customElements.define('foo-bar', class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'open'})
    this.shadowRoot.innerHTML = '
foo-bar here
';
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>::part(baz) {
  background-color: red;
}</code>```

<foo-bar></foo-bar>```

Please note that you can not do something like ::part(foo) + .internal-css-class {...}.

Other than that, you can always work with CSS's inherited properties, these also affect the shadow DOM. E.g. putting the web component into an
 will affect it's font-size and -weight (unless it specifically defines its own values for those properties).

Body:
is there any way how can I change CSS inside shadow-root without using JS I mean CSS only. I looked through some things but cant find a way how to do it without js.

lets say we have code

   #shadow-root (open)

how can I access child with CSS only?

Body:
Only if the component author explicit allows it using the part attribute on the element in the shadow DOM. In that case you can apply CSS to that element using the ::part pseudo element selector:

Here's an example:

customElements.define('foo-bar', class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'open'})
    this.shadowRoot.innerHTML = '<p part="baz">foo-bar here</p>';
  }
});

::part(baz) {
  background-color: red;
}

<foo-bar></foo-bar>

Please note that you can not do something like ::part(foo) + .internal-css-class {...}.

Other than that, you can always work with CSS's inherited properties, these also affect the shadow DOM. E.g. putting the web component into an <h1> will affect it's font-size and -weight (unless it specifically defines its own values for those properties).


问:
How to add extra data OneSignal Push Notification?
How to send extra data(such as notification id) using oneSignal in spring boot? I have already send simple notification to android application but I am confused about sending extra data. Can anybody help me?</p>

答:
You can send extra data as a map of data using the data parameter in their REST API. Refer to the following for more info:

https://documentation.onesignal.com/reference/create-notification#attachments

After sending the extra data, you can then get it using the relevant methods of OneSignal SDK.


问:
Changing background color on any number input higher than 0 in JavaScript
My question is simple so I hope it shouldn't be so hard to solve. Not as hard as it is for me at least :).

```<code><div id="block">
    <input type="number" min="0" value="0">
</div>
</code>```

https://jsfiddle.net/wbrnmldr/9n60r82y/2/

[EDIT ]Ok since I'm clearly too dumb to explain it properly I will do it again. The grey  around the input field is supposed to go yellow, not the input field itself.

So I have this simple div as seen above. What is supposed to happen is that the background color of this div changes from #F1F1F1 to #FFD200 anytime the input value doesn't equal 0 anymore. And to make it more complicated, if the value is zero again it should return to #F1F1F1. I already got it to work when submitting the value but my goal is to see it happen in real-time.

Can anybody help me tackle this problem?
Thanks in advance!

Following are some of the things I tried but I didn't get to work:

```<code>$('.input').each(function() {
    var inputValue = $(this);

    inputValue.data('oldValue', inputValue.val());

    inputValue.bind("propertychange change click keyup input paste",   function(event){
        if (inputValue.data('oldValue') != inputValue.val()) {
        inputValue.data('oldValue', inputValue.val());

        document.getElementsByClassName('block').style.backgroundColor = "#FFD200";
    }

    });
});
</code>```
```<code>function changeColor() {
    document.getElementById("tracker-option-block").style.backgroundColor = "FFD200";
    return false;
}
</code>```

答:
you can use addEventListener (change) to get value always on change input
then change background color</p>
```<code>document.querySelector('input').addEventListener("change",function(){
if(document.querySelector('#block input').value>0){
document.querySelector('#block input').style.backgroundColor= "#54BAB9";
}
else{
document.querySelector('#block input').style.backgroundColor= "#F1F1F1";
}
})
</code>```

Body:
My question is simple so I hope it shouldn't be so hard to solve. Not as hard as it is for me at least :).

    <input type="number" min="0" value="0">

https://jsfiddle.net/wbrnmldr/9n60r82y/2/

[EDIT ]Ok since I'm clearly too dumb to explain it properly I will do it again. The grey  around the input field is supposed to go yellow, not the input field itself.

So I have this simple div as seen above. What is supposed to happen is that the background color of this div changes from #F1F1F1 to #FFD200 anytime the input value doesn't equal 0 anymore. And to make it more complicated, if the value is zero again it should return to #F1F1F1. I already got it to work when submitting the value but my goal is to see it happen in real-time.

Can anybody help me tackle this problem?
Thanks in advance!

Following are some of the things I tried but I didn't get to work:

$('.input').each(function() {
    var inputValue = $(this);

    inputValue.data('oldValue', inputValue.val());

    inputValue.bind("propertychange change click keyup input paste",   function(event){
        if (inputValue.data('oldValue') != inputValue.val()) {
        inputValue.data('oldValue', inputValue.val());

        document.getElementsByClassName('block').style.backgroundColor = "#FFD200";
    }

    });
});

function changeColor() {
    document.getElementById("tracker-option-block").style.backgroundColor = "FFD200";
    return false;
}

Body:
you can use addEventListener (change) to get value always on change input
then change background color

document.querySelector('input').addEventListener("change",function(){
if(document.querySelector('#block input').value>0){
document.querySelector('#block input').style.backgroundColor= "#54BAB9";
}
else{
document.querySelector('#block input').style.backgroundColor= "#F1F1F1";
}
})


问:
New databricks feature: import is not working
I have uploaded my databricks notebooks to a repo and replace %run sentences with import using the new databrick public available features (Repo integration and python import): https://databricks.com/blog/2021/10/07/databricks-repos-is-now-generally-available.html

But its seems its not working

I already activate the repo integration option in the Admin panel but i Get this error

ModuleNotFoundError: No module named 'petitions'

For simplicity I moved all python files to the same directory. I get the error in the procesado notebook

[

答:
If your are using Azure DataBricks and Python Notebooks, you can't import them as modules.

From the documentation:

If you want to import the notebook as a Python module, you must edit
the notebook in a code editor and remove the line # Databricks
Notebook source. Removing that line converts the notebook to a regular
Python file.

Documentation:
https://learn.microsoft.com/en-us/azure/databricks/repos#work-with-python-and-r-modules


问:
Gevent infinite queue consumer?
I am trying to have a consumer on a separate thread that never dies. The consumer can get arbitrary number of tasks to execute.

I have been fiddling with asyncio and gevent but haven't managed to get anything that works. Below is a very simplified example of what I'm trying to do.

```<code>q = gevent.queue.SimpleQueue()

def run_task(task):
    print(f"Started task {task} @ {time.time()}")
    gevent.sleep(1)
    print(f"Finished task {task} @ {time.time()}")

def consumer():
    while True:
        task = q.get()
        print(f"Dequed task {task} for consumption")
        gevent.spawn(run_task, task)

q.put(1)
q.put(2)
q.put(3)
consumer()
</code>```

Output

```<code>Dequed task 1 for consumption
Dequed task 2 for consumption
Dequed task 3 for consumption
</code>```

Clearly run_task is never executed for the tasks. I can use join() but then the tasks are run in sequence. Using joinall() doesn't seem to be a viable solution either since the queue will keep getting arbitrary tasks.

Any ideas how to approach this?

答:
There are two issues with your code:

SimpleQueue is an alias of the Python standard library queue which requires gevent monkey patching to use.

You are running your consumer on the main thread.

This code works as expected:

```<code>import gevent
import gevent.queue
import time

q = gevent.queue.Queue()

def run_task(task):
    print(f"Started task {task} @ {time.time()}")
    gevent.sleep(1)
    print(f"Finished task {task} @ {time.time()}")

def consumer():
    while True:
        task = q.get()
        print(f"Dequed task {task} for consumption")
        gevent.spawn(run_task, task)

q.put(1)
q.put(2)
q.put(3)

gevent.spawn(consumer)

gevent.sleep(1000)
</code>```

Title: Gevent infinite queue consumer?

Body:
I am trying to have a consumer on a separate thread that never dies. The consumer can get arbitrary number of tasks to execute.

I have been fiddling with asyncio and gevent but haven't managed to get anything that works. Below is a very simplified example of what I'm trying to do.

q = gevent.queue.SimpleQueue()

def run_task(task):
    print(f"Started task {task} @ {time.time()}")
    gevent.sleep(1)
    print(f"Finished task {task} @ {time.time()}")

def consumer():
    while True:
        task = q.get()
        print(f"Dequed task {task} for consumption")
        gevent.spawn(run_task, task)

q.put(1)
q.put(2)
q.put(3)
consumer()

Output

Dequed task 1 for consumption
Dequed task 2 for consumption
Dequed task 3 for consumption

Clearly run_task is never executed for the tasks. I can use join() but then the tasks are run in sequence. Using joinall() doesn't seem to be a viable solution either since the queue will keep getting arbitrary tasks.

Any ideas how to approach this?

Body:
There are two issues with your code:

SimpleQueue is an alias of the Python standard library queue which requires gevent monkey patching to use.

You are running your consumer on the main thread.

This code works as expected:

import gevent
import gevent.queue
import time

q = gevent.queue.Queue()

def run_task(task):
    print(f"Started task {task} @ {time.time()}")
    gevent.sleep(1)
    print(f"Finished task {task} @ {time.time()}")

def consumer():
    while True:
        task = q.get()
        print(f"Dequed task {task} for consumption")
        gevent.spawn(run_task, task)

q.put(1)
q.put(2)
q.put(3)

gevent.spawn(consumer)

gevent.sleep(1000)


问:
Visual Basic 6 and Visual Basic in Visual Studio
Is the code used in Visual Studio for Visual Basic the same as the code for Visual Basic 6.0?

The Visual Basic 6.0 IDE is no longer supported, so I can't get a hold of that version, but a tutoring pupil of mine is doing work in Studio Basic 6. Will I be able to help using Visual Studio or are they different coding languages?

答:
You can install visual studio 6, and can use visual basic 6,
I have installed in windows 10.
There is some problem during installing. I have removed mdac_typ.exe, and continued installing.</p>


问:
How to get instance attribute value from parent class using OOP? Tkinter, Python
I try to add a custom message box using the class MessageboxYesNo. But when trying to do so I get an attribute error from the parent class.

```<code>import tkinter as tk
from sys import platform

class MainApp(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.parent.title("My app")
        self.set_app_size_and_position()

        self.messagebox1 = MessageboxYesNo(self.parent, "QUIT", "Are you sure you want to quit?")

    def set_app_size_and_position(self):
        # get screen width and height
        self.screen_width = int(self.parent.winfo_screenwidth())
        self.screen_height = int(self.parent.winfo_screenheight())

        self.app_width_mac = int(self.screen_width/2)
        self.app_height_mac = int(self.screen_height)
        self.app_x_pos_mac = int(self.screen_width/2)
        self.app_y_pos_mac = 0

        if platform == "darwin":
            self.parent.geometry(f"{self.app_width_mac}x{self.app_height_mac}+{self.app_x_pos_mac}+{self.app_y_pos_mac}")

class MessageboxYesNo(MainApp):
    def __init__(self, parent, title, text):
        MainApp.__init__(self, parent)
        #inherits the MainApp to be able to get the parent's instance variable value from app_x_pos_mac and app_y_pos_mac

        self.parent = parent

        self.title = title
        self.text = text

        self.toplevel = tk.Toplevel(self.parent)
        self.toplevel.title(self.title)

        #set x- and y-coordinates for centering the messagebox
        self.x_pos_messagebox = int(self.app_x_pos_mac+(self.app_x_pos_mac/2))
        self.y_pos_messagebox = 0

        #position the messagebox in the center of the app
        self.toplevel.geometry(f"500x300+{self.x_pos_messagebox}+{self.y_pos_messagebox}")

        #add labels and buttons to messagebox
        self.l1=tk.Label(self.toplevel, image="::tk::icons::question")
        self.l1.grid(row=0, column=0, pady=(7, 0), padx=(10, 30), sticky="e")

        self.l2=tk.Label(self.toplevel,text=self.text)
        self.l2.grid(row=0, column=1, columnspan=3, pady=(7, 10), sticky="w")

        self.b1=tk.Button(self.toplevel,text="Yes",width = 10)
        self.b1.grid(row=1, column=1, padx=(2, 35), sticky="e")

        self.b2=tk.Button(self.toplevel,text="No", width = 10)
        self.b2.grid(row=1, column=2, padx=(2, 35), sticky="e")

def main():
    root = tk.Tk()
    app = MainApp(root)
    Driver(app.parent)
    app.pack()

    root.mainloop()

if __name__ == "__main__":
    main()
</code>```

I get this traceroute below. It seems like the parent that gets passed to MainApp.init(self, parent) method in the MessageboxYesNo class, gets confused somehow.

```<code>Traceback (most recent call last):
  File "//AcademyApp.py", line 307, in <module>
    main()
  File "//AcademyApp.py", line 300, in main
    app = MainApp(root)
  File "//AcademyApp.py", line 78, in __init__
    self.messagebox1 = MessageboxYesNo(self.parent, "QUIT", "Are you sure you want to quit?")
  File "//AcademyApp.py", line 263, in __init__
    MainApp.__init__(self, parent)
  File "//AcademyApp.py", line 68, in __init__
    self.parent.title("My app")
AttributeError: 'Frame' object has no attribute 'title'
</code>```

It seems that the self.parent in the class MessageboxYesNo gets confused with the self.parent in class MainApp. How can we solve this?

If I try the code without any of my other app code. I get this error instead:

```<code>File "/.py", line 12, in __init__
    self.messagebox1 = MessageboxYesNo(self.parent, "QUIT", "Are you sure you want to quit?")
  File "/.py", line 29, in __init__
    MainApp.__init__(self, parent)
  File "/.py", line 12, in __init__
    self.messagebox1 = MessageboxYesNo(self.parent, "QUIT", "Are you sure you want to quit?")
  File "/.py", line 29, in __init__
    MainApp.__init__(self, parent)
  File "/.py", line 7, in __init__
    tk.Frame.__init__(self, parent, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 3116, in __init__
    cnf = _cnfmerge((cnf, kw))
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 105, in _cnfmerge
    elif isinstance(cnfs, (type(None), str)):
RecursionError: maximum recursion depth exceeded in __instancecheck__
</code>```

It is like it is looping, but don't know why?

If I change the MessageboxYesNo class to this it works, but then I can't figure out how to get the value from the instance variable app_x_pos_mac?

```<code>class MessageboxYesNo(tk.Frame):
    def __init__(self, parent, title, text):
        tk.Frame.__init__(self, parent)

        self.parent = parent

        self.title = title
        self.text = text

        self.toplevel = tk.Toplevel(self.parent)
        self.toplevel.title(self.title)

        print(self.parent.app_x_pos_mac) #this can't get the variable value from the MainApp class
</code>```

答:
It appears the reason it is confusing the parents is because you're passing MainApp's parent to MessageboxYesNo. Instead, write:

```<code>self.messagebox1 = MessageboxYesNo(self, "QUIT", "Are you sure you want to quit?")
</code>```

But you will also need to remove the MainApp.__init__(self, parent) line from your  MessageboxYesNo class, otherwise it will continue to recursively loop.

Body:
I try to add a custom message box using the class MessageboxYesNo. But when trying to do so I get an attribute error from the parent class.

import tkinter as tk
from sys import platform

class MainApp(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.parent.title("My app")
        self.set_app_size_and_position()

        self.messagebox1 = MessageboxYesNo(self.parent, "QUIT", "Are you sure you want to quit?")

    def set_app_size_and_position(self):
        # get screen width and height
        self.screen_width = int(self.parent.winfo_screenwidth())
        self.screen_height = int(self.parent.winfo_screenheight())

        self.app_width_mac = int(self.screen_width/2)
        self.app_height_mac = int(self.screen_height)
        self.app_x_pos_mac = int(self.screen_width/2)
        self.app_y_pos_mac = 0

        if platform == "darwin":
            self.parent.geometry(f"{self.app_width_mac}x{self.app_height_mac}+{self.app_x_pos_mac}+{self.app_y_pos_mac}")

class MessageboxYesNo(MainApp):
    def __init__(self, parent, title, text):
        MainApp.__init__(self, parent)
        #inherits the MainApp to be able to get the parent's instance variable value from app_x_pos_mac and app_y_pos_mac

        self.parent = parent

        self.title = title
        self.text = text

        self.toplevel = tk.Toplevel(self.parent)
        self.toplevel.title(self.title)

        #set x- and y-coordinates for centering the messagebox
        self.x_pos_messagebox = int(self.app_x_pos_mac+(self.app_x_pos_mac/2))
        self.y_pos_messagebox = 0

        #position the messagebox in the center of the app
        self.toplevel.geometry(f"500x300+{self.x_pos_messagebox}+{self.y_pos_messagebox}")

        #add labels and buttons to messagebox
        self.l1=tk.Label(self.toplevel, image="::tk::icons::question")
        self.l1.grid(row=0, column=0, pady=(7, 0), padx=(10, 30), sticky="e")

        self.l2=tk.Label(self.toplevel,text=self.text)
        self.l2.grid(row=0, column=1, columnspan=3, pady=(7, 10), sticky="w")

        self.b1=tk.Button(self.toplevel,text="Yes",width = 10)
        self.b1.grid(row=1, column=1, padx=(2, 35), sticky="e")

        self.b2=tk.Button(self.toplevel,text="No", width = 10)
        self.b2.grid(row=1, column=2, padx=(2, 35), sticky="e")

def main():
    root = tk.Tk()
    app = MainApp(root)
    Driver(app.parent)
    app.pack()

    root.mainloop()

if __name__ == "__main__":
    main()

I get this traceroute below. It seems like the parent that gets passed to MainApp.init(self, parent) method in the MessageboxYesNo class, gets confused somehow.

Traceback (most recent call last):
  File "//AcademyApp.py", line 307, in <module>
    main()
  File "//AcademyApp.py", line 300, in main
    app = MainApp(root)
  File "//AcademyApp.py", line 78, in __init__
    self.messagebox1 = MessageboxYesNo(self.parent, "QUIT", "Are you sure you want to quit?")
  File "//AcademyApp.py", line 263, in __init__
    MainApp.__init__(self, parent)
  File "//AcademyApp.py", line 68, in __init__
    self.parent.title("My app")
AttributeError: 'Frame' object has no attribute 'title'

It seems that the self.parent in the class MessageboxYesNo gets confused with the self.parent in class MainApp. How can we solve this?

If I try the code without any of my other app code. I get this error instead:

File "/.py", line 12, in __init__
    self.messagebox1 = MessageboxYesNo(self.parent, "QUIT", "Are you sure you want to quit?")
  File "/.py", line 29, in __init__
    MainApp.__init__(self, parent)
  File "/.py", line 12, in __init__
    self.messagebox1 = MessageboxYesNo(self.parent, "QUIT", "Are you sure you want to quit?")
  File "/.py", line 29, in __init__
    MainApp.__init__(self, parent)
  File "/.py", line 7, in __init__
    tk.Frame.__init__(self, parent, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 3116, in __init__
    cnf = _cnfmerge((cnf, kw))
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 105, in _cnfmerge
    elif isinstance(cnfs, (type(None), str)):
RecursionError: maximum recursion depth exceeded in __instancecheck__

It is like it is looping, but don't know why?

If I change the MessageboxYesNo class to this it works, but then I can't figure out how to get the value from the instance variable app_x_pos_mac?

class MessageboxYesNo(tk.Frame):
    def __init__(self, parent, title, text):
        tk.Frame.__init__(self, parent)

        self.parent = parent

        self.title = title
        self.text = text

        self.toplevel = tk.Toplevel(self.parent)
        self.toplevel.title(self.title)

        print(self.parent.app_x_pos_mac) #this can't get the variable value from the MainApp class

Body:
It appears the reason it is confusing the parents is because you're passing MainApp's parent to MessageboxYesNo. Instead, write:

self.messagebox1 = MessageboxYesNo(self, "QUIT", "Are you sure you want to quit?")

But you will also need to remove the MainApp.__init__(self, parent) line from your  MessageboxYesNo class, otherwise it will continue to recursively loop.


问:
How to add default in every case in c++
how do i add default in every case?
it does not allow me to do it like this and will error in the second default,

```<code>switch (select)
{

    case 1:
        here1:
        cout<<"statement"<<endl;

    default:
        cout<<"statement"<<endl;
        goto here1;

        break;

    case 2:
        here2:
        cout<<"statement"<<endl;

    default:
        cout<<"statement"<<endl;
        goto here2;

        break;

</code>```

i need default inside every case, how am i gonna do that?

答:
it looks like you are trying to execute the same piece of code for every case so why can't you just do so.

default just works if "incase nothing works" and if something works default doesn't execute.

Title: How to add default in every case in c++

Body:
how do i add default in every case?
it does not allow me to do it like this and will error in the second default,

switch (select)
{

    case 1:
        here1:
        cout<<"statement"<<endl;

    default:
        cout<<"statement"<<endl;
        goto here1;

        break;

    case 2:
        here2:
        cout<<"statement"<<endl;

    default:
        cout<<"statement"<<endl;
        goto here2;

        break;

i need default inside every case, how am i gonna do that?